branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file syntax.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "syntax.h"
#include <ctype.h> // For isdigit()
#include <string.h> // For memset(), strchr(), strrchr()
// -----------------------------------------------------------------------
// File type support definition
// -----------------------------------------------------------------------
static const char* HL_C_Extensions[] = { ".h", ".c", ".cpp", NULL };
static const char* HL_C_KeyWords[] = {
"switch", "if", "while", "for", "break", "continue", "return", "else",
"struct", "union", "typedef", "static", "enum", "class", "case",
"int|", "long|", "double|", "float|", "char|", "unsigned|", "signed|",
"void|", NULL
};
static EDE_EditorSyntax HLDB[] = {
{
"c",
HL_C_Extensions,
HL_C_KeyWords,
"//",
HLFLAGS_NUMBER | HLFLAGS_STRING
}
};
// -----------------------------------------------------------------------
// Static Helpers
// -----------------------------------------------------------------------
static bool IsSeparator(int c) {
return isspace(c) || c == '\0' || strchr(",.()+-/*=~%<>[];", c) != NULL;
}
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
void EDE_EditorSelectSyntax() {
EDE().Syntax = nullptr; // Cleanup
if (!EDE().FileName) return;
char* ext = strrchr(EDE().FileName, '.');
for (int hl = 0; hl < EDE_HLDB_Length(); ++hl) {
EDE_EditorSyntax* s = &HLDB[hl];
unsigned int i = 0;
while(s->FileMatch[i]) {
bool is_ext = (s->FileMatch[i][0] == '.');
if ((is_ext && ext && !strcmp(ext, s->FileMatch[i])) ||
(!is_ext && strstr(EDE().FileName, s->FileMatch[i]))) {
EDE().Syntax = s;
for (int filerow = 0; filerow < EDE().DisplayRows; ++filerow)
EDE_EditorUpdateSyntax(&EDE().Rows[filerow]);
return;
}
++i;
}
}
}
void EDE_EditorUpdateSyntax(EDE_EditorRows* row) {
// TODO(<NAME>): Again this function realloc everytime it is called
// to update the syntax highlighting, which is not good in my opinion.
row->HighLight = (unsigned char*) realloc(row->HighLight, row->RSize);
memset(row->HighLight, HL_NORMAL, row->RSize);
if (!EDE().Syntax) return;
char* scs = (char*) EDE().Syntax->SingleLineComment;
int scs_len = scs ? strlen(scs) : 0;
char** keywords = (char**) EDE().Syntax->KeyWords;
bool prev_separator = true;
int inside_string = 0;
int i = 0;
while (i < row->RSize) {
char c = row->Render[i];
unsigned char prev_hl = (i > 0) ? row->HighLight[i - 1] : HL_NORMAL;
// Highlight comment
if (scs_len && !inside_string) {
if (!strncmp(&row->Render[i], scs, scs_len)) {
memset(&row->HighLight[i], HL_COMMENT, row->RSize - i);
break;
}
}
// Highlight strings
if (EDE().Syntax->Flags &HLFLAGS_STRING) {
if (inside_string) {
row->HighLight[i] = HL_STRING;
if (c == '\\' && i + 1 < row->Size) {
row->HighLight[i + 1] = HL_STRING;
i += 2;
continue;
}
if (c == inside_string) inside_string = 0;
++i;
prev_separator = true;
continue;
} else {
if (c == '"' || c == '\'') {
inside_string = c;
row->HighLight[i] = HL_STRING;
++i;
continue;
}
}
}
// Hightlight numbers
if (EDE().Syntax->Flags & HLFLAGS_NUMBER) {
if ((isdigit(c) && (prev_separator || prev_hl == HL_NUMBER)) ||
(c == '.' && prev_hl == HL_NUMBER)) {
row->HighLight[i] = HL_NUMBER;
++i;
prev_separator = false;
continue;
}
}
// Highlight key words
if (prev_separator) {
int j;
for (j = 0; keywords[j]; ++j) {
int klen = strlen(keywords[j]);
bool ktype = keywords[j][klen - 1] == '|';
if (ktype) --klen;
if (!strncmp(&row->Render[i], keywords[j], klen) &&
IsSeparator(row->Render[i + klen])) {
memset(&row->HighLight[i], ktype ? HL_KEYTYPE : HL_KEYWORD, klen);
i += klen;
break;
}
}
if (keywords[j] != NULL) {
prev_separator = false;
continue;
}
}
prev_separator = IsSeparator(c);
++i;
}
}
// TODO(<NAME>): Abstract this for easy theme maker
int EDE_EditorSyntaxToColor(int highlight) {
switch(highlight) {
case HL_COMMENT: return 36;
case HL_KEYWORD: return 33;
case HL_KEYTYPE: return 32;
case HL_NUMBER : return 31;
case HL_STRING : return 35;
case HL_MATCH : return 34;
default: return 37;
}
}
// HLDB API
EDE_EditorSyntax* EDE_HLDB() { return HLDB; }
int EDE_HLDB_Length() { return sizeof(HLDB) / sizeof(HLDB[0]); }
<file_sep># EDE
Ethan Development Editor
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file syntax.h
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EDE_SYNTAX_H_
#define EDE_SYNTAX_H_
#include "utils.h"
// -----------------------------------------------------------------------
// Structure and type definition
// -----------------------------------------------------------------------
enum EditorHighlight {
HL_NORMAL = 0,
HL_COMMENT ,
HL_KEYWORD ,
HL_KEYTYPE ,
HL_NUMBER ,
HL_STRING ,
HL_MATCH
};
enum EditorHighlightFlags {
HLFLAGS_NUMBER = 1 << 0,
HLFLAGS_STRING = 1 << 1,
};
struct EDE_EditorSyntax {
const char* FileType;
const char** FileMatch;
const char** KeyWords;
const char* SingleLineComment;
int Flags;
};
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
void EDE_EditorSelectSyntax(); // Tries to match the current filename to one of the filematch in HLDB
void EDE_EditorUpdateSyntax(EDE_EditorRows* row); // Update the syntax highlighting
int EDE_EditorSyntaxToColor(int highlight); // Return the color based on syntax
EDE_EditorSyntax* EDE_HLDB(); // Return the Hightlight Database
int EDE_HLDB_Length(); // Return the length of the Highlight Database
#endif // EDE_SYNTAX_H_
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file terminal.h
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EDE_TERMINAL_H_
#define EDE_TERMINAL_H_
#include "memory.h"
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
void EDE_TermRefreshScreen(); // Refresh the terminal screen.
int EDE_TermGetSize(int *cols, int * rows); // Get the size of the terminal.
void EDE_TermSetStatusMessage(const char* msg, ...); // Set the message to the status line
// Render
// ---
void EDE_TermDrawMessageBar(FixedBuffer *fb, int message_len); // Drawing the message bar below the status bar.
void EDE_TermDrawStatusBar(FixedBuffer *fb, const char* status, int status_len); // Drawing the status bar at the end line of terminal screen.
void EDE_TermDrawRows(FixedBuffer *fb, const char* welcome_msg, int welcome_len); // Drawing the rows primitives.
#endif // EDE_TERMINAL_H_
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file input.h
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EDE_INPUT_H_
#define EDE_INPUT_H_
#define CTRL_KEY(key) ((key) & 0x1f)
// -----------------------------------------------------------------------
// Type Definition & Structure
// -----------------------------------------------------------------------
enum EditorKey {
BACKSPACE = 127,
KEY_LEFT = 1000, // For not overlaping with input key
KEY_UP ,
KEY_RIGHT ,
KEY_DOWN ,
KEY_DEL ,
KEY_HOME ,
KEY_END ,
PAGE_DOWN ,
PAGE_UP ,
};
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
int EDE_ReadKey(); // Wait for key press then return the character.
void EDE_ProcessKeyPressed(); // Wait for one key press then handle it.
char* EDE_MessagePrompt(const char* prompt, void (*callback)(char*, int)); // Get the user prompt input in the message bar.
#endif // EDE_INPUT_H_
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file terminal.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "terminal.h"
#include "utils.h"
#include "config.h"
#include "syntax.h"
#include <ctype.h> // For iscntrl()
#include <stdarg.h> // For va_list(), va_start(), va_end()
#include <string.h> // For strlen(), memset()
#include <sys/ioctl.h> // For ioctl(), winsize, TIOCGWINSZ
// -----------------------------------------------------------------------
// Static Helpers
// -----------------------------------------------------------------------
int EDE_TermGetCursorPosition(int *cols, int *rows) {
// NOTE(Nghia Lam): <ESC>[6n query the cursor information data.
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4)
return -1;
char buf[32];
unsigned int i = 0;
while (i < sizeof(buf) - 1) {
if (read(STDOUT_FILENO, &buf[i], 1) != 1) break;
if (buf[i] == 'R') break;
++i;
}
buf[i] = '\0';
if (buf[0] != '\x1b' || buf[1] != '[') return -1;
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1;
return 0;
}
void EDE_TermScreenScroll() {
if (EDE().CursorY < EDE().RowOffset)
EDE().RowOffset = EDE().CursorY;
if (EDE().CursorY >=
EDE().RowOffset + EDE().ScreenRows)
EDE().RowOffset = EDE().CursorY - EDE().ScreenRows + 1;
if (EDE().CursorX < EDE().ColOffset)
EDE().ColOffset = EDE().CursorX;
if (EDE().CursorX >=
EDE().ColOffset + EDE().ScreenCols)
EDE().ColOffset = EDE().CursorX - EDE().ScreenCols + 1;
}
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
void EDE_TermRefreshScreen() {
EDE_TermScreenScroll();
// Calculate buffer size of all drawing command
// TODO(<NAME>): Maybe we can abstract this part to another function
// ---
// Init welcome message
char welcome[80];
int welcome_len = snprintf(welcome,
sizeof(welcome),
"Ethan Development Editor -- Version %s",
EDE_VERSION);
if (welcome_len > EDE().ScreenCols)
welcome_len = EDE().ScreenCols;
// Init status bar
char status[80];
int status_len = snprintf(status,
sizeof(status),
" %.20s [%s] - %d/%d lines %s",
EDE().FileName ? EDE().FileName : "[No name]",
EDE().Syntax ? EDE().Syntax->FileType : "No file type",
EDE().CursorY + 1,
EDE().DisplayRows,
EDE().IsDirty ? "- (modified)" : "");
if (status_len > EDE().ScreenCols)
status_len = EDE().ScreenCols;
// Init message bar
int message_len = (strlen(EDE().StatusMsg) > EDE().ScreenCols)
? EDE().ScreenCols : strlen(EDE().StatusMsg);
// Cursor Position Buffer
char cursor_buf[32];
snprintf(cursor_buf,
sizeof(cursor_buf),
"\x1b[%d;%dH",
EDE().CursorY - EDE().RowOffset + 1, // Convert to 1-based Index
EDE().CursorX - EDE().ColOffset + 1); // Convert to 1-based Index
// Input Drawing Buffer
int input_buf = 0;
for(int i = 0; i < EDE().DisplayRows; ++i) {
int row_size = (EDE().Rows[i].Size > EDE().ScreenCols) ? EDE().ScreenCols : EDE().Rows[i].Size;
int current_color = -1;
input_buf += row_size;
// Syntax coloring add to buffer
// TODO(<NAME>): Doing this way is optimal with memory but its speed may not be good.
// Since we loop through all the file 2 two just to store the memory and then drawing...
for (int j = 0; j < row_size; ++j) {
if (EDE().Rows[i].HighLight[j] == HL_NORMAL) {
if (current_color != -1) {
input_buf += 5; // Change to text default color
current_color = -1;
}
} else {
int color = EDE_EditorSyntaxToColor(EDE().Rows[i].HighLight[j]);
if (color != current_color) {
current_color = color;
char buf_color[16];
int clen = snprintf(buf_color, sizeof(buf_color), "\x1b[%dm", color);
input_buf += clen;
}
}
}
input_buf += 5; // Reset to text default color
}
// NOTE(<NAME>): A fixed buffer to contain all the command lists for refresh
// the terminal screen, which included:
// - 6: Escape sequence <ESC>[?25l - Hide cursor before re-drawing screen -
// - 3: Escape sequence <ESC>[H - Re-position cursor to top left corner |-> 15 bytes
// - 6: Escape sequence <ESC>[?25h - Re-enable cursor after re-drawing screen -
// - rows * 6: ~<ESC>[K\r\n at the begining of each row.
// - welcome_len: Size for welcome message when open a blank EDE.
// - cursor_buf: Size for cursor position drawing command.
// - input_buf: Size for text input drawing command
// - status_len: Size for drawing status bar. Please see EDE_TermDrawStatusBar() for more details.
// - message_len: Size for drawing message bar. Please see EDE_TermDrawMessageBar() for more details.
int buffer_size = 15 // Size of all Escape sequence command
+ (EDE().ScreenRows * 6) // Size of each line drawing command
+ welcome_len // Welcome message's length
+ (EDE().ScreenCols - welcome_len) / 2 // Welcome message's padding (for center)
+ strlen(cursor_buf) // Cursor position drawing command
+ input_buf // Input drawing command
+ status_len + EDE().ScreenCols + 9 // Status Bar drawing command
+ message_len + 3; // Message Bar drawing command
// This fixed buffer will allocate all the memory require for all the command once.
// Then we only need to add the character command to it later. This approach will
// prevent from dynamic relocate memory again and again during run-time.
FixedBuffer fb(buffer_size);
// NOTE(<NAME>):
// - \x1b: Escape squence (or 27 in decimal) start, follow by [ character
EDE_FixedBufAppend(&fb, "\x1b[?25l", 6); // Hide cursor before re-drawing screen
EDE_FixedBufAppend(&fb, "\x1b[H", 3); // Re-position cursor to top left corner
EDE_TermDrawRows(&fb, welcome, welcome_len);
EDE_TermDrawStatusBar(&fb, status, status_len);
EDE_TermDrawMessageBar(&fb, message_len);
EDE_FixedBufAppend(&fb, cursor_buf, strlen(cursor_buf)); // Positioning Cursor
EDE_FixedBufAppend(&fb, "\x1b[?25h", 6); // Re-enable cursor after re-drawing screen
// Write the batch buffer at once
write(STDOUT_FILENO, fb.Buf, fb.Size);
}
int EDE_TermGetSize(int *cols, int * rows) {
winsize ws;
// NOTE(<NAME>): Since ioctl() wont always give us the right number from
// every terminal, so we will provide some fallback here.
// The idea is to position the cursor at the bottom right of the terminal
// screen, then query the columns and rows based on the the cursor's pos.
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12)
return -1;
return EDE_TermGetCursorPosition(cols, rows);
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
void EDE_TermSetStatusMessage(const char* msg, ...) {
va_list ap;
va_start(ap, msg);
vsnprintf(EDE().StatusMsg, sizeof(EDE().StatusMsg), msg, ap);
va_end(ap);
EDE().StatusTime = time(NULL); // Got the current time
}
// Render
// ---
void EDE_TermDrawRows(FixedBuffer *fb, const char* welcome_msg, int welcome_len) {
for (int y = 0; y < EDE().ScreenRows; ++y) {
int file_row = y + EDE().RowOffset;
if (file_row >= EDE().DisplayRows) {
if (EDE().DisplayRows == 0 && y == EDE().ScreenRows / 3) {
// Center welcome message
int padding = (EDE().ScreenCols - welcome_len) / 2;
if (padding) {
EDE_FixedBufAppend(fb, "~", 1);
--padding;
}
while(--padding)
EDE_FixedBufAppend(fb, " ", 1);
EDE_FixedBufAppend(fb, welcome_msg, welcome_len);
}
else {
EDE_FixedBufAppend(fb, "~", 1);
}
} else {
int len = EDE().Rows[file_row].RSize - EDE().ColOffset;
if (len < 0) len = 0;
if (len > EDE().ScreenCols) len = EDE().ScreenCols;
// Render each text with different color based on syntax highlighting
char* c = &EDE().Rows[file_row].Render[EDE().ColOffset];
unsigned char* hl = &EDE().Rows[file_row].HighLight[EDE().ColOffset];
int current_color = -1;
for (int i = 0; i < len; ++i) {
if (hl[i] == HL_NORMAL) {
if (current_color != -1) {
EDE_FixedBufAppend(fb, "\x1b[39m", 5);
current_color = -1;
}
} else {
int color = EDE_EditorSyntaxToColor(hl[i]);
if (color != current_color) {
char buf_color[16];
int clen = snprintf(buf_color, sizeof(buf_color), "\x1b[%dm", color);
EDE_FixedBufAppend(fb, buf_color, clen);
current_color = color;
}
}
EDE_FixedBufAppend(fb, &c[i], 1); // Append the character
}
EDE_FixedBufAppend(fb, "\x1b[39m", 5); // Reset to text color default
}
EDE_FixedBufAppend(fb, "\x1b[K", 3); // Clear the line
EDE_FixedBufAppend(fb, "\r\n", 2); // Go to the new line
}
}
// NOTE(<NAME>):
// - Escape sequence <Esc>[7m: Invert drawing color to use black as text color,
// white as background color.
// - Escape sequence <Esc>[m: Invert back to normal drawing color.
void EDE_TermDrawStatusBar(FixedBuffer *fb, const char* status, int status_len) {
EDE_FixedBufAppend(fb, "\x1b[7m", 4); // Invert drawing color to use black as text color, white as background color.
EDE_FixedBufAppend(fb, status, status_len);
while (status_len < EDE().ScreenCols) {
EDE_FixedBufAppend(fb, " ", 1);
++status_len;
}
EDE_FixedBufAppend(fb, "\x1b[m", 3); // Revert back to normal drawing color.
EDE_FixedBufAppend(fb, "\r\n", 2); // Status line.
}
// NOTE(<NAME>):
// - Escape sequence <Esc>[K: Clear the message bar
void EDE_TermDrawMessageBar(FixedBuffer *fb, int message_len) {
EDE_FixedBufAppend(fb, "\x1b[K", 3); // Clear the message bar.
if (message_len && (time(NULL) - EDE().StatusTime) < 1) // Draw the message only 1 seconds
EDE_FixedBufAppend(fb, EDE().StatusMsg, message_len);
}
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file file_io.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "file_io.h"
#include "command.h"
#include "terminal.h"
#include "syntax.h"
#include "input.h"
#include <string.h> // For memcpy(), strerror()
#include <fcntl.h> // For open(), O_RDWR, O_CREAT
#include <unistd.h> // For ftruncate(), close()
#include <errno.h> // For errno
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
char* EDE_EditorRowsToString(int *buffer_size) {
int total_size = 0;
for (int i = 0; i < EDE().DisplayRows; ++i)
total_size += EDE().Rows[i].Size + 1; // Add 1 byte for the new line character
*buffer_size = total_size;
char* buf = new char[total_size];
char* travel = buf;
for (int i = 0; i < EDE().DisplayRows; ++i) {
memcpy(travel, EDE().Rows[i].Chars, EDE().Rows[i].Size);
travel += EDE().Rows[i].Size;
*travel = '\n';
++travel;
}
return buf; // We return the allocate chars here, expect the use to call delete[] afterward.
}
void EDE_EditorOpen(const char* file_name) {
delete[] EDE().FileName; // Clean up current open file
EDE().FileName = strdup(file_name);
EDE_EditorSelectSyntax();
FILE *fp = fopen(file_name, "r");
if (!fp) EDE_ErrorHandler("fopen");
char *line = nullptr;
size_t linecap = 0;
ssize_t linelen = 0;
while ((linelen = getline(&line, &linecap, fp)) != -1) {
while(linelen > 0 && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r'))
--linelen;
EDE_EditorInsertRow(EDE().DisplayRows, line, linelen);
}
free(line);
fclose(fp);
EDE().IsDirty = false;
}
void EDE_EditorSave() {
if (EDE().FileName == nullptr) {
EDE().FileName = EDE_MessagePrompt("Save as: %s", nullptr);
if (EDE().FileName == nullptr) {
EDE_TermSetStatusMessage("Save aborted ..!");
return;
}
EDE_EditorSelectSyntax();
}
int bufsize = 0;
char* buf = EDE_EditorRowsToString(&bufsize);
// NOTE(<NAME>):
// - O_RDWR : Open for reading & writing.
// - O_CREAT : Create a new file if it doesnt exist.
// - 0644 : The code permission for reading and writing text file.
// - ftruncate(): Set the file size to the specific number. It will cut off
// the data if the file is shorter or add 0 to the end if the
// file is longer.
int fd = open(EDE().FileName, O_RDWR | O_CREAT, 0644);
if (fd != -1) {
if (ftruncate(fd, bufsize) != -1) {
if (write(fd, buf, bufsize) == bufsize) {
close(fd);
delete[] buf; // Cleanup
EDE().IsDirty = false;
EDE_TermSetStatusMessage("%d bytes has been written to disk !", bufsize);
return;
}
}
close(fd);
}
// Clean up
delete[] buf;
EDE_TermSetStatusMessage("Cannot save! I/O Error: %s", strerror(errno));
}<file_sep># =====================================================
# _______ _____ _______
# | ___| \| ___|
# | ___| -- | ___|
# |_______|_____/|_______|
# ---
# Ethan Development Editor
# =====================================================
# @file CMakeLists - EDE
# @author <NAME> <<EMAIL>>
#
# @brief
#
# @license Copyright 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------
# Default Setup
# -----------------------------------------------------
cmake_minimum_required(VERSION 3.2)
project(EDE)
# ------------------------------------------------------
# C++17 Support
# ------------------------------------------------------
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# ------------------------------------------------------
# Compiler Flag
# ------------------------------------------------------
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang")
# using Clang
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++")
add_definitions( -c -Wall -msse2 )
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
# using GCC
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
add_definitions( -c -Wall -msse2 )
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
# using Intel C++
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
add_definitions( -c -Wall -msse2 )
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
# using Visual Studio C++
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
add_definitions( -c -W4 )
endif()
if (CMAKE_BUILD_TYPE STREQUAL "")
# CMake defaults to leaving CMAKE_BUILD_TYPE empty. This screws up
# differentiation between debug and release builds.
set(CMAKE_BUILD_TYPE "Debug"
CACHE STRING "Choose the type of build, options are: None (CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) \"Debug\" \"Release\" \"RelWithDebInfo\" \"MinSizeRel\"."
FORCE)
add_definitions(-DEDE_DEBUG)
endif()
if (CMAKE_BUILD_TYPE STREQUAL "Release")
add_definitions(-DEDE_RELEASE)
endif()
# ------------------------------------------------------
# Build Folders
# ------------------------------------------------------
set(EDE_PATH ${CMAKE_CURRENT_SOURCE_DIR})
set(EDE_BIN "bin")
set(EDE_LIB "lib")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${EDE_PATH}/${EDE_BIN})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${EDE_PATH}/${EDE_BIN})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${EDE_PATH}/${EDE_BIN})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${EDE_PATH}/${EDE_BIN})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${EDE_PATH}/${EDE_BIN})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${EDE_PATH}/${EDE_BIN})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG ${EDE_PATH}/${EDE_BIN})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELWITHDEBINFO ${EDE_PATH}/${EDE_BIN})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${EDE_PATH}/${EDE_BIN}/${EDE_LIB})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${EDE_PATH}/${EDE_BIN}/${EDE_LIB})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${EDE_PATH}/${EDE_BIN}/${EDE_LIB})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO ${EDE_PATH}/${EDE_BIN}/${EDE_LIB})
# ------------------------------------------------------
# Build Sources
# ------------------------------------------------------
set(EDE_SRC_DIR "${CMAKE_CURRENT_LIST_DIR}/src")
set(HEADERS
"${EDE_SRC_DIR}/terminal.h"
"${EDE_SRC_DIR}/command.h"
"${EDE_SRC_DIR}/file_io.h"
"${EDE_SRC_DIR}/memory.h"
"${EDE_SRC_DIR}/syntax.h"
"${EDE_SRC_DIR}/utils.h"
"${EDE_SRC_DIR}/input.h"
)
set(SOURCES
"${EDE_SRC_DIR}/terminal.cpp"
"${EDE_SRC_DIR}/command.cpp"
"${EDE_SRC_DIR}/file_io.cpp"
"${EDE_SRC_DIR}/memory.cpp"
"${EDE_SRC_DIR}/syntax.cpp"
"${EDE_SRC_DIR}/utils.cpp"
"${EDE_SRC_DIR}/input.cpp"
"${EDE_SRC_DIR}/main.cpp"
)
if (WIN32)
add_executable(EDE WIN32 ${SOURCES} ${HEADERS})
else()
add_executable(EDE ${SOURCES} ${HEADERS})
endif()
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file utils.h
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EDE_UTILS_H_
#define EDE_UTILS_H_
// -----------------------------------------------------------------------
// Import Libraries
// TODO(Nghia Lam): Find a better way to organize this.
// -----------------------------------------------------------------------
#include <termios.h> // For termios, tcgetattr(), tcgetattr(), ECHO, TCSAFLUSH
#include <unistd.h> // For read(), STDIN_FILENO
#include <stdlib.h> // For atexit();
#include <stdio.h> // For printf(), vsnprint(), perror(), fopen(), getline(), FILE
#include <time.h> // For time_t
// -----------------------------------------------------------------------
// Structure and type definition
// -----------------------------------------------------------------------
struct EDE_EditorSyntax;
struct EDE_EditorRows {
int Size;
int RSize;
char* Chars;
char* Render;
unsigned char* HighLight;
};
struct EDE_EditorConfig {
int CursorX, CursorY;
int RowOffset;
int ColOffset;
int ScreenCols;
int ScreenRows;
int DisplayRows;
char* FileName;
bool IsDirty;
char StatusMsg[80];
time_t StatusTime;
EDE_EditorRows* Rows;
EDE_EditorSyntax* Syntax;
termios DefaultSettings; // Default configuration of terminal
};
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
void EDE_InitEditor(); // Init Editor values when startup
void EDE_InitSettings(); // Config the editor when startup
void EDE_ErrorHandler(const char* s); // Out the error information
EDE_EditorConfig& EDE(); // Get the global editor config
#endif // EDE_UTILS_H_
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file memory.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "memory.h"
#include "utils.h"
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
void EDE_FixedBufAppend(FixedBuffer *fb, const char *s, int len) {
if (len > fb->Size - fb->Index) {
EDE_ErrorHandler("EDE_FixedBufAppend");
return;
}
memcpy(&fb->Buf[fb->Index], s, len);
fb->Index += len;
}
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file memory.h
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EDE_MEMORY_H_
#define EDE_MEMORY_H_
#include <string.h> // For memcpy(), memset()
// -----------------------------------------------------------------------
// Type Definition & Structure
// -----------------------------------------------------------------------
struct FixedBuffer {
int Size;
int Index;
char *Buf;
FixedBuffer(int size) : Size(size), Index(0) {
Buf = new char[Size];
memset(Buf, 0, Size);
}
~FixedBuffer() { delete[] Buf; }
};
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
// Fixed Buffers
void EDE_FixedBufAppend(FixedBuffer *fb, const char *s, int len); // Append new elements to the buffer
#endif // EDE_MEMORY_H_
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file file_io.h
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EDE_FILE_IO_H_
#define EDE_FILE_IO_H_
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
char* EDE_EditorRowsToString(int *buffer_size); // Convert all rows to string for saving.
void EDE_EditorOpen(const char* file_name); // Open and reading a file from disk.
void EDE_EditorSave(); // Save the dirty file to the disk.
#endif // EDE_FILE_IO_H_
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file utils.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "utils.h"
#include "syntax.h"
#include "terminal.h"
// -----------------------------------------------------------------------
// Static Helpers
// -----------------------------------------------------------------------
static EDE_EditorConfig E; // Is this safe?
static void DisableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.DefaultSettings) == -1)
EDE_ErrorHandler("tcsetattr");
}
static void EnableRawMode() {
if (tcgetattr(STDIN_FILENO, &E.DefaultSettings) == -1)
EDE_ErrorHandler("tcgetattr");
atexit(DisableRawMode);
termios raw = E.DefaultSettings;
// NOTE(Nghia Lam): Input Flags
// - BRKINT turn off the break condition, which will send signal to the
// program, just like how Ctrl-C did.
// - IXON disable software flow control like Ctrl-S & Ctrl-Q in terminal
// mode. (Ctrl-S stop data being transmitted util you pressed Ctrl-Q).
// - ICRNL fix the Ctrl-M and Enter key to be overlap output 10 byte as
// Ctrl-J.
// - INPCK disable parity checking, which doesnt seem to support in
// modern terminal emulators.
// - ISTRIP make the 8th bits of each input to be stripped. This may
// be already turn off in some systems.
raw.c_iflag &= ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP);
// NOTE(Nghia Lam): Output Flags
// - OPOST turn off the post processing output.
raw.c_oflag &= ~(OPOST);
// NOTE(<NAME>): Set the input character size to be 8 bits per bytes.
// Some systems may already set this.
raw.c_cflag |= (CS8);
// NOTE(<NAME>): Local Flags
// - ECHO is a bitflag which allow us to print what we are typing to the
// terminal, which maybe useful for some cases, but not in a text editor,
// so we disable it here in the local flags.
// - ICANON is a flag that allow us to disable the canonical mode, this
// means that we will finally read input byte-by-byte instead of line-by-line
// (We can get the input immediately without pressing Enter).
// - ISIG is a flag which allow us to disable Ctrl-C and Ctrl-Z in
// terminal mode.
// - IEXTEN disable the Ctrl-V function in terminal where it waits for us
// to type another character and then send it literally.
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 0; // read() return as soon as possible if there is any input.
raw.c_cc[VTIME] = 1; // maximum of time to wait before read(), it is 100ms here.
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
EDE_ErrorHandler("tcsetattr");
}
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
void EDE_InitEditor() {
// TODO(<NAME>): Checking whether we are using GUI or Terminal mode here
E.CursorX = 0;
E.CursorY = 0;
E.RowOffset = 0;
E.ColOffset = 0;
E.DisplayRows = 0;
E.StatusTime = 0;
E.StatusMsg[0] = '\0';
E.IsDirty = false;
E.Rows = nullptr;
E.FileName = nullptr;
E.Syntax = nullptr;
if (EDE_TermGetSize(&E.ScreenCols, &E.ScreenRows) == -1)
EDE_ErrorHandler("EDE_TermGetSize");
E.ScreenRows -= 2; // For status bar + message bar
}
void EDE_InitSettings() {
EnableRawMode();
}
void EDE_ErrorHandler(const char* s) {
// Clear the screen when exit
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
// Output error and exit
perror(s);
exit(1);
}
EDE_EditorConfig& EDE() { return E; }
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file input.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "input.h"
#include "config.h"
#include "command.h"
#include "file_io.h"
#include "terminal.h"
#include <errno.h> // For errno, EAGAIN
#include <ctype.h> // For iscntrl()
// -----------------------------------------------------------------------
// Main APIs
// TODO(Nghia Lam): Change to Command system and mapping command.
// -----------------------------------------------------------------------
int EDE_ReadKey() {
char c = '\0';
int nread = 0;
while(!(nread = read(STDIN_FILENO, &c, 1))) {
if (nread == -1 && errno != EAGAIN)
EDE_ErrorHandler("read");
}
// Handle special command key
// ---
// NOTE(Nghia Lam): When ever we meet an escape sequence we will try
// to read two more byte to find which key is pressed.
if (c == '\x1b') {
char seq[3];
if (read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b';
if (read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b';
if (seq[0] == '[') {
if (seq[1] >= '0' && seq[1] <= '9') {
// NOTE(<NAME>):
// - Page-Up is represent as <Esc>[5~
// - Page-Down is represent as <Esc>[6~
if (read(STDIN_FILENO, &seq[2], 1) != 1) return '\x1b';
if (seq[2] == '~') {
switch (seq[1]) {
case '1': return KEY_HOME;
case '3': return KEY_DEL;
case '4': return KEY_END;
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
case '7': return KEY_HOME;
case '8': return KEY_END;
}
}
} else {
// NOTE(<NAME>): Since arrow key terminal will return as an escape sequence
// with '\x1b[' follow with A, B, C, D (depend on which arrow is pressed up,
// down, right or left).
switch(seq[1]) {
case 'A': return KEY_UP; // Up arrow key
case 'B': return KEY_DOWN; // Down arrow key
case 'C': return KEY_RIGHT; // Right arrow key
case 'D': return KEY_LEFT; // Left arrow key
case 'H': return KEY_HOME; // Home key
case 'F': return KEY_END; // End key
}
}
} else if (seq[0] == 'O') {
switch (seq[1]) {
case 'H': return KEY_HOME;
case 'F': return KEY_END;
}
}
return '\x1b';
} else {
return c;
}
}
// NOTE(<NAME>): Currently using vi-binding for this editor
void EDE_ProcessKeyPressed() {
static int quit_times = EDE_QUIT_TIME;
int c = EDE_ReadKey();
switch (c) {
// Quit: Ctrl-Q
// ---
case CTRL_KEY('q'): {
if (EDE().IsDirty && quit_times > 0) {
EDE_TermSetStatusMessage("Warning!! File has unsaved changes. "
"Press Ctrl-Q %d more times to quit.",
quit_times);
quit_times--;
return;
}
// Clear screen when exit
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
break;
}
// Primitives
// ---
case '\r': {
EDE_EditorInsertNewLine();
break;
}
// NOTE(<NAME>): Originally, the Ctrl-H combo would return the control code 8,
// which is similar to the backspace control code in some old terminal.
// -> We might dont want it to be like this.
case CTRL_KEY('h'):
case BACKSPACE:
case KEY_DEL: {
if (c == KEY_DEL) EDE_EditorMoveCursor(KEY_RIGHT);
EDE_EditorDeleteChar();
break;
}
case CTRL_KEY('l'):
case '\x1b': {
// TODO(<NAME>): Handle this key
break;
}
case CTRL_KEY('f'): {
EDE_EditorFind();
break;
}
// File I/O
// ---
case CTRL_KEY('s'): {
EDE_EditorSave();
break;
}
// Cursor Movement
// ---
case KEY_UP:
case KEY_DOWN:
case KEY_RIGHT:
case KEY_LEFT: {
EDE_EditorMoveCursor(c);
break;
}
case PAGE_UP:
case PAGE_DOWN: {
// Make PAGE_UP, PAGE_DOWN scrolling
if (c == PAGE_UP) {
EDE().CursorY = EDE().RowOffset;
} else if (c == PAGE_DOWN) {
EDE().CursorY = EDE().RowOffset + EDE().ScreenRows - 1;
if (EDE().CursorY > EDE().DisplayRows)
EDE().CursorY = EDE().DisplayRows;
}
int times = EDE().ScreenRows;
while (--times)
EDE_EditorMoveCursor(c == PAGE_UP ? KEY_UP : KEY_DOWN);
break;
}
case KEY_HOME: {
EDE().CursorX = 0;
break;
}
case KEY_END: {
if (EDE().CursorY < EDE().DisplayRows)
EDE().CursorX = EDE().Rows[EDE().CursorY].Size;
break;
}
// Input char
// ---
default: {
EDE_EditorInsertChar(c);
break;
}
}
quit_times = EDE_QUIT_TIME;
}
char* EDE_MessagePrompt(const char* prompt, void (*callback)(char*, int)) {
size_t buffer_size = 128;
char* buffer = new char[buffer_size];
size_t buffer_len = 0;
buffer[0] = '\0';
while(1) {
EDE_TermSetStatusMessage(prompt, buffer);
// TODO(<NAME>): Check whether we are using GUI mode or terminal mode.
EDE_TermRefreshScreen();
int c = EDE_ReadKey();
if (c == '\x1b') {
// Quit if pressed ESC
EDE_TermSetStatusMessage("");
if (callback) callback(buffer, c);
delete[] buffer;
return nullptr;
} else if (c == '\r') {
// Return if pressed Enter
if (buffer_len != 0) {
EDE_TermSetStatusMessage("");
if (callback) callback(buffer, c);
return buffer;
}
} else if (c == KEY_DEL || c == BACKSPACE || c == CTRL_KEY('h')) {
// Handle Delete Key
if (buffer_len != 0)
buffer[--buffer_len] = '\0';
} else if (!iscntrl(c) && c < 128) {
// Normal Input
if (buffer_len == buffer_size - 1) {
buffer_size *= 2;
buffer = (char*) realloc(buffer, buffer_size);
}
buffer[buffer_len++] = c;
buffer[buffer_len] = '\0';
}
if (callback) callback(buffer, c);
}
}
<file_sep>#!/bin/bash
# Author : <NAME>
# Copyright (c) <NAME>
/usr/local/bin/cmake --build build
echo "Finish !!"
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file command.h
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef EDE_COMMAND_H_
#define EDE_COMMAND_H_
#include "utils.h"
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
// Cursor Commands
// ---
void EDE_EditorMoveCursor(const int key); // Move the cursor in the screen
// Find Commands
// ---
void EDE_EditorFind(); // Find the character in the message prompt
// Edit Commands
// ---
void EDE_EditorDeleteChar(); // Delete the char at the position of cursor.
void EDE_EditorInsertChar(int c); // Insert the require char to the current row.
void EDE_EditorInsertNewLine(); // Insert the new line at the cursor position.
// Rows Low Level API
// TODO(Nghia Lam): Consider to make this private/static
// ---
void EDE_EditorFreeRow(EDE_EditorRows* row); // Cleanup the required row.
void EDE_EditorDeleteRow(int at); // Delete the entire row.
void EDE_EditorUpdateRow(EDE_EditorRows* row); // Update render status for the row
void EDE_EditorInsertRow(int at, const char* s, size_t len); // Insert line of text into specific position
void EDE_EditorRowDeleteChar(EDE_EditorRows* row, int at); // Delete character at a specific position in a row
void EDE_EditorRowInsertChar(EDE_EditorRows* row, int at, int c); // Insert character at a specific position in a row
void EDE_EditorRowAppendString(EDE_EditorRows* row, const char* s, size_t len); // Append a string to the end of a row.
#endif // EDE_COMMAND_H_
<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file main.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -----------------------------------------------------------------------
// NOTE(Nghia Lam): This program is currently follow the instruction of:
//
// https://viewsourcecode.org/snaptoken/kilo/
//
// The tutorial is implemented in C, but the goal is a fast, robust modern
// text editor which is written in C++17
// Here is a todo list:
// ---
// TODO(Nghia Lam): Walk through the tutorial of kilo.
// TODO(Nghia Lam): Add support for Windows
// TODO(Nghia Lam): Re-create it in C++17 with data oriented mindset.
// TODO(Nghia Lam): Support both terminal mode and graphical mode.
// TODO(Nghia Lam): Multiple file support
// -----------------------------------------------------------------------
// Feature tests macros for getline()
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
// -----------------------------------------------------------------------
// Import Libraries
// -----------------------------------------------------------------------
#include "utils.h"
#include "input.h"
#include "terminal.h"
#include "file_io.h"
// -----------------------------------------------------------------------
// Entry point
// -----------------------------------------------------------------------
int main(int argc, char* argv[]) {
EDE_InitSettings();
EDE_InitEditor();
if (argc >= 2)
EDE_EditorOpen(argv[1]);
EDE_TermSetStatusMessage("HELP: Ctrl-S to save | Ctrl-Q to quit | Ctrl-F to find !");
while (1) {
// TODO(<NAME>): Check whether we are using GUI mode or terminal mode.
EDE_TermRefreshScreen();
EDE_ProcessKeyPressed();
}
return 0;
}<file_sep>// =====================================================
// _______ _____ _______
// | ___| \| ___|
// | ___| -- | ___|
// |_______|_____/|_______|
// ---
// Ethan Development Editor
// =====================================================
// @file command.cpp
// @author <NAME> <<EMAIL>>
//
// @brief
//
// @license Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "command.h"
#include "utils.h"
#include "input.h"
#include "config.h"
#include "syntax.h"
#include <string.h> // For memmove()
// -----------------------------------------------------------------------
// Main APIs
// -----------------------------------------------------------------------
// Cursor Commands
// ---
void EDE_EditorMoveCursor(const int key) {
// Query the current row
EDE_EditorRows* row = (EDE().CursorY >= EDE().DisplayRows) ? nullptr : &EDE().Rows[EDE().CursorY];
switch(key) {
case KEY_UP: {
if (EDE().CursorY != 0)
--EDE().CursorY;
break;
}
case KEY_DOWN: {
if (EDE().CursorY < EDE().DisplayRows)
++EDE().CursorY;
break;
}
case KEY_LEFT: {
if (EDE().CursorX != 0) {
--EDE().CursorX;
} else if (EDE().CursorY > 0) {
// Move to the end of the previous line
--EDE().CursorY;
EDE().CursorX = EDE().Rows[EDE().CursorY].Size;
}
break;
}
case KEY_RIGHT: {
if (row && EDE().CursorX < row->Size) {
++EDE().CursorX;
} else if (row && EDE().CursorX == row->Size) {
// Move to the begining of the next line
++EDE().CursorY;
EDE().CursorX = 0;
}
break;
}
}
// Re-query the row for snapping cursor position
// - Only allow the cursor the position at the very end of texts
// in current line
row = (EDE().CursorY >= EDE().DisplayRows) ? nullptr : &EDE().Rows[EDE().CursorY];
int row_len = row ? row->Size : 0;
if (EDE().CursorX > row_len)
EDE().CursorX = row_len;
}
// Find Commands
// ---
static void EDE_EditorFindCallback(char* query, int key) {
static int last_match = -1;
static int direction = 1;
static int saved_hl_line;
static char* saved_hl = nullptr;
if (saved_hl) {
memcpy(EDE().Rows[saved_hl_line].HighLight,
saved_hl,
EDE().Rows[saved_hl_line].RSize);
delete[] saved_hl;
saved_hl = nullptr;
}
// NOTE(<NAME>): Support search forward and backward
switch(key) {
case '\r':
case '\x1b': {
last_match = -1;
direction = 1;
return;
}
case KEY_RIGHT:
case KEY_DOWN: {
direction = 1;
break;
}
case KEY_LEFT:
case KEY_UP: {
direction = -1;
break;
}
default: {
last_match = -1;
direction = 1;
break;
}
}
if (last_match == -1) direction = 1;
int current = last_match;
// TODO(<NAME>): This is not quite optimal for searching,
// maybe I should think of another idea to make this better.
for (int i = 0; i < EDE().DisplayRows; ++i) {
current += direction;
if (current == -1) current = EDE().DisplayRows - 1;
else if (current == EDE().DisplayRows) current = 0;
EDE_EditorRows* row = &EDE().Rows[current];
char* match = strstr(row->Render, query);
if (match) {
last_match = current;
EDE().CursorY = current;
EDE().CursorX = match - row->Render;
EDE().RowOffset = EDE().DisplayRows;
saved_hl_line = current;
saved_hl = new char[row->RSize];
memcpy(saved_hl, row->HighLight, row->RSize);
memset(&row->HighLight[match - row->Render], HL_MATCH, strlen(query));
break;
}
}
}
void EDE_EditorFind() {
int saved_cx = EDE().CursorX;
int saved_cy = EDE().CursorY;
int saved_coloff = EDE().ColOffset;
int saved_rowoff = EDE().RowOffset;
char* query = EDE_MessagePrompt("Search: %s (Use ESC | Arrows | Enter)",
EDE_EditorFindCallback);
if (query) {
delete[] query;
} else {
EDE().CursorX = saved_cx;
EDE().CursorY = saved_cy;
EDE().ColOffset = saved_coloff;
EDE().RowOffset = saved_rowoff;
}
}
// Edit Commands
// ---
void EDE_EditorDeleteChar() {
if (EDE().CursorY == EDE().DisplayRows) return;
if (EDE().CursorX == 0 && EDE().CursorY == 0) return;
EDE_EditorRows* row = &EDE().Rows[EDE().CursorY];
if (EDE().CursorX > 0) {
EDE_EditorRowDeleteChar(row, EDE().CursorX - 1);
--EDE().CursorX;
} else {
EDE().CursorX = EDE().Rows[EDE().CursorY - 1].Size;
EDE_EditorRowAppendString(&EDE().Rows[EDE().CursorY - 1], row->Chars, row->Size);
EDE_EditorDeleteRow(EDE().CursorY);
--EDE().CursorY;
}
}
void EDE_EditorInsertChar(int c) {
if (EDE().CursorY == EDE().DisplayRows)
EDE_EditorInsertRow(EDE().DisplayRows, "", 0);
EDE_EditorRowInsertChar(&EDE().Rows[EDE().CursorY], EDE().CursorX, c);
++EDE().CursorX;
}
void EDE_EditorInsertNewLine() {
if (EDE().CursorX == 0) {
EDE_EditorInsertRow(EDE().CursorY, "", 0);
} else {
EDE_EditorRows* row = &EDE().Rows[EDE().CursorY];
EDE_EditorInsertRow(EDE().CursorY + 1,
&row->Chars[EDE().CursorX],
row->Size - EDE().CursorX);
row = &EDE().Rows[EDE().CursorY];
row->Size = EDE().CursorX;
row->Chars[row->Size] = '\0';
EDE_EditorUpdateRow(row);
}
++EDE().CursorY;
EDE().CursorX = 0;
}
// Row Low Level API
// ---
void EDE_EditorRowAppendString(EDE_EditorRows* row, const char* s, size_t len) {
row->Chars = (char*) realloc(row->Chars, row->Size + len + 1);
memcpy(&row->Chars[row->Size], s, len);
row->Size += len;
row->Chars[row->Size] = '\0';
EDE_EditorUpdateRow(row);
EDE().IsDirty = true;
}
void EDE_EditorRowInsertChar(EDE_EditorRows* row, int at, int c) {
// TODO(<NAME>): Again, this method reallocate the memory every input...
// -> Is there any better way to solve this?
if (at < 0 || at > row->Size) at = row->Size;
row->Chars = (char*) realloc(row->Chars, row->Size + 2);
memmove(&row->Chars[at + 1], &row->Chars[at], row->Size - at + 1);
++row->Size;
row->Chars[at] = c;
EDE_EditorUpdateRow(row);
EDE().IsDirty = true;
}
void EDE_EditorRowDeleteChar(EDE_EditorRows* row, int at) {
if (at < 0 || at >= row->Size) return;
memmove(&row->Chars[at], &row->Chars[at + 1], row->Size - at);
--row->Size;
EDE_EditorUpdateRow(row);
EDE().IsDirty = true;
}
void EDE_EditorUpdateRow(EDE_EditorRows* row) {
int tabs = 0;
for (int i = 0; i < row->Size; ++i)
if (row->Chars[i] == '\t') ++tabs;
// Cleanup previouse row
delete[] row->Render;
row->Render = new char[row->Size + tabs * EDE_TAB_WIDTH + 1];
int idx = 0;
for (int i = 0; i < row->Size; ++i) {
if (row->Chars[i] == '\t') {
// NOTE(<NAME>): Currently we only support render space for tabs
row->Render[idx++] = ' ';
while (idx % EDE_TAB_WIDTH != 0)
row->Render[idx++] = ' ';
} else {
row->Render[idx++] = row->Chars[i];
}
}
row->Render[idx] = '\0';
row->RSize = idx;
EDE_EditorUpdateSyntax(row);
}
void EDE_EditorInsertRow(int at, const char* s, size_t len) {
if (at < 0 || at > EDE().DisplayRows) return;
// TODO(<NAME>am): This method reallocate each line of file, which may cause some
// performance issue -> Need more tests and optimization ?
EDE().Rows = (EDE_EditorRows*) realloc(EDE().Rows,
sizeof(EDE_EditorRows) * (EDE().DisplayRows + 1));
memmove(&EDE().Rows[at + 1],
&EDE().Rows[at],
sizeof(EDE_EditorRows) * (EDE().DisplayRows - at));
EDE().Rows[at].Size = len;
EDE().Rows[at].Chars = new char[len + 1];
memcpy(EDE().Rows[at].Chars, s, len);
EDE().Rows[at].Chars[len] = '\0';
EDE().Rows[at].RSize = 0;
EDE().Rows[at].Render = nullptr;
EDE().Rows[at].HighLight = nullptr;
EDE_EditorUpdateRow(&EDE().Rows[at]);
++EDE().DisplayRows;
EDE().IsDirty = true;
}
void EDE_EditorDeleteRow(int at) {
if (EDE().CursorY == EDE().DisplayRows)
return;
EDE_EditorFreeRow(&EDE().Rows[at]);
memmove(&EDE().Rows[at],
&EDE().Rows[at + 1],
sizeof(EDE_EditorRows) * (EDE().DisplayRows - at - 1));
--EDE().DisplayRows;
EDE().IsDirty = true;
}
void EDE_EditorFreeRow(EDE_EditorRows* row) {
delete[] row->HighLight;
delete[] row->Render;
delete[] row->Chars;
}
<file_sep>#!/bin/bash
# Author : <NAME>
# Copyright (c) <NAME>
rm -rf bin
rm -rf build
rm -rf compile_command.json
/usr/local/bin/cmake -G Xcode -H. -B build
| 34464e6ea728e8f373faaa594e5a2fb9dae25da1 | [
"CMake",
"Markdown",
"C",
"C++",
"Shell"
] | 19 | C++ | zZnghialamZz/EDE | 54e3edc3488a40076418e4f023d5b206b6746233 | 188ba4a119e64ae7430e781c58442defa94cac16 |
refs/heads/master | <repo_name>janghaeun/windows_programming<file_sep>/memo/memo/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace memo
{
public partial class FormNotePad : Form
{
private bool changed = false;
public FormNotePad()
{
InitializeComponent();
}
private void textBoxNote_TextChanged(object sender, EventArgs e)
{
changed = true;
}
private void saveTextToFile()
{
if(this.Text=="제목 없음")
{
if(saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
string str = saveFileDialog1.FileName;
var sw = new StreamWriter(str,false);
var text = this.textBoxNote.Text;
sw.Write(text);
sw.Flush();
sw.Close();
var f = new FileInfo(str);
this.Text = f.Name;
}
}
else
{
string str = saveFileDialog1.FileName;
var sw = new StreamWriter(str, false);
var text = this.textBoxNote.Text;
sw.Write(text);
sw.Flush();
sw.Close();
var f = new FileInfo(str);
this.Text = f.Name;
}
}
private void 새로만들기NToolStripMenuItem_Click(object sender, EventArgs e)
{
if(this.changed != false)
{
var msg = MessageBox.Show("변경 내용을 제목 없음으로 저장하시겠습니까?", "메모장", MessageBoxButtons.YesNoCancel);
if (msg == DialogResult.Yes)
{
saveTextToFile();
this.Text = "제목 없음";
this.textBoxNote.ResetText();
this.changed = false;
}
else if(msg == DialogResult.No)
{
this.Text = "제목 없음";
this.textBoxNote.ResetText();
this.changed = false;
}
else if(msg == DialogResult.Cancel)
{
return;
}
}
else
{
this.textBoxNote.ResetText();
this.Text = "제목 없음";
this.changed = false;
}
}
private void 열기OToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
string str = openFileDialog1.FileName;
var sr = new StreamReader(str);
this.textBoxNote.Text = sr.ReadToEnd();
sr.Close();
var f = new FileInfo(str);
this.Text = f.Name;
this.changed = false;
}
}
private void 저장SToolStripMenuItem_Click(object sender, EventArgs e)
{
saveTextToFile();
this.changed = false;
}
private void 다른이름으로저장AToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
string str = saveFileDialog1.FileName;
var sw = new StreamWriter(str, false);
var text = this.textBoxNote.Text;
sw.Write(text);
sw.Flush();
sw.Close();
var f = new FileInfo(str);
this.Text = f.Name;
this.changed = false;
}
}
private void FormNotePad_FormClosing(object sender, FormClosingEventArgs e)
{
if(this.changed != false)
{
e.Cancel = true;
var msg = MessageBox.Show("변경 내용을 제목 없음으로 저장하시겠습니까?", "메모장", MessageBoxButtons.YesNoCancel);
if(msg == DialogResult.Yes)
{
saveTextToFile();
}
else if(msg == DialogResult.No)
{
this.Dispose();
}else if(msg == DialogResult.Cancel)
{
return;
}
}
}
private void 끝내기XToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void 실행취소UToolStripMenuItem_Click(object sender, EventArgs e)
{
this.textBoxNote.Undo();
}
private void 잘라내기XToolStripMenuItem_Click(object sender, EventArgs e)
{
this.textBoxNote.Cut();
}
private void 복사CToolStripMenuItem_Click(object sender, EventArgs e)
{
this.textBoxNote.Copy();
}
private void 붙여넣기VToolStripMenuItem_Click(object sender, EventArgs e)
{
this.textBoxNote.Paste();
}
private void 삭제DToolStripMenuItem_Click(object sender, EventArgs e)
{
this.textBoxNote.Text = "";
}
private void 모두선택AToolStripMenuItem_Click(object sender, EventArgs e)
{
this.textBoxNote.SelectAll();
}
private void 시간날짜TToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void 자동줄바꿈WToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void 글꼴FToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private string strFind;
private FormFind formFind;
private void FormFindNextButton_Click(object sender, EventArgs e)
{
var updown = -1;
var str = this.textBoxNote.Text;
var findword = formFind.textBoxWord.Text;
if(formFind.checkBoxCap.Checked == false) {
str = str.ToUpper();
findword = findword.ToUpper();
}
if(formFind.radioButtonUp.Checked == true)
{
if(textBoxNote.SelectionStart != 0)
{
updown = str.LastIndexOf(findword,textBoxNote.SelectionStart-1);
}
}
else
{
updown = str.IndexOf(findword, textBoxNote.SelectionStart + textBoxNote.SelectionLength);
}
if(updown == -1)
{
MessageBox.Show("'" + findword + "'를 찾을 수 없습니다.", "메모장", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
this.textBoxNote.Select(updown,findword.Length);
this.textBoxNote.Focus();
this.textBoxNote.ScrollToCaret();
}
}
private void 찾기FToolStripMenuItem_Click(object sender, EventArgs e)
{
if(!(formFind == null || formFind.Visible == false))
{
formFind.Focus();
return;
}
formFind = new FormFind();
if (textBoxNote.SelectionLength == 0)
formFind.textBoxWord.Text = strFind;
else
{
formFind.textBoxWord.Text = textBoxNote.SelectedText;
}
formFind.buttonNext.Click += new System.EventHandler(FormFindNextButton_Click);
formFind.Show();
}
}
}
| 13baa7a8d54b0d1ba8ca0d1d9fc2dc24c8d1b67a | [
"C#"
] | 1 | C# | janghaeun/windows_programming | e739d77c3c3b0c9c257e62250efff9cdb652022f | fe8bbd8164bb8a0c6e56ec2163533ea8ee9096f9 |
refs/heads/master | <repo_name>ysawiris/orayeb-app<file_sep>/App.js
import React, { Component } from "react";
import { StyleSheet, View, Platform } from "react-native";
import TimedSlideshow from "react-native-timed-slideshow";
// import Slideshow from "react-native-slideshow";
export default class App extends Component {
render() {
const items = [
{
uri: "https://orayeb.herokuapp.com/documents/0205mitsu.jpg",
title: "<NAME>",
text: "American Plaza",
fullWidth: false,
},
{
uri:
"https://images.unsplash.com/photo-1540648639573-8c848de23f0a?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mjd8fHN1c2hpfGVufDB8fDB8&auto=format&fit=crop&w=800&q=60",
title: "<NAME>",
text: "Captiol",
duration: 5000,
fullWidth: false,
},
{
uri:
"https://images.unsplash.com/photo-1534604973900-c43ab4c2e0ab?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTh8fHN1c2hpfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60",
title: "<NAME>",
text: "Galleria",
fullWidth: false,
},
];
return <TimedSlideshow items={items} />;
}
}
// export default class App extends Component {
// constructor() {
// super();
// this.state = {
// position: 1,
// interval: null,
// dataSource: [
// {
// title: "Title 1",
// caption: "Caption 1",
// url: "http://127.0.0.1:8000/media/documents/0205mitsu.jpg",
// },
// {
// title: "Title 2",
// caption: "Caption 2",
// url: "http://127.0.0.1:8000/media/documents/0205mitsu.jpg",
// },
// {
// title: "Title 3",
// caption: "Caption 3",
// url:
// "https://reactnativecode.000webhostapp.com/images/flowers-background-butterflies-beautiful-87452.jpeghttp://127.0.0.1:8000/media/documents/0205mitsu.jpg",
// },
// ],
// };
// }
// componentWillMount() {
// this.setState({
// interval: setInterval(() => {
// this.setState({
// position:
// this.state.position === this.state.dataSource.length
// ? 0
// : this.state.position + 1,
// });
// }, 5000),
// });
// }
// componentWillUnmount() {
// clearInterval(this.state.interval);
// }
// render() {
// return (
// <View style={styles.MainContainer}>
// <Slideshow
// dataSource={this.state.dataSource}
// position={this.state.position}
// onPositionChanged={(position) => this.setState({ position })}
// />
// </View>
// );
// }
// }
// const styles = StyleSheet.create({
// MainContainer: {
// flex: 1,
// alignItems: "center",
// paddingTop: Platform.OS === "ios" ? 20 : 0,
// backgroundColor: "#FFF8E1",
// },
// });
| 5ecc454842918362083504e75c5a34fafb7b87a1 | [
"JavaScript"
] | 1 | JavaScript | ysawiris/orayeb-app | 91b5da7418ad2dec6d76ec2d457f993e1fafa74a | 59e14c9653992f0246fab575859faa59f8fc4735 |
refs/heads/master | <file_sep>using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
using SpaceOrigin.Planets;
using DigitalRubyShared;
namespace SpaceOrigin.AR
{
public class ARPlacementController : MonoBehaviour
{
public ARRaycastManager raycastManager;
public GameObject placementHintObject;
public LayerMask placementHintLayer;
public Camera arCamera;
public ARObject arObject;
private TapGestureRecognizer tapGesture;
private List<ARRaycastHit> _hits = new List<ARRaycastHit>();
private Vector2 _screenCenter;
void Start()
{
_screenCenter = new Vector2((Screen.width / 2), (Screen.height / 2));
CreateTapGesture();
placementHintObject.SetActive(false);
}
void Update()
{
if (raycastManager.Raycast(_screenCenter, _hits, TrackableType.PlaneWithinPolygon))
{
var hitPose = _hits[0].pose;
placementHintObject.SetActive(true);
placementHintObject.transform.position = hitPose.position;
}
else
{
placementHintObject.SetActive(false);
}
}
private void CreateTapGesture()
{
tapGesture = new TapGestureRecognizer();
tapGesture.StateUpdated += TapGestureCallback;
FingersScript.Instance.AddGesture(tapGesture);
}
private void TapGestureCallback(GestureRecognizer gesture)
{
if (gesture.State == GestureRecognizerState.Ended)
{
OnTapped();
}
}
private void OnTapped( )
{
Ray ray = arCamera.ScreenPointToRay(_screenCenter);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100, placementHintLayer))
{
arObject.SetObjectActive(true);
arObject.Move(placementHintObject.transform.position +Vector3.up*1.1f);
}
#if UNITY_EDITOR
arObject.SetObjectActive(true);
arObject.Move(placementHintObject.transform.position + Vector3.up * 1.1f);
#endif
}
}
}
<file_sep># PlanetEarth-AR-Unity
Augmented reality app, lets you interact with the planet earth<br/>
<p align="center">
<img src= https://github.com/SabinMG/PlanetEarth-AR-Unity/blob/master/AppScreen.jpg width="550" title="Gameplay image">
</p>
## App controls
Scan the floor and tap on the placement white hint image to place the object(earth model)<br/>
Rotate - simply drag the object<br/>
Scale - do a pinch action
## About code
Uses Unity AR foundation package to support both ios and android.
https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@3.0/manual/index.html
## Assets used
gesture control - https://assetstore.unity.com/packages/tools/input-management/fingers-lite-free-finger-touch-gestures-for-unity-64276
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SpaceOrigin.AR;
namespace SpaceOrigin.Planets
{
public class Planet : ARObject
{
protected override void Start()
{
base.Start();
}
protected override void Update()
{
base.Update();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SpaceOrigin.Planets
{
[CreateAssetMenu(fileName = "CityDatas", menuName = "ScriptableObjects/CityDataList", order = 1)]
public class CityDatasScriptableObject : ScriptableObject
{
public List<CityData> cityDataList;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SpaceOrigin.Utilities
{
public class HideOnAwake : MonoBehaviour
{
public bool hide = true;
void Awake()
{
gameObject.SetActive(!hide);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SpaceOrigin.Planets
{
[System.Serializable]
public struct CityData
{
public string cityName;
public float latitude;
public float longitude;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SpaceOrigin.Planets;
using TMPro;
namespace SpaceOrigin.Planets
{
public class CityDataVisualizer : MonoBehaviour
{
public TextMeshPro cityNameText;
private CityData _cityInfo;
private bool _initalizedData = false;
private Earth _planetEarth;
void Start()
{
}
void Update() // TOD0): update ony if therer is a update on postion and roation on the planetEarth,
{
if (_initalizedData)
{
Quaternion defaultRotaion = (Quaternion.AngleAxis(_cityInfo.longitude, -_planetEarth.transform.up) * Quaternion.AngleAxis(_cityInfo.latitude, -_planetEarth.transform.right));
transform.position = _planetEarth.transform.position + ((defaultRotaion * _planetEarth.transform.rotation) * new Vector3(0, 0, _planetEarth.Radius*1.02f));
}
}
public void SetCityData(CityData cityData, Earth planetEarth)
{
_planetEarth = planetEarth;
_cityInfo = cityData;
cityNameText.text = _cityInfo.cityName;
_initalizedData = true;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IScalable
{
void Scale(float deltaScale);
}
<file_sep>using UnityEngine;
namespace SpaceOrigin.Utilities
{
public class CameraFacingBillboard : MonoBehaviour
{
public Camera mainCamera { set; private get; }
void LateUpdate()
{
if (mainCamera != null) //_camera = Camera.main; // caching main camera
transform.LookAt(transform.position + mainCamera.transform.rotation * Vector3.forward, mainCamera.transform.rotation * Vector3.up);
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SpaceOrigin.ObjectPool;
using SpaceOrigin.Utilities;
namespace SpaceOrigin.Planets
{
public class Earth : Planet
{
public CityDatasScriptableObject cityDatasSO;
public string cityDataVisPrefabname = "CityDataVisualizer";
public float minScale = .3f;
public float maxScale = 3.0f;
private bool _initializedPlanet = false ;
private float _radius = .5f;
public float Radius { get => _radius; set => _radius = value; }
protected override void Start()
{
base.Start();
}
protected override void Update()
{
base.Update();
}
public override void Move(Vector3 location)
{
base.Move(location);
if (!_initializedPlanet)
{
CreateCityDataVisulizers();
_initializedPlanet = true;
}
}
public override void Scale(float scaleDelta)
{
Vector3 localScale = transform.localScale;
localScale *= scaleDelta;
float x = Mathf.Clamp(localScale.x, minScale, maxScale);
_radius = x/2.0f;
transform.localScale = new Vector3(x,x,x);
}
private void CreateCityDataVisulizers()
{
for (int i = 0; i < cityDatasSO.cityDataList.Count; i++)
{
CityData cityData = cityDatasSO.cityDataList[i];
GameObject cityDataVisObj = PoolManager.Instance.GetObjectFromPool(cityDataVisPrefabname);
CityDataVisualizer cityDataVisualizerComp = cityDataVisObj.GetComponent<CityDataVisualizer>();
cityDataVisObj.GetComponent<CameraFacingBillboard>().mainCamera = arCamera;
cityDataVisualizerComp.SetCityData(cityData, this);
cityDataVisObj.SetActive(transform);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SpaceOrigin.AR
{
public class ARObject : MonoBehaviour,IMovable,IRotatable,IScalable
{
public Camera arCamera;
private LayerMask _arObjectLayer;
protected virtual void Start()
{
_arObjectLayer |= (1 << gameObject.layer);
}
protected virtual void Update()
{
}
public virtual void Move(Vector3 position)
{
transform.position = position;
}
public virtual void Rotate(float deltaRotation)
{
transform.Rotate(0, deltaRotation, 0); // for now only y axis
}
public virtual void Scale(float scaleDelta)
{
transform.localScale *= scaleDelta;
}
public void SetObjectActive(bool active)
{
gameObject.SetActive(active);
}
public bool IsObjectInFrontTouch(Vector3 touchInput)
{
Ray ray = arCamera.ScreenPointToRay(touchInput);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100, _arObjectLayer))
{
return true;
}
return false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DigitalRubyShared;
namespace SpaceOrigin.AR
{
public class ManipulationHandler : MonoBehaviour
{
public float gerstureRotationSpeed = 2.0f;
public ARObject manipulationTarget;
private PanGestureRecognizer panGesture;
private ScaleGestureRecognizer scaleGesture;
void Start()
{
CreatePanGesture();
CreateScaleGesture();
}
private void CreatePanGesture()
{
panGesture = new PanGestureRecognizer();
panGesture.MinimumNumberOfTouchesToTrack = 1;
panGesture.StateUpdated += PanGestureCallback;
FingersScript.Instance.AddGesture(panGesture);
}
private void CreateScaleGesture()
{
scaleGesture = new ScaleGestureRecognizer();
scaleGesture.StateUpdated += ScaleGestureCallback;
FingersScript.Instance.AddGesture(scaleGesture);
}
private void PanGestureCallback(GestureRecognizer gesture)
{
if (gesture.State == GestureRecognizerState.Executing)
{
float deltaX = (panGesture.DeltaX / 25.0f)* gerstureRotationSpeed;
if(manipulationTarget.IsObjectInFrontTouch(new Vector3(gesture.FocusX, gesture.FocusY,0))) manipulationTarget.Rotate(-deltaX);
}
}
private void ScaleGestureCallback(GestureRecognizer gesture)
{
if (gesture.State == GestureRecognizerState.Executing)
{
if (manipulationTarget.IsObjectInFrontTouch(new Vector3(gesture.FocusX, gesture.FocusY, 0))) manipulationTarget.Scale(scaleGesture.ScaleMultiplier);
}
}
}
}
| 2fa57dbede76d6194da64ac8cbc15d32cf64067b | [
"Markdown",
"C#"
] | 12 | C# | SabinMG/PlanetEarth-AR-Unity | 46c9af3d7fba28c5f8c7a96ac566b401e9d145b5 | 01da30e510216f418340473085c5e602d3641e78 |
refs/heads/master | <repo_name>Tinkerforge/tf-wireshark-dissector<file_sep>/packet-tfp.c
/* packet-tfp.c
* Routines for Tinkerforge protocol packet disassembly
* By <NAME> <<EMAIL>>
* Copyright 2013 <NAME>
*
* $Id$
*
* Wireshark - Network traffic analyzer
* By <NAME> <<EMAIL>>
* Copyright 1998 <NAME>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <glib.h>
#include <epan/packet.h>
#include <epan/dissectors/packet-usb.h>
/* defines */
#define tfp_PORT 4223
#define tfp_USB_VENDOR_ID 0x16D0
#define tfp_USB_PRODUCT_ID 0x063D
#define BASE58_MAX_STR_SIZE 13
/* variables for creating the tree */
static gint proto_tfp = -1;
static gint ett_tfp = -1;
/* header field variables */
static gint hf_tfp_uid = -1;
static gint hf_tfp_uid_numeric = -1;
static gint hf_tfp_len = -1;
static gint hf_tfp_fid = -1;
static gint hf_tfp_seq = -1;
static gint hf_tfp_r = -1;
static gint hf_tfp_a = -1;
static gint hf_tfp_oo = -1;
static gint hf_tfp_e = -1;
static gint hf_tfp_future_use = -1;
static gint hf_tfp_payload = -1;
/* bit and byte offsets for dissection */
static const gint byte_offset_len = 4;
static const gint byte_offset_fid = 5;
static const gint byte_count_tfp_uid = 4;
static const gint byte_count_tfp_len = 1;
static const gint byte_count_tfp_fid = 1;
static const gint byte_count_tfp_flags = 2;
static const gint bit_count_tfp_seq = 4;
static const gint bit_count_tfp_r = 1;
static const gint bit_count_tfp_a = 1;
static const gint bit_count_tfp_oo = 2;
static const gint bit_count_tfp_e = 2;
static const gint bit_count_tfp_future_use = 6;
/* base58 encoding variable */
static const char BASE58_ALPHABET[] =
"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
/* function for encoding a number to base58 string */
static void
base58_encode(guint32 value, char *str) {
guint32 mod;
gint i = 0;
gint k;
gchar reverse_str[BASE58_MAX_STR_SIZE] = {'\0'};
while (value >= 58) {
mod = value % 58;
reverse_str[i] = BASE58_ALPHABET[mod];
value = value / 58;
++i;
}
reverse_str[i] = BASE58_ALPHABET[value];
for (k = 0; k <= i; k++) {
str[k] = reverse_str[i - k];
}
for (; k < BASE58_MAX_STR_SIZE; k++) {
str[k] = '\0';
}
}
/* common dissector function for dissecting TFP payloads */
static void
dissect_tfp_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) {
gint byte_offset = 0;
gint bit_offset = 48;
guint8 hv_tfp_len;
guint8 hv_tfp_fid;
guint8 hv_tfp_seq;
gchar tfp_uid_string[BASE58_MAX_STR_SIZE];
base58_encode(tvb_get_letohl(tvb, 0), &tfp_uid_string[0]);
hv_tfp_len = tvb_get_guint8(tvb, byte_offset_len);
hv_tfp_fid = tvb_get_guint8(tvb, byte_offset_fid);
hv_tfp_seq = tvb_get_bits8(tvb, bit_offset, bit_count_tfp_seq);
col_add_fstr(pinfo->cinfo, COL_INFO,
"UID: %s, Len: %d, FID: %d, Seq: %d",
&tfp_uid_string[0], hv_tfp_len, hv_tfp_fid, hv_tfp_seq);
/* call for details */
if (tree) {
proto_tree *tfp_tree;
proto_item *ti;
ti = proto_tree_add_protocol_format(tree, proto_tfp, tvb, 0, -1,
"Tinkerforge Protocol, UID: %s, Len: %d, FID: %d, Seq: %d",
&tfp_uid_string[0], hv_tfp_len, hv_tfp_fid, hv_tfp_seq);
tfp_tree = proto_item_add_subtree(ti, ett_tfp);
/* Use ...string_format_value() so we can show the complete generated string but specify */
/* the field length as being just the 4 bytes from which the string is generated. */
ti = proto_tree_add_string_format_value(tfp_tree,
hf_tfp_uid,
tvb, byte_offset, byte_count_tfp_uid,
&tfp_uid_string[0], "%s", &tfp_uid_string[0]);
PROTO_ITEM_SET_GENERATED(ti);
proto_tree_add_item(tfp_tree,
hf_tfp_uid_numeric,
tvb,
byte_offset,
byte_count_tfp_uid,
ENC_LITTLE_ENDIAN);
byte_offset += byte_count_tfp_uid;
proto_tree_add_item(tfp_tree,
hf_tfp_len,
tvb,
byte_offset,
byte_count_tfp_len,
ENC_LITTLE_ENDIAN);
byte_offset += byte_count_tfp_len;
proto_tree_add_item(tfp_tree,
hf_tfp_fid,
tvb,
byte_offset,
byte_count_tfp_fid,
ENC_LITTLE_ENDIAN);
byte_offset += byte_count_tfp_fid;
proto_tree_add_bits_item(tfp_tree,
hf_tfp_seq,
tvb,
bit_offset,
bit_count_tfp_seq,
ENC_LITTLE_ENDIAN);
bit_offset += bit_count_tfp_seq;
proto_tree_add_bits_item(tfp_tree,
hf_tfp_r,
tvb,
bit_offset,
bit_count_tfp_r,
ENC_LITTLE_ENDIAN);
bit_offset += bit_count_tfp_r;
proto_tree_add_bits_item(tfp_tree,
hf_tfp_a,
tvb,
bit_offset,
bit_count_tfp_a,
ENC_LITTLE_ENDIAN);
bit_offset += bit_count_tfp_a;
proto_tree_add_bits_item(tfp_tree,
hf_tfp_oo,
tvb,
bit_offset,
bit_count_tfp_oo,
ENC_LITTLE_ENDIAN);
bit_offset += bit_count_tfp_oo;
proto_tree_add_bits_item(tfp_tree,
hf_tfp_e,
tvb,
bit_offset,
bit_count_tfp_e,
ENC_LITTLE_ENDIAN);
bit_offset += bit_count_tfp_e;
proto_tree_add_bits_item(tfp_tree,
hf_tfp_future_use,
tvb,
bit_offset,
bit_count_tfp_future_use,
ENC_LITTLE_ENDIAN);
bit_offset += bit_count_tfp_future_use;
if ((tvb_reported_length(tvb)) > 8) {
byte_offset += byte_count_tfp_flags;
proto_tree_add_item(tfp_tree,
hf_tfp_payload,
tvb,
byte_offset,
-1,
ENC_NA);
}
}
}
/* dissector function for dissecting TCP payloads */
static void
dissect_tfp_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
col_set_str(pinfo->cinfo, COL_PROTOCOL, "TFP over TCP");
col_clear(pinfo->cinfo, COL_INFO);
dissect_tfp_common(tvb, pinfo, tree);
}
/* dissector function for dissecting USB payloads */
static void
dissect_tfp_usb(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
usb_conv_info_t *usb_conv_info;
usb_conv_info = (usb_conv_info_t *)pinfo->usb_conv_info;
if (usb_conv_info->deviceVendor == tfp_USB_VENDOR_ID) {
col_set_str(pinfo->cinfo, COL_PROTOCOL, "TFP over USB");
if (usb_conv_info->deviceProduct == tfp_USB_PRODUCT_ID) {
col_clear(pinfo->cinfo, COL_INFO);
dissect_tfp_common(tvb, pinfo, tree);
}
else {
/* ToDo? Display "Unknown Product" ?? */
}
return;
}
else {
return; /* Not tfp_USB_VENDOR_ID */
}
}
/* protocol register function */
void
proto_register_tfp(void)
{
/* defining header formats */
static hf_register_info hf_tfp[] = {
{ &hf_tfp_uid,
{ "UID (String)",
"tfp.uid",
FT_STRINGZ,
BASE_NONE,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_uid_numeric,
{ "UID (Numeric)",
"tfp.uid_numeric",
FT_UINT32,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_len,
{ "Length",
"tfp.len",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_fid,
{ "Function ID",
"tfp.fid",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_seq,
{ "Sequence Number",
"tfp.seq",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_r,
{ "Response Expected",
"tfp.r",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_a,
{ "Authentication",
"tfp.a",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_oo,
{ "Other Options",
"tfp.oo",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_e,
{ "Error Code",
"tfp.e",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_future_use,
{ "Future Use",
"tfp.future_use",
FT_UINT8,
BASE_DEC,
NULL,
0x0,
NULL,
HFILL
}
},
{ &hf_tfp_payload,
{ "Payload",
"tfp.payload",
FT_BYTES,
BASE_NONE,
NULL,
0x0,
NULL,
HFILL
}
}
};
/* setup protocol subtree array */
static gint *ett[] = {
&ett_tfp
};
/* defining the protocol and its names */
proto_tfp = proto_register_protocol (
"Tinkerforge Protocol",
"TFP",
"tfp"
);
proto_register_field_array(proto_tfp, hf_tfp, array_length(hf_tfp));
proto_register_subtree_array(ett, array_length(ett));
}
/* handoff function */
void
proto_reg_handoff_tfp(void) {
static dissector_handle_t
tfp_handle_tcp,
tfp_handle_usb;
tfp_handle_tcp = create_dissector_handle(dissect_tfp_tcp, proto_tfp);
tfp_handle_usb = create_dissector_handle(dissect_tfp_usb, proto_tfp);
dissector_add_uint("tcp.port", tfp_PORT, tfp_handle_tcp);
dissector_add_uint("usb.bulk", IF_CLASS_VENDOR_SPECIFIC, tfp_handle_usb);
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
<file_sep>/README.rst
Tinkerforge Wireshark Dissector
===============================
This repository contains a Wireshark dissector for the Tinkerforge
USB and TCP/IP protocol. Find more information `here <http://www.tinkerforge.com/en/doc/Low_Level_Protocols/TCPIP.html>`__.
Installation
------------
This dissector `got included <https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=9324>`__
into the official Wireshark `codebase <http://anonsvn.wireshark.org/viewvc/trunk/epan/dissectors/packet-tfp.c>`__
and will be available on the next release of Wireshark (current version is
1.10.2) as a built-in dissector. For older versions one can add and use this
dissector as a built-in or plugin dissector by following the Wireshark
`documentation <http://www.wireshark.org/docs/wsdg_html_chunked/ChDissectAdd.html>`__.
| 23e57d493df7d3b81e4aed780d7b9de63f797090 | [
"C",
"reStructuredText"
] | 2 | C | Tinkerforge/tf-wireshark-dissector | 18d25e5afdb61965b444d70a9af8b638dc108af1 | bb38c1ec152937174702f564bc5aa1bcb3801812 |
refs/heads/master | <repo_name>EmmanuelSantiago/Repaso_Clases_Objetos_call_aplly_bid_22_02_2021<file_sep>/main.js
const calculadora = function(){
let valors = Math.max(this.primer_v, this.segundo_v, this.tercer_v, this.cuarto_v)
if (valors >= 5){
let suma = this.primer_v + this.segundo_v + this.tercer_v + this.cuarto_v
let resta = this.primer_v - this.segundo_v - this.tercer_v - this.cuarto_v
let multi = this.primer_v * this.segundo_v * this.tercer_v * this.cuarto_v
let divi = valors/4
return (` El numero mayor es ${valors}\n la suma es ${suma}\n la resta es ${resta}\n la multiplicacion es ${multi}\n la division es ${divi}`)
}else{
return (` El numero mayor es ${valors}`)
}
}
const data = new Object ({
primer_v : 25,
segundo_v : 3,
tercer_v : 2,
cuarto_v : 1,
});
console.log(calculadora.call(data)); | d7f6dbad8ff84da44ef9f54d67746036f6a5c510 | [
"JavaScript"
] | 1 | JavaScript | EmmanuelSantiago/Repaso_Clases_Objetos_call_aplly_bid_22_02_2021 | 4dfa3dd770d9198b1d7bd1214031e895b7f491a8 | b8331b9984b74705aeb24c933025ab65742f7e69 |
refs/heads/master | <file_sep>import { dev } from "https://cdn.jsdelivr.net/gh/learnpoint/piko@0.9.6/mod.js";
dev(); | b3329f39eec51695a87402729897837aa8c73b7e | [
"JavaScript"
] | 1 | JavaScript | Dhanfia/dhanfia-site | 1b6bb9eb94bf2fc121e1524c56abbf3db2a0f7f8 | cde00d05e9a67340915b4995caa27853db05fbf4 |
refs/heads/master | <repo_name>BacchusPlateau/SpaceMan3D<file_sep>/SuperSpaceman3D/GameViewController.swift
//
// GameViewController.swift
// SuperSpaceman3D
//
// Created by <NAME> on 5/27/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
var mainScene : SCNScene!
var spotLight : SCNNode!
override func viewDidLoad() {
super.viewDidLoad()
mainScene = createMainScene()
createMainCamera()
setupLighting(scene: mainScene)
mainScene!.rootNode.addChildNode(createFloorNode())
mainScene!.rootNode.addChildNode(Collectable.pyramidNode())
mainScene!.rootNode.addChildNode(Collectable.sphereNode())
mainScene!.rootNode.addChildNode(Collectable.boxNode())
mainScene!.rootNode.addChildNode(Collectable.tubeNode())
mainScene!.rootNode.addChildNode(Collectable.cylinderNode())
mainScene!.rootNode.addChildNode(Collectable.torusNode())
let sceneView = self.view as! SCNView
sceneView.scene = mainScene
sceneView.showsStatistics = true
sceneView.allowsCameraControl = true
}
func setupLighting(scene: SCNScene) {
let ambientLight = SCNNode()
ambientLight.light = SCNLight()
ambientLight.light!.type = SCNLight.LightType.ambient
ambientLight.light!.color = UIColor.white
scene.rootNode.addChildNode(ambientLight)
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLight.LightType.spot
lightNode.light!.castsShadow = true
lightNode.light!.color = UIColor(white: 0.8, alpha: 1.0)
lightNode.position = SCNVector3Make(0, 80, 30)
lightNode.rotation = SCNVector4Make(1, 0, 0, Float(-Double.pi / 2.8))
lightNode.light!.spotInnerAngle = 0
lightNode.light!.spotOuterAngle = 50
lightNode.light!.shadowColor = UIColor.black
lightNode.light!.zFar = 500
lightNode.light!.zNear = 50
scene.rootNode.addChildNode(lightNode)
}
func createMainCamera() {
let cameraNode = SCNNode()
cameraNode.name = "mainCamera"
cameraNode.camera = SCNCamera()
cameraNode.camera?.zFar = 1000
cameraNode.position = SCNVector3(x: 0, y: 15, z: 10)
cameraNode.rotation = SCNVector4(x: 0, y: 0, z: 0, w: -Float.pi/4 * 0.5) //Float(-M_PI_4*0.75))
let heroNode = mainScene.rootNode.childNode(withName: "hero", recursively: true)
heroNode?.addChildNode(cameraNode)
// mainScene.rootNode.addChildNode(cameraNode)
}
func createHeroCamera() {
let cameraNode = mainScene.rootNode.childNode(withName: "mainCamera", recursively: true)
cameraNode?.camera?.zFar = 500
cameraNode?.position = SCNVector3(x: 50, y: 0, z: -20)
cameraNode?.rotation = SCNVector4(x: 0, y: 0, z: 0, w: Float.pi / 4 * 0.5)
cameraNode?.eulerAngles = SCNVector3(x: -70, y: 0, z: 0)
let heroNode = mainScene.rootNode.childNode(withName: "hero", recursively: true)
heroNode?.addChildNode(cameraNode!)
mainScene.rootNode.childNode(withName: "hero", recursively: true)?.addChildNode(cameraNode!)
}
func createMainScene() -> SCNScene {
let mainScene = SCNScene(named: "art.scnassets/hero.dae")
return mainScene!
}
func createFloorNode() -> SCNNode {
let floorNode = SCNNode()
floorNode.geometry = SCNFloor()
floorNode.geometry?.firstMaterial?.diffuse.contents = "floor"
return floorNode
}
}
| d64d6f0608ef3af5c3d2be16b09614a74e95dd38 | [
"Swift"
] | 1 | Swift | BacchusPlateau/SpaceMan3D | 6dee4bd30edb63771a370eea79dae66872f111d2 | 5f48a7101456ca8be94f685e574c619cae2bf5cc |
refs/heads/master | <file_sep>[Winston](https://github.com/gleidsonf/winston-rocket-chat) Transport for
[Rocket Chat](https://rocket.chat/) chat integration.
npm install --save winston-rocketchat-transport
Basic transport that works just like all other winston transports. Sends logged
messages to a specified Slack chat channel.
Configuration options:
* `webhook_url`: **required** The webhook URL, something like
`https://yourworkspace.rocket.chat/hooks/<KEY>`
* `level`: If specified, this logger will only log messages at the specified
level of importance and more important messages
* `custom_formatter`: a `function (level, msg, meta)` which returns a Slack
payload object
---
var winston = require('winston');
var RocketChat = require('winston-rocketchat-transport');
winston.add(RocketChat, {
webhook_url: "<KEY>",
level: 'error',
handleExceptions: true
});
<file_sep>const util = require('util');
const request = require('request');
const winston = require('winston');
function RocketChat(config) {
if (!config) throw new Error('Missing config');
if (!config.webhook_url) throw new Error('Missing webhook_url in config');
winston.Transport.call(this, config);
this.config = config;
this.handleExceptions = !!config.handleExceptions;
}
util.inherits(RocketChat, winston.Transport);
winston.transports.RocketChat = RocketChat;
RocketChat.prototype.log = function (level, msg, meta, callback) {
callback = callback || function (err) {
if (err) console.error(err.stack);
};
const message =
this.config.custom_formatter
? this.config.custom_formatter(level, msg, meta)
: { text: "*" + level + "* " + msg, attachments: msg.attachments || [] };
const payload = {
text: message.text || this.config.text,
parseUrls: false,
attachments: message.attachments || this.config.attachments,
};
request.post({
uri: this.config.webhook_url,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
},
(err, res, body) => {
if (err) return callback(err);
if (res.statusCode !== 200) return callback(new Error(`Unexpected status code from RocketChat: ${res.statusCode}`));
this.emit('logged');
callback(null, true);
},
);
};
module.exports = RocketChat;
| d3a95ee30b15fdeb1fffa47aba46c7a2aabb315d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | gleidsonf/winston-rocket-chat | e9228ad3ed46ed195dea67108b709b783d067d69 | 942e3f329ce3555180b85b378b9ed85f003c2cb3 |
refs/heads/master | <repo_name>pblvsk/PStatus<file_sep>/index.php
<!DOCTYPE html>
<?PHP
include "config.inc.php";
if (isset($_GET['refresh'])) {
$refresh = $_GET['refresh'];
}
?>
<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">
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" src="/media/js/site.js?_=45ee69f7580387099dcc5163940d7394">
</script>
<script type="text/javascript" src="/media/js/dynamic.php?comments-page=extensions%2Fresponsive%2Fexamples%2Fstyling%2Fbootstrap.html" async>
</script>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.4.js">
</script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js">
</script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js">
</script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js">
</script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" class="init">
$(document).ready(function() {
$('#status').DataTable();
} );
</script>
<meta http-equiv="refresh" content="<?PHP
echo $refresh;
?>">
<title>PStatus</title>
<style>
.progress {
margin-bottom: 0 !important;
background-color: #DA2A2A;
-webkit-box-shadow: none;
box-shadow: none;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#status td.on_off:contains('offline')").css('background-color','#E05667');
$("#status td.on_off:contains('online')").css('background-color','#56E08E');
});
</script>
</head>
<body>
<?PHP
include "navbar.php";
?>
<center>
<div class="container">
<table class="table table-striped table-bordered" id="status">
<thead>
<tr><th colspan="5"><center><b><img src="icons/005-computer-screen.png" width="16" height="16"> Server Ping Status</th></tr>
<tr><th><b>DEVICE</th><th><b>INFO</th><th><b>PURPOSE</th><th><b>STATUS</th><th><b>UPTIME</th></tr>
</thead>
<tbody>
<?PHP
$db_handle = mysqli_connect($DBServer, $DBUser, $DBPassword);
$db_found = mysqli_select_db($db_handle, 'status');
if ($db_found) {
$SQL = "select * from servers order by device desc";
$result = mysqli_query($db_handle, $SQL);
while ($db_field = mysqli_fetch_assoc($result)) {
$device = $db_field['device'];
$ip = $db_field['ip'];
$id = $db_field['id'];
$port = $db_field['port'];
$info = $db_field['info'];
$purpose = $db_field['purpose'];
$count = $db_field['count'];
$ups = $db_field['ups'];
$downs = $db_field['downs'];
$online = pingtest($ip);
$value = $ups;
$max = $count;
$scale = 1.0;
if (!empty($max)) {
$percent = ($value * 100) / $max;
} else {
$percent = 0;
}
if ($percent > 100) {
$percent = 100;
}
print "<tr><td><a href='services.php?device=" . $device . "&parent=" . $id . "&ip=" . $ip . "' alt='" . $ip . "'>" . $device . "</a></td><td>" . $info . "</td><td>" . $purpose . "</td><td class='on_off'><Center>" . ($online ? 'online' : 'offline') . "</td><td><div class='progress'><div class='progress-bar progress-bar-success' role='progressbar' aria-valuenow='" . round($percent * $scale) . "' aria-valuemin='0' aria-valuemax='100' style='width:" . round($percent * $scale) . "%'>" . round($percent * $scale) . "%</div></div></td></tr>";
}
mysqli_close($db_handle);
}
?>
</tbody>
</table>
</div>
<?PHP
function pingtest($ip)
{
exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($ip)), $errorNo, $errorStr);
return $errorStr === 0;
}
mysqli_close($db_handle);
?>
<script>
var myVar;
function myFunction() {
myVar = setTimeout(showPage, 3000);
}
function showPage() {
document.getElementById("loader").style.display = "none";
document.getElementById("myDiv").style.display = "block";
}
</script>
<br>
<?PHP
include "footer.php";
?>
<?PHP
include "aboutmodal.php";
?>
</body>
</html>
<file_sep>/README.md
# PStatus
Ping of internal servers and port check of related services with a Web front end.
# Requirements
* Web server running PHP (7 is tested.. 5 should work fine)
* PHP Pear - https://wonderphp.wordpress.com/2014/02/28/installing-pear-mail-for-php-on-ubuntu/
* MYSQL Database (import status.sql to a database named "status")
* uptime.php needs to be run as a cron timer - */10 * * * * /usr/bin/php /var/www/html/status/uptime.php
# WIP
* Users + Permissions
# Planned
* Display uptime data including last uptime / downtime
* Edit Services
* Add / Edit users so htaccess is no longer required
* Enable / Disable email alerts (Currently always on)
* Enable Disable alerts per device
# Done
* Add auto refresh rate
* Add services for each parent server
* Add Smart device controls
* Run in backgroud to build stats of uptime
* Reset uptime data
* Email alerts with threshold
* Option to display Smart Devices or not
* Configurable settings via gui
* Delete Servers and Services
* Edit Servers
* removed smart devices and tables
* Added search / sorting for main device table
# Screenshot





# Credit
Original idea sparked by https://gist.github.com/k0nsl/733955a3c3093832de49
<file_sep>/uptime.php
<?PHP
include "config.inc.php";
$db_handle = mysqli_connect($DBServer, $DBUser, $DBPassword);
$db_found = mysqli_select_db($db_handle, 'status');
if ($db_found)
{
$SQL = "select * from servers";
$result = mysqli_query($db_handle, $SQL);
while ($db_field = mysqli_fetch_assoc($result))
{
$id = $db_field['id'];
$device = $db_field['device'];
$ip = $db_field['ip'];
$downs = $db_field['downs'];
$date = date("Y-m-d H:i:s");
$up = pingtest($ip);
$online = $up ? 'online' : 'offline';
if ($online == 'online'){
$SQL2 = "UPDATE servers SET count = count + 1, ups = ups + 1, downs = '0', lastup = '" . $date . "' WHERE id = '" . $id . "'";
}
else
{
if ($downs + 1 >= $alert_limit){
$SQL2 = "UPDATE servers SET count = count + 1, downs = '0', lastdown = '" . $date . "' WHERE id = '" . $id . "'";
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_STRICT);
set_include_path("." . PATH_SEPARATOR . ($UserDir = dirname($_SERVER['DOCUMENT_ROOT'])) . "/pear/php" . PATH_SEPARATOR . get_include_path());
require_once "Mail.php";
$host = "ssl://" . $smtp;
$username = $smtp_username;
$password = $<PASSWORD>;
$port = $smtp_port;
$to = $admin_email;
$email_from = $smtp_username;
$email_subject = "PStatus - Device Down - " .$device ;
$email_body = $device . " has not replied to " . $alert_limit . " ping request(s)" ;
$email_address = "<EMAIL>";
$headers = array ('From' => $email_from, 'To' => $to, 'Subject' => $email_subject, 'Reply-To' => $email_address);
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $<PASSWORD>));
$mail = $smtp->send($to, $headers, $email_body);
}
else
{
$SQL2 = "UPDATE servers SET count = count + 1, downs = downs + 1, lastdown = '" . $date . "' WHERE id = '" . $id . "'";
}
}
if (mysqli_query($db_handle, $SQL2)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db_handle);
}
}
$SQL3 = "select * from smartdevices";
$result = mysqli_query($db_handle, $SQL3);
while ($db_field = mysqli_fetch_assoc($result))
{
$id = $db_field['id'];
$ip = $db_field['ip'];
$date = date("Y-m-d H:i:s");
$up = pingtest($ip);
$online = $up ? 'online' : 'offline';
if ($online == 'online'){
$SQL4 = "UPDATE smartdevices SET count = count + 1, ups = ups + 1, lastup = '" . $date . "' WHERE id = '" . $id . "'";
}
else
{
$SQL4 = "UPDATE smartdevices SET count = count + 1, downs = downs + 1, lastdown = '" . $date . "' WHERE id = '" . $id . "'";
}
if (mysqli_query($db_handle, $SQL4)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($db_handle);
}
}
}
function pingtest($ip) {
exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($ip)), $errorNo, $errorStr);
return $errorStr === 0;
}
?>
| 6bc4f3ad295b634a4ca0e1816fd6e51890a4d7b4 | [
"Markdown",
"PHP"
] | 3 | PHP | pblvsk/PStatus | b2ee6719b83f13d130398b08c7f5fb5f1b82bf22 | 2e94da59d1f0c8bfc85c87afe7ebe16ec12c0b08 |
refs/heads/master | <repo_name>AndyRazafy/datalabs<file_sep>/nlp/stats.py
import json
from json import JSONEncoder
class Stat:
def __init__(self, losses, time):
self.losses = losses
self.time = time
def make_stat(losses, time):
stat = Stat(losses, time)
return stat
class StatEncoder(JSONEncoder):
def default(self, o):
return o.__dict__<file_sep>/al/src/components/stats/functions/stat-func.js
export function getLabelsCounts(labels, docs) {
let counts = [];
let i = 0;
while (i < labels.length) {
counts.push(0);
i++;
}
for(let doc of docs) {
for(let ent of doc.ents) {
const index = labels.indexOf(ent.label);
counts[index] = counts[index] + 1;
}
}
return counts;
}
export function getLabelEvalutation(evaluation, labels, scoreLabel) {
let scores = [];
for(let label of labels) {
scores.push(evaluation['ents_per_type'][label][scoreLabel].toFixed(2));
}
return scores;
}
export function getTestDocs(docs, test) {
let newDocs = [];
for(let d in docs) {
for(let r in test) {
if(test[r] === docs[d]._id) {
newDocs.push(docs[d]);
break;
}
}
}
return newDocs;
}
export function generateRGBA(number) {
let rgbas = [];
let i = 0;
while(i < number) {
rgbas.push(randomColor(10));
i++;
}
return rgbas;
}
function randomColor(brightness){
function randomChannel(brightness){
var r = 255-brightness;
var n = 0|((Math.random() * r) + brightness);
var s = n.toString(16);
return (s.length===1) ? '0'+s : s;
}
return '#' + randomChannel(brightness) + randomChannel(brightness) + randomChannel(brightness);
}<file_sep>/al/src/utils/api/api.js
export const DATA_API = "http://localhost:80/api";
export const TRAIN_API = 'http://localhost:5000';
export const CONFIG = {
headers: {
'Content-Type': 'application/json'
}
}<file_sep>/al/src/components/annotations/AnnotationLayout.js
import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { DATA_API, TRAIN_API, CONFIG } from '../../utils/api/api';
import { addEntityToDocAndUpdateDocs, deleteEntityOfDocAndUpdateDocs, deleteAllEntitiesOfDocAndUpdateDocs,
getReadyDocsFromDocs, excludeFromDocs, pushReadyDocsToArray, replaceEntityAndConfidenceOfDocsPredicted,
sortPredictionByConfidenceAfterPrediction, updateConfidenceOfDocsAfterTraining } from './functions/document-func';
// actions
import { loadingAction } from '../../actions/loading-actions';
import DocCard from './DocCard';
import Labels from './Labels';
import './css/annotation.css';
class AnnotationLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
selection: {
str: '',
start: 0,
end: 0
},
dataset: undefined,
docs: [],
labels: [],
ready: [],
trained: [],
test: [],
pageNumber: 1,
pageSize: 5
}
}
componentDidMount = () => {
this.initData();
}
initData = () => {
const { id } = this.props.match.params;
this.props.loadingAction(true, "Chargement des données...");
axios.get(`${DATA_API}/datasets/${id}`)
.then(res => {
const dataset = res.data;
const docs = dataset.docs || [];
const labels = dataset.labels || [];
const ready = dataset.ready || [];
const trained = dataset.trained || [];
const test = dataset.test || [];
this.setState({ dataset, docs, labels, ready, trained, test });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
loadDocs = () => {
const { id } = this.props.match.params;
this.props.loadingAction(true, "Chargement des documents...");
axios.get(`${DATA_API}/datasets/${id}/docs`)
.then(res => {
const docs = res.data;
this.setState({ docs });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
loadLabels = () => {
const { id } = this.props.match.params;
this.props.loadingAction(true, "Chargement des labels...");
axios.get(`${DATA_API}/datasets/${id}/labels`)
.then(res => {
const labels = res.data;
this.setState({ labels });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
loadReady = () => {
const { id } = this.props.match.params;
this.props.loadingAction(true, "Chargement des données...");
axios.get(`${DATA_API}/datasets/${id}/ready`)
.then(res => {
const ready = res.data;
this.setState({ ready });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
loadTrained = () => {
const { id } = this.props.match.params;
this.props.loadingAction(true, "Chargement des données...");
axios.get(`${DATA_API}/datasets/${id}/trained`)
.then(res => {
const trained = res.data;
this.setState({ trained });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
loadTest = () => {
const { id } = this.props.match.params;
this.props.loadingAction(true, "Chargement des données...");
axios.get(`${DATA_API}/datasets/${id}/test`)
.then(res => {
const test = res.data;
this.setState({ test });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
save = () => {
this.saveDocs();
this.saveReady();
}
saveDocs = () => {
const { id } = this.props.match.params;
const { docs } = this.state;
const newDocs = { docs: docs };
this.props.loadingAction(true, "Sauvegarde des documents...");
axios.put(`${DATA_API}/datasets/${id}/docs`, newDocs, CONFIG)
.then(() => {
this.loadDocs();
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
saveReady = () => {
const { id } = this.props.match.params;
const { ready } = this.state;
const newReady = { ready: ready };
this.props.loadingAction(true, "Sauvegarde...");
axios.put(`${DATA_API}/datasets/${id}/ready`, newReady, CONFIG)
.then(() => {
this.loadReady();
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
addLabel = (newName) => {
const { id } = this.props.match.params;
const newLabel = { label: [{ name: newName }]};
this.props.loadingAction(true, "Ajout en cours...");
axios.put(`${DATA_API}/datasets/${id}/labels`, newLabel, CONFIG)
.then((res) => {
this.loadLabels();
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
updateTrained = () => {
const { ready } = this.state;
if(ready.length !== 0) {
const { id } = this.props.match.params;
let { trained } = this.state;
const data = { trained: pushReadyDocsToArray(trained, ready) };
this.props.loadingAction(true, "Modification en cours...");
axios.put(`${DATA_API}/datasets/${id}/trained`, data, CONFIG)
.then((res) => {
this.loadTrained();
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
}
updateTest = () => {
const { ready } = this.state;
if(ready.length !== 0) {
const { id } = this.props.match.params;
let { test } = this.state;
const data = { test: pushReadyDocsToArray(test, ready) };
this.props.loadingAction(true, "Modification en cours...");
axios.put(`${DATA_API}/datasets/${id}/test`, data, CONFIG)
.then((res) => {
const ready = [];
this.setState({ pageNumber: 1, ready });
this.loadTest();
this.save();
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
}
train = () => {
const { ready } = this.state;
if(ready.length > 0) {
let docs = getReadyDocsFromDocs(this.state.docs, ready);
const data = { model: this.state.dataset.model, data: docs };
this.props.loadingAction(true, "Entrainement en cours...");
axios.post(`${TRAIN_API}/update`, data, CONFIG)
.then((res) => {
updateConfidenceOfDocsAfterTraining(docs);
this.updateTrained();
const ready = [];
this.setState({ pageNumber: 1, ready });
this.save();
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
}
predict = () => {
let docs = excludeFromDocs(this.state.docs, this.state.trained);
if(docs.length > 0) {
const data = { model: this.state.dataset.model, data: docs };
this.props.loadingAction(true, "Prédiction...");
axios.post(`${TRAIN_API}/predict`, data, CONFIG)
.then((res) => {
const docs = replaceEntityAndConfidenceOfDocsPredicted(this.state.docs, res.data);
this.setState({ docs });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
}
addEntity = (label) => {
const { selection } = this.state;
if(label && label.name && selection.docId) {
const newEntity = {
start: selection.start,
end: selection.end,
label: label.name
};
const newDocs = addEntityToDocAndUpdateDocs(this.state.docs, selection.docId, newEntity);
this.setState({ docs: newDocs });
}
}
deleteEntity = (docId, entity) => {
if(docId && entity) {
const newDocs = deleteEntityOfDocAndUpdateDocs(this.state.docs, docId, entity);
this.setState({ docs: newDocs });
}
}
deleteAllEntitiesOfDocs = (docId) => {
if(docId) {
const newDocs = deleteAllEntitiesOfDocAndUpdateDocs(this.state.docs, docId);
this.setState({ docs: newDocs });
}
}
updateReady = (docId) => {
let { ready } = this.state;
if(ready.includes(docId)) {
let index = ready.indexOf(docId);
ready.splice(index, 1);
}
else {
ready.push(docId);
}
this.setState({ ready });
}
updateSelection = (newSelection) => {
if(newSelection && newSelection.docId) {
this.setState({ selection: newSelection });
}
}
changePageSize = (e) => {
this.setState({ pageSize: Number(e.target.value) });
}
getNumberOfPages = (docsCount, pageSize) => {
const nbrOfPages = Math.ceil(docsCount / pageSize);
return nbrOfPages;
}
previousPage = () => {
const { pageNumber } = this.state;
const expectedPageNumber = pageNumber - 1;
if(expectedPageNumber > 0)
this.setState({ pageNumber: expectedPageNumber });
}
nextPage = (length) => {
const { pageNumber, pageSize } = this.state;
const expectedPageNumber = pageNumber + 1;
const numberOfPages = this.getNumberOfPages(length, pageSize);
if(expectedPageNumber <= numberOfPages)
this.setState({ pageNumber: expectedPageNumber });
}
paginate = (array, size, number) => {
if(array.length > 0) {
let newArray = [];
let i = (number - 1) * size;
let len = (number * size);
while(i < len) {
if(array[i]) {
newArray.push(array[i]);
}
i++;
}
return newArray;
}
return array;
}
filterDocs = (docs) => {
const { trained, test } = this.state;
let filteredDocs = excludeFromDocs(docs, trained);
filteredDocs = excludeFromDocs(filteredDocs, test);
return filteredDocs;
}
displaySettingDiv = (docsToDisplay) => {
const ids = docsToDisplay.map(d => d._id);
const numberOfPages = this.getNumberOfPages(docsToDisplay.length, this.state.pageSize) || 1;
const { selection, pageNumber, pageSize, ready } = this.state;
return(
<div className="setting-div">
<div className="row">
<div className="six columns setting-info-div">
<span className="setting-info-span">{`${pageNumber} / ${numberOfPages} pages`}</span>
<span className="setting-info-span setting-info-select">
<select onChange={(e) => this.changePageSize(e)} value={pageSize}>
<option value="1">1</option>
<option value="5">5</option>
<option value="10">10</option>
</select>
{' '}par page
</span>
{' | '}<span className="setting-info-span">{`${ready.length} doc. prêt(s)`}</span>
</div>
<div className="six columns setting-btn-div">
<button className="setting-btn" onClick={() => this.save()}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-cloud-upload-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M8 0a5.53 5.53 0 0 0-3.594 1.342c-.766.66-1.321 1.52-1.464 2.383C1.266 4.095 0 5.555 0 7.318 0 9.366 1.708 11 3.781 11H7.5V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V11h4.188C14.502 11 16 9.57 16 7.773c0-1.636-1.242-2.969-2.834-3.194C12.923 1.999 10.69 0 8 0zm-.5 14.5V11h1v3.5a.5.5 0 0 1-1 0z"/>
</svg>
</button>
{' | '}
<button className="setting-btn" onClick={() => this.train()}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-cpu-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M5.5.5a.5.5 0 0 0-1 0V2A2.5 2.5 0 0 0 2 4.5H.5a.5.5 0 0 0 0 1H2v1H.5a.5.5 0 0 0 0 1H2v1H.5a.5.5 0 0 0 0 1H2v1H.5a.5.5 0 0 0 0 1H2A2.5 2.5 0 0 0 4.5 14v1.5a.5.5 0 0 0 1 0V14h1v1.5a.5.5 0 0 0 1 0V14h1v1.5a.5.5 0 0 0 1 0V14h1v1.5a.5.5 0 0 0 1 0V14a2.5 2.5 0 0 0 2.5-2.5h1.5a.5.5 0 0 0 0-1H14v-1h1.5a.5.5 0 0 0 0-1H14v-1h1.5a.5.5 0 0 0 0-1H14v-1h1.5a.5.5 0 0 0 0-1H14A2.5 2.5 0 0 0 11.5 2V.5a.5.5 0 0 0-1 0V2h-1V.5a.5.5 0 0 0-1 0V2h-1V.5a.5.5 0 0 0-1 0V2h-1V.5zm1 4.5A1.5 1.5 0 0 0 5 6.5v3A1.5 1.5 0 0 0 6.5 11h3A1.5 1.5 0 0 0 11 9.5v-3A1.5 1.5 0 0 0 9.5 5h-3zm0 1a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5h-3z"/>
</svg>
</button>
<button className="setting-btn" onClick={() => this.predict()}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-lightning-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M11.251.068a.5.5 0 0 1 .227.58L9.677 6.5H13a.5.5 0 0 1 .364.843l-8 8.5a.5.5 0 0 1-.842-.49L6.323 9.5H3a.5.5 0 0 1-.364-.843l8-8.5a.5.5 0 0 1 .615-.09z"/>
</svg>
</button>
<button className="setting-btn" onClick={() => this.updateTest()}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-bookmark-check-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M4 0a2 2 0 0 0-2 2v13.5a.5.5 0 0 0 .74.439L8 13.069l5.26 2.87A.5.5 0 0 0 14 15.5V2a2 2 0 0 0-2-2H4zm6.854 5.854a.5.5 0 0 0-.708-.708L7.5 7.793 6.354 6.646a.5.5 0 1 0-.708.708l1.5 1.5a.5.5 0 0 0 .708 0l3-3z"/>
</svg>
</button>
{' | '}
<button className="setting-btn" onClick={() => this.deleteAllEntitiesOfDoc([selection.docId])}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-file-earmark-x-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M2 2a2 2 0 0 1 2-2h5.293A1 1 0 0 1 10 .293L13.707 4a1 1 0 0 1 .293.707V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2zm7.5 1.5v-2l3 3h-2a1 1 0 0 1-1-1zM6.854 7.146a.5.5 0 1 0-.708.708L7.293 9l-1.147 1.146a.5.5 0 0 0 .708.708L8 9.707l1.146 1.147a.5.5 0 0 0 .708-.708L8.707 9l1.147-1.146a.5.5 0 0 0-.708-.708L8 8.293 6.854 7.146z"/>
</svg>
</button>
<button className="setting-btn" onClick={() => this.deleteAllEntitiesOfDocs(ids)}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-x-circle-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-4.146-3.146a.5.5 0 0 0-.708-.708L8 7.293 4.854 4.146a.5.5 0 1 0-.708.708L7.293 8l-3.147 3.146a.5.5 0 0 0 .708.708L8 8.707l3.146 3.147a.5.5 0 0 0 .708-.708L8.707 8l3.147-3.146z"/>
</svg>
</button>
<button className="setting-btn" onClick={() => this.previousPage()}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-skip-backward-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M.5 3.5A.5.5 0 0 0 0 4v8a.5.5 0 0 0 1 0V4a.5.5 0 0 0-.5-.5z"/>
<path d="M.904 8.697l6.363 3.692c.54.313 1.233-.066 1.233-.697V4.308c0-.63-.692-1.01-1.233-.696L.904 7.304a.802.802 0 0 0 0 1.393z"/>
<path d="M8.404 8.697l6.363 3.692c.54.313 1.233-.066 1.233-.697V4.308c0-.63-.693-1.01-1.233-.696L8.404 7.304a.802.802 0 0 0 0 1.393z"/>
</svg>
</button>
<button className="setting-btn" onClick={() => this.nextPage(docsToDisplay.length)}>
<svg width="1.3em" height="1.3em" viewBox="0 0 16 16" className="bi bi-skip-forward-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M15.5 3.5a.5.5 0 0 1 .5.5v8a.5.5 0 0 1-1 0V4a.5.5 0 0 1 .5-.5z"/>
<path d="M7.596 8.697l-6.363 3.692C.693 12.702 0 12.322 0 11.692V4.308c0-.63.693-1.01 1.233-.696l6.363 3.692a.802.802 0 0 1 0 1.393z"/>
<path d="M15.096 8.697l-6.363 3.692c-.54.313-1.233-.066-1.233-.697V4.308c0-.63.693-1.01 1.233-.696l6.363 3.692a.802.802 0 0 1 0 1.393z"/>
</svg>
</button>
</div>
</div>
</div>
);
}
displayBackToDatasetProfileLink = (dataset) => {
return(
<div className="row" style={{ padding: 5 }}>
<span>
<svg style={{ verticalAlign: "middle" }} width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-arrow-left-short" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M7.854 4.646a.5.5 0 0 1 0 .708L5.207 8l2.647 2.646a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 0 1 .708 0z"/>
<path fillRule="evenodd" d="M4.5 8a.5.5 0 0 1 .5-.5h6.5a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5z"/>
</svg>
</span>
<Link to={`/donnees/${dataset._id}`}>{dataset.model}</Link>
</div>
)
}
render() {
const { dataset, docs, labels, ready, pageNumber, pageSize } = this.state;
const docsToDisplay = this.filterDocs(docs);
const paginatedDocs = this.paginate(docsToDisplay, pageSize, pageNumber);
paginatedDocs.sort((a, b) => (a.confidence - b.confidence));
return(
<div style={{position: "relative"}}>
{dataset && this.displayBackToDatasetProfileLink(dataset)}
<div className="annotation-fixed-header">
<Labels dataset={this.state.dataset} labels={labels} addLabel={this.addLabel} addEntity={this.addEntity} />
{this.displaySettingDiv(docsToDisplay)}
</div>
<DocCard
dataset={dataset}
docs={paginatedDocs}
updateSelection={this.updateSelection}
ready={ready}
deleteEntity={this.deleteEntity}
updateReady={this.updateReady} />
</div>
);
}
}
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {
loadingAction: (value, message) => dispatch(loadingAction(value, message)),
};
};
export default connect(mapStateToProps, mapDispatchToProps) (AnnotationLayout);<file_sep>/al/src/components/loading/Loading.js
import React from 'react';
import Modal from 'react-modal';
import './css/loading.css';
const customStyles = {
content : {
top : '30%',
left : '35%',
width : '30%',
height : 'fit-content',
border : 'none'
}
};
export default function Loading(props) {
return(
<Modal style={customStyles} isOpen={true} shouldCloseOnOverlayClick={false} >
<div className="loading-container">
<div className="sk-chase">
<div className="sk-chase-dot"></div>
<div className="sk-chase-dot"></div>
<div className="sk-chase-dot"></div>
<div className="sk-chase-dot"></div>
<div className="sk-chase-dot"></div>
<div className="sk-chase-dot"></div>
</div>
<span className="loading-text">{props.message}</span>
</div>
</Modal>
);
}<file_sep>/al/src/components/datasets/CreateDataset.js
import React from 'react';
import { connect } from 'react-redux';
import axios from 'axios';
import { Link, withRouter } from 'react-router-dom';
import { DATA_API, TRAIN_API, CONFIG } from '../../utils/api/api';
import { nameAlreadyExist, modelAlreadyExist, Dataset, importDataToTextareaFromFile, shuffle, textToDoc } from './functions/create-dataset';
// actions
import { loadingAction } from '../../actions/loading-actions';
import './css/create-dataset.css';
class CreateDataset extends React.Component {
constructor(props) {
super(props);
this.state = {
datasets: []
}
this.newModel = React.createRef();
this.file = React.createRef();
this.docs = React.createRef();
this.shuffle = React.createRef();
}
componentDidMount = () => {
this.loadData();
}
loadData = () => {
this.props.loadingAction(true, "Chargement des données...");
axios.get(`${DATA_API}/datasets`)
.then(res => {
this.setState({ datasets: res.data });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
createModelRequest = (model) => {
this.props.loadingAction(true, "Création du modèle...");
axios.post(`${TRAIN_API}/create`, model, CONFIG)
.then(res => {
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
createDatasetRequest = (newDataset) => {
this.props.loadingAction(true, "Ajout en cours...");
axios.post(`${DATA_API}/datasets`, newDataset, CONFIG)
.then(res => {
const model = { model: newDataset.model };
this.createModelRequest(model);
this.props.history.push('/donnees');
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
createDataset = () => {
const newModel = this.newModel.current.value.trim();
let docs = this.docs.current.value.split('\n');
const onShuffle = this.shuffle.current.checked;
if(newModel && !modelAlreadyExist(this.state.datasets, newModel)) {
let newDocs = [];
for(let i in docs) {
newDocs.push(textToDoc(docs[i]));
}
if(onShuffle)
newDocs = shuffle(newDocs);
const labels = [];
const ready = [];
const trained = [];
const test = [];
const newDataset = Dataset(newModel, newDocs, labels, ready, trained, test);
this.createDatasetRequest(newDataset);
}
}
onChangeFile = (e) => {
importDataToTextareaFromFile(this.file.current.files[0], this.docs.current);
}
displayCreateDatasetForm = () => {
return(
<form>
<h1 className="form-title">Ajout de modèle</h1>
<div className="row">
<div className="six columns">
<label htmlFor="exampleModelInput">Modèle</label>
<input ref={this.newModel} className="u-full-width" type="text" placeholder="ex: nom_prenom_modele" id="exampleModelInput" required={true}/>
</div>
</div>
<div className="row Row">
<div className="six columns">
<label htmlFor="exampleFileInput">Données</label>
<input ref={this.file} onChange={(e) => this.onChangeFile(e)} className="u-full-width" type="file" id="exampleFileInput" required={true}/>
</div>
</div>
<div className="row Row">
<label htmlFor="exampleMessage">Aperçu</label>
<textarea ref={this.docs} className="u-full-width" id="exampleMessage" readOnly={true}></textarea>
</div>
<div className="row Row">
<label className="example-send-yourself-copy">
<input ref={this.shuffle} type="checkbox"/>
<span className="label-body">Mélanger les documents</span>
</label>
</div>
<div className="row Row" style={{ textAlign: "right" }}>
<Link to="/donnees" className="button">
Annuler
</Link>{' '}
<button type="button" className="button-primary" onClick={() => this.createDataset()}>Ajouter</button>
</div>
</form>
);
}
render() {
const { datasets} = this.state;
return(
<div className="container create-dataset-container">
{this.displayCreateDatasetForm(datasets)}
</div>
);
}
}
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {
loadingAction: (value, message) => dispatch(loadingAction(value, message)),
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(CreateDataset));<file_sep>/webservice/routes/api/routes.js
const express = require("express");
const router = express.Router();
// Dataset Model
const Dataset = require("../../models/Dataset");
// @route GET api/datasets
// @desc Get all datasets
// @access Public
router.get("/datasets", (req, res) => {
Dataset.find()
.then(datasets => res.json(datasets))
.catch(err => res.status(404).json({ message: err.message }));
});
// @route GET api/datasets/:id
// @desc Get dataset by id
// @access Public
router.get("/datasets/:id", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => res.json(dataset))
.catch(err => res.status(404).json({ message: err.message }));
});
// @route GET api/datasets/:id/labels
// @desc Get dataset's labels
// @access Public
router.get("/datasets/:id/docs", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => res.json(dataset.docs))
.catch(err => res.status(404).json({ message: err.message }));
});
// @route GET api/datasets/:id/labels
// @desc Get dataset's labels
// @access Public
router.get("/datasets/:id/labels", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => res.json(dataset.labels))
.catch(err => res.status(404).json({ message: err.message }));
});
// @route GET api/datasets/:id/ready
// @desc Get dataset's ready
// @access Public
router.get("/datasets/:id/ready", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => res.json(dataset.ready))
.catch(err => res.status(404).json({ message: err.message }));
});
// @route GET api/datasets/:id/trained
// @desc Get dataset's trained
// @access Public
router.get("/datasets/:id/trained", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => res.json(dataset.trained))
.catch(err => res.status(404).json({ message: err.message }));
});
// @route GET api/datasets/:id/trained
// @desc Get dataset's trained
// @access Public
router.get("/datasets/:id/test", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => res.json(dataset.test))
.catch(err => res.status(404).json({ message: err.message }));
});
// @route POST api/datasets
// @desc Create a dataset
// @access Public
router.post("/datasets", (req, res) => {
const newDataset = new Dataset({
model: req.body.model,
labels: req.body.labels,
docs: req.body.docs,
ready: req.body.ready,
trained: req.body.trained,
test: req.body.test
});
newDataset.save()
.then(dataset => res.json({ success: 1, data: dataset }))
.catch(err => {res.status(404).json({ success: 0, message: err.message })});
});
// @route PUT api/datasets
// @desc Update a dataset docs
// @access Public
router.put("/datasets/:id/docs", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => dataset.updateOne({
docs: req.body.docs
})).then(() => res.json({ success: 1 }))
.catch(err => res.status(404).json({ success: 0, message: err.message }));
});
// @route POST api/datasets//:id/labels
// @desc add label to dataset
// @access Public
router.put("/datasets/:id/labels", (req, res) => {
Dataset.findByIdAndUpdate(
req.params.id,
{$push: {labels: req.body.label}},
{useFindAndModify: false})
.then(() => res.json({ success: 1 }))
.catch(err => {res.status(404).json({ success: 0, message: err.message })});
});
// @route PUT api/datasets
// @desc Update a dataset labels
// @access Public
router.put("/datasets/:id/ready", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => dataset.updateOne({
ready: req.body.ready
})).then(() => res.json({ success: 1 }))
.catch(err => res.status(404).json({ success: 0, message: err.message }));
});
// @route PUT api/datasets
// @desc Update a dataset
// @access Public
router.put("/datasets/:id/trained", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => dataset.updateOne({
trained: req.body.trained
})).then(() => res.json({ success: 1 }))
.catch(err => res.status(404).json({ success: 0, message: err.message }));
});
// @route PUT api/datasets
// @desc Update a dataset
// @access Public
router.put("/datasets/:id/test", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => dataset.updateOne({
test: req.body.test
})).then(() => res.json({ success: 1 }))
.catch(err => res.status(404).json({ success: 0, message: err.message }));
});
// @route DELETE api/datasets
// @desc Delete a dataset
// @access Public
router.delete("/datasets/:id", (req, res) => {
Dataset.findById(req.params.id)
.then(dataset => dataset.remove()
.then(() => res.json({ success: 1 })))
.catch(err => res.status(404).json({ success: 0, message: err.message }));
});
module.exports = router;<file_sep>/nlp/process.py
import spacy
import warnings
import random
import os
import datetime as dt
from spacy.util import minibatch, compounding
from spacy.gold import GoldParse
from spacy.scorer import Scorer
from stats import make_stat
import sys
from collections import defaultdict
def load_model(name):
dir = './models/' + name
nlp = spacy.load(dir)
return nlp
def save_model(nlp, name):
dir = './models/' + name
nlp.to_disk(dir)
def create_blank_model(name):
nlp = spacy.blank("fr")
save_model(nlp, name)
def remove_model(name):
dir = './models/' + name
os.remove(dir)
def load_train_data(data):
TRAIN_DATA = []
for item in data:
ents = []
for ent in item['ents']:
ents.append((ent['start'], ent['end'], ent['label']))
TRAIN_DATA.append((item['text'], {'entities': ents}))
return TRAIN_DATA
def update_model(name, train_data, n_iter):
nlp = load_model(name)
isNew = False
if "ner" not in nlp.pipe_names:
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner, last=True)
isNew = True
else:
ner = nlp.get_pipe("ner")
# add labels
for _, annotations in train_data:
for ent in annotations.get("entities"):
ner.add_label(ent[2])
# get names of other pipes to disable them during training
pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
stats = []
# only train NER
with nlp.disable_pipes(*other_pipes), warnings.catch_warnings():
# show warnings for misaligned entity spans once
warnings.filterwarnings("once", category=UserWarning, module='spacy')
if isNew is True:
nlp.begin_training()
for itn in range(n_iter):
losses = {}
# batch up the examples using spaCy's minibatch
batches = minibatch(train_data, size=compounding(4.0, 32.0, 1.001))
for batch in batches:
texts, annotations = zip(*batch)
nlp.update(
texts, # batch of texts
annotations, # batch of annotations
drop=0.5, # dropout - make it harder to memorise data
losses=losses,
)
#print("Losses", losses)
now = dt.datetime.now()
stat = make_stat(losses, str(now))
stats.append(stat)
save_model(nlp, name)
return stats
def predict_model(nlp, input):
doc = nlp(input)
return doc
def evaluate(model, examples):
scorer = Scorer()
for input_, annot in examples:
doc_gold_text = model.make_doc(input_)
gold = GoldParse(doc_gold_text, entities=annot.get("entities"))
pred_value = model(input_)
scorer.score(pred_value, gold)
return scorer.scores
def confidence(nlp, doc):
beams = nlp.entity.beam_parse([ doc ], beam_width = 16, beam_density = 0.0001)
entity_scores = defaultdict(float)
for beam in beams:
for score, ents in nlp.entity.moves.get_beam_parses(beam):
for start, end, label in ents:
entity_scores[(start, end, label)] += score
threshold = 0.1
value = 0
length = 0
for key in entity_scores:
score = entity_scores[key]
if(score > threshold):
value += score
length += 1
if(length > 0):
value /= length
return value<file_sep>/webservice/models/Dataset.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Dataset Schema
const DatasetSchema = new Schema({
model: {
type: String,
required: true
},
labels: [{
name: {
type: String,
required: true
}
}],
docs: [{
text: {
type: String,
required: true
},
ents: [{
start: {
type: Number,
required: true
},
end: {
type: Number,
required: true
},
label: {
type: String,
required: true
}
}],
confidence: {
type: Number,
required: true
},
}],
ready: [],
trained: [],
test: []
});
module.exports = Dataset = mongoose.model("dataset", DatasetSchema);<file_sep>/al/src/components/navs/NavBar.js
import React from 'react';
import { Link } from 'react-router-dom';
import './css/navbar.css';
export default function NavBar(props) {
return(
<nav className="navbar">
<div className="container">
<ul className="navbar-list">
<li className="navbar-item"><Link to="/donnees" className="navbar-link">Modèles</Link></li>
</ul>
</div>
</nav>
);
}<file_sep>/nlp/routes.py
from flask import Flask, request
from process import load_model, predict_model, load_train_data, update_model, create_blank_model, remove_model, evaluate, confidence
from flask_cors import CORS
from stats import StatEncoder
import json
app = Flask(__name__)
CORS(app)
@app.route('/')
def hello_world():
return 'NLP is cool'
@app.route('/create', methods=['POST'])
def create():
input = request.get_json(force=True)
modelName = str(input.get('model'))
create_blank_model(modelName)
return json.dumps({ "success": 1 })
@app.route('/update', methods=['POST'])
def update():
input = request.get_json(force=True)
modelName = str(input.get('model'))
data = input.get('data')
trainData = load_train_data(data)
stats = update_model(modelName, trainData, 25)
return json.dumps(stats, indent=4, cls=StatEncoder)
@app.route('/predict', methods=['POST'])
def predict():
input = request.get_json(force=True)
modelName = str(input.get('model'))
data = input.get('data')
nlp = load_model(modelName)
for item in data:
doc = predict_model(nlp, str(item['text']))
conf = confidence(nlp, doc)
item['confidence'] = conf
ents = []
for ent in doc.ents:
ents.append({ "start": ent.start_char, "end": ent.end_char, "label": ent.label_})
item['ents'] = ents
return json.dumps(data)
@app.route('/evaluate', methods=['POST'])
def evalutate_model():
input = request.get_json(force=True)
modelName = str(input.get('model'))
data = input.get('data')
nlp = load_model(modelName)
testData = load_train_data(data)
scores = evaluate(nlp, testData)
return json.dumps(scores)
@app.route('/delete', methods=['POST'])
def delete():
input = request.get_json(force=True)
modelName = str(input.get('model'))
remove_model(modelName)
return json.dumps({ "success": 1 })<file_sep>/al/src/components/annotations/Labels.js
import React from 'react';
import Modal from 'react-modal';
import './css/label.css';
const customStyles = {
content : {
top : '25%',
left : '33%',
width : '30%',
height : 'fit-content'
}
};
Modal.setAppElement('#root');
class Labels extends React.Component {
constructor(props) {
super(props);
this.state = {
newName: '',
createLabelModalIsOpen: false
}
}
setNewName = (e) => {
this.setState({ newName: e.target.value.trim() });
}
handleCreateLabelModal = () => {
this.setState((oldState) => ({
createLabelModalIsOpen: !oldState.createLabelModalIsOpen
}));
}
nameAlreadyExists = () => {
const { labels } = this.props;
const newName = this.state.newName;
for(let label in labels) {
if(labels[label].name && labels[label].name.toLowerCase() === newName.toLowerCase())
return true;
}
return false;
}
inputsAreEmpty = () => {
const newName = this.state.newName;
return (newName === '');
}
createLabel = () => {
this.props.addLabel(this.state.newName);
this.setState({ newName: '' })
this.handleCreateLabelModal();
}
displayCreateLabelModal = () => {
return(
<Modal style={customStyles} isOpen={this.state.createLabelModalIsOpen} onRequestClose={() => this.handleCreateLabelModal()}>
<div className="container">
<h3 style={{borderBottom: "2px solid #eee"}}>Ajouter un label</h3>
<form>
<div className="row">
<div className="six columns">
<label htmlFor="nameInput">Nom</label>
<input value={this.state.newName} onChange={(e) => this.setNewName(e)} className="u-full-width" style={{ width: 320 }} type="text" placeholder="ex: option" id="nameInput"/>
<span style={{color: "#f00"}}>{this.nameAlreadyExists() && "Le nom existe déjà!"}</span>
</div>
</div>
<div style={{marginTop: 20, paddingTop: 10, borderTop: "2px solid #eee", textAlign: "right"}}>
<button type="button" className="button-primary" onClick={() => this.createLabel()} disabled={(this.nameAlreadyExists() || this.inputsAreEmpty()) ? true : false}>Ajouter</button>
</div>
</form>
</div>
</Modal>
);
}
displayLabels = (labels) => {
if(labels) {
return(
<React.Fragment>
{labels.map((label, index) => (
<button key={index} className="button-primary label-btn" onClick={() => this.props.addEntity(label)}>{label.name}</button>
))}
</React.Fragment>
);
}
}
render() {
const { dataset, labels } = this.props;
return(
<div className="label-div">
{this.displayCreateLabelModal()}
<div className="label-list">
<button className="add-label-btn" onClick={() => this.handleCreateLabelModal()}>
<svg width="1.5em" height="1.5em" viewBox="0 0 16 16" className="bi bi-plus-circle-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM8.5 4a.5.5 0 0 0-1 0v3.5H4a.5.5 0 0 0 0 1h3.5V12a.5.5 0 0 0 1 0V8.5H12a.5.5 0 0 0 0-1H8.5V4z"/>
</svg>
</button>
{dataset && this.displayLabels(labels)}
</div>
</div>
);
}
}
export default Labels;
<file_sep>/al/src/components/datasets/Dataset.js
import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { DATA_API } from '../../utils/api/api';
// actions
import { loadingAction } from '../../actions/loading-actions';
import './css/dataset-profile.css';
class Dataset extends React.Component {
constructor(props) {
super(props);
this.state = {
dataset: undefined,
}
}
componentDidMount = () => {
this.initData();
}
initData = () => {
const { id } = this.props.match.params;
this.props.loadingAction(true, "Chargement des données...");
axios.get(`${DATA_API}/datasets/${id}`)
.then(res => {
const dataset = res.data;
this.setState({ dataset, name: dataset.name, model: dataset.model });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
getFinishRate = (total, finished) => {
if(finished > 0 && total > 0)
return (finished * 100) / total;
return 0;
}
displayDatasetsTable = (dataset) => {
return(
<table className="u-full-width">
<thead>
<tr>
<th># doc.</th>
<th># doc. entrainés</th>
<th># doc. test</th>
<th># doc. prêts</th>
<th># labels</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>{dataset.docs.length}</td>
<td>{dataset.trained.length}</td>
<td>{dataset.test.length}</td>
<td>{dataset.ready.length}</td>
<td>{dataset.labels.length}</td>
</tr>
</tbody>
</table>
)
}
displayProfile = (dataset) => {
return(
<div>
<div className="profile-nav">
<Link className="profile-nav-link" to={`/annotation/${dataset._id}`}>Annotation</Link>
<Link className="profile-nav-link" to={`/donnees/${dataset._id}/stats`}>Stats</Link>
<Link className="profile-nav-link" to={`/donnees/${dataset._id}/stats`}>Documents</Link>
<Link className="profile-nav-link" to={`/donnees/${dataset._id}/test`}>Test</Link>
</div>
<div className="row">
<div className="ten columns">
<label htmlFor="model" className="profile-header-label">Modèle:</label>
<h5 id="model" className="profile-header-info">{dataset.model}</h5>
</div>
<div className="two columns">
<label className="profile-header-label">Complétion:</label>
<h5 className="profile-header-info right">{`${this.getFinishRate(dataset.docs.length, (dataset.trained.length + dataset.test.length)).toFixed(0)} %`}</h5>
</div>
</div>
<div>
{this.displayDatasetsTable(dataset)}
</div>
</div>
);
}
render() {
const { dataset } = this.state;
return(
<div className="container profile-container">
{dataset && this.displayProfile(dataset)}
</div>
);
}
}
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {
loadingAction: (value, message) => dispatch(loadingAction(value, message)),
};
};
export default connect(mapStateToProps, mapDispatchToProps) (Dataset);<file_sep>/al/src/components/datasets/Datasets.js
import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { DATA_API, CONFIG } from '../../utils/api/api';
// actions
import { loadingAction } from '../../actions/loading-actions';
import './css/datasets.css';
class Datasets extends React.Component {
constructor(props) {
super(props);
this.state = {
datasets: []
}
}
componentDidMount = () => {
this.loadData();
}
loadData = () => {
this.props.loadingAction(true, "Chargement des données...");
axios.get(`${DATA_API}/datasets`)
.then(res => {
this.setState({ datasets: res.data });
this.props.loadingAction(false, "");
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
deleteDataset = (datasetId) => {
this.props.loadingAction(true, "Suppression...");
axios.delete(`${DATA_API}/datasets/${datasetId}`, CONFIG)
.then(res => {
this.loadData();
})
.catch(err => {
this.props.loadingAction(false, "");
})
}
getFinishRate = (total, finished) => {
if(finished > 0 && total > 0)
return (finished * 100) / total;
return 0;
}
displayDatasetsTable = (datasetsArray) => {
if(datasetsArray === undefined || datasetsArray.length === 0) {
return(
<div className="dts-empty-content-container">
<p>0 modèles</p>
</div>
);
}
else {
return(
<table className="u-full-width">
<thead>
<tr>
<th>Modèle</th>
<th># labels</th>
<th># doc.</th>
<th># doc. test</th>
<th># doc. entrainés</th>
<th># doc. prêts</th>
<th>Complétion</th>
<th>Stats</th>
<th></th>
</tr>
</thead>
<tbody>
{datasetsArray.map((item, index) => (
<tr key={index}>
<td><Link to={`/donnees/${item._id}`}>{item.model}</Link></td>
<td>{item.labels.length}</td>
<td>{item.docs.length}</td>
<td>{item.test.length}</td>
<td>{item.trained.length}</td>
<td>{item.ready.length}</td>
<td>{`${this.getFinishRate(item.docs.length, (item.trained.length + item.test.length)).toFixed(0)} %`}</td>
<td><Link to={`/donnees/${item._id}/stats`}>stats</Link></td>
<td>
<div className="remove-btn" onClick={() => this.deleteDataset(item._id)}>
<svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-trash-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5a.5.5 0 0 0-1 0v7a.5.5 0 0 0 1 0v-7z"/>
</svg>
</div>
</td>
</tr>
))}
</tbody>
</table>
)
}
}
render() {
const { datasets} = this.state;
return(
<div className="dts-container">
<Link to="/donnees/ajout" className="button-primary">
Ajouter
</Link>
<br/>
{`${datasets.length} modèle(s) trouvé(s)`}
<div className="dts-content">
{this.displayDatasetsTable(datasets)}
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {
loadingAction: (value, message) => dispatch(loadingAction(value, message)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Datasets);<file_sep>/al/src/components/datasets/functions/create-dataset.js
export function nameAlreadyExist(datasets, newName) {
for(let d in datasets) {
if(datasets[d].name === newName)
return true;
}
return false;
}
export function modelAlreadyExist(datasets, newModel) {
for(let d in datasets) {
if(datasets[d].model === newModel)
return true;
}
return false;
}
export function Dataset(model, docs, labels, ready, trained, test) {
const dataset = {
model: model,
docs: docs,
labels: labels,
ready: ready,
trained: trained,
test: test
};
return dataset;
}
export function importDataToTextareaFromFile(file, textarea) {
const reader = new FileReader();
reader.onloadend = function (e) {
textarea.value = reader.result;
}
reader.readAsText(file);
}
export function shuffle(array) {
for(let i = array.length - 1; i > 0; i--){
const j = Math.floor(Math.random() * i)
const temp = array[i]
array[i] = array[j]
array[j] = temp
}
return array;
}
export function textToDoc(text) {
const doc = {
text: text,
ents: [],
confidence: 0
}
return doc;
}<file_sep>/al/src/reducers/loading-reducer.js
const initialState = {
loading: false,
loadingMessage: ""
};
const loadingReducer = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_LOADING':
let loading = action.payload.value;
let loadingMessage = action.payload.message;
return {
...state,
loading,
loadingMessage
};
default: return state
}
}
export default loadingReducer; | 1fcd784c673148af6f8b31b7976a2a0996cc39fc | [
"JavaScript",
"Python"
] | 16 | Python | AndyRazafy/datalabs | 7cda6adeb753758cb3f3741611e251b11676ba2b | 0c6d5632c1a106fc6f9365907a455e9f80732792 |
refs/heads/master | <file_sep># Complete the insert function in your editor so that it creates a new Node
# (pass data as the Node constructor argument) and inserts it at the tail of the
# linked list referenced by the head parameter. Once the new node is added,
# return the reference to the head node.
# Note: If the head argument passed to the insert function is null,
# then the initial list is empty.
###
# okay so I still don't think I fully get everything about this, but I managed to
# do it with this general tutorial:
# https://www.youtube.com/watch?v=JlMyYuY1aXU
# and this also helps about the idea:
# https://www.youtube.com/watch?v=JlMyYuY1aXU
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
if head == None:
head = Node(data)
else:
current = head
while current.next != None:
current = current.next
# once we reach the next = none we get to a new Node:
current.next = Node(data)
return head
#Complete this method
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
<file_sep>#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
arr = []
# get the symbols as stripped strings
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
# init a hourglass sum which is infinitely small
hourglass = -math.inf
# create hourglass sums
for i in range(4):
for j in range(4):
hourglassnew = arr[i][j]+arr[i][1+j]+arr[i][2+j]+arr[i+1][1+j]+arr[i+2][0+j]+arr[i+2][1+j]+arr[i+2][2+j]
# if the hourglass sum is greater than the previous one, add it
if hourglassnew > hourglass:
hourglass = hourglassnew
print(hourglass) # print result
<file_sep># this is the first file I imported using git and my terminal
# yayyy!! :)
# The task was to count the maximum consecutive 1's
# in an input converted to binary.
# the script should be self-explanatory, I will add more descriptions
# to future code ;)
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
assert 1 <= n <= 10**6
binary = bin(n)[2:]
counter = 0
saved = int()
for i in range(0, len(binary)):
if binary[i] == "1":
counter +=1
if binary[i] == "0":
counter = 0
if counter > saved:
saved = counter
print(saved)
<file_sep>#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
if n == 1:
return(1)
else:
# create a list for the numbers to multiply
number = []
for i in reversed(range(1, n+1)):
number.append(i)
# now multiply all items of that list:
# number[1]*number[1+1]*number[1+2...]
result = 1
for j in range(0, len(number)):
try:
# what it should do:
print(number[j], "times", number[j+1])
except IndexError:
break
# I don't know why the following works, but it works
result = result * number[0+j]
return(result)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
# The open function opens a file and gives you a file object used to access the file's contents according to the specified modes.
#The "w" mode supplied in your example opens a file for reading, discarding any data previously in that file.
#The os.environ is used to get the environmental variables.
# https://www.reddit.com/r/learnpython/comments/99fktz/came_across_this_in_hackerrank/
n = int(input())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
<file_sep>######
#useful videos on this topic:
# basic classes: https://www.youtube.com/watch?v=ZDa-Z5JzLYM
# Python Objects (4 Parts): https://www.youtube.com/watch?v=u9xZE5t9Y30
# Part 4 goes into the concept of inheritance which is also used here
# abstract classes: https://www.youtube.com/watch?v=PDMe3wgAsWg
from abc import ABCMeta, abstractmethod
# this code was there:
class Book(object, metaclass=ABCMeta): # create class
def __init__(self,title,author):
self.title=title # assign title to title
self.author=author # assign author to author
@abstractmethod
def display(): pass # this means that we HAVE TO implement a display method
# into the subclass MyBook
# this code is new:
#Write MyBook class
class MyBook(Book): # this includes the above class Book (Inheritance)
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def display(self): # don't forget the "self" in parantheses!
print("Title: " + title + "\nAuthor: " + author + "\nPrice: " + str(price))
###
#this code was there:
title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()
<file_sep># I did not know classes before, here is a very helpful tutorial
# on youtube: https://www.youtube.com/watch?v=ZDa-Z5JzLYM
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print("Name:", self.lastName + ",", self.firstName)
print("ID:", self.idNumber)
class Student(Person):
# Class Constructor
#
# Parameters:
# firstName - A string denoting the Person's first name.
# lastName - A string denoting the Person's last name.
# id - An integer denoting the Person's ID number.
# scores - An array of integers denoting the Person's test scores.
#
# Write your constructor here
def __init__(self, firstName, lastName, idNum, scores):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNum #note that idNumber refers to the Person class
self.scores = scores
# Function Name: calculate
# Return: A character denoting the grade.
#
# Write your function here
def calculate(self):
average = sum(self.scores)/len(self.scores)
if 90 <= average <= 100:
return 'O'
if 80 <= average < 90:
return 'E'
if 70 <= average < 80:
return 'A'
if 55 <= average < 70:
return 'P'
if 40 <= average < 55:
return 'D'
return 'T'
line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())
<file_sep># Task
#Complete the Difference class by writing the following:
# A class constructor that takes an array of integers as a parameter and saves
# it to the elements instance variable.
# A computeDifference method that finds the maximum absolute difference between
# any 2 numbers in N and stores it in the maximumDifference instance variable.
# This is probably not the solution they wanted
# They say "to find the maximum difference, computeDifference checks each
# element in the array and finds the maximum difference between any 2 elements...
# What I did was just taking the max and min to create the difference.
# Alternatively one would use a for loop. But this solution went through all the
# test cases, so yeah... let's count it ;P
class Difference:
def __init__(self, a):
self.__elements = a
# Add your code here
def computeDifference(self):
minimum = min(self.__elements)
maximum = max(self.__elements)
self.maximumDifference = maximum - minimum
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
<file_sep>#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
assert 1<=N<=100, "Error!"
if N % 2 != 0:
print("Weird")
# If is even and in the inclusive range of to , print Not Weird
if N % 2 == 0:
if 2 <= N <= 5:
print("Not Weird")
if 6 <= N <= 20:
print("Weird")
if N > 20:
print("Not Weird")
| c018bf2ba42cd957616687e17c9cf10bc211d382 | [
"Python"
] | 8 | Python | glaswasser/30DaysOfCode_Python | 6db77d1e3a2db621615c305c0a693d57e9913719 | 5b47cf2da290d4508e623b40477a7a9c5b6b9861 |
refs/heads/master | <file_sep>// CALCULATOR.JS
//
//
//
//
var Calc = {
Model : {
memory : 0,
op: "",
display : 1,
substr: "",
isDot: 0,
isEval: 0
},
View : {
textRow : {id: "textRow", type: "text", value: "", onclick:""},
button7 : {id: "button7", type: "button", value: 7, onclick:""},
button8 : {id: "button8", type: "button", value: 8, onclick:""},
button9 : {id: "button9", type: "button", value: 9, onclick:""},
button4 : {id: "button4", type: "button", value: 4, onclick:""},
button5 : {id: "button5", type: "button", value: 5, onclick:""},
button6 : {id: "button6", type: "button", value: 6, onclick:""},
button1 : {id: "button1", type: "button", value: 1, onclick:""},
button2 : {id: "button2", type: "button", value: 2, onclick:""},
button3 : {id: "button3", type: "button", value: 3, onclick:""},
button0 : {id: "button0", type: "button", value: 0, onclick:""},
buttonDot : {id: "buttonDot", type: "button", value: ".", onclick:""},
buttonMinus : {id: "buttonMinus", type: "button", value: "-", onclick:""},
buttonTimes : {id: "buttonTimes", type: "button", value: "*", onclick:""},
buttonDiv : {id: "buttonDiv", type: "button", value: "/", onclick:""},
buttonEqual : {id: "buttonEqual", type: "button", value: "=", onclick:""},
buttonClear : {id: "buttonClear", type: "button", value: "C", onclick:""},
buttonMR : {id: "buttonMR", type: "button", value: "MR", onclick:""},
buttonMMinus : {id: "buttonMMinus", type: "button", value: "M-", onclick:""},
buttonMPlus : {id: "buttonMPlus", type: "button", value: "M+", onclick:""},
buttonMClear : {id: "buttonMClear", type: "button", value: "MC", onclick:""},
buttonPlus : {id: "buttonPlus", type: "button", value: "+", onclick:""}
},
Controller : {
buttonsHandler : function(currVal) {
Calc.Model.isEval = 0;
if(currVal == "M+"){
if(textRow.value != ""){
Calc.Model.memory = eval(Calc.Model.memory + "+(" + textRow.value + ")");
if(textRow.value.indexOf(".") > -1){
Calc.Model.isDot = 1;
}
else{
Calc.Model.isDot = 0;
}
}
Calc.Model.display = 0;
}
else if(currVal == "M-"){
if(textRow.value != ""){
Calc.Model.memory = eval(Calc.Model.memory + "-(" + textRow.value +")");
if(textRow.value.indexOf(".") > -1){
Calc.Model.isDot = 1;
}
else{
Calc.Model.isDot = 0;
}
}
Calc.Model.display = 0;
}
else if(currVal == "MR"){
textRow.value = Calc.Model.memory;
Calc.Model.display = 0;
if(textRow.value.indexOf(".") > -1){
Calc.Model.isDot = 1;
}
else{
Calc.Model.isDot = 0;
}
}
else if(currVal == "MC"){
Calc.Model.memory = 0;
Calc.Model.display = 0;
if(textRow.value.indexOf(".") > -1){
Calc.Model.isDot = 1;
}
else{
Calc.Model.isDot = 0;
}
}
else if(currVal == "C"){
textRow.value = "";
Calc.Model.display = 0;
Calc.Model.isDot = 0;
Calc.Model.op = "";
}
else if(currVal == "."){
if(Calc.Model.isDot == 0){
textRow.value += currVal;
Calc.Model.isDot = 1;
}
Calc.Model.display = 0;
}
else{
if(currVal == "+"){
Calc.Model.op = "+";
Calc.Model.isDot = 0;
}
else if(currVal == "-"){
Calc.Model.op = "-";
Calc.Model.isDot = 0;
}
else if(currVal == "*"){
Calc.Model.op = "*";
Calc.Model.isDot = 0;
}
else if(currVal == "/"){
Calc.Model.op = "/";
Calc.Model.isDot = 0;
}
Calc.Model.display = 1;
}
if(Calc.Model.display == 1)
{
if(textRow.value === 0){
textRow.value = currVal;
}
else
{
textRow.value += currVal;
}
}
},
eval: function(){
if(Calc.Model.isEval == "1")
{
textRow.value = eval(textRow.value + Calc.Model.substr);
}
else
{
if(Calc.Model.op != "" && textRow.value != "")
{
Calc.Model.substr = textRow.value.substr(textRow.value.lastIndexOf(Calc.Model.op),textRow.value.length);
textRow.value = eval(textRow.value);
Calc.Model.isEval = 1;
Calc.Model.op = "";
}
}
if(textRow.value.indexOf(".") > -1){
Calc.Model.isDot = 1;
}
}
},
run : function() {
Calc.attachHandlers();
return Calc.display();
},
displayElement : function (element) {
var s = "<input ";
s += " id=\"" + element.id + "\"";
s += " type=\"" + element.type + "\"";
s += " value= \"" + element.value + "\"";
s += " onclick= \"" + element.onclick + "\"";
s += ">";
return s;
},
display : function() {
var s;
s = "<table id=\"myTable\">";
s += "<tr>" + Calc.displayElement(Calc.View.textRow) + "</tr>";
s += "<tr>";
s += "<td>" + Calc.displayElement(Calc.View.button7) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.button8) + "</td>";
s += "<td>" +Calc.displayElement(Calc.View.button9) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonPlus) + "</td>";
s += "</tr>";
s += "<tr>";
s += "<td>" + Calc.displayElement(Calc.View.button4) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.button5) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.button6) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonMinus) + "</td>";
s += "</tr>";
s += "<tr>";
s += "<td>" + Calc.displayElement(Calc.View.button1) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.button2) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.button3) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonTimes) + "</td>";
s += "</tr>";
s += "<tr>";
s += "<td>" + Calc.displayElement(Calc.View.button0) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonDot) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonEqual) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonDiv) + "</td>";
s += "</tr>";
s += "<tr>";
s += "<td>" + Calc.displayElement(Calc.View.buttonClear) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonMR) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonMMinus) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonMPlus) + "</td>";
s += "<td>" + Calc.displayElement(Calc.View.buttonMClear) + "</td>";
s += "</tr>";
s += "</table>";
return s;
},
attachHandlers : function() {
for (var i = 0; i <= 9; i++) {
Calc.View["button" + i].onclick ="Calc.Controller.buttonsHandler(this.value)";
}
Calc.View.buttonPlus.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonMinus.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonTimes.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonDiv.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonEqual.onclick = "Calc.Controller.eval()";
Calc.View.buttonMPlus.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonMMinus.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonMR.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonClear.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonDot.onclick = "Calc.Controller.buttonsHandler(this.value)";
Calc.View.buttonMClear.onclick = "Calc.Controller.buttonsHandler(this.value)";
},
} // end of Calc;
| b8ed509cb8e739c8830ae5eac16a7de6d567686e | [
"JavaScript"
] | 1 | JavaScript | chiajun93/COMS319_Lab5 | f625d9f8ee019adefba169af7fec9ea9033e2bc1 | 8b572ca9870a0a32d3f4c7f4abfc843121855bb4 |
refs/heads/master | <repo_name>dagursunil/DownloadDemo<file_sep>/downlodDemo/src/test/java/com/sk/download/service/impl/DownloadHTTPFileServiceImplTests.java
package com.sk.download.service.impl;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class DownloadHTTPFileServiceImplTests {
@Autowired
private DownloadHTTPFileServiceImpl httpService;
String inputUrl = "https://www.google.com/doodles";
@Test
public void testResponseFromUrl() throws IOException {
httpService = new DownloadHTTPFileServiceImpl();
int responseCode = httpService.getRepornseFromURL(inputUrl.trim());
assertEquals(200, responseCode);
}
@Test(expected = IOException.class)
public void testResponseFromUrlWhenUrlUnknown() throws IOException {
String inputUrlUn = "https://www.testone.com/";
httpService = new DownloadHTTPFileServiceImpl();
httpService.getRepornseFromURL(inputUrlUn.trim());
}
@Test
public void testgetFileName() throws IOException {
testResponseFromUrl();
String fileName = "";
fileName = httpService.getFileName(inputUrl, fileName);
assertEquals("doodles", fileName);
}
}
<file_sep>/downlodDemo/src/main/java/com/sk/download/util/FilesUtil.java
package com.sk.download.util;
import java.io.File;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author sunil
*
*/
public class FilesUtil {
public static String SERVER = "server";
public static String PORT = "port";
public static String USERNAME = "username";
public static String PASSWORD = "<PASSWORD>";
public static String PATH = "path";
public static boolean isValidPath(String path) {
try {
Paths.get(path);
} catch (InvalidPathException | NullPointerException ex) {
return false;
}
return true;
}
public static boolean locationExists(String path) {
File f = new File(path);
if (f.exists()) {
return true;
}
return false;
}
public static void deleteFile(File downloadedFile) {
if (downloadedFile != null && downloadedFile.exists())
downloadedFile.delete();
}
public static Map<String, String> parseUrl(String url) {
String server = null;
String port = null;
String username = null;
String password = <PASSWORD>;
String path = null;
Map<String, String> urlAttributeMap = new HashMap<>();
url = url.trim();
String params[] = url.split("@");
if (params[0].compareTo("") != 0) {
String paramsfst[] = params[0].split(":");
if (params.length == 1) {
if (paramsfst.length >= 1) {
server = parsePort(paramsfst[0]);
if (paramsfst.length == 2) {
port = parsePort(paramsfst[1]);
}
}
} else {
String paramssec[] = params[1].split(":");
if (paramssec.length >= 1) {
server = parsePort(paramssec[0]);
if (paramssec.length == 2) {
port = parsePort(paramssec[1]);
}
}
if (paramsfst.length == 2) {
username = paramsfst[0];
password = <PASSWORD>];
}
}
if (url.contains("/")) {
path = url.substring(url.indexOf("/"), url.length());
}
}
urlAttributeMap.put(PORT, port);
urlAttributeMap.put(PATH, path);
urlAttributeMap.put(USERNAME, username);
urlAttributeMap.put(PASSWORD, <PASSWORD>);
urlAttributeMap.put(SERVER, server);
return urlAttributeMap;
}
private static String parsePort(String port) {
int i = port.indexOf("/");
if (i == -1) {
return port;
}
return port.substring(0, i);
}
}
<file_sep>/downlodDemo/src/main/java/com/sk/download/service/impl/DownloadHTTPFileServiceImpl.java
package com.sk.download.service.impl;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sk.download.exception.DownloadException;
import com.sk.download.service.DownloadService;
import com.sk.download.util.FilesUtil;
/**
*
* @author sunil
*
*/
public class DownloadHTTPFileServiceImpl implements DownloadService {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private URL url;
HttpURLConnection httpConn;
@Override
public void download(String inputUrl, String outputLocation) throws IOException, DownloadException {
int responseCode = getRepornseFromURL(inputUrl);
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
fileName = getFileName(inputUrl, fileName);
String saveFilePath = "";
if (outputLocation.endsWith("/")) {
saveFilePath = outputLocation + fileName;
} else {
saveFilePath = outputLocation + File.separator + fileName;
}
try (BufferedInputStream in = new BufferedInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath)) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
LOGGER.info("Download file from HTTP server successful.");
} catch (IOException e) {
LOGGER.error("Error while downloading from HTTP server", inputUrl);
File newFile = new File(saveFilePath);
FilesUtil.deleteFile(newFile);
throw new DownloadException("Error while downloading from HTTP server" + inputUrl);
}
} else {
throw new DownloadException("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
public String getFileName(String inputUrl, String fileName) {
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = inputUrl.substring(inputUrl.lastIndexOf("/") + 1, inputUrl.length());
}
LOGGER.info("Content-Type = " + contentType);
LOGGER.info("Content-Disposition = " + disposition);
LOGGER.info("Content-Length = " + contentLength);
LOGGER.info("fileName = " + fileName);
return fileName;
}
public int getRepornseFromURL(String inputUrl) throws IOException {
int responseCode = 0;
try {
url = new URL(inputUrl);
httpConn = (HttpURLConnection) url.openConnection();
responseCode = httpConn.getResponseCode();
} catch (IOException e) {
throw new IOException("Excpetion in getting reponse from URL " + inputUrl);
}
return responseCode;
}
}
<file_sep>/downlodDemo/README.md
# DownloadDemo
This project is implemented to download file from different protocols like HTTP,HTTPS,FTP,SFTP.
# Product ready dependency
1. Logger configuration.
2. To create a ‘fully executable’ jar with Maven use the following plugin configuration:
```xml
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
```
# Points to be noted
a.) A new property 'input.urls' has been introduced which is being used by application to get list of different protocols.values need to be comma separated.
b.) A new property 'output.location' has been introduced which should be a directory available in system.
c.) last value in path separated by '/' is being regarded as file name. For example https://google.com/doodle in this url doodle will be considered as file name.
# How to build
Prerequisite : maven should be installed and enabled.
For executing the project directly from directory please follow steps mentioned below :
Windows :
1.) Go to project directory .
2.) Open command prompt.
3.) Type mvnw clean install
4.) type mvnw spring-boot:run
Unix :
1. cd to project directory.
2.) ./mvnw clean install
3.) ./mvnw spring-boot:run
<file_sep>/downlodDemo/src/test/java/com/sk/download/service/impl/DownloadSFTPFileImplTest.java
package com.sk.download.service.impl;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.sk.download.exception.DownloadException;
import com.sk.download.util.FilesUtil;
public class DownloadSFTPFileImplTest {
DownloadSFTPFileImpl service;
private String url="sftp://demo:password@test.rebex.net:22/pub/example/readme.txt";
private Map<String,String> attributesMap=new HashMap<>();
private String outputLocation="E:/output";
@Before
public void setup() {
service=new DownloadSFTPFileImpl();
String [] urlArr=url.split("//");
attributesMap=FilesUtil.parseUrl(urlArr[1]);
}
@Test
public void testConnectSFTPServer() throws Exception {
service.setDownloadAttributes(attributesMap);
boolean isConnected=service.connectSFTPServer();
assertEquals(true,isConnected);
}
@Test
public void testConnectFailureSFTPServer() throws Exception {
attributesMap.put(FilesUtil.USERNAME, null);
service.setDownloadAttributes(attributesMap);
boolean isConnected=service.connectSFTPServer();
assertEquals(false,isConnected);
}
@Test
public void testdownloadFromFTPServer() throws IOException, DownloadException {
service.setDownloadAttributes(attributesMap);
boolean isDownloaded=service.downloadFromSFTPServer(outputLocation);
assertEquals(true, isDownloaded);
}
@Test(expected = DownloadException.class)
public void testdownloadFailedFromFTPServer() throws IOException, DownloadException {
attributesMap.put(FilesUtil.SERVER,"test.sftp.com");
service.setDownloadAttributes(attributesMap);
boolean isDownloaded=service.downloadFromSFTPServer(outputLocation);
assertEquals(false, isDownloaded);
}
}
<file_sep>/downlodDemo/src/main/java/com/sk/download/downlodDemo/DownloadDemoApplication.java
package com.sk.download.downlodDemo;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.sk.download.exception.DownloadException;
import com.sk.download.service.DownloadService;
import com.sk.download.service.impl.DownloadFTPFileServiceImpl;
import com.sk.download.service.impl.DownloadHTTPFileServiceImpl;
import com.sk.download.service.impl.DownloadSFTPFileImpl;
import com.sk.download.util.FilesUtil;
/**
*
* @author sunil
*
*/
@SpringBootApplication
public class DownloadDemoApplication implements CommandLineRunner {
@Value("${input.urls}")
private String inputurl;
@Value("${output.location}")
private String outputLocation;
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
public static void main(String[] args) {
SpringApplication.run(DownloadDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
downloadFromInputList(inputurl);
}
public void downloadFromInputList(String inputurl) {
String[] inputUrlArr = inputurl.split(",");
ExecutorService service = Executors.newCachedThreadPool();
if (outputLocation != null && FilesUtil.isValidPath(outputLocation)
&& FilesUtil.locationExists(outputLocation)) {
DownloadService downloadService = null;
for (int i = 0; i < inputUrlArr.length; i++) {
String inputUrl = inputUrlArr[i];
if (inputUrl.startsWith("http") || inputUrl.startsWith("https")) {
downloadService = new DownloadHTTPFileServiceImpl();
downloadService(inputurl, service, inputUrl, downloadService);
} else if (inputUrl.startsWith("ftp")) {
downloadService = new DownloadFTPFileServiceImpl();
downloadService(inputurl, service, inputUrl, downloadService);
} else if (inputUrl.startsWith("sftp")) {
downloadService = new DownloadSFTPFileImpl();
downloadService(inputurl, service, inputUrl, downloadService);
}
}
} else {
LOGGER.error("Invalid output location", outputLocation);
}
service.shutdown();
}
private void downloadService(String inputurl, ExecutorService service, String inputUrl,
DownloadService downloadService) {
service.submit(() -> {
try {
downloadService.download(inputUrl, outputLocation);
} catch (DownloadException | IOException e) {
LOGGER.error("Error in downloading from URL " + inputurl);
e.printStackTrace();
}
});
}
}
<file_sep>/downlodDemo/src/test/java/com/sk/download/downloadDemo/DownloadDemoTestSuite.java
package com.sk.download.downloadDemo;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import com.sk.download.service.impl.DownloadFTPFileServiceImplTests;
import com.sk.download.service.impl.DownloadHTTPFileServiceImplTests;
import com.sk.download.service.impl.DownloadSFTPFileImplTest;
import com.sk.download.util.FileUtilsTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
DownloadFTPFileServiceImplTests.class,
DownloadSFTPFileImplTest.class,
DownloadHTTPFileServiceImplTests.class,
FileUtilsTest.class
})
public class DownloadDemoTestSuite {
}
<file_sep>/downlodDemo/src/test/java/com/sk/download/downloadDemo/DownloadDemoApplicationTest.java
package com.sk.download.downloadDemo;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.sk.download.downlodDemo.DownloadDemoApplication;
@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
"input.urls=https://google.com/doodles,ftp://demo-user:demo-user@demo.wftpserver.com/download/manual_en.pdf,sftp://demo:password@test.rebex.net:22/pub/example/readme.txt" })
public class DownloadDemoApplicationTest {
@Value("${input.urls}")
private String inputurl;
DownloadDemoApplication downloadDemoApplication;
long timeoutExpiredMs = System.currentTimeMillis() + 15000;
@Before
public void setup() {
downloadDemoApplication = new DownloadDemoApplication();
org.springframework.test.util.ReflectionTestUtils.setField(downloadDemoApplication, "outputLocation",
"E:/output");
}
@Test
public void main() {
DownloadDemoApplication.main(new String[] {});
}
@Test
public void testDownloadFromInputList() throws Exception {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
int threadCountBefore = bean.getThreadCount();
downloadDemoApplication.downloadFromInputList(inputurl);
int threadCountAfter = bean.getThreadCount();
// As three new threads have been launched ,so checking for there execution
// completion
while (threadCountAfter != threadCountBefore) {
long waitMillis = timeoutExpiredMs - System.currentTimeMillis();
if (waitMillis <= 0) {
System.out.println("Time out reached");
break;
}
Thread.sleep(1000);
threadCountAfter = bean.getThreadCount();
}
}
}
<file_sep>/downlodDemo/src/main/java/com/sk/download/service/impl/DownloadSFTPFileImpl.java
package com.sk.download.service.impl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.sk.download.exception.DownloadException;
import com.sk.download.service.DownloadService;
import com.sk.download.util.FilesUtil;
/**
*
* @author sunil
*
*/
public class DownloadSFTPFileImpl implements DownloadService {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private String server;
private String port;
private String username;
private String password;
private String path;
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
@Override
public void download(String inputUrl, String outputLocation) throws IOException, DownloadException {
String[] urlArr = inputUrl.split("//");
if (urlArr.length > 1) {
Map<String, String> attributesMap = FilesUtil.parseUrl(urlArr[1]);
if (attributesMap.size() > 0) {
setDownloadAttributes(attributesMap);
downloadFromSFTPServer(outputLocation);
} else {
throw new DownloadException("Input URL incorrect .Please verify the same.");
}
} else {
throw new DownloadException("Input URL incorrect .Please verify the same.");
}
}
public void setDownloadAttributes(Map<String, String> attributesMap) {
this.server = attributesMap.get(FilesUtil.SERVER);
this.port = attributesMap.get(FilesUtil.PORT);
this.path = attributesMap.get(FilesUtil.PATH);
this.username = attributesMap.get(FilesUtil.USERNAME);
this.password = attributesMap.get(FilesUtil.PASSWORD);
}
public boolean downloadFromSFTPServer(String outputLocation) throws IOException, DownloadException {
File newFile = null;
try {
boolean isConnected = connectSFTPServer();
if (isConnected) {
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
String pathValue = this.path.substring(0, this.path.lastIndexOf("/"));
String file = this.path.substring(path.lastIndexOf("/") + 1, path.length());
if (!pathValue.isEmpty()) {
channelSftp.cd(pathValue);
}
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(channelSftp.get(file));
if (outputLocation.endsWith("/")) {
newFile = new File(outputLocation + file);
} else {
newFile = new File(outputLocation + "/" + file);
}
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
LOGGER.info("Writing to file: ");
bos.write(buffer, 0, readCount);
}
LOGGER.info("Download successful from sftp server ");
bis.close();
bos.close();
if (session.isConnected()) {
session.disconnect();
}
return true;
} else {
throw new DownloadException("Could not connect to Server " + this.server);
}
} catch (Exception ex) {
FilesUtil.deleteFile(newFile);
LOGGER.error("File download failed from server ", this.server);
if (session.isConnected()) {
session.disconnect();
}
throw new DownloadException(ex.getMessage());
}
}
public boolean connectSFTPServer(){
try {
JSch jsch = new JSch();
if (this.port != null && !this.port.isEmpty()) {
this.port = this.port.trim();
session = jsch.getSession(this.username, this.server, Integer.parseInt(this.port));
} else {
session = jsch.getSession(this.username, this.server);
}
session.setPassword(this.password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
return session.isConnected();
} catch (JSchException|NumberFormatException e) {
LOGGER.error("Connection failed to server "+server);
return false;
}
}
public String getServer() {
return server;
}
public String getPort() {
return port;
}
public String getUsername() {
return username;
}
public String getPath() {
return path;
}
}
| f431b6ff66348b35c06ad145db5cc30c024dc204 | [
"Markdown",
"Java"
] | 9 | Java | dagursunil/DownloadDemo | 1d492a1d2dee72115705b4a306589f265ab6369b | e2314d4c2a768140d57866b032d8755fa2385075 |
refs/heads/master | <file_sep>from sqlalchemy import (
create_engine,
MetaData,
)
from sqlalchemy.orm import (
sessionmaker,
scoped_session,
)
from ..config import AppConfig
from .models import Base
from contextlib import contextmanager
from sqlalchemy.dialects.postgresql import insert
from alembic.config import Config
from alembic import command
"""
doing:
import alembic
and then using
alembic.config.Config
does not work, the above is the way their documentation suggests you do this.
Since it's not an issue with relative/absolute imports on my end, as the same
thing happens in the python shell in any directory/package, clearly they're
doing some import-related shenanigans.
"""
from pathlib import Path
engine = create_engine(AppConfig.DATABASE_URI)
Session = sessionmaker(bind=engine)
alembic_config_path = AppConfig.PROJECT_DIRECTORY / 'backend/alembic.ini'
def recreate_database():
metadata = MetaData()
metadata.reflect(bind=engine)
metadata.drop_all(engine)
Base.metadata.create_all(engine)
alembic_cfg = Config(alembic_config_path)
command.stamp(alembic_cfg, "head")
@contextmanager
def contextual_session(*args, **kwargs):
session = Session(*args, **kwargs)
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
db_session = scoped_session(sessionmaker(bind=engine))
def insert_if_not_exists(session, model, rows):
table = model.__table__
stmt = insert(table).values(rows)
on_conflict_stmt = stmt.on_conflict_do_nothing(
index_elements=table.primary_key.columns,
)
session.execute(on_conflict_stmt)
if __name__ == "__main__":
from models import *
with contextual_session() as session:
import pdb;pdb.set_trace()
pass
<file_sep>import csv
from .models import (
MyFitnessPal
)
from datetime import datetime
from .crud import contextual_session
import argparse
<file_sep>from flask import Flask
from ..config import AppConfig
from flask_login import LoginManager
from ..backend.crud import db_session
login_manager = LoginManager()
def create_app():
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(AppConfig)
app.session = db_session
login_manager.init_app(app)
with app.app_context():
from .home import home
from .auth import auth
from . import callbacks
app.register_blueprint(home.home_bp)
app.register_blueprint(auth.auth_bp)
from .plotlydash.dashboard import create_dashboard
app = create_dashboard(app)
return app
<file_sep>from dash import Dash
from .callbacks import register_callbacks
from .layout import layout as dash_layout
from flask_login import login_required
def create_dashboard(server):
dash_app = Dash(
server=server,
routes_pathname_prefix='/dashboard/',
)
dash_app.layout = dash_layout
register_callbacks(dash_app)
_protect_dash_views(dash_app)
return dash_app.server
def _protect_dash_views(dash_app):
for view_func in dash_app.server.view_functions:
if view_func.startswith(dash_app.config.routes_pathname_prefix):
dash_app.server.view_functions[view_func] = login_required(dash_app.server.view_functions[view_func])
<file_sep>from flask import current_app as app
@app.teardown_appcontext
def shutdown_session(exception=None):
app.session.remove()
<file_sep>from passlib.context import CryptContext
pwd_context = CryptContext(
schemes=[
'argon2',
],
deprecated='auto',
)
<file_sep>from dash.dependencies import (
Input,
Output,
)
from flask_login import current_user
from flask import current_app as app
from dash.dependencies import (
Input,
Output,
)
import pandas as pd
from plotly import (
express as px,
graph_objects as go,
)
from ...backend.models import(
AppUser,
MoodSurveyResponse,
SleepSurveyResponse,
)
metric_checklist_kwargs = {
'options': [
{'label': 'Daily Mood (1-5)', 'value': 'DMD'},
{'label': 'Sleep Hours', 'value': 'HRS'},
{'label': 'Sleep Quality (1-5)', 'value': 'QLT'},
{'label': 'Rise Ease (1-5)', 'value': 'EAS'},
{'label': 'Adderal Crash (0-3)', 'value': 'CRS'},
{'label': 'Energy (1-5)', 'value': 'ENR'},
],
'value': [
'DMD',
'HRS',
],
'labelStyle': {
'display': 'inline-block',
}
}
metric_column_map = {
'HRS': 'sleep_hours',
'QLT': 'sleep_quality',
'EAS': 'rise_ease',
'DMD': 'mood',
'CRS': 'adderall_crash',
'ENR': 'energy',
}
def register_callbacks(dash_app):
@dash_app.callback(Output('metric-graph', 'figure'), [Input('metric-checklist', 'value')])
def update_graph(metrics):
if current_user.is_authenticated:
mood_survey_data = pd.read_sql(
app.session.query(
MoodSurveyResponse.mood,
MoodSurveyResponse.adderall_crash,
MoodSurveyResponse.energy,
MoodSurveyResponse.date_time,
).filter(
MoodSurveyResponse.app_user == current_user
).statement,
app.session.bind,
)
sleep_survey_data = pd.read_sql(
app.session.query(
SleepSurveyResponse.sleep_hours,
SleepSurveyResponse.date_time,
SleepSurveyResponse.sleep_quality,
SleepSurveyResponse.rise_ease,
).filter(
SleepSurveyResponse.app_user == current_user
).statement,
app.session.bind
)
mood_survey_data.set_index('date_time')
sleep_survey_data.set_index('date_time')
combined_data = pd.merge(sleep_survey_data, mood_survey_data, how='outer')
# import pdb;pdb.set_trace()
fig = go.Figure()
for metric in metrics:
column_name = metric_column_map[metric]
fig.add_trace(
go.Scatter(
x=combined_data['date_time'],
y=combined_data[column_name],
mode='lines',
name=column_name,
)
)
return fig
else:
return {
"layout": {
"xaxis": {
"visible": false
},
"yaxis": {
"visible": false
},
"annotations": [
{
"text": "No matching data found",
"xref": "paper",
"yref": "paper",
"showarrow": false,
"font": {
"size": 28
}
}
]
}
}
<file_sep>import argparse
import gspread
from .models import (
MoodSurveyResponse,
SleepSurveyResponse,
AppUser,
)
from dateutil.parser import parse
from .crud import (
insert_if_not_exists,
contextual_session,
)
survey_types = {
'mood': "Daily Mood Survey (Responses)",
'sleep': "Daily Sleep Survey (Responses)",
}
def download_gforms_data(session, user):
user_email = user.email
gspread_client = gspread.oauth()
for survey_type, spreadsheet_name in survey_types.items():
response_spreadsheet = gspread_client.open(spreadsheet_name)
response_worksheet = response_spreadsheet.get_worksheet(0)
unfiltered_survey_responses = response_worksheet.get_all_records()
user_survey_responses = [
response for response in unfiltered_survey_responses
if response['Email Address'] == user.email
]
add_survey_responses_to_database(session, user, survey_type, user_survey_responses)
def add_survey_responses_to_database(session, user, survey_type, survey_responses):
user_id = user.id
rows = []
if survey_type == 'mood':
model = MoodSurveyResponse
for survey_response in survey_responses:
row = {
"mood": survey_response['Mood'],
"energy": survey_response['Energy'],
"sleep_hours": survey_response['Sleep Hours'],
"adderall_crash": survey_response['Adderall Crash'],
"date_time": parse(survey_response['Timestamp']),
"app_user_id": user_id,
}
rows.append(row)
elif survey_type == 'sleep':
model = SleepSurveyResponse
for survey_response in survey_responses:
row = {
"sleep_quality": survey_response['Quality'],
"sleep_hours": survey_response['Hours'],
"rise_ease": survey_response['Rise'],
"date_time": parse(survey_response['Timestamp']),
"app_user_id": user_id,
}
rows.append(row)
insert_if_not_exists(session, model, rows)
def download_gforms_responses_for_user(user_id):
with contextual_session() as session:
user = session.query(AppUser).get(user_id)
download_gforms_data(session, user)
<file_sep>from .forms import (
LoginForm,
)
from ..backend.models import (
AppUser,
)
from ..backend.crud import (
contextual_session,
)
from flask import (
current_app as app,
render_template,
flash,
redirect,
url_for,
)
from flask_login import (
current_user,
)
@app.route('/')
@app.route('/index')
def index():
user = current_user
title = 'LifeTracker'
template_vars = {
'user': current_user,
'title': title,
}
return render_template('index.html', **template_vars)
<file_sep>import gspread
gc = gspread.oauth()
sh = gc.open("Example spreadsheet")
print(sh.sheet1.get('A1'))
<file_sep>import os
from dotenv import load_dotenv
from pathlib import Path
project_directory = Path(__file__).parent.absolute()
flask_env_path = project_directory / '.flaskenv'
backend_env_path = project_directory / '.dbenv'
load_dotenv(dotenv_path=flask_env_path)
load_dotenv(dotenv_path=backend_env_path)
class AppConfig(object):
PROJECT_DIRECTORY = project_directory
DATABASE_URI = os.getenv(
'DATABASE_URI',
)
SECRET_KEY = os.getenv(
'FLASK_SECRET_KEY',
)
FLASK_ENV = os.getenv(
'FLASK_ENV',
)
FLASK_APP = os.getenv(
'FLASK_APP',
)
<file_sep>from life_tracker.backend.gforms_wrapper import (
download_gforms_responses_for_user,
)
from life_tracker.backend.models import AppUser
from life_tracker.backend.crud import contextual_session
user_id = 1
if __name__ == '__main__':
download_gforms_responses_for_user(user_id)
<file_sep>from .forms import (
LoginForm,
RegistrationForm,
)
from flask import (
current_app as app,
Blueprint,
render_template,
flash,
redirect,
url_for,
)
from flask_login import (
current_user,
login_user,
logout_user,
login_required,
)
from .. import (
login_manager
)
from ...backend.models import AppUser
auth_bp = Blueprint(
'auth_bp', __name__,
template_folder='templates',
static_folder='static',
)
@login_manager.user_loader
def load_user(id):
return app.session.query(AppUser).get(int(id))
def unauthorized():
flash('You must be logged in to view that page')
return redirect(url_for('home_bp.login'))
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
failed_login_message = 'Invalid email or password.'
# We don't need to log in a user who's already logged in
if current_user.is_authenticated:
return redirect(url_for('home_bp.index'))
# The user has submitted a login form, if they exist log them in
# otherwise, give a generic and unhelpful error (to avoid exploits)
form = LoginForm()
if form.validate_on_submit():
user = app.session.query(AppUser).filter_by(email=form.email.data).first()
if user is None or not user.check_password(form.password.data):
flash(failed_login_message)
return redirect(url_for('auth_bp.login'))
login_user(user, remember=form.remember_me.data)
return redirect(url_for('home_bp.index'))
# The user has not submitted a login form, therefore render it unto them
return render_template(
'login.html',
title='Sign In',
form=form
)
@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('home_bp.index'))
form = RegistrationForm()
if form.validate_on_submit():
user = AppUser(
first_name=form.first_name.data,
last_name=form.last_name.data,
email=form.email.data,
)
user.set_password(form.password.data)
app.session.add(user)
app.session.commit()
flash('Welcome {}, you are now a registerd user!'.format(user.first_name))
return redirect(url_for('auth_bp.login'))
return render_template('register.html', title='Register', form=form)
@auth_bp.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('auth_bp.login'))
<file_sep>from flask_wtf import FlaskForm
from wtforms import (
StringField,
PasswordField,
BooleanField,
SubmitField,
)
from wtforms.validators import (
DataRequired,
Email,
Length,
EqualTo,
Optional,
ValidationError,
)
from flask import (
current_app as app,
)
from ...backend.models import (
AppUser,
)
class RegistrationForm(FlaskForm):
"""User registration form."""
first_name = StringField(
'First name',
validators=[
DataRequired(),
],
)
last_name = StringField(
'Last name',
validators=[
Optional(),
],
)
email = StringField(
'Email',
validators=[
Length(min=6),
DataRequired(),
Email(),
],
)
password = PasswordField(
'<PASSWORD>',
validators=[
DataRequired(),
Length(min=6, message='Please choose a stronger password'),
],
)
confirm_password = PasswordField(
'Confirm your password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.'),
],
)
submit = SubmitField('Register')
def validate_email(self, email):
user = app.session.query(AppUser).filter_by(email=email.data).first()
if user is not None:
raise ValidationError('That email is already registered.')
class LoginForm(FlaskForm):
email = StringField(
'Email',
validators=[DataRequired()],
)
password = PasswordField(
'<PASSWORD>',
validators=[DataRequired()],
)
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
<file_sep># LifeTracker
## Technical Documentation
[The wiki](https://github.com/SeanGrady/life_tracker/wiki)
## Why a life tracker?
### Patterns
We are not always adept at recognizing cause/effect patterns that influence our lives. Some of these patterns take place over too long of a time period to be easily noticed. For example, daily vitamin D supplementation can take 2-3 months to noticeably affect mood in the best of cases, and up to a year to completely reverse severe deficiency. Other patterns occur over short timescales but still have too much lag between the cause and the effect to be easily noticed, especially if the link between the two doesn't seem obvious--like the mild "hangover" affect some people get the day _after_ eating too much sugar. Still other patterns affect "noisy" aspects of our lives which many other factors influence. Folks with mood disorders are very familiar with this category: I feel a lot better today, it must be the new morning exercise routine! Or... is it the caffeine I had before lunch? Or that I got more sleep than usual last night? Maybe it was the ibuprofen I took yesterday, I've heard that can have an impact on mood...
The best way to begin addressing these kinds of disconnects is with data. It's a lot easier to notice that you always feel awful the day after you eat too much salt if you can graph your salt intake and daily well-being side by side. There are many different existing solutions that try to solve all or part of this issue, but I have found none that provide all of the three things that are, in my opinion, essential to success:
* **Centralization**: an easy way to get all your data in one place. Food, exercise, sleep, whatever else you happen to be tracking.
* **Personalization**: an easy way to define and track any personal metric that you want to improve. Weight is one example that's pretty well handled by existing solutions, but what about energy levels? Or flexibility? Or chronic symptoms?
* **Pattern Recognition**: an easy way to find correlations and cause/effect relationships in the data. In the simplest case just being able to look at your data side-by-side can reveal surprising things.
### Logging for Humans
We are not always good at answering questions about ourselves and our past behavior, which makes it hard to know if something you're trying to change is actually improving or worsening without being able to go back and look at past data. I track my food consumption meticulously, but if you were to ask me to tell you how many calories I ate per day this week without checking first I would be very confident and probably very wrong.
In a perfect world, you would put all your data into this app and it would immediately pop up a helpful assistant with a dialogue box that said something like "It looks like you're trying to get rid of chronic headaches. You've been skipping lunch a lot, have you tried eating more frequently during the day?" While this is a wonderful long-term goal, it's certainly beyond the scope of a personal project done in one's spare time. We're smart critters, though, and usually we have a pretty good idea of what we might want to change. The hope behind this project is that an easy, customizable, and reliable means of tracking actions and target metrics is enough to help people more effectively help themselves.
## What this project aims to do
* Integrate with as many existing data collection and tracking solutions as possible. Examples are food tracking apps (like LoseIt, MyFitnessPal and Cronometer), or exercise tracking devices (like Fitbit or the Apple Watch).
* Provide a flexible interface for defining your own metrics and logging them. Tags that can be applied to any given day (for example, `headache` if you had a headache that day) are one possible method. Custom survey questions emailed to you every evening asking questions about your day ("On a scale of 1 to 5 how severe was your anxiety today?") are another.
* Make it easy to compare any and all of your data to discover trends over time as well as correlations or cause/effect relationships.
* Allow other people (e.g. personal trainers, primary care doctors, family members) access to some or all of your data.
## What this project does not (currently) aim to do
* Any kind of machine learning involving training models on personal data. This is something I would like to explore as I continue to flesh out the project, but the reality is that aside from some very basic statistical analysis there will almost certainly not be enough data to learn anything meaningful with these methods until users start to have 6 months+ of highly detailed data available.
* Be anywhere near anything HIPAA-related. Currently, the HIPAA regulations say that broadly speaking as long as you don't bill health insurance or work with anyone who does, you are not a covered entity. Therefore, while providing the information in this app to anyone of your choice including your healthcare provider(s) should be easy for a user to do, working with anyone who is a HIPAA-covered entity or business associate is right out.
## What this project may aim to do in the future
* Integrate data that was originally HIPAA-covered PHI, such as lab results obtained with your primary care physician--think tracking cholesterol levels over time. I am not a HIPAA lawyer, but my understanding of the regulations is that if a user independently requests their medical data from their healthcare provider(s) and voluntarily uploads it to an app like this one, it is no longer covered under HIPAA. I will want to consult someone who _is_ a HIPAA lawyer before starting anything like this.
* Implement data analysis and possibly limited machine learning. Already-established-as-useful statistical metrics like heart rate variation day to day (not the beat-to-beat heart rate variability/HRV/RR variability, although that would be good to track) are one option here, as is general statistical analysis like determining possible correlations via pairwise covariance. Bag-of-words sentiment analysis on uploaded journal entries is one possible example of a machine-learning-related method that may also yield useful results, since it can use existing models and does not need to be trained directly on user data.
<file_sep>import unittest
from life_tracker.backend.cronometer import snake_case_cronometer_column_name
class TestSnakeCaseColumnName(unittest.TestCase):
def test_one_word(self):
original_field_name = 'Date'
target_field_name = 'date'
new_field_name = snake_case_cronometer_column_name(original_field_name)
self.assertEqual(new_field_name, target_field_name)
def test_no_parens(self):
original_field_name = 'Food Name'
target_field_name = 'food_name'
new_field_name = snake_case_cronometer_column_name(original_field_name)
self.assertEqual(new_field_name, target_field_name)
def test_one_paren(self):
original_field_name = 'Caffeine (mg)'
target_field_name = 'caffeine_mg'
new_field_name = snake_case_cronometer_column_name(original_field_name)
self.assertEqual(new_field_name, target_field_name)
def test_two_parens(self):
original_field_name = 'B5 (Pantothenic Acid) (mg)'
target_field_name = 'b5_pantothenic_acid_mg'
new_field_name = snake_case_cronometer_column_name(original_field_name)
self.assertEqual(new_field_name, target_field_name)
def test_hyphen(self):
original_field_name = 'Trans-Fats (g)'
target_field_name = 'trans_fats_g'
new_field_name = snake_case_cronometer_column_name(original_field_name)
self.assertEqual(new_field_name, target_field_name)
def test_microgram_nonsense(self):
original_field_name = 'B12 (Cobalamin) (µg)'
target_field_name = 'b12_cobalamin_ug'
new_field_name = snake_case_cronometer_column_name(original_field_name)
self.assertEqual(new_field_name, target_field_name)
if __name__ == '__main__':
unittest.main()
<file_sep>from sqlalchemy import (
Column,
Integer,
String,
Date,
Float,
DateTime,
Time,
Boolean,
ForeignKey,
UniqueConstraint,
)
from sqlalchemy.ext.declarative import (
declarative_base,
declared_attr,
)
from sqlalchemy.orm import (
relationship,
)
from flask_login import UserMixin as FlaskLoginMixin
from .security import (
pwd_context,
)
Base = declarative_base()
class AppUserMixin(object):
@declared_attr
def app_user_id(cls):
return Column(
Integer,
ForeignKey('app_user.id'),
nullable=False,
primary_key=True,
)
class AppUser(FlaskLoginMixin, Base):
__tablename__ = 'app_user'
id = Column(
Integer,
primary_key=True,
nullable=False,
)
password_hash = Column(String)
first_name = Column(String)
last_name = Column(String)
email = Column(
String,
unique=True,
)
mood_survey_responses = relationship(
'MoodSurveyResponse',
backref='app_user',
)
sleep_survey_responses = relationship(
'SleepSurveyResponse',
backref='app_user',
)
weigh_ins = relationship(
'WeighIn',
backref='app_user',
)
loseit_foods = relationship(
'LoseitFood',
backref='app_user',
)
def set_password(self, password):
hashed = self.encrypt_password(password)
self.password_hash = hashed
def check_password(self, password):
return self.check_encrypted_password(password, self.password_hash)
def encrypt_password(self, password):
return pwd_context.encrypt(password)
def check_encrypted_password(self, password, hashed):
return pwd_context.verify(password, hashed)
class LoseitFood(Base, AppUserMixin):
__tablename__ = 'loseit_food'
id = Column(
Integer,
primary_key=True,
nullable=False,
)
raw_date = Column(Date)
raw_name = Column(String)
raw_type = Column(String)
raw_quantity = Column(Float)
raw_units = Column(String)
raw_calories = Column(Integer)
raw_fat_g = Column(Float)
raw_protein_g = Column(Float)
raw_carbohydrates_g = Column(Float)
raw_saturated_fat_g = Column(Float)
raw_sugars_g = Column(Float)
raw_fiber_g = Column(Float)
raw_cholesterol_mg = Column(Float)
raw_sodium_mg = Column(Float)
class DailyLogMixin(object):
@declared_attr
def date(cls):
return Column(
Date,
primary_key=True,
nullable=False,
)
class BodyFatPercentage(Base, AppUserMixin, DailyLogMixin):
__tablename__ = 'body_fat_percentage'
body_fat_percentage = Column(Float)
class WeighIn(Base, AppUserMixin, DailyLogMixin):
__tablename__ = 'weigh_in'
weight_lbs = Column(Float)
class GformResponseMixin(object):
@declared_attr
def date_time(cls):
return Column(
DateTime,
nullable=False,
primary_key=True,
)
class SleepSurveyResponse(Base, AppUserMixin, GformResponseMixin):
__tablename__ = 'sleep_survey_response'
sleep_quality = Column(Integer)
sleep_hours = Column(Float)
rise_ease = Column(Integer)
class MoodSurveyResponse(Base, AppUserMixin, GformResponseMixin):
__tablename__ = 'mood_survey_response'
mood = Column(Integer)
energy = Column(Integer)
adderall_crash = Column(Integer)
sleep_hours = Column(Float)
class CronometerLogExportMixin(object):
"""
Mixin for Cronometer log-type exports -- i.e. those with a separate 'Date'
and 'Time' column. The summary type exports (currently only one) only have
a 'Date' column.
"""
@declared_attr
def time(cls):
return Column(
Time,
nullable=False,
primary_key=True,
)
@declared_attr
def day(cls):
return Column(
Date,
nullable=False,
primary_key=True,
)
@declared_attr
def group(cls):
return Column(
String,
nullable=False,
primary_key=True,
)
class CronometerExercise(Base, AppUserMixin, CronometerLogExportMixin):
__tablename__ = 'cronometer_exercise'
exercise = Column(
String,
nullable=False,
primary_key=True,
)
minutes = Column(Float)
calories_burned = Column(Float)
class CronometerNote(Base, AppUserMixin, CronometerLogExportMixin):
__tablename__ = 'cronometer_note'
note = Column(
String,
nullable=False,
)
class CronometerBiometric(Base, AppUserMixin, CronometerLogExportMixin):
__tablename__ = 'cronometer_biometric'
"""
Overload the CronometerLogExportMixin's time column because for whatever
reason time can be None for biometrics
"""
time = Column(
Time,
nullable=True,
primary_key=False,
)
metric = Column(
String,
nullable=False,
primary_key=True,
)
unit = Column(String)
amount = Column(Float)
class CronometerDailySummary(Base, AppUserMixin):
__tablename__ = 'cronometer_daily_summary'
date = Column(
Date,
nullable=False,
primary_key=True,
)
completed = Column(Boolean)
energy_kcal = Column(Float)
alcohol_g = Column(Float)
caffeine_mg = Column(Float)
water_g = Column(Float)
b1_thiamine_mg = Column(Float)
b2_riboflavin_mg = Column(Float)
b3_niacin_mg = Column(Float)
b5_pantothenic_acid_mg = Column(Float)
b6_pyridoxine_mg = Column(Float)
b12_cobalamin_ug = Column(Float)
folate_ug = Column(Float)
vitamin_a_iu = Column(Float)
vitamin_c_mg = Column(Float)
vitamin_d_iu = Column(Float)
vitamin_e_mg = Column(Float)
vitamin_k_ug = Column(Float)
calcium_mg = Column(Float)
copper_mg = Column(Float)
iron_mg = Column(Float)
magnesium_mg = Column(Float)
manganese_mg = Column(Float)
phosphorus_mg = Column(Float)
potassium_mg = Column(Float)
selenium_ug = Column(Float)
sodium_mg = Column(Float)
zinc_mg = Column(Float)
carbs_g = Column(Float)
fiber_g = Column(Float)
starch_g = Column(Float)
sugars_g = Column(Float)
net_carbs_g = Column(Float)
fat_g = Column(Float)
cholesterol_mg = Column(Float)
monounsaturated_g = Column(Float)
polyunsaturated_g = Column(Float)
saturated_g = Column(Float)
trans_fats_g = Column(Float)
omega_3_g = Column(Float)
omega_6_g = Column(Float)
cystine_g = Column(Float)
histidine_g = Column(Float)
isoleucine_g = Column(Float)
leucine_g = Column(Float)
lysine_g = Column(Float)
methionine_g = Column(Float)
phenylalanine_g = Column(Float)
protein_g = Column(Float)
threonine_g = Column(Float)
tryptophan_g = Column(Float)
tyrosine_g = Column(Float)
valine_g = Column(Float)
class CronometerServing(Base, AppUserMixin, CronometerLogExportMixin):
__tablename__ = 'cronometer_serving'
food_name = Column(
String,
nullable=False,
primary_key=True,
)
amount = Column(
String,
nullable=False,
primary_key=True,
)
category = Column(String)
energy_kcal = Column(Float)
alcohol_g = Column(Float)
caffeine_mg = Column(Float)
water_g = Column(Float)
b1_thiamine_mg = Column(Float)
b2_riboflavin_mg = Column(Float)
b3_niacin_mg = Column(Float)
b5_pantothenic_acid_mg = Column(Float)
b6_pyridoxine_mg = Column(Float)
b12_cobalamin_ug = Column(Float)
folate_ug = Column(Float)
vitamin_a_iu = Column(Float)
vitamin_c_mg = Column(Float)
vitamin_d_iu = Column(Float)
vitamin_e_mg = Column(Float)
vitamin_k_ug = Column(Float)
calcium_mg = Column(Float)
copper_mg = Column(Float)
iron_mg = Column(Float)
magnesium_mg = Column(Float)
manganese_mg = Column(Float)
phosphorus_mg = Column(Float)
potassium_mg = Column(Float)
selenium_ug = Column(Float)
sodium_mg = Column(Float)
zinc_mg = Column(Float)
carbs_g = Column(Float)
fiber_g = Column(Float)
starch_g = Column(Float)
sugars_g = Column(Float)
net_carbs_g = Column(Float)
fat_g = Column(Float)
cholesterol_mg = Column(Float)
monounsaturated_g = Column(Float)
polyunsaturated_g = Column(Float)
saturated_g = Column(Float)
trans_fats_g = Column(Float)
omega_3_g = Column(Float)
omega_6_g = Column(Float)
cystine_g = Column(Float)
histidine_g = Column(Float)
isoleucine_g = Column(Float)
leucine_g = Column(Float)
lysine_g = Column(Float)
methionine_g = Column(Float)
phenylalanine_g = Column(Float)
protein_g = Column(Float)
threonine_g = Column(Float)
tryptophan_g = Column(Float)
tyrosine_g = Column(Float)
valine_g = Column(Float)
<file_sep>import pandas as pd
from .crud import contextual_session
from .export_ingestion import insert_dataframe_ignore_duplicates
from .models import (
CronometerNote,
CronometerDailySummary,
CronometerExercise,
CronometerServing,
CronometerBiometric,
)
def snake_case_cronometer_column_name(column_name):
column_name = column_name.replace(
') (',
'_',
)
column_name = column_name.replace(
' (',
'_',
)
column_name = column_name.replace(
')',
'',
)
column_name = column_name.replace(
' ',
'_',
)
column_name = column_name.replace(
'-',
'_',
)
column_name = column_name.replace(
'µ',
'u',
)
column_name = column_name.lower()
return column_name
class CronometerDataLoader(object):
def __init__(self, user, session, export_directory):
self.user = user
self.session = session
self.export_directory = export_directory
self.export_types = [
'exercise',
'biometric',
'serving',
'note',
'daily_summary',
]
self.export_models = {
'exercise': CronometerExercise,
'biometric': CronometerBiometric,
'serving': CronometerServing,
'note': CronometerNote,
'daily_summary': CronometerDailySummary,
}
self.export_filenames = {
'exercise': 'exercises.csv',
'biometric': 'biometrics.csv',
'serving': 'servings.csv',
'note': 'notes.csv',
'daily_summary': 'dailySummary.csv',
}
def load_exports_into_database(self):
for export in self.export_types:
export_filepath = self.export_directory / self.export_filenames[export]
export_data = pd.read_csv(export_filepath)
export_data['app_user_id'] = self.user.id
"""Rename the columns so that they match the model/table's column names"""
column_names = export_data.columns.values.tolist()
column_rename_map = {
name: snake_case_cronometer_column_name(name)
for name in column_names
}
export_data = export_data.rename(columns=column_rename_map)
insert_dataframe_ignore_duplicates(
export_data,
self.export_models[export],
)
<file_sep>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import unittest
class LifetrackerHomePageTest(unittest.TestCase):
def setUp(self):
chrome_options = webdriver.chrome.options.Options()
'''
chrome_options.add_argument('--remote-debugging-port=9222')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
'''
self.browser = webdriver.Chrome('/opt/WebDriver/bin/chromedriver', options=chrome_options)
def tearDown(self):
time.sleep(1)
self.browser.quit()
# Edith has heard about a life tracking app. She goes to check out its home
# page.
# She notices the title
def test_title(self):
self.browser.get('http://localhost:5000')
self.assertIn('LifeTracker', self.browser.title)
# There are some examples of things the lifetracker can do
# There is a login/register doodad
if __name__ == '__main__':
unittest.main()
<file_sep>import csv
from .models import LoseitFood, WeighIn
from datetime import datetime
from .crud import contextual_session
import argparse
fieldnames_map = {
'Date': 'raw_date',
'Name': 'raw_name',
'Type': 'raw_type',
'Quantity': 'raw_quantity',
'Units': 'raw_units',
'Calories': 'raw_calories',
'Fat (g)': 'raw_fat_g',
'Protein (g)': 'raw_protein_g',
'Carbohydrates (g)': 'raw_carbohydrates_g',
'Saturated Fat (g)': 'raw_saturated_fat_g',
'Sugars (g)': 'raw_sugars_g',
'Fiber (g)': 'raw_fiber_g',
'Cholesterol (mg)': 'raw_cholesterol_mg',
'Sodium (mg)': 'raw_sodium_mg',
}
def read_loseit_export(filepath, filetype):
if filetype == 'food':
read_food_log(filepath)
elif filetype == 'weight':
read_weight_log(filepath)
else:
raise ValueError("Unsupported file type.")
def read_weight_log(filepath):
with open(filepath) as csv_file:
weight_reader = csv.DictReader(csv_file, delimiter=',', quotechar='"')
weight_records = []
for line in weight_reader:
weight_record = read_weight_log_line(line)
weight_records.append(weight_record)
with contextual_session() as session:
session.add_all(weight_records)
def read_weight_log_line(line_map):
date = datetime.strptime(line_map['Date'], '%m/%d/%Y')
weight = float(line_map['Weight'])
weigh_in = WeighIn(
date=date,
weight_lbs=weight,
)
return weigh_in
def read_food_log(filepath):
with open(filepath) as csv_file:
food_reader = csv.DictReader(csv_file, delimiter=',', quotechar='"')
food_records = []
for line in food_reader:
food_record = read_food_log_line(line)
food_records.append(food_record)
with contextual_session() as session:
session.add_all(food_records)
def set_not_applicable_to_none(value):
if value == "n/a":
return None
else:
return value
def read_food_log_line(line_map):
line_map = dict(zip(line_map, map(set_not_applicable_to_none, line_map.values())))
calories = line_map['Calories']
try:
calories = int(calories)
except ValueError:
calories = ('').join(calories.strip().split(','))
calories = int(calories)
food = LoseitFood(
raw_date=datetime.strptime(line_map['Date'], '%m/%d/%Y').date(),
raw_name=line_map['Name'],
raw_type=line_map['Type'],
raw_quantity=float(line_map['Quantity']),
raw_units=line_map['Units'],
raw_calories=calories,
raw_fat_g=line_map['Fat (g)'],
raw_protein_g=line_map['Protein (g)'],
raw_carbohydrates_g=line_map['Carbohydrates (g)'],
raw_saturated_fat_g=line_map['Saturated Fat (g)'],
raw_sugars_g=line_map['Sugars (g)'],
raw_fiber_g=line_map['Fiber (g)'],
raw_cholesterol_mg=line_map['Cholesterol (mg)'],
raw_sodium_mg=line_map['Sodium (mg)'],
)
return food
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--filepath",
help="Path to Loseit export csv file.",
type=str,
)
parser.add_argument(
"-t",
"--filetype",
help="Export type. 'food' for food log, 'weight' for weight log",
type=str,
)
args = parser.parse_args()
read_loseit_export(args.filepath, args.filetype)
<file_sep>import dash_core_components as dcc
import dash_html_components as html
from .callbacks import metric_checklist_kwargs
layout = html.Div(
children=[
html.H1(children='Dashboard'),
dcc.Checklist(id='metric-checklist', **metric_checklist_kwargs),
dcc.Graph(id='metric-graph'),
],
)
<file_sep>from sqlalchemy.dialects.postgresql import insert
from datetime import datetime
from sqlalchemy import (
Table,
MetaData,
)
from .models import Base
from .crud import contextual_session
def create_mirrored_table(name, base_table):
meta = MetaData()
columns = [
column.copy()
for column in base_table.columns
]
mirrored_table = Table(
name,
meta,
*columns,
)
return mirrored_table
def insert_dataframe_ignore_duplicates(dataframe, orm_table):
database_table = orm_table.__table__
tablename_datetime_format = '%Y%m%d_%H%M%S'
temp_table_name = (
database_table.name
+ '_temporary_{}'.format(datetime.now().strftime(tablename_datetime_format))
)
# create the temporary table
temp_table = create_mirrored_table(temp_table_name, database_table)
with contextual_session() as session:
connection = session.get_bind()
temp_table.create(connection)
dataframe.to_sql(
temp_table_name,
if_exists='append',
index=False,
con=connection,
)
#do the sqlalchemy postgres upsert thing
insert_statement = insert(
database_table,
).from_select(
names=temp_table.columns.keys(),
select=temp_table,
)
do_nothing_statement = insert_statement.on_conflict_do_nothing()
connection.execute(do_nothing_statement)
temp_table.drop(connection)
<file_sep>from life_tracker.flask_app import create_app
from life_tracker.backend.models import *
from flask import current_app as app
from flask_login import current_user, login_user
app = create_app()
@app.shell_context_processor
def make_shell_context():
context = {
'app': app,
'current_user': current_user,
'AppUser': AppUser,
}
return context
if __name__ == "__main__":
app.run(host='0.0.0.0')
<file_sep>from life_tracker.backend.cronometer import CronometerDataLoader
from life_tracker.backend.crud import contextual_session
from life_tracker.backend.models import AppUser
from pathlib import Path
import argparse
from life_tracker.config import AppConfig
default_user_id = 1
default_export_directory = AppConfig.PROJECT_DIRECTORY / 'backend/data_ingestion/exports/cronometer_exports'
def ingest_data(user_id, export_directory):
with contextual_session() as session:
user = session.query(AppUser).get(user_id)
loader = CronometerDataLoader(
user,
session,
export_directory,
)
loader.load_exports_into_database()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-e',
'--export_directory',
help='Relative path to cronometer export directory',
type=str,
default=default_export_directory,
)
parser.add_argument(
'-u',
'--user_id',
help='User id to put the data under',
type=int,
default=default_user_id,
)
args = parser.parse_args()
ingest_data(args.user_id, args.export_directory)
<file_sep>from flask import (
current_app as app,
Blueprint,
render_template,
)
from flask_login import (
current_user,
)
home_bp = Blueprint(
'home_bp', __name__,
template_folder='templates',
static_folder='static',
)
@home_bp.route('/')
@home_bp.route('/index')
def index():
user = current_user
template_vars = {
'user': current_user,
}
return render_template('index.html', **template_vars)
| db29b9b1076b1c399f06990b696cf098d596713d | [
"Markdown",
"Python"
] | 25 | Python | SeanGrady/life_tracker | 333b03844cb418e492421e6719e50332364f541a | 70646cdf288a2f31763b831a6c338fcaa06dd4c8 |
refs/heads/master | <file_sep>## (3.1)20-05
- Fixes #1
- Fixes #2
- Changed default values of dry run and notification payload
- Now on Vue Min js
## (3.0)21-03
- Rewrote whole site with VueJs.
- Fine grained error reporting.
- Ability to select to target.
- Added functionality to have pre-filled testing values.
## (1.3)18-09
- Sending notification object is optional, and user can change the flag
- 1.3.1 A small bugfix
## (1.2)15-09
- Solve one bug that prevents to send notification
## (1.1)12-09
- Some bugfixing.
- (Beta) Api Call logs, currently log for all API calls are being printed in Console. In future you can see & possibly copy calls.
## (1.0)16-06
- Ability to send notifications,
- Ability to subscribe multiple topics
## (v0.8)13-06
- Some updates related to performance
- Getting subscribed topics list.
- Ability to add topics (Alpha-Currently hardcoded)<file_sep># fcmutils
Repository of FCM Utils.
This repository is designed as a tool to work with FCM.
Currently it checks validity of existing token and prints the output.
In near future will serve as a console to send notification if existing token is valid or not.
[ChangeLog](changelog.md)
# Functionality
## Identifying the device
Using instance id api, it identifies device frrom given token. It will also give you details about the device.
Reference : [InstanceId Server reference-Device Info](https://developers.google.com/instance-id/reference/server#get_information_about_app_instances)
## Managing topics
Using above apis it will know topics subscribed to given device and will let you manage topics subscription.
Reference : [InstanceId Server reference-Managing Topics](https://developers.google.com/instance-id/reference/server#create_relationship_maps_for_app_instances)
## Construct and send notification
Construct notifications using `notification` and `data` payloads and will send it to devices or topic.
More documentations coming soon
Test it at https://prashamtrivedi.github.io/fcmutils/
# TODOs
- [ ] Migrate to Firebase Admin Api.
- [ ] Use FCM server v1 to send notifications.
- [ ] Update UI receiving new objects.
- [ ] Split code properly and add testing.<file_sep>var instanceIdObject = {
appKey: '',
deviceToken: '',
isFocused: false,
toValidate: false
};
var iidResponse = {
applicationVersion: '',
application: '',
platform: '',
platformIcon: '',
errorMessage: '',
rel: [topicResponse]
};
var topicResponse = {
name: '',
addDate: ''
}
var isResponseAvailable = false;
var isDataLoading = false;
var notificationPayload = {
title: '',
body: '',
sound: '',
badge: '',
android_channel_id: '',
tag: '',
color: '',
icon: '',
click_action: ''
};
var dataPayload = {};
var notification = {
to: '',
collapse_key: '',
priority: '',
content_available: '',
time_to_live: '',
dry_run: false,
notification: notificationPayload,
data: dataPayload,
restricted_package_name: ''
};
const dataOptions = {
props: ['currentid'],
name: 'dataOption',
template: `<li class="mdl-list__item">
<div class="mdl-list__item-primary-content">
<div class="leftInverse mdl-textfield mdl-js-textfield mdl-textfield--floating-label" :class="keyObject" >
<input class="mdl-textfield__input" type="text" v-model="key" :id="'data'+currentid" autocomplete="on" @focus="changeFocus('key')" @change="addKey" >
<label class="mdl-textfield__label" :for="'data'+currentid">Key</label>
</div>
<div class="rightInverse mdl-textfield mdl-js-textfield mdl-textfield--floating-label" style="margin: 0px 10px;" :class="valueObject" >
<input class="mdl-textfield__input" type="text" v-model="value" :id="'value'+currentid" autocomplete="on" @change="addKey" @focus="changeFocus('value')">
<label class="mdl-textfield__label" :for="'value'+currentid">Value</label>
</div>
</div>
</li>`,
data: function () {
return {
key: '',
value: '',
hasKeyFocus: false,
hasValueFocus: false
};
},
methods: {
addKey: function () {
dataPayload[this.key] = this.value
},
changeFocus: function (params) {
if (params == 'key') {
this.hasKeyFocus = true;
} else {
this.hasValueFocus = true;
}
}
},
computed: {
keyObject: function () {
return changeClass(this.key, false, this.hasKeyFocus)
},
valueObject: function () {
return changeClass(this.value, false, this.hasValueFocus)
}
}
};
Vue.component('data-object', dataOptions);
const topicOptions = {
props: ['topic'],
name: 'topic',
template: `<li class="mdl-list__item mdl-list__item--two-line">
<span class="mdl-list__item-primary-content">Name: {{topic.name}}
<span class="mdl-list__item-sub-title">Subscribed On: {{topic.addDate}}</span></span>
<span class="mdl-list__item-secondary-action">
<button id="sendNotification" @click="sendNotifications(topic.name)" class="mdl-button mdl-js-button mdl-button--colored mdl-js-ripple-effect">
Send Notification
</button>
</span></span>
</li>`,
methods: {
sendNotifications: function (name) {
visibility.sendNotifications(`/to/${name}`);
}
}
};
Vue.component('topic-item', topicOptions);
var app = new Vue({
el: '#version',
data: {
version: '3.1'
},
});
var instanceIdThing = new Vue({
el: "#instanceIdFields",
data: instanceIdObject,
computed: {
appKeyObject: function () {
return changeClass(this.appKey, this.toValidate, this.isFocused)
},
deviceTokenObject: function () {
return changeClass(this.deviceToken, this.toValidate, this.isFocused)
}
}
});
function changeClass(keyToCheck, toValidate, isFocused) {
if (isFocused == undefined) {
isFocused = !ifStringEmpty(keyToCheck);
}
if (isFocused) {
return 'is-focused';
} else {
if (toValidate) {
if (ifStringEmpty(keyToCheck)) {
return 'is-invalid'
}
} else {
return ''
}
}
}
var topics = new Vue({
el: "#topics",
data: {
showTopics: false,
topicNames: '',
toVerify: false
},
methods: {
subscribeTopics: function () {
this.toVerify = true;
console.log(instanceIdObject.appKey)
console.log(instanceIdObject.deviceToken)
updateTopics(this.topicNames, data => {
}, error => {
})
}
},
computed: {
topicsObject: function () {
if (this.toVerify && (this.topicNames == '' || this.topicNames == undefined)) {
return 'is-invalid'
} else {
return ''
}
}
}
})
function getToNames() {
var namesArray = []
if (!ifStringEmpty(instanceIdObject.deviceToken)) {
namesArray.push(instanceIdObject.deviceToken);
}
if (iidResponse != undefined && !isListEmpty(iidResponse.rel))
namesArray = namesArray.concat(iidResponse.rel.filter(function (topic) {
return topic != undefined
}).map(function (topic) {
return `/to/${topic.name}`
}));
return namesArray;
}
function isListEmpty(list) {
return (list == undefined && list.length == 0);
}
var notifications = new Vue({
el: "#notificationDiv",
data: {
sendNotification: false,
notificationTo: "",
timeToLive: 2419200,
priority: 5,
collapseKey: "",
contentAvailable: false,
dryRun: false,
sendNotificationPayload: false,
title: '',
body: '',
sound: '',
badge: '',
channelId: '',
tag: '',
color: '',
androidIcon: '',
clickAction: '',
currentItems: 1,
dataKey: [],
dataValues: [],
validateTitle: false
},
methods: {
prepareAndSendNotification: function () {
notification.to = this.notificationTo;
notification.collapse_key = this.collapseKey;
notification.priority = this.priority;
notification.time_to_live = this.timeToLive;
notification.dry_run = this.dryRun;
this.validateTitle = this.sendNotificationPayload
if (this.sendNotificationPayload && !ifStringEmpty(this.title)) {
notificationPayload.title = this.title;
notificationPayload.body = this.body;
notificationPayload.sound = this.sound;
notificationPayload.badge = this.badge;
notificationPayload.icon = this.androidIcon;
notificationPayload.color = this.color;
notificationPayload.android_channel_id = this.channelId;
notificationPayload.click_action = this.clickAction;
notification.notification = clean(notificationPayload);
notification.data = dataPayload;
sendNotificationObject(clean(notification))
} else if (!this.sendNotificationPayload) {
notification.data = dataPayload;
sendNotificationObject(clean(notification))
}
},
addDataObject: function () {
this.currentItems += 1;
}
},
computed: {
toObject: function () {
return changeClass(this.notificationTo, this.sendNotification, undefined)
},
titleObject: function () {
return changeClass(this.title, this.validateTitle, undefined)
}
}
});
function ifStringEmpty(string) {
return string == '' || string == undefined || string == null || string == 'null'
}
var visibility = new Vue({
el: "#responseVisibility",
data: {
hasResponse: isResponseAvailable,
isLoading: isDataLoading,
application: iidResponse.application,
platformIcon: iidResponse.platformIcon,
applicationVersion: iidResponse.applicationVersion,
errorMessage: '',
topics: []
},
methods: {
verifyToken: function () {
instanceIdThing.toValidate = true
if (ifStringEmpty(instanceIdObject.deviceToken) || ifStringEmpty(instanceIdObject.appKey)) {
} else {
this.isLoading = true;
getInstanceIdInfo(instanceIdObject.deviceToken, instanceIdObject.appKey, test => {
visibility.isLoading = false;
if (test != undefined) {
console.log(test);
console.log(test.rel.application);
console.log(test.application);
console.log(test.applicationVersion);
this.hasResponse = true;
this.application = test.application;
this.platformIcon = test.platformIcon;
this.applicationVersion = test.applicationVersion;
this.topics = iidResponse.rel;
}
console.log(test);
}, errorMessage => {
this.hasResponse = false;
console.log(errorMessage);
visibility.isLoading = false;
this.errorMessage = errorMessage;
})
}
},
useTestValues: function () {
instanceIdThing.appKey = testInstanceIdObject.appKey
instanceIdThing.deviceToken = testInstanceIdObject.deviceToken
instanceIdThing.isFocused = true
},
sendNotifications: function (name) {
if (ifStringEmpty(name)) {
name = instanceIdObject.deviceToken;
}
notifications.notificationTo = name;
console.log(notifications.notificationTo);
notifications.sendNotification = !notifications.sendNotification;
},
manageTopics: function () {
topics.showTopics = !topics.showTopics;
}
}
});
function sendNotificationObject(cleanedData, key) {
const settings = {
method: "POST",
url: "https://fcm.googleapis.com/fcm/send",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(cleanedData),
beforeSend: function (request) {
request.setRequestHeader("Authorization", "key=" + instanceIdObject.appKey);
},
success: function (data) {
console.log(this.url);
console.log(this.data);
console.log("Sent");
if (data.failure >= 0) {
console.log(data);
document.querySelector("#snackBar").MaterialSnackbar.showSnackbar({
'message': 'Notification Not Sent,Reason '+data.results[0]["error"]
});
} else {
document.querySelector("#snackBar").MaterialSnackbar.showSnackbar({
'message': 'Notification Sent'
});
}
},
error: function (xhr, status, error) {
const err = xhr.responseText;
console.log(err);
document.querySelector("#snackBar").MaterialSnackbar.showSnackbar({
'message': 'Notification Not Sent'
});
}
};
$.ajax(settings)
}
function clean(obj) {
const propNames = Object.getOwnPropertyNames(obj);
for (let i = 0; i < propNames.length; i++) {
const propName = propNames[i];
// if (typeof obj[propName] == "object") {
// clean(obj[propName]);
// }
if (obj[propName] === null || obj[propName] === undefined || obj[propName] === "") {
delete obj[propName];
}
}
return obj;
}
function getInstanceIdInfo(instanceId, key, successCallback, failureCallback) {
iidResponse = new Object();
iidResponse.rel = [];
const settings = {
method: "GET",
url: "https://iid.googleapis.com/iid/info/" + instanceId + "?details=true",
contentType: "application/json; charset=utf-8",
beforeSend: function (request) {
request.setRequestHeader("Authorization", "key=" + key);
},
success: function (data) {
console.log(data);
iidResponse.applicationVersion = data.applicationVersion;
iidResponse.application = data.application;
if (data.platform === "ANDROID") {
iidResponse.platformIcon = "phone_android"
} else if (data.platform === "IOS") {
iidResponse.platformIcon = "phone_iphone"
} else if (data.platform === "CHROME") {
iidResponse.platformIcon = "laptop_chromebook"
}
iidResponse.platform = data.platform;
if (data.rel !== undefined && data.rel.topics !== undefined) {
for (const topic in data.rel.topics) {
topicResponse = {};
topicResponse.name = topic;
var topicDate = data.rel.topics[topic].addDate;
topicResponse.addDate = topicDate;
if (topicResponse != undefined)
iidResponse.rel.push(topicResponse)
}
}
successCallback(iidResponse);
},
error: (xhr, status, error) => {
console.log(error);
console.log(xhr.responseText);
const err = xhr.responseText;
iidResponse.errorMessage = err;
failureCallback(err)
}
};
$.ajax(settings)
}
function updateTopics(topics, successFun, errorFun) {
console.log(iidResponse);
console.log(window.token);
console.log(topics);
const topicArray = topics.split(",").map(function (topic) {
return topic.trim()
});
topicArray.forEach(function (topic) {
const settings = {
method: "POST",
url: "https://iid.googleapis.com/iid/v1/" + instanceIdObject.deviceToken + "/rel/topics/" + topic,
contentType: "application/json; charset=utf-8",
beforeSend: function (request) {
request.setRequestHeader("Authorization", "key=" + instanceIdObject.appKey);
},
success: function (data) {
console.log('subscribed');
console.log(this.url);
console.log(this.data);
successFun(this.data)
},
error: function (xhr, status, error) {
var err = JSON.parse(xhr.responseText);
errorFun(err.error);
}
};
$.ajax(settings)
});
}<file_sep>var instanceIdObject = {
appKey: '',
deviceToken: '',
isFocused: false,
toValidate: false
}; | 4ef6477f254bcadab2356c37f84fa864c9035844 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | PrashamTrivedi/fcmutils | 599439a9e7c2847e38fda6cf35e2bdbc00afd730 | 88cc61b39ad21dd374628d701404a27ad579b59e |
refs/heads/master | <file_sep>class CreateDcrelations < ActiveRecord::Migration
def change
create_table :dcrelations, {:primary_key => :doctor_id} do |t|
t.integer :doctor_id, :null => false
t.integer :clinic_id, :null => false
t.timestamps
end
end
end
<file_sep>require 'test_helper'
class DcrelationsHelperTest < ActionView::TestCase
end
<file_sep>class Clinic < ActiveRecord::Base
attr_accessible :clinic_id, :name
has_many :dcrelations, dependent: :destroy
has_many :doctors, :through => :dcrelations
end
<file_sep>class Dcrelation < ActiveRecord::Base
attr_accessible :clinic_id, :doctor_id
belongs_to :doctor
belongs_to :clinic
validates :clinic_id, :doctor_id, presence: true
end
<file_sep>class Doctor < ActiveRecord::Base
attr_accessible :doctor_id, :name
has_one :dcrelation, dependent: :destroy
has_one :clinic, :through => :dcrelation
end
<file_sep>class DcrelationsController < ApplicationController
def create
@dcrelation = Dcrelation.new(:clinic_id => params[:clinic_id],:doctor_id => params[:doctor_id])
if @dcrelation.save
flash[:success] = "doctor added!"
redirect_to :back
else
render :back
end
end
def destroy
@dcrelation = Dcrelation.find(params[:id])
@dcrelation.destroy
redirect_to :back
end
end
<file_sep>require 'test_helper'
class OnedocHelperTest < ActionView::TestCase
end
<file_sep>class CreateClinics < ActiveRecord::Migration
def change
create_table :clinics, {:primary_key => :clinic_id} do |t|
t.string :name
t.integer :clinic_id
t.timestamps
end
end
end
| 9c87c5c7c85a5e7be2478c672d88957d253507f4 | [
"Ruby"
] | 8 | Ruby | szlike/onedoc | 144ca6a53ed53514b32d6b2113ddd37ee4af0264 | b88fc7dd8f620eab5b15fe9be73bdc517b999ed0 |
refs/heads/master | <repo_name>cas81695/Employee-Tracker<file_sep>/DB/seed.sql
USE employees_trackerDB;
INSERT INTO department (name)
VALUES ("Sales");
INSERT INTO department (name)
VALUES ("Engineering");
INSERT INTO department (name)
VALUES ("Finance");
INSERT INTO department (name)
VALUES ("Legal");
INSERT INTO role (title, salary, department_id)
VALUES ("Sales Lead", 100000, 1);
INSERT INTO role (title, salary, department_id)
VALUES ("Lead Engineer", 150000, 2);
INSERT INTO role (title, salary, department_id)
VALUES ("Software Engineer", 120000, 2);
INSERT INTO role (title, salary, department_id)
VALUES ("Accountant", 125000, 3);
INSERT INTO role (title, salary, department_id)
VALUES ("Legal Team Lead", 250000, 4);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Natsu", "Dragnel", 1, 3);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Lucy", "Heartfilia", 2, 1);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Gray", "Fullbuster", 3, null);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Juvia", "Lockster", 4, 3);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Vegeta", "Sayian", 5, null);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Nico", "Robin", 2, null);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Kirito", "Swordsman", 4, 7);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Asuna", "Maiden", 1, 2);
| b865970cbd2b4f1186452cfbba9e865fb00b1a41 | [
"SQL"
] | 1 | SQL | cas81695/Employee-Tracker | fc7ba9deda8ff6f32acf555657e267941c46a13e | b66faee95f7cbaa506ee019a623b470ed10735bf |
refs/heads/master | <file_sep>import numpy as np
import cv2
#black img
img=np.zeros((512,512,3),np.uint8)
#draw a diagonal line of thickness 5px
cv2.line(img,(0,0),(511,511),(255,0,0),5)
cv2.imshow('img',img)
#cv2.imwrite('line.png',img)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import cv2
import numpy as np
img= cv2.imread('apple1.jpg')
res=cv2.resize(img,None,fx=1,fy=2,interpolation=cv2.INTER_CUBIC)
#height, width = img.shape[:2]
#res = cv2.resize(img,(2*width, 2*height), interpolation = cv2.INTER_CUBIC)
cv2.imshow('img',img)
cv2.imshow('res_img',res)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import numpy as np
import cv2
img1=cv2.imread('img1.png',1)
img2=cv2.imread('img2.png',1)
res=cv2.addWeighted(img1,0.7,img2,0.3,0)
cv2.imshow('image',res)
#write
#cv2.imwrite('combined.png',res)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import numpy as np
import cv2
#for gray scale
img=cv2.imread('apple1.jpg',-1)
#show image
cv2.namedWindow('image_window',cv2.WINDOW_NORMAL)
cv2.imshow('image_window',img)
#write
cv2.imwrite('applegrey.png',img)
k=cv2.waitKey(100000)#time in ms
cv2.destroyAllWindows()
<file_sep>import cv2
import numpy as np
img1=cv2.imread('1.png',1)
img2=cv2.imread('2.png',1)
# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels=img2.shape
roi=img1[0:rows,0:cols]
# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)
# Put logo in ROI and modify the main image
dst = cv2.add(img1,img2)
img1[0:rows, 0:cols ] = dst
cv2.imshow('res',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import numpy as np
import cv2
img=cv2.imread('72.jpg',1)
area= img[280:340, 330:390]
#copying of area
img[273:333, 100:160] = area
#splitting and merging
#b,g,r = cv2.split(img)
#img = cv2.merge((b,g,r))
cv2.imshow('show_image',img)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import cv2
import numpy as np
img = cv2.imread('colors.png',1)
px=img[100,100]
print(px)
#accessing only blue pixel
blue=img[100,100,0]
print(blue)
#modification of pixel value
img[100,100] = [255,255,255]
print(img[100,100])
#show img
cv2.imshow('image_window_name',img)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import numpy as np
import cv2
#for gray scale
img=cv2.imread('apple1.jpg',0)
#show image
cv2.namedWindow('image_window',cv2.WINDOW_NORMAL)
cv2.imshow('image_window',img)
k=cv2.waitKey(0)
if k==ord(s):
cv2.imwrite('applegrey.png',img)
cv2.destroyAllWindows()
<file_sep>import numpy as np
import cv2
#for gray scale
img=cv2.imread('apple1.jpg',-1)
#show image
cv2.imshow('show_image',img)
#write
cv2.imwrite('applegrey.png',img)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import cv2
import numpy as np
img = cv2.imread('colors.png',1)
print(img.shape)
print(img.size)
print(img.dtype)
#show img
cv2.imshow('image_window_name',img)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import numpy as np
import cv2
#create a black img
img=np.zeros((512,512,3),np.uint8)
#draw a rectangle of thickness 5px on that img
#cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
#draw circle
#cv2.circle(img,(447,63), 63, (0,0,255), -1)
#drawing ellipse
#cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
#text on img
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_4)
#show img
cv2.imshow('img',img)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import cv2
import numpy as np
#mouse callback fun
def draw_circle(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img,(x,y),100,(255,0,0),-1)
#create a black img a window and bound window with fun
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallBack('image',draw_circle)
while(1):
cv2.imshow('image',img)
if cv2.waitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindow()
<file_sep>import numpy as np
import cv2
img1=cv2.imread('mg1.png',1)
img2=cv2.imread('img2.png',1)
res=img1+img2 #numpy add
cv2.imshow('image',res)
#write
cv2.imwrite('combined.png',res)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>import cv2
import numpy as np
img = cv2.imread('apple1.jpg',1)
rows=100
cols=100
M = cv2.getRotationMatrix2D((50,50),90,1)
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('img_window',img)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep># OPENCV_Python_Codes
A repository contains opencv codes for image processing in python language..
<file_sep># import opencv
import cv2
# Read image
src = cv2.imread("threshold.png", cv2.IMREAD_GRAYSCALE)
# Set threshold and maxValue
thresh = 0
maxValue = 255
# Basic threshold example
th, dst = cv2.threshold(src, thresh, maxValue, cv2.THRESH_BINARY);
cv2.imshow('image',dst)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
| 4f0b78dc07d11d09a1532475bb75f931635f4fa3 | [
"Markdown",
"Python"
] | 16 | Python | himanshushukla254/OPENCV_Python_Codes | 812e2d944e8580f9596bd116d86f75de48377161 | 287cef9986ba543a5290f4c6b00d7cca9db69cbc |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\CompanyDetails;
use App\CompanyWallets;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use App\UserWallets;
use App\UserDetails;
use Illuminate\Support\Str;
class RegisterController extends Controller
{
public function index()
{
return view('auth.register');
}
public function register(Request $request)
{
$validator = $this->validator($request->all());
// if ($validator->fails()) {
// }
if ($request->has('isCompany')) {
$user = $this->createCompany($request->all());
$company = CompanyWallets::create([
'user_id' => $user->id,
'actual_amount' => 0.00
]);
$companyDetails = CompanyDetails::create([
'user_id' => $user->id,
'api_token' => Hash::make(Str::uuid()),
'company_name' => $user->username,
]);
$this->guard()->login($user);
return redirect('/company/home');
}
$user = $this->createUser($request->all());
$createUser = UserWallets::create([
'user_id' => $user->id,
'actual_amount' => 0.00
]);
$createDetails = UserDetails::create([
'user_id' => $user->id,
'four_digit_pin' => rand(1000, 9999),
]);
$this->guard()->login($user);
return redirect('/user/home');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function createCompany(array $data)
{
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => <PASSWORD>($data['password']),
'isCompany' => ($data['isCompany']) ? true : false
]);
}
protected function createUser(array $data)
{
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => <PASSWORD>($data['<PASSWORD>']),
]);
}
protected function guard()
{
return Auth::guard();
}
}
<file_sep><?php
return [
'Sandbox-baseUrl' => 'https://sandboxapi.fsi.ng',
'paygo-account' => '0704558184',
'Sandbox-Key' => 'insert here your sandbox key',
'Ocp-Apim-Subscription-Key' => '1cc664165bd4490e97019c61a492d19a',
'Ocp-Apim-Trace' => 'true',
'Appid' => '69',
];
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use phpDocumentor\Reflection\Types\Nullable;
class CompaniesDetails extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('companies_details', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('company_name')->nullable();
$table->string('api_token');
$table->bigInteger('user_id')->unsigned();
$table->string('account_number')->nullable();
$table->string('bank_name')->nullable();
// $table->bigInteger('user_id')->unsigned();
// $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
// $table->bigInteger('country_id')->unsigned();
// $table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
// $table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/register', 'RegisterController@index')->name('register');
Route::get('/login', 'LoginController@index')->name('login');
Route::post('/login', 'LoginController@authenticate')->name('login');
Route::post('/register', 'RegisterController@register')->name('register');
Route::group(['middleware' => ['auth']], function () {
//Company Authenticated routes
Route::post('company/add_account', 'CompanyController@addAccount');
// Route::post('company/home', 'CompanyController@index');
Route::get('company/home', 'CompanyController@index');
});
Route::group(['middleware' => ['auth']], function () {
//User Authenticated Routes
Route::get('user/home', 'UserController@index');
Route::post('user/buyAirtime', 'UserController@buyAirtime');
Route::post('user/deposit', 'UserController@deposit');
Route::post('user/add_account', 'UserController@addAccount');
});
Route::get('logout', 'LoginController@logout')->name('logout');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Company;
use App\CompanyAccount;
use App\CompanyDetails;
use App\CompanyTransactions;
use App\CompanyWallets;
use Illuminate\Support\Facades\Auth;
class CompanyController extends Controller
{
public function index()
{
$companyWallet = CompanyWallets::where(['user_id' => Auth::user()->id])->first();
$companyDetails = CompanyDetails::where(['user_id' => Auth::user()->id])->first();
$companyTransactions = CompanyTransactions::where(['user_id' => Auth::user()->id])->get();
// dd($userWallet);
$data = [
'companyWallet' => $companyWallet,
'success' => 'login Success',
'error' => null,
'companyDetails' => $companyDetails,
'companyTransactions' => $companyTransactions
];
// dd($data);
return view('Companies.home')->with('data', $data);
}
public function addAccount(Request $request)
{
$companyAccount = CompanyDetails::where(['user_id' => Auth::user()->id])->first();
$companyAccount->update([
'bank_name' => $request->input('select_bank'),
'account_number' => $request->account_number,
]);
return redirect('company/home');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
class LoginController extends Controller
{
public function index()
{
return view('auth.login');
}
public function authenticate(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
if (Auth::user()->isCompany == 1) {
return redirect('/company/home');
}
if (Auth::user()->isCompany == 0) {
return redirect('/user/home');
}
}
return redirect('/');
}
public function logout()
{
Auth::logout();
return redirect('/');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\User;
use App\UserAccount;
use App\UserDetails;
use App\UserTransactions;
use Illuminate\Http\Request;
use App\UserWallets;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
class UserController extends Controller
{
public function index()
{
$userWallet = UserWallets::where(['user_id' => Auth::user()->id])->first();
$userAccount = UserAccount::where(['user_id' => Auth::user()->id])->first();
$userDetails = UserDetails::where(['user_id' => Auth::user()->id])->first();
$userTransactions = UserTransactions::where(['user_id' => Auth::user()->id])->get();
// dd($userWallet);
$data = [
'userWallet' => $userWallet,
'success' => 'Success',
'userAccount' => $userAccount,
'error' => null,
'userDetails' => $userDetails,
'userTransactions' => $userTransactions
];
return view('Users.home')->with('data', $data);
}
public function buyAirtime(Request $request)
{
$userWallets = UserWallets::where(['user_id' => Auth::user()->id])->first();
if ($userWallets->actual_amount < $request->amount) {
return redirect('user/home');
}
$remainingAmount = $userWallets->actual_amount - $request->amount;
// $response = Http::post(config('paygo.Sandbox-baseUrl') . '/atlabs/airtime/send', [
// 'recipients' => [
// 'phoneNumber' => $request->number,
// 'amount' => $request->amount,
// 'currencyCode' => 'NGN'
// ]
// ]);
// dd($response);
// if ($response->ok()) {
$createTransaction = UserTransactions::create([
'user_id' => Auth::user()->id,
'trans_ref' => Str::uuid(),
'type' => 'Airtime',
'trans_amount' => $request->amount
]);
$userWallets->update(['actual_amount' => $remainingAmount]);
return redirect('user/home');
// }
return redirect('user/home');
}
public function addAccount(Request $request)
{
$userAccount = UserAccount::create([
'bank_name' => $request->input('select_bank'),
'account_number' => $request->account_number,
'user_id' => Auth::user()->id
]);
return redirect('user/home');
}
public function deposit(Request $request)
{
// dd($request);
try {
$referenceId = Str::uuid();
$userAccount = UserAccount::where(['user_id' => Auth::user()->id])->first();
// $response = Http::withHeaders([
// 'Sandbox-Key' => config('paygo.Sandbox-Key'),
// 'Ocp-Apim-Subscription-Key' => '1cc664165bd4490e97019c61a492d19a',
// 'Ocp-Apim-Trace' => "true",
// 'Appid' => '69',
// 'Content-Type' => 'application/json',
// 'ipval' => 0
// ])->post(config('paygo.Sandbox-baseUrl') . '/sterling/accountapi/api/Spay/InterbankTransferReq', [
// 'Referenceid' => $referenceId,
// 'RequestType' => 'deposit',
// 'Translocation' => 01,
// 'SessionID' => 01,
// 'FromAccount' => $userAccount->account_number,
// 'ToAccount' => config('paygo.paygo-account'),
// 'Amount' => $request->amount,
// 'DestinationBankCode' => '01',
// 'NEResponse' => '01',
// 'BenefiName' => '01',
// 'PaymentReference' => $referenceId,
// 'OriginatorAccountName' => '01',
// 'translocation' => '01'
// ]);
// if ($response->ok()) {
$createTransaction = UserTransactions::create([
'user_id' => Auth::user()->id,
'trans_ref' => Str::uuid(),
'type' => 'Deposit',
'trans_amount' => $request->amount
]);
// dd($createTransaction);
// dd($createTransaction);
$updateWallet = UserWallets::where(['user_id' => Auth::user()->id])->first();
$newAmount = $updateWallet->actual_amount + $request->amount;
$updateWallet->update(['actual_amount' => $newAmount]);
// dd($updateWallet);
return redirect('user/home');
// }
} catch (\Exception $e) {
return redirect('user/home');
dd($e);
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\CompanyDetails;
use App\CompanyTransactions;
use App\CompanyWallets;
use App\User;
use App\UserDetails;
use App\UserWallets;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Str;
use App\UserTransactions;
class PaymentController extends Controller
{
public function payment(Request $request)
{
$api_token = $request->header('auth-token');
$companyDetails = CompanyDetails::where(['api_token' => $api_token])->first();
if (is_null($companyDetails)) {
$response = [
'statusCode' => 401,
'message' => 'Sorry You are Unauthorised',
];
return Response::json($response, 401);
}
// dd($companyDetails);
$user = User::where(['username' => $request->username])->first();
$userDetails = UserDetails::where(['user_id' => $user->id])->first();
// dd($user);
// dd($request->pin);
if ($userDetails->four_digit_pin != $request->pin) {
$response = [
'statusCode' => 401,
'message' => 'Pin not corrrect',
];
return Response::json($response, 401);
}
$userWallets = UserWallets::where(['user_id' => $user->id])->first();
if ($userWallets->actual_amount < $request->amount) {
$response = [
'statusCode' => 400,
'message' => 'Insuficient funds',
];
return Response::json($response, 400);
}
$remainingAmount = $userWallets->actual_amount - $request->amount;
$createTransaction = UserTransactions::create([
'user_id' => $user->id,
'trans_ref' => Str::uuid(),
'type' => 'Payment to' . $companyDetails->company_name,
'trans_amount' => $request->amount
]);
$userWallets->update(['actual_amount' => $remainingAmount]);
//Company side
$companyTransaction = CompanyTransactions::create([
'user_id' => $companyDetails->user_id,
'payer' => 'pay from ' . $request->username,
'trans_ref' => Str::uuid(),
'actual_amount' => $request->amount,
'type' => 'checkout payment'
]);
$companyWallet = CompanyWallets::where(['user_id' => $companyDetails->user_id])->first();
$newWallet = $companyWallet->actual_amount + $request->amount;
$companyWallet->update(['actual_amount' => $newWallet]);
$response = [
'statusCode' => 200,
'message' => 'success',
];
return Response::json($response, 200);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserAccount extends Model
{
protected $table = 'user_accounts';
protected $fillable = ['bank_name', 'account_number', 'user_id'];
protected $hidden = ['created_at', 'updated_at'];
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CompanyTransactions extends Model
{
protected $table = 'companies_transactions';
protected $fillable = ['user_id', 'payer', 'trans_ref', 'actual_amount', 'type'];
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CompanyDetails extends Model
{
protected $table = 'companies_details';
protected $fillable = ['api_token', 'company_name', 'user_id', 'account_number', 'bank_name'];
}
| 45e9e6652a9f99ca2d276570dbeeea58a35ea316 | [
"PHP"
] | 11 | PHP | Achay009/fsi | e2ec2a0035598e095052000132b3555e6c3775f4 | 29a250bd607ebc204d78df5d44a28af48971bf5e |
refs/heads/master | <repo_name>IDisposable/downworthy<file_sep>/Source/content_script.js
(function() {
var _self = this;
var _dictionary;
function getDictionary(callback) {
chrome.extension.sendRequest({id: "getDictionary"}, function(response) {
_dictionary = response; // Store the dictionary for later use.
callback.apply(_self, arguments);
});
}
function handleText(textNode) {
var replacements = _dictionary.replacements;
var v = textNode.nodeValue;
var regex, original;
for(original in replacements) {
regex = new RegExp('\\b' + original + '\\b', 'g');
v = v.replace(regex, replacements[original]);
}
// TODO: Allow for more complicated regexes in the dictionary file?
v = v.replace(/\b(?:Top )?((?:(?:\d+|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen|Twenty|Thirty|Forty|Fourty|Fifty|Sixty|Seventy|Eighty|Ninety|Hundred)(?: |-)?)+) Things/g, "Inane Listicle of $1 Things You've Already Seen Somewhere Else");
v = v.replace(/\b[Rr]estored [Mm]y [Ff]aith [Ii]n [Hh]umanity\b/g, "Affected Me In No Meangingful Way Whatsoever");
v = v.replace(/\b[Rr]estored [Oo]ur [Ff]aith [Ii]n [Hh]umanity\b/g, "Affected Us In No Meangingful Way Whatsoever");
v = v.replace(/\b(?:Top )?((?:(?:\d+|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen|Twenty|Thirty|Forty|Fourty|Fifty|Sixty|Seventy|Eighty|Ninety|Hundred)(?: |-)?)+) Weird/g, "$1 Boring");
v = v.replace(/\b^(Is|Can|Do|Will) (.*)\?\B/g, "$1 $2? Maybe, but Most Likely Not.");
textNode.nodeValue = v;
}
function walk(node) {
// I stole this function from here: - ZW
// And I stole it from ZW - AG
// http://is.gd/mwZp7E
var child, next;
switch(node.nodeType) {
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while(child) {
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // Text node
handleText(node);
break;
}
}
chrome.extension.sendRequest({id: 'isPaused?'}, function(response) {
var isPaused = response.value;
console.log('isPaused is ' + isPaused);
if(!isPaused) {
getDictionary(function() {
walk(document.body);
});
}
});
})(); | 508a9d9d4ef5bcbe5e6527326e41f90cbef26a7d | [
"JavaScript"
] | 1 | JavaScript | IDisposable/downworthy | fc302ae62a3e5b4f96d89bdfbdc739c9268f27f0 | 174952b4241b9c55ec4ce3ca902bf05902d05339 |
refs/heads/master | <repo_name>tpageforfunzies/kafkaonkube<file_sep>/update/Dockerfile
FROM python:2.7.10
EXPOSE 5000
COPY update.py .
CMD python update.py<file_sep>/complete/app.py
from flask import Flask
app = Flask('__main__')
# from rediscluster import StrictRedisCluster
# startup_nodes = [{"host": "192.168.64.5", "port": "30000", "password": "<PASSWORD>"}]
# rc = StrictRedisCluster(startup_nodes=startup_nodes,decode_responses=True)
@app.route('/')
def hello_world():
return "this is the main page"
@app.route('/delete')
def delete():
return "this is the delete endpoint"
@app.route('/create')
def create():
# global rc
# rc.set("foo", "bar")
return "this is the create endpoint"
@app.route('/read')
def read():
# global rc
# return rc.get("foo")
return "this is the read endpoint"
@app.route('/update')
def update():
return "this is the update endpoint"
if __name__ == '__main__':
app.run(host='0.0.0.0')
<file_sep>/complete/requirements.txt
Flask==1.0.2
redis-py-cluster==1.3.5 <file_sep>/read/read.py
from flask import Flask
app = Flask('__main__')
@app.route('/read')
def hello_world():
return "this is the read service"
if __name__ == '__main__':
app.run(host='0.0.0.0')<file_sep>/create/Dockerfile
FROM python:2.7.10
EXPOSE 5000
COPY create.py .
CMD python create.py<file_sep>/read/Dockerfile
FROM python:2.7.10
EXPOSE 5000
COPY read.py .
CMD python read.py<file_sep>/create/create.py
from flask import Flask
app = Flask('__main__')
@app.route('/create')
def create_route():
return "this is the create endpoint"
if __name__ == '__main__':
app.run(host='0.0.0.0')<file_sep>/delete/Dockerfile
FROM python:2.7.10
EXPOSE 5000
COPY delete.py .
CMD python delete.py | c0907b70fc1f7d68cf8c68d4b14250a191f79ca2 | [
"Python",
"Text",
"Dockerfile"
] | 8 | Dockerfile | tpageforfunzies/kafkaonkube | c2c27092725a9f4e80278c205dc3fcec8dc31267 | 38297195c59ab71801bf8b9b7890269541c5c2f0 |
refs/heads/master | <file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# hx supports the "lexer" output mode
# in which it doesn't colorize the output,
# it shows the raw internal token stream.
# This test ensures that the lexing process works as intended.
SYSLOGLINE="$(syslogline 1 | LEX)"
KERNELLINE="$(sysloggrep 'OUT=eth0' | LEX)"
REPEATLINE="$(sysloggrep 'repeated 5 times' | LEX)"
# The lexed kernel line should contain at least the app name and the info block somewhere:
assertRegex "$KERNELLINE" "/$(re_tok $T_APP "kernel:")/"
assertRegex "$KERNELLINE" "/$(re_tok $T_INFO "\\[269611.241825\\]")/"
# The repetition line should contain T_REPEAT, T_MESSAGE, T_REPEATEND, in this order.
re_repeatline="/$(re_tok $T_REPEAT "message repeated 5 times:.*?").*"
re_repeatline="${re_repeatline}$(re_tok $T_MESSAGE "Failed to load.*").*"
re_repeatline="${re_repeatline}$(re_tok $T_REPEATEND)/"
assertRegex "$REPEATLINE" "$re_repeatline"
# Now we'll try to match one line exactly, token for token:
re_syslogline="/^${RW}$(re_ztok $T_LINE)"
re_syslogline="${re_syslogline}$(re_tok $T_DATE "Jun 16 10:27:20")"
re_syslogline="${re_syslogline}$(re_tok $T_HOST "test-pc")"
re_syslogline="${re_syslogline}$(re_tok $T_APP "rsyncd\\[31755\\]:?")"
re_syslogline="${re_syslogline}$(re_tok $T_MESSAGE "sent 63 bytes received 100688092 bytes total size 100663296")"
re_syslogline="${re_syslogline}$(re_ztok $T_EOL)/"
assertRegex "$SYSLOGLINE" "$re_syslogline"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/urls.log"
# 2020-04-24 13:02:15,318 INFO: Server started at http://localhost:8080
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Server started")/"
assertRegex "$line" "/$(re_tok $T_TRACE "at http:\/\/localhost:8080")/"
# 2020-04-24 13:02:15,318 INFO: API available at https://test:test@localhost.my-domain/rest.service/api
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "API available")/"
assertRegex "$line" "/$(re_tok $T_TRACE "at https:\/\/test:test@localhost\.my-domain\/rest.service\/api")/"
success
<file_sep># hx Screenshots
#### Apache logs
[<img alt="Apache2 logs, original" src="img/apache0.png" width="49%">](img/apache0.png)
[<img alt="Apache2 logs using hx" src="img/apache1.png" width="49%">](img/apache1.png)
#### Syslog
[<img alt="Syslog, original" src="img/syslog0.png" width="49%">](img/syslog0.png)
[<img alt="Syslog using hx" src="img/syslog1.png" width="49%">](img/syslog1.png)
#### `tail -f` on Multiple Files
[<img alt="tail -f, original" src="img/tailf0.png" width="49%">](img/tailf0.png)
[<img alt="tail -f using hx" src="img/tailf1.png" width="49%">](img/tailf1.png)
#### nginx Error Log
[<img alt="nginx, original" src="img/nginx0.png" width="49%">](img/nginx0.png)
[<img alt="nginx using hx" src="img/nginx1.png" width="49%">](img/nginx1.png)
#### Postfix Errors
[<img alt="Postfix, original" src="img/postfix0.png" width="95%">](img/postfix0.png)
[<img alt="Postfix using hx" src="img/postfix1.png" width="95%">](img/postfix1.png)
#### SSH
[<img alt="SSH, original" src="img/ssh0.png" width="95%">](img/ssh0.png)
[<img alt="SSH using hx" src="img/ssh1.png" width="95%">](img/ssh1.png)
<file_sep>[](https://travis-ci.org/mle86/hx)
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/bug-ua.log"
# 2021-08-22 12:00:00: User-Agent: Firefox/90.0.0 ...
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_LINE).*$(re_tok $T_MESSAGE "User-Agent: Firefox.*")/" \
"A log line with 'User-Agent: ...' after a prefix was incorrectly recognized as a continuation line!"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# This test depends on test-syslog-logs.
logfile="$HERE/samples/syslog-java.log"
re_backslash='(?:\\)'
# Jan 19 18:10:07 mypc myapp[100]: 2021-01-19 18:10:07,591 [1234567] WARN - my.app.name - failed to boot
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "Jan 19 18:10:07")/"
assertRegex "$line" "/$(re_tok $T_APP "myapp\[100\]:?")/"
assertRegex "$line" "/$(re_tok $T_DATE "2021-01-19 18:10:07,591")/"
assertRegex "$line" "/$(re_tok $T_INFO "\[1234567\]")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "WARN\W*")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE ".*failed to boot")/"
# Jan 19 18:12:15 mypc myapp[100]: org.myapp.MyJavaException: Not acceptable.
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_ERROR "org\.myapp\.MyJavaException:?")/"
# Jan 19 18:12:15 mypc myapp[100]: Error: Not acceptable.
# Jan 19 18:12:15 mypc myapp[100]: at Object.method (./proj/helper/test.js:31:34)
line="$(logline "$logfile" 3 | LEX)"
assertRegex "$line" "/^$(re_tok $T_CONTLINE)/"
assertRegex "$line" "/$(re_tok $T_INFO "\s*at Object\.method\W*")/"
assertRegex "$line" "/$(re_tok $T_TRACE "\W*\.\/proj\/helper\/test\.js:31:34\W*")/"
# Jan 19 18:12:15 mypc myapp[100]: #011at [eval]:15
line="$(logline "$logfile" 4 | LEX)"
assertRegex "$line" "/^$(re_tok $T_CONTLINE).*$(re_tok $T_INFO "(?:#011)?at .*")/"
# Jan 19 18:12:16 mypc myapp[100]: stderr: /home/me/proj/src/test.js:44
line="$(logline "$logfile" 5 | LEX)"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "stderr:?")/"
assertRegex "$line" "/$(re_tok "$T_TRACE|$T_FILENAME" "\/home\/me\/proj\/src\/test\.js:44")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/bug-fn-inuse.log"
# 2020-04-24 13:02:13,114 WARN: Strange entry in use/foo/bar.html
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Strange entry")/"
assertRegex "$line" "/$(re_tok $T_TRACE "in use\/foo\/bar\.html")/"
# 2020-04-24 13:02:13,114 WARN: Syntax error in use.c
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Syntax error")/"
assertRegex "$line" "/$(re_tok $T_TRACE "in use\.c")/"
# 2020-04-24 13:02:13,114 WARN: Address already in use
line="$(logline "$logfile" 3 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Address already in use")/" \
"A trailing 'in use' was incorrectly recognized as a filename suffix."
# 2021-10-09 12:00:00,000 WARN: unexpected end-of-file in prolog
line="$(logline "$logfile" 4 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "unexpected end-of-file in prolog")/" \
"A trailing 'in prolog' was incorrectly recognized as a filename suffix."
line="$(logline "$HERE/samples/certbot.log" 2 | LEX)"
# 2019-06-05 04:33:37,590:WARN:certbot.log:Root logging level set at 30
assertRegex "$line" "/$(re_tok $T_MESSAGE ":?Root logging level set at 30")/" \
"A trailing 'set at 30' was incorrectly recognized as a filename suffix."
# Mar 03 12:00:00 myftp daemon: Cannot create directory: File exists
line="$(logline "$logfile" 5 | LEX)"
reOriginalMessage="$(re_tok $T_MESSAGE "Cannot create directory: File exists")"
reSplitMessage="$(re_tok $T_MESSAGE "Cannot create directory:?")$(re_tok $T_MESSAGE ":? ?File exists")"
assertRegex "$line" "/(?:$reOriginalMessage|$reSplitMessage)/" \
"A trailing 'file exists' was incorrectly recognized as a filename suffix."
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# hx supports the "printer" output mode
# in which it doesn't try to analyze any log input,
# it simply accepts a prepared token stream
# (as returned by the --lexer mode)
# and turns it into readable colorized output.
#
# So if the --lexer and the --printer mode are combined,
# the result should be exactly the same as the default mode!
# assertSamePrinterOutput LINE
# Compares the results of "hx --lexer | hx --printer" against the "hx" default mode.
# If everything is in order, both commands should have identical output.
assertSamePrinterOutput () {
local inputLine="$1"
local normalModeOutput="$(printf '%s\n' "$inputLine" | HX)"
local printerOutput="$(printf '%s\n' "$inputLine" | LEX | HX --printer)"
assertEq "$printerOutput" "$normalModeOutput" \
"\"hx\" and \"hx --lexer | hx --printer\" produced different output!"
}
assertSamePrinterOutput "$(syslogline 1)"
assertSamePrinterOutput "$(sysloggrep 'OUT=eth0')"
assertSamePrinterOutput "$(sysloggrep 'repeated 5 times')"
assertSamePrinterOutput "$(logline "$HERE/samples/apache2.log" 1)"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/bug-inword.log"
# Aug 1 12:00:00 myhost gdm-password]: gkr-pam: unlocked login keyring
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "gdm-password.*")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE ".*unlocked login keyring")/" \
"A trailing 'login keyring' was incorrectly recognized as 'log' immediately followed by 'in keyring' as an error source!"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# hx recognizes the HX_SETTINGS env variable
# which can be used to enable/disable/change some settings.
#
# This test depends on test-reduced-colors.
# Jun 24 01:37:40 myhost CRON[17920]: pam_unix(cron:session): session opened for user root by (uid=0)
normline="$(logline "$HERE/samples/tail-f.log" 2)"
# ==> /var/log/auth.log <==
metaline="$(logline "$HERE/samples/tail-f.log" 1)"
# thrown in File:123
contline=" thrown in File:123"
lmc_input="$(printf '%s\n%s\n%s\n' "$normline" "$metaline" "$contline")"
# Test "ecma48" option:
assertEq "$(HX_SETTINGS='ecma48' "$HX" < "$HERE/samples/syslog.log")" "$(HX --ecma48 < "$HERE/samples/syslog.log")" \
"HX_SETTINGS=ecma48 did not have same effect as --ecma48 cmdline option!"
# Test "ecma48" option plus garbage options:
assertEq "$(HX_SETTINGS=' foo ecma48 bar ' "$HX" < "$HERE/samples/syslog.log")" "$(HX --ecma48 < "$HERE/samples/syslog.log")" \
"HX_SETTINGS=\"garbage ecma48 garbage\" did not have same effect as --ecma48 cmdline option!"
# Test "noecma48" option right after "ecma48" option:
assertEq "$(HX_SETTINGS=' foo ecma48 bar noecma48 ' "$HX" < "$HERE/samples/syslog.log")" "$(HX < "$HERE/samples/syslog.log")" \
"HX_SETTINGS=\"ecma48 noecma48\" did NOT disable the ecma48 output mode!"
# Test "lp"/"cp"/"mp" options:
set_prefixes='foo mp="<M> " cp="<C> " bar lp="<L> " zog'
output="$(printf '%s\n' "$lmc_input" | HX_SETTINGS="$set_prefixes" "$HX" | strip_ansi)"
assertRegex "$output" "/^<L> Jun/m"
assertRegex "$output" "/^<M> ==>/m"
assertRegex "$output" "/^<C> \s*thrown/m"
# Test "loglineprefix"/"contlineprefix"/"metalineprefix" options:
set_prefixes='metalineprefix="<MM> " contlineprefix="<CC> " loglineprefix="<LL> "'
output="$(printf '%s\n' "$lmc_input" | HX_SETTINGS="$set_prefixes" "$HX" | strip_ansi)"
assertRegex "$output" "/^<LL> Jun/m"
assertRegex "$output" "/^<MM> ==>/m"
assertRegex "$output" "/^<CC> \s*thrown/m"
# Test "px" option:
set_prefixes='px="<!>" '
output="$(printf '%s\n' "$lmc_input" | HX_SETTINGS="$set_prefixes" "$HX" | strip_ansi)"
assertRegex "$output" "/^<!>Jun/m"
assertRegex "$output" "/^<!>==>/m"
assertRegex "$output" "/^<!>\s*thrown/m"
# Test "lineprefix" option:
set_prefixes='lineprefix="<!!>" '
output="$(printf '%s\n' "$lmc_input" | HX_SETTINGS="$set_prefixes" "$HX" | strip_ansi)"
assertRegex "$output" "/^<!!>Jun/m"
assertRegex "$output" "/^<!!>==>/m"
assertRegex "$output" "/^<!!>\s*thrown/m"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests pure-ftpd-specific message parsing.
#
# This test depends on test-syslog-logs.
logfile="$HERE/samples/syslog-pureftpd.log"
# Mar 03 12:00:00 myhost pure-ftpd: (?@127.0.0.1) [INFO] Logout.
line="$(logline "$logfile" 3 | LEX)"
assertRegex "$line" "/$(re_tok $T_CLIENT "\(\?@127\.0\.0\.1\)").*$(re_tok $T_LOGLEVEL "\[INFO\]").*$(re_tok $T_MESSAGE "Logout\.")/"
# Sep 28 12:00:00 myhost pure-ftpd: (username@ip11.22.33.44.isp.net) [DEBUG] Command [list] []
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_CLIENT "\(username@ip11\.22\.33\.44\.isp\.net\)").*$(re_tok $T_LOGLEVEL "\[DEBUG\]").*$(re_tok $T_MESSAGE "Command \[list\] \[\]")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/bug-datedigit.log"
# Wed Aug 14 10:21:13 2021: message
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "Wed Aug 14 10:21:13 2021:?")$(re_tok $T_MESSAGE)/"
# Wed Aug 4 10:21:13 2021: message
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "Wed Aug 4 10:21:13 2021:?")$(re_tok $T_MESSAGE)/" \
"Single-digit day-of-month with double space was not recognized correctly!"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/nginx.log"
# 2021/07/10 12:00:00 [error] 40#40: *44 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 127.0.35.1, server: test.tld, request: "GET /info HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "my-sys"
errorLine="$(logline "$logfile" 1 | LEX)"
assertRegex "$errorLine" "/$(re_tok $T_MESSAGE "recv\(\) failed \(104: Connection reset by peer\)")/"
assertRegex "$errorLine" "/$(re_tok $T_INFO "while reading response .* host: \"my-sys\".*")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests parsing of some messages generated by SSH.
# These formats are not really SSH-specific,
# this is just a place as good as any to test them.
#
# This test depends on test-syslog-logs.
logfile="$HERE/samples/ssh.log"
# Sep 7 13:53:43 myhost1 ssh[11000]: debug3: hostkeys_foreach: reading file "/home/me/.ssh/known_hosts"
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "ssh\[11000\]:?")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "debug3:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "hostkeys_foreach: reading file.*")/"
# Sep 7 13:53:43 myhost1 ssh[11000]: debug3: record_hostkey: found key type ECDSA in file /home/me/.ssh/known_hosts:16
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "record_hostkey: found key type ECDSA")/"
assertRegex "$line" "/$(re_tok $T_TRACE "in file \/home\/me\/\.ssh\/known_hosts:16")/"
# Sep 7 13:53:38 myhost1 ssh[11000]: debug1: /home/me/.ssh/config line 22: Applying options for myhost6
line="$(logline "$logfile" 3 | LEX)"
assertRegex "$line" "/$(re_tok $T_TRACE "\/home\/me\/\.ssh\/config line 22:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE ":? ?Applying options for myhost6")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/exception-stack.log"
re_backslash='(?:\\)'
# May 7 13:41:07 myhost myapp: ExceptionStack: could not validate 'known_prop': 'UNKNOWNVAL123' (stack: ValidationException: could not validate 'known_prop': 'UNKNOWNVAL123') (ErrorPkg\ExceptionStack @ src/Validation/Validator:161) (trace: src/Controller/UpdateController:59, src/RequestDispatch:134, public/index:18)
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_ERROR "ExceptionStack:?")(?:$(re_tok $T_MESSAGE ":"))?$(re_tok $T_MESSAGE ":? ?could not validate.*")/"
assertRegex "$line" "/$(re_tok $T_STACK "\s*\(stack: ValidationException: could not validate 'known_prop': 'UNKNOWNVAL123'\)")/"
assertRegex "$line" "/$(re_tok $T_TRACE "\(ErrorPkg${re_backslash}ExceptionStack @ src\/Validation\/Validator:161\)")/"
# 2019-02-12 11:05:52 ExceptionStack: foo bar (stack: InvalidArgumentException: foo; LogicException; RuntimeException/223: bar) (ErrorPkg\ExceptionStack @ TEST:37) (trace: aa, bb, cc)
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_MESSAGE "foo bar *")/"
assertRegex "$line" "/$(re_tok $T_STACK "\s*\(stack: InvalidArgumentException: foo; LogicException; RuntimeException/223: bar\)")/"
# TODO: test special highlighting of the (stack:…) section
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/apache2.log"
# [Tue Mar 26 20:49:29.019045 2019] [:error] [pid 54] [client 172.30.0.1:60248] PHP Warning: mysql_free_result() expects parameter 1 to be resource, null given in /srv/db.php on line 85
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "\[Tue Mar 26 20:49:29.019045 2019\]")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "\[:error\]")/"
assertRegex "$line" "/$(re_tok $T_APP "\[pid 54\]")/"
assertRegex "$line" "/$(re_tok $T_INFO "\[client 172.30.0.1:60248\]")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE ".*mysql_free_result\(\) expects parameter 1 to be resource, null given")/"
assertRegex "$line" "/$(re_tok $T_TRACE "in /srv/db.php on line 85")/"
# [Fri May 31 15:34:11.711154 2019] [proxy:warn] [pid 2197:tid 140111931162368] [client 127.0.0.1:24124] AH01144: No protocol handler was valid for the URL /foo/bar/test.php (scheme 'http'). If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_ERROR "AH01144:")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "No protocol handler.*")/"
# [Thu Jun 06 18:59:35.966014 2019] [authn_file:error] [pid 29838:tid 140111088789248] (13)Permission denied: [client 127.0.0.1:8092] AH01620: Could not open password file: /home/confluence/htpasswd
line="$(logline "$logfile" 3 | LEX)"
regex="$(re_tok $T_MESSAGE ".*Permission denied:.*")"
regex="$regex.*$(re_tok $T_ERROR "AH01620:")"
regex="$regex.*$(re_tok $T_MESSAGE "Could not open password file.*")"
assertRegex "$line" "/$regex/" # normal message part before and after T_ERROR!
# www.hostname.tld:80 127.0.50.33 - - [28/Apr/2019:15:28:14 +0200] "GET / HTTP/1.1" 302 452 "-" "Monitoring Bot"
line="$(logline "$logfile" 7 | LEX)"
assertRegex "$line" "/$(re_tok $T_HOST "www.hostname.tld:80")/"
assertRegex "$line" "/$(re_tok $T_CLIENT "127.0.50.33")/"
assertRegex "$line" "/$(re_tok $T_DATE "\[28\/Apr\/2019:15:28:14 \+0200\]")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "\"?GET / HTTP/1.1\"?")/"
assertRegex "$line" "/$(re_tok $T_HTTP_STATUS "302")/"
assertRegex "$line" "/$(re_tok $T_INFO "452 \"-\" \"Monitoring Bot\"")/"
# bb.hostname.tld:80 127.0.0.1 identUser basicUser [01/Apr/2019:17:22:03 +0200] "GET /img/upload/wf1.png HTTP/1.1" 304 165 "http://bb.hostname.tld/profile.php?UID=1&edit=1" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0"
line="$(logline "$logfile" 8 | LEX)"
assertRegex "$line" "/$(re_tok $T_USERNAME "identUser")/"
assertRegex "$line" "/$(re_tok $T_USERNAME "basicUser")/"
# AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
line="$(logline "$logfile" 10 | LEX)"
assertRegex "$line" "/$(re_tok $T_ERROR "AH00558:")$(re_tok $T_APP "apache2:")$(re_tok $T_MESSAGE)/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/bug-http-status.log"
# 2021-08-10 12:00:00,306:DEBUG:urllib3.connectionpool:http://r3.o.lencr.org:80 "POST / HTTP/1.1" 200 503
line="$(logline "$logfile" | LEX)"
reLine=
reLine="$reLine$(re_tok $T_DATE "2021-08-10 12:00:00,306:")"
reLine="$reLine$(re_tok $T_LOGLEVEL "DEBUG:")"
reLine="$reLine$(re_tok $T_APP "urllib3\.connectionpool:")"
assertRegex "$line" "/$reLine/"
reLine="(?:$(re_tok $T_MESSAGE "http://r3.o.lencr.org:80")$(re_tok $T_MESSAGE "\"POST / HTTP/1.1\".*")|$(re_tok $T_MESSAGE "http://r3.o.lencr.org:80 \"POST / HTTP/1.1\".*"))"
assertRegex "$line" "/$reLine/" \
"HTTP status at end of line was printed in the wrong position!"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/java.log"
# 2019-10-24 14:31:18.484 FINE MyUtil: moved /tmp/file1 to /tmp/file2 [info]
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2019-10-24 14:31:18\.484")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "FINE ?")/"
assertRegex "$line" "/$(re_tok $T_APP "MyUtil:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE ":? ?moved.*")/"
# at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
line="$(logline "$logfile" 3 | LEX)"
assertRegex "$line" "/^$(re_tok $T_CONTLINE)/"
assertRegex "$line" "/$(re_tok $T_INFO "\s+at org\.h2\.message.*")/"
# ... 16 more
line="$(logline "$logfile" 5 | LEX)"
assertRegex "$line" "/^$(re_tok $T_CONTLINE)/"
assertRegex "$line" "/$(re_tok $T_INFO "\s*\.\.\. 16 more")/"
#[2020-09-20T06:20:47,942][INFO ][o.e.x.m.p.l.CppLogMessageHandler] [0a0359200001] [controller/100] init
line="$(logline "$logfile" 7 | LEX)"
re=
re="${re}$(re_tok $T_DATE '\[.*\]')"
re="${re}$(re_tok $T_LOGLEVEL '\[INFO \]')"
re="${re}$(re_tok $T_INFO '\[.+CppLogMessageHandler\]')"
re="${re}$(re_tok $T_INFO '\[0a0359200001\].*')"
re="${re}$(re_tok $T_MESSAGE 'init')"
assertRegex "$line" "/$re/"
# [fe80.local..recover()] WARN javax.jmdns.impl.JmDNSImpl - fe80..recover() Could not recover we are Down!
line="$(logline "$logfile" 9 | LEX)"
re=
re="${re}$(re_tok $T_APP '\[fe80.+\(\)\]')"
re="${re}$(re_tok $T_LOGLEVEL 'WARN')"
re="${re}(?:$(re_tok $T_INFO 'javax.*')$(re_tok $T_INFO '-')|$(re_tok $T_INFO 'javax.* -'))"
re="${re}$(re_tok $T_MESSAGE 'fe80.*Could not recover.*')"
assertRegex "$line" "/$re/"
# 18:00:00.357 INFO [Node.<init>] - message
line="$(logline "$logfile" 10 | LEX)"
re=
re="${re}$(re_tok $T_DATE '18:00:00\.357')"
re="${re}$(re_tok $T_LOGLEVEL 'INFO')"
re="${re}$(re_tok $T_APP '\[Node\.<init>\](?: -)?')"
re="${re}$(re_tok "$T_APP|$T_INFO" '-')?"
re="${re}$(re_tok $T_MESSAGE 'message')"
assertRegex "$line" "/$re/"
# 2022-05-10 18:00:00.297:INFO: message
line="$(logline "$logfile" 11 | LEX)"
re=
re="${re}$(re_tok $T_DATE '2022-05-10 18:00:00\.297:')"
re="${re}$(re_tok $T_LOGLEVEL 'INFO:')"
re="${re}$(re_tok $T_MESSAGE 'message')"
assertRegex "$line" "/$re/"
# 12:00:00.871 INFO - message
line="$(logline "$logfile" 12 | LEX)"
re=
re="${re}$(re_tok $T_DATE '12:00:00\.871')"
re="${re}$(re_tok $T_LOGLEVEL 'INFO(?: -)?')"
re="${re}$(re_tok "$T_APP|$T_INFO" '-')?"
re="${re}$(re_tok $T_MESSAGE 'message')"
assertRegex "$line" "/$re/"
# [java] [1652207719.965][WARN]: message
line="$(logline "$logfile" 13 | LEX)"
re=
re="${re}$(re_tok $T_APP '\[java\]')"
re="${re}$(re_tok $T_DATE '\[1652207719\.965\]')"
re="${re}$(re_tok $T_LOGLEVEL '\[WARN\]:?')"
re="${re}$(re_tok "$T_LOGLEVEL|$T_INFO" ':')?"
re="${re}$(re_tok $T_MESSAGE 'message')"
assertRegex "$line" "/$re/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests parsing of some messages generated by Bind named.
#
# This test depends on test-syslog-logs.
logfile="$HERE/samples/named.log"
# Jun 1 01:01:01 robant named[1400]: client 192.168.3.11#40162 (my-domain.tld): query (cache) 'my-domain.tld/SOA/IN' denied
line="$(logline "$logfile" 1 | LEX)"
reApp="$(re_tok $T_APP "named\[1400\]:?")"
reCli="$(re_tok $T_CLIENT "client 1172.16.58.3#40162")"
reInf="$(re_tok $T_INFO "\(my-domain.tld\):?")"
reMsg="$(re_tok $T_MESSAGE "query .*")"
assertRegex "$line" "/$reApp$reCli$reInf$reMsg/"
success
<file_sep>#!/bin/sh
HX="$HERE/../src/hx"
HX () { "$HX" "$@" ; }
LEX () { HX --lexer "$@" ; }
SYSLOG="$HERE/samples/syslog.log"
# logline LOGFILE [LINENO=1 [LINES=1]]
logline () { tail -n "+${2:-1}" -- "$1" | head -n ${3:-1} ; }
# syslogline [LINENO=1]
syslogline () { logline "$SYSLOG" "$1" ; }
# sysloggrep GREPEXPR
sysloggrep () { grep -m 1 -e "$@" -- "$SYSLOG" ; }
# RE_CONTENT: Matches one character of token content. Add "*" or "+" for an entire token's content.
RE_CONTENT="(?:\\\\.|[^\\\\)])"
# RW: Matches the whitespace before, between, and after tokens.
RW="(?:^| +|\$|\\n)"
# RE_SGR0: Matches the ANSI SGR0 sequence.
RE_SGR0='(?:\x1b\[0(?:;0)*m)'
# copied from Token.pm:
T_APP='A'
T_DATE='D'
T_HOST='H'
T_LOGLEVEL='G'
T_LINE='L'
T_EMPTYLINE='EL'
T_METALINE='ML'
T_CONTLINE='CL'
T_PACKEDLINE='PKL'
T_EOL='Z'
T_CLIENT='C'
T_USERNAME='UN'
T_FNCALL='F'
T_INFO='I'
T_STACK='S'
T_TRACE='T'
T_REPEAT='RP'
T_REPEATEND='RE'
T_WRAP='WR'
T_WRAPEND='WE'
T_ERROR='X'
T_MESSAGE='M'
T_KV='KV'
T_JSON='JS'
T_FILENAME='FN'
T_HTTP_STATUS='HS'
strip_ansi () { perl -pe "s/\\x1b\\[\\d+(?:;\\d+)*m//g"; }
# re_b
# Regex to match the sequence which turns text bold.
re_b () { printf '%s' "\\x1b\\[(?:(?:\\d\\+;)*0;)?1m"; }
# re_col COLORCODE
# Regex to match the sequence which colorizes text.
# Separate multiple allowed color codes with "|".
re_col () { printf '%s' "\\x1b\\[(?:(?:\\d\\+;)*0;)?(?:$1)m"; }
# re_b_col COLORCODE
# Regex to match the sequence which colorizes and boldens text.
# Separate multiple allowed color codes with "|".
re_b_col () { printf '%s' "\\x1b\\[(?:(?:\\d\\+;)*0;)?(?:(?:$1)(?:;|\\x1b\\[)1|1(?:;|\\x1b\\[)(?:$1))m"; }
# re_xtok TOKENTYPE CONTENT [ISOPT=no]
# Regex to match one token of TOKENTYPE type (can be multiple allowed types; separate with "|")
# which either has exact content CONTENT,
# or whose content is ignored if the second argument is missing.
re_xtok () {
local re_attr="(?:\\[[^\\]]*\\])?"
local re_content="${RE_CONTENT}*"
local opt='?'
if [ $# -ge 2 ]; then
re_content="$2"
if [ -n "$2" ] && [ "$2" != " ? ?" ] && [ "$3" != "yes" ]; then
opt=
fi
fi
# Token contents cannot contain plain closing parentheses.
# To avoid cluttering all regexes in the test scripts,
# let's make sure our patterns match the actually expected contents:
re_content="$(printf '%s' "$re_content" | sed 's/\\)/\\\\\\)/g')"
# printf '%s' "(?:^|\\s)(?:$1)${re_attr}(?:\\(${re_content}\\))${opt}${RW}"
printf '%s' "(?:\\b(?:$1)${re_attr}(?:\\(${re_content}\\))${opt}${RW})"
}
# re_tok TOKENTYPE CONTENT
# Regex to match one token of TOKENTYPE type (can be multiple allowed types; separate with "|")
# which either has content CONTENT (where one leading and/or one trailing space will be ignored),
# or whose content is ignored if the second argument is missing.
re_tok () {
if [ $# -lt 2 ]; then re_xtok "$1"; return; fi
re_xtok "$1" " ?$2 ?"
}
# re_ztok TOKENTYPE
# Matches an empty token.
# If the TOKENTYPE is T_EOL or T_EMPTYLINE, a linebreak content is also allowed.
re_ztok () {
local re_content=''
if [ "$1" = "$T_EOL" ] || [ "$1" = "$T_EMPTYLINE" ]; then
re_content="(?:\\\\n)?"
fi
re_xtok "$1" "$re_content" yes
}
# re_optbrk
# Matches an optional linebreak.
re_optbrk () {
printf '%s\n' "(?:\\\\n)?"
}
# assertContainsNoAnsiSequences STRING [ERRMSG]
assertContainsNoAnsiSequences () {
assertRegex "$1" "!/\x1b\[/" \
"${2:-"String '$1' contained ANSI sequences when it shouldn't!"}"
}
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/postgres.log"
# 2021-10-10 11:00:00.001 UTC [16000] LOG: listening on IPv4 address "0.0.0.0", port 5432
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2021-10-10 11:00:00.001 UTC")/"
assertRegex "$line" "/$(re_tok $T_INFO "\[16000\]")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "LOG: ?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "listening on IPv4 address \"0.0.0.0\", port 5432")/"
# 2021-10-10 12:00:00.001 UTC [16000] user@db LOG: could not receive data from client: Connection reset by peer
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_INFO "\[16000\]")$(re_tok $T_CLIENT "user@db")$(re_tok $T_LOGLEVEL "LOG: ?")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Make sure the program can start and can handle input,
# i.e. it won't crash and it will print _something._
assertCmd "\"$HX\" </dev/null"
assertCmd "head -n1 \"$HERE/samples/syslog.log\" | \"$HX\""
[ -n "$ASSERTCMDOUTPUT" ] || fail "hx produced no output!"
assertContains "$ASSERTCMDOUTPUT" '[' \
"hx output contained no ansi coloring sequences at all!"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# This class tests the nginx error format when handling php-fpm error output.
# There's special treatment for wrapped error messages
# so that only the important part appears in white while the rest should be grayed-out.
# Additionally, this scripts tests some PHP exception output specialties
# (the exception class name should be T_ERROR, not T_MESSAGE).
logfile="$HERE/samples/nginx-fastcgi.log"
# 2019/06/22 12:32:30 [error] 29744#29744: *30354220 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.16.31.10, server: www.hostname.tld, request: "GET /_sub/_page/_images/101010.html HTTP/1.0", upstream: "fastcgi://127.0.0.1:9000", host: "www.hostname.tld"
errorLine="$(logline "$logfile" 1 | LEX)"
assertRegex "$errorLine" "/$(re_tok $T_DATE "2019\/06\/22 12:32:30")/"
assertRegex "$errorLine" "/$(re_tok $T_LOGLEVEL "\[error\]")/"
assertRegex "$errorLine" "/$(re_tok $T_APP "29744#29744:?")/"
# We don't care if the "*30354220" will become part of the WRAP or a separate INFO block:
assertRegex "$errorLine" "/(?:$(re_tok $T_INFO "\*30354220")$(re_tok $T_WRAP "FastCGI sent in stderr: \"")|$(re_tok $T_WRAP "\*30354220 FastCGI sent in stderr: \""))/"
assertRegex "$errorLine" "/$(re_tok $T_MESSAGE "Primary script unknown")/"
assertRegex "$errorLine" "/$(re_tok $T_WRAPEND "\" while reading response header from upstream\b.*")/"
# We don't care if the part after the comma is part of the WRAPEND or a separate trailing INFO block:
assertRegex "$errorLine" "/$(re_tok "$T_WRAPEND|$T_INFO" "(?:\" while reading response header from upstream)?,? ?client: 172\.0\.0\.1, server: www\.hostname\.tld, request: \"GET \/_sub\/_page\/_images\/101010\.html HTTP\/1\.0\", upstream: \"fastcgi:\/\/127\.0\.0\.1:9000\", host: \"www\.hostname\.tld\"$(re_optbrk)")/"
# 2019/06/22 12:42:35 [error] 70#70: *5538 FastCGI sent in stderr: "PHP message: PHP Fatal error: Class MyBaseLookupAction not found in /var/www/myapp/classes/actions/custom/lookup/MyCustomLookupAction.php on line 12" while reading response header from upstream, client: 172.19.0.1, server: my.app.tld, request: "GET /lookup?q=xyzxyzxyz HTTP/1.0", upstream: "fastcgi://127.0.0.1:9000", host: "my.app.tld", referrer: "http://my.app.tld/lookup/entity?id=120041"
phpErrorLine="$(logline "$logfile" 2 | LEX)"
rePhp1="$(re_tok $T_MESSAGE "PHP message: PHP Fatal error: Uncaught")"
rePhp2="$(re_tok $T_ERROR "TestException:?")"
rePhp3="(?:$(re_tok $T_MESSAGE ":?"))?"
rePhp4="$(re_tok $T_MESSAGE ":? ?foobar")"
assertRegex "$phpErrorLine" "/$(re_tok $T_WRAP ".*sent in stderr: \"")/"
assertRegex "$phpErrorLine" "/${rePhp1}${rePhp2}${rePhp3}${rePhp4}/"
assertRegex "$phpErrorLine" "/$(re_tok $T_TRACE "in /var/www/myapp/classes/actions/custom/lookup/MyCustomLookupAction\.php on line 12")/"
assertRegex "$phpErrorLine" "/$(re_tok $T_WRAPEND "\" while reading.*")/"
# 2021/05/31 12:00:00 [error] 60#60: *3 FastCGI sent in stderr: "PHP message: 2021-05-30T12:00:00+02:00 [critical] Uncaught Exception: Cache::__construct(/proj/tmp): failed to open dir: Permission denied" while reading upstream, client: 127.0.0.1, server: test.tld, request: "GET /my/test HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "test.tld"
phpErrorLine="$(logline "$logfile" 3 | LEX)"
reWrapBegin="$(re_tok $T_WRAP ".*stderr: \"")"
rePhp="$(re_tok $T_MESSAGE "PHP message: .* Permission denied")"
reWrapEnd=""$(re_tok $T_WRAPEND "\" while reading upstream.*")
assertRegex "$phpErrorLine" "/${reWrapBegin}${rePhp}${reWrapEnd}/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests nested info brackets.
#
# This test depends on test-syslog-logs.
logfile="$HERE/samples/nested-info.log"
# Aug 1 12:00:00 myhost kernel: [drm:drm_dp_send_dpcd_read [drm_kms_helper]] info
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_INFO "\[drm:drm_dp_send_dpcd_read \[drm_kms_helper\]\]")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests proftpd-specific message parsing.
# (Similar to syslog.)
logfile="$HERE/samples/proftpd.log"
# 2020-07-10 12:00:00,001 mysys proftpd[20000] mysys: ProFTPD 1.3.5e standalone mode SHUTDOWN
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2020-07-10 12:00:00,001")/"
assertRegex "$line" "/$(re_tok $T_HOST "mysys")/"
assertRegex "$line" "/(?:$(re_tok $T_APP "proftpd\[20000\] mysys:?")|$(re_tok $T_APP "proftpd\[20000\]")$(re_tok "$T_APP|$T_HOST" "mysys:?"))/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "ProFTPD.*")/"
# 2021-08-12 06:00:00,000 mysys proftpd[35000] mysys.hostname.fqdn: message
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/(?:$(re_tok $T_APP "proftpd\[35000\] mysys\.hostname\.fqdn:?")|$(re_tok $T_APP "proftpd\[35000\]")$(re_tok "$T_APP|$T_HOST" "mysys\.hostname\.fqdn:?"))/"
# 2021-08-12 11:00:00,000 mysys proftpd[46000] mysys.hostname.fqdn (127.0.0.1[127.0.0.1]): FTP session closed.
line="$(logline "$logfile" 3 | LEX)"
assertRegex "$line" "/(?:$(re_tok $T_APP "proftpd\[46000\] mysys\.hostname\.fqdn \(127\.0\.0\.1\[127\.0\.0\.1\]\):?")|$(re_tok $T_APP "proftpd\[46000\]")$(re_tok "$T_APP|$T_HOST" "mysys\.hostname\.fqdn \(127\.0\.0\.1\[127\.0\.0\.1\]\):?"))/"
xferlogfile="$HERE/samples/proftpd-xferlog.log"
# Sun Aug 01 12:00:00 2021 0 client.addr 3910000 /home/user/storage/image.jpg b _ o r username ftp 0 * c
line="$(logline "$xferlogfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_CLIENT "client.addr")$(re_tok $T_MESSAGE "3910000")$(re_tok $T_FILENAME "/home/user/storage/image.jpg").*$(re_tok $T_MESSAGE "o").*$(re_tok $T_USERNAME "username")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/nextcloud.log"
# 2021-08-22 12:00:00:600 [ warning nextcloud.sync.networkjob ]: Network job timeout QUrl("/")
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2021-08-22 12:00:00:600")/"
assertRegex "$line" "/$(re_tok "$T_LOGLEVEL|$T_INFO" "\[.*")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL ".*warning.*")/"
assertRegex "$line" "/$(re_tok $T_APP "nextcloud\.sync\.networkjob \]:\s*")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Network job timeout.*")/"
# 2021-08-22 12:00:00:603 [ debug nextcloud.sync.cookiejar ] [ OCC::CookieJar::cookiesForUrl ]: QUrl("...") requests: (...)
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "nextcloud\.sync\.cookiejar \]\s*")$(re_tok $T_INFO "\[ OCC::CookieJar::cookiesForUrl \]:\s*")$(re_tok $T_MESSAGE "QUrl.*")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# This test depends on test-symfony4-logs and test-apache-logs.
logfile="$HERE/samples/sym4-packed.log"
re_backslash='(?:\\)'
line="$(logline "$logfile" 1 | LEX)"
rePart0="^$(re_tok $T_LINE).*" # make sure it's not a CONTLINE (some of the packed parts look like a contline, but that should have no visible effect in a packed line)
rePart1="$(re_tok $T_ERROR "SoapFault:?")"
rePart1="${rePart1}$(re_tok $T_MESSAGE ":")?$(re_tok $T_MESSAGE ":? ?Could not connect to host")"
rePart1="${rePart1}$(re_tok $T_TRACE "in \/var\/myproj\/Import.php:20")"
rePart1="${rePart1}$(re_tok "$T_MESSAGE|$T_INFO")?"
rePart2="$(re_tok $T_PACKEDLINE)$(re_tok $T_INFO "Stack trace:")"
rePart3="$(re_tok $T_PACKEDLINE)"
rePart3="${rePart3}$(re_tok $T_INFO "#0")"
rePart3="${rePart3}$(re_tok $T_TRACE "\[internal function\]:? ?")"
rePart3="${rePart3}$(re_tok $T_INFO ":")?"
rePart3="${rePart3}$(re_tok $T_FNCALL "SoapClient->.*")"
rePart3="${rePart3}.*"
rePart4="$(re_tok $T_PACKEDLINE)$(re_tok $T_INFO "#1").*"
rePart5="$(re_tok $T_PACKEDLINE)"
rePart5="${rePart5}$(re_tok $T_DATE "Next")"
rePart5="${rePart5}$(re_tok $T_ERROR "App${re_backslash}Exception${re_backslash}CustomSOAPException")"
rePart5="${rePart5}$(re_tok $T_MESSAGE ":")?"
rePart5="${rePart5}$(re_tok $T_MESSAGE ":? ?soap request failed: Could not connect to host")"
rePart5="${rePart5}$(re_tok $T_TRACE "in \/var\/myproj\/Exception\/CustomSOAPException.php:20")"
rePart5="${rePart5}.*"
rePart6="$(re_tok $T_PACKEDLINE)$(re_tok $T_INFO "Stack trace:")"
rePart7="$(re_tok $T_PACKEDLINE)$(re_tok $T_INFO "#0")"
assertRegex "$line" "/$rePart0$rePart1$rePart2$rePart3$rePart4$rePart5$rePart6$rePart7/"
logfile="$HERE/samples/apache2-php-packed.log"
# [Fri Jul 30 14:00:00.100000 2020] [php7:notice] [pid 6001] [client 127.0.0.1:51000] PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'test'@'localhost' (using password: YES) in /proj/db.php:8\nStack trace:\n#0 /proj/db.php(8): PDO->__construct()\n#1 /proj/save.php(9): require('/home/mle/web/v...')\n#2 {main}\n thrown in /proj/db.php on line 8, referer: http://other.tld/foo
re=
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "\[?php7:notice\]?")/"
assertRegex "$line" "/$(re_tok "$T_MESSAGE|$T_ERROR" "PHP Fatal error:.*")/"
assertRegex "$line" "/$(re_tok $T_ERROR "PDOException:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "SQLSTATE.*")/"
assertRegex "$line" "/$(re_tok $T_TRACE "in \/proj\/db.php:8")/"
re="${re}$(re_tok $T_PACKEDLINE).*$(re_tok $T_INFO "Stack trace.*").*"
re="${re}$(re_tok $T_PACKEDLINE).*$(re_tok $T_INFO "#0").*"
re="${re}$(re_tok $T_PACKEDLINE).*$(re_tok $T_INFO "#1").*$(re_tok $T_FNCALL "require.*").*"
assertRegex "$line" "/${re}/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests processing of the "tail -f" output format.
#
# This test depends on test-syslog-logs.
logfile="$HERE/samples/tail-f.log"
output="$(HX --lexer < "$logfile")"
# ==> /var/log/auth.log <==
# Jun 24 01:37:40 myhost CRON[17920]: pam_unix(cron:session): session opened for user root by (uid=0)
# ==> /var/log/auth.log.1 <==
# Jun 24 01:37:40 myhost CRON[17921]: pam_unix(cron:session): session closed for user root
re_meta1="$(re_tok $T_METALINE)$(re_tok $T_MESSAGE "==>")$(re_tok $T_FILENAME "\/var\/log\/auth\.log")$(re_tok $T_MESSAGE "<==$(re_optbrk)")"
re_meta2="$(re_tok $T_METALINE)$(re_tok $T_MESSAGE "==>")$(re_tok $T_FILENAME "\/var\/log\/auth\.log\.1")$(re_tok $T_MESSAGE "<==$(re_optbrk)")"
re_app1="$(re_tok $T_APP "CRON\[17920\]:?")"
re_app2="$(re_tok $T_APP "CRON\[17921\]:?")"
re_msg1="$(re_tok $T_MESSAGE ".*session opened.*")"
re_msg2="$(re_tok $T_MESSAGE ".*session closed.*")"
assertRegex "$output" "/${re_meta1}.*${re_app1}.*${re_msg1}.*${re_meta2}.*${re_app2}.*${re_msg2}/s"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/certbot.log"
# 2019-06-05 04:33:37,578:DEBUG:certbot.main:Discovered plugins: PluginsRegistry(PluginEntryPoint#apache,PluginEntryPoint#manual,PluginEntryPoint#null,PluginEntryPoint#standalone,PluginEntryPoint#webroot)
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2019-06-05 04:33:37,578:?")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL ":?DEBUG:?")/"
assertRegex "$line" "/$(re_tok $T_APP ":?certbot\.main:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Discovered plugins: PluginsRegistry.*")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Jun 16 10:27:20 test-pc rsyncd[31755]: sent 63 bytes received 100688092 bytes total size 100663296
line="$(syslogline 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "Jun 16 10:27:20")/"
assertRegex "$line" "/$(re_tok $T_HOSTNAME "test-pc")/"
assertRegex "$line" "/$(re_tok $T_APP "rsyncd\[31755\]:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "sent 63 bytes.*")/"
# Jun 16 10:27:20 test-pc kernel: [ 2961.795960] TCP: request_sock_TCP: Possible SYN flooding on port 4444. Sending cookies. Check SNMP counters.
line="$(syslogline 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "kernel:?")/"
assertRegex "$line" "/$(re_tok $T_INFO "\[ 2961.795960\]")/"
assertRegex "$line" "/$(re_tok $T_APP "TCP: ")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "request_sock_TCP: Possible.*")/"
# Jul 17 18:52:43 hostname1 gnome-software[12960]: message repeated 5 times: [ Failed to load snap icon: local snap has no icon]
line="$(syslogline 5 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "gnome-software\[12960\]:?")/"
assertRegex "$line" "/$(re_tok $T_REPEAT "message repeated 5 times: \[")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Failed to load snap icon.*")/"
assertRegex "$line" "/$(re_tok $T_REPEATEND "\]$(re_optbrk)")/"
# Aug 6 11:15:00 hostname1 org.gnome.Shell.desktop[19986]: [Parent 25206, Gecko_IOThread] WARNING: pipe error (47): Connection reset by peer: file /build/firefox-tGfEvD/firefox-68.0.1+build1/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 358
line="$(syslogline 6 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "org.gnome.Shell.desktop\[19986\]:?")/"
assertRegex "$line" "/$(re_tok $T_INFO "\[Parent 25206, Gecko_IOThread\]")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "WARNING:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "pipe error \(47\): Connection reset by peer.*")/"
assertRegex "$line" "/$(re_tok $T_TRACE ".*file .*ipc_channel_posix.cc, line 358")/"
# Aug 6 11:15:01 hostname1 org.gnome.Shell.desktop[19986]: ###!!! [Parent][RunMessage] Error: Channel closing: too late to send/recv, messages will be lost
line="$(syslogline 7 | LEX)"
assertRegex "$line" "/$(re_tok $T_INFO "###!!!.*")/"
assertRegex "$line" "/$(re_tok $T_INFO ".*\[Parent\]\[RunMessage\]")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "Error:*")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE ".*Channel closing.*")/"
# Aug 6 11:15:01 hostname1 CRON[16964]: (root) CMD ( test -x /etc/cron.daily/popularity-contest && /etc/cron.daily/popularity-contest --crond)
line="$(syslogline 8 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "CRON\[16964\]:?")/"
assertRegex "$line" "/$(re_tok $T_USERNAME "(\()?root(\))?")/"
assertRegex "$line" "/$(re_tok $T_INFO "CMD \(\s*")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "\s*test .* --crond")/"
assertRegex "$line" "/$(re_tok $T_INFO "\)$(re_optbrk)")/"
# Aug 1 12:00:00 hostname1 kernel: [ 35.099202] audit: type=1400 audit(1000000000.008:38): apparmor="DENIED" operation="capable" profile="/snap/snapd/12704/usr/lib/snapd/snap-confine" pid=2000 comm="snap-confine" capability=4 capname="fsetid"
line="$(syslogline 11 | LEX)"
assertRegex "$line" "/(?=\S*?[\[,]src=audit\b)(?=\S*?[\[,]k=apparmor\b)$(re_tok $T_KV "apparmor=\"DENIED\"")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/python.log"
# 2019-05-31 11:42:02,115 - __init__.py[WARN]: Attempting setup of ephemeral network on ens3 with 169.254.0.1/16 brd 169.254.255.255
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2019-05-31 11:42:02,115(?: -)?")/"
assertRegex "$line" "/$(re_tok $T_APP "__init__\.py")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "\[WARN\]:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Attempting .*")/"
# error: <class 'socket.error'>, [Errno 99] Cannot assign requested address: file: /usr/lib/python2.7/socket.py line: 571
line="$(logline "$logfile" 2 | LEX)"
reError="$(re_tok $T_LOGLEVEL "error:?")"
reType="$(re_tok $T_APP ":? ?<class 'socket\.error'>,?")"
reErrno="$(re_tok $T_ERROR ",? ?\[Errno 99\]")"
reMsg="$(re_tok $T_MESSAGE "Cannot assign requested address:?")"
reSource="$(re_tok $T_TRACE ":? ?file: \/usr\/lib\/python2\.7\/socket\.py line: 571")"
assertRegex "$line" "/${reError}${reType}${reErrno}${reMsg}${reSource}/"
# error: <class 'socket.error'>, [Errno 99] Cannot assign requested address in file:///usr/lib/python2.7/socket.py:571
line="$(logline "$logfile" 3 | LEX)"
reSource="$(re_tok $T_TRACE "(?:in )?file:\/\/\/usr\/lib\/python2\.7\/socket\.py:571")"
assertRegex "$line" "/${reMsg}${reSource}/"
# FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
line="$(logline "$logfile" 4 | LEX)"
assertRegex "$line" "/(?:$(re_tok $T_ERROR "FileNotFoundError:")$(re_tok $T_ERROR "\[Errno 2\]")|$(re_tok $T_ERROR "FileNotFoundError: \[Errno 2\]"))$(re_tok $T_MESSAGE)/"
# Traceback (most recent call last):
line="$(logline "$logfile" 5 | LEX)"
assertRegex "$line" "/$(re_tok $T_CONTLINE).*$(re_tok $T_INFO "Traceback.*")/"
# File "/home/user/.local/lib/python3.7/site-packages/rest_framework/views.py", line 457, in handle_exception
line="$(logline "$logfile" 6 | LEX)"
assertRegex "$line" "/$(re_tok $T_CONTLINE)/"
assertRegex "$line" "/$(re_tok $T_TRACE "File \"/home/user/.local/lib/python3.7/site-packages/rest_framework/views.py\", line 457,?")/"
assertRegex "$line" "/$(re_tok $T_FNCALL "(?:in )?handle_exception")/"
# self.raise_uncaught_exception(exc)
line="$(logline "$logfile" 6 2 | LEX | tail -n1)"
assertRegex "$line" "/$(re_tok $T_CONTLINE)/"
success
<file_sep>```
# make install
```
This will copy the hx script to <code>/usr/local/bin/<b>hx</b></code>
and the man page to <code>/usr/local/share/man/man1/<b>hx.1</b>.gz</code>.
The script's internal modules
will be copied to `/usr/local/lib/hx-modules/`.
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# hx recognizes the HX_COLORS env variable
# which can be used to set custom colors
# for various token classes.
#
# This test depends on test-mode-printer
# because this way we don't have to use any specific log format
# (which might require specific tests to be run first)
# and on test-set-settings
# so that we can set custom prefix symbols.
strip_sgr0 () { perl -pe "s/\\x1b\\[0m//g"; }
re_linebegin="^${RE_SGR0}?"
PRN () {
local colorDefinitions="$1" ; shift
HX_COLORS="$colorDefinitions" HX_SETTINGS="px=\"# \"" "$HX" --printer "$@"
}
input="$HERE/samples/alltokens.hxt"
# Using the "*=0" sequence should get rid of all coloring sequences except possibly SGR0:
outputWithoutColors="$(PRN '*=0' < "$input" | strip_sgr0)"
assertContainsNoAnsiSequences "$outputWithoutColors" \
"hx with HX_COLORS=\"*=0\" still produced some ANSI sequences in its output!"
# prefix symbols in red, green, blue;
# date in bold-red, app in bold-green, host in bold-yellow, info-prefixes in bold-violet, info-suffixes in violet;
# message in faint-white;
# nothing else.
output="$(PRN 'SY=31:ML=32:CL=34:dt=1;31:ap=1;32:hn=1;33:ix=1;35:in=35:ms=2;37:*=0' <"$input")"
assertRegex "$output" "/${re_linebegin}$(re_col 32 "# ").*${re_linebegin}$(re_col 31 "# ").*${re_linebegin}$(re_col 34 "# ")/ms"
assertRegex "$output" "/$(re_b_col 31)date/"
assertRegex "$output" "/$(re_b_col 32)app/"
assertRegex "$output" "/$(re_b_col 33)host/"
assertRegex "$output" "/$(re_b_col 35)infoprefix/"
assertRegex "$output" "/$(re_col 35)infosuffix/"
assertRegex "$output" "/$(re_col '2;37')message/"
# json wrapper in yellow; keys in blue; nothing else.
output="$(PRN 'jw=33:ke=34:*=0' <"$input")"
assertRegex "$output" "/$(re_col 33)\{$(re_col 0)\"$(re_col 34)k1$(re_col 0)\":\[2.*\"$(re_col 34)y1$(re_col 0)\":\"json\"[^\x1b]*\}\]$(re_col 33)\}$(re_col 0)/"
# test "aa=bb"-style reference color assignment:
input="L D(2019 ) I(- ) A(appname ) M(msg ) Z"
colors="*=35:dt=34:ap=dt" # date in blue, appname same but also bold+italic (!), everything else violet
output="$(printf '%s\n' "$input" | PRN "$colors")"
assertRegex "$output" "/$(re_col 34 "2019")/"
assertRegex "$output" "/$(re_col 34 "appname")/"
assertRegex "$output" "/$(re_col 35 "msg")/"
# test "aa=bb;1"-style appending reference color assignment:
input="L D(2019 ) I(- ) A(appname ) M(msg ) Z"
colors="*=35:dt=34:ap=dt;1;3" # date in blue, appname same but also bold+italic (!), everything else violet
output="$(printf '%s\n' "$input" | PRN "$colors")"
assertRegex "$output" "/$(re_col 34 "2019")/"
assertRegex "$output" "/$(re_col '34;1;3' "appname")/"
assertRegex "$output" "/$(re_col 35 "msg")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# This test depends on test-syslog-logs.
logfile="$HERE/samples/mysqld.log"
# 2019-05-21T12:25:57.649219Z 0 [Note] /usr/sbin/mysqld: ready for connections.
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2019-05-21T12:25:57.649219Z")/"
assertRegex "$line" "/$(re_tok $T_INFO "0")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "\[Note\]")/"
assertRegex "$line" "/$(re_tok $T_APP "\/usr\/sbin\/mysqld:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "ready for connections.")/"
# Mar 28 08:15:00 myhost mariadbd[1830]: 2022-03-28 8:15:00 129 [Warning] Access denied for user anonymous@192.168.0.1 (using password: NO)
line="$(logline "$logfile" 7 | LEX)"
re=
re="${re}$(re_tok $T_DATE "Mar 28 08:15:00")"
re="${re}$(re_tok $T_HOST "myhost")"
re="${re}$(re_tok $T_APP "mariadbd\[1830\]:")"
re="${re}$(re_tok $T_DATE "2022-03-28 8:15:00")"
re="${re}$(re_tok $T_INFO "129")"
re="${re}$(re_tok $T_LOGLEVEL "\[Warning\]")"
re="${re}$(re_tok $T_MESSAGE)"
assertRegex "$line" "/$re/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/second-error-code.log"
re_backslash='(?:\\)'
# [2018-01-01 10:00:00] php.CRITICAL: Uncaught Exception: An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused {"json":["data"]} []
line="$(logline "$logfile" 1 | LEX)"
re=
re="${re}$(re_tok $T_ERROR "Exception:?")(?:$(re_tok $T_MESSAGE ":"))?"
re="${re}$(re_tok $T_MESSAGE ":? ?An exception occurred in driver.*")"
re="${re}$(re_tok $T_ERROR "SQLSTATE.*").*"
re="${re}$(re_tok $T_MESSAGE ".*Connection refused").*"
re="${re}$(re_tok $T_JSON "\{.*\}")"
assertRegex "$line" "/$re/"
# [2021-01-01 10:00:00] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\InvalidFieldNameException: "An exception occurred while executing '(SQL)' with params ["H90"]: SQLSTATE[42S22]: Column not found: 1054 Unknown column 't0.access' in 'field list'" at /proj/AbstractMySQLDriver.php line 60 {"json":["data"]} []
line="$(logline "$logfile" 3 | LEX)"
re=
re="${re}$(re_tok $T_ERROR "Doctrine${re_backslash}DBAL${re_backslash}Exception${re_backslash}InvalidFieldNameException:?")(?:$(re_tok $T_MESSAGE ":"))?"
re="${re}$(re_tok $T_MESSAGE ":? ?\"An exception occurred while executing '.*' with params \[.*\]: ?")"
re="${re}$(re_tok $T_ERROR "SQLSTATE(?:\[42S22\]:?)?").*"
re="${re}$(re_tok $T_MESSAGE ".*Column not found:.*")"
assertRegex "$line" "/$re/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
SYSLOGLINE="$(syslogline 1 | HX)"
KERNELLINE="$(sysloggrep 'OUT=eth0' | HX)"
REPEATLINE="$(sysloggrep 'repeated 5 times' | HX)"
color_date='33'
color_host="$color_date"
color_app="$color_date"
color_msg='37|0'
color_rpt='34'
color_info='30|37|38;5;243'
color_prefix="$color_info|38;2;125;117;83"
assertRegex "$SYSLOGLINE" "/$(re_col $color_date)Jun 16\\b/"
assertRegex "$SYSLOGLINE" "/$(re_col $color_host)test-pc\\b/"
assertRegex "$SYSLOGLINE" "/$(re_col $color_app)rsyncd\\b/"
assertRegex "$SYSLOGLINE" "/$(re_col $color_msg)sent 63 bytes\\b/"
assertRegex "$KERNELLINE" "/$(re_col $color_prefix)\\[269611.241825\\]/"
assertRegex "$REPEATLINE" "/$(re_col $color_rpt)message repeated 5 times:/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/firefox.log"
# 1628583436258 FirefoxAccounts TRACE initializing new storage manager
line="$(logline "$logfile" 1 | LEX)"
reTs="$(re_tok $T_DATE "1628583436258\t?")"
reApp="$(re_tok $T_APP "\t?FirefoxAccounts\t?")"
reLvl="$(re_tok $T_LOGLEVEL "\t?TRACE\t?")"
reMsg="$(re_tok $T_MESSAGE "init.*")"
assertRegex "$line" "/$reTs$reApp$reLvl$reMsg/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/elastic.log"
# [2021-08-01T14:00:00.585+0000][1][gc,cpu ] GC(13) User=0.10s Sys=0.00s Real=0.01s
line="$(logline "$logfile" | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "\[2021-08-01T14:00:00\.585\+0000\]")/"
assertRegex "$line" "/(?:$(re_tok $T_INFO "\[1\]")$(re_tok $T_INFO "\[gc,cpu \]")|$(re_tok $T_INFO "\[1\]\[gc,cpu \]"))/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "GC\(13\).*")/"
success
<file_sep>
#### Screenshots
**Apache logs,** original vs. colored with hx:
[<img alt="Apache2 logs, original" src="/doc/img/apache0.png" width="49%">](/doc/img/apache0.png)
[<img alt="Apache2 logs using hx" src="/doc/img/apache1.png" width="49%">](/doc/img/apache1.png)
**Syslog:**
[<img alt="Syslog, original" src="/doc/img/syslog0.png" width="49%">](/doc/img/syslog0.png)
[<img alt="Syslog using hx" src="/doc/img/syslog1.png" width="49%">](/doc/img/syslog1.png)
→ [More Screenshots](/doc/Screenshots.md)
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests postfix-specific message parsing.
#
# This test depends on test-syslog-logs.
logfile="$HERE/samples/syslog-postfix.log"
# Jun 6 04:47:07 hostname2 postfix/local[8013]: 812F1252C46: to=<<EMAIL>>, orig_to=<root>, relay=local, delay=0.03, delays=0.02/0.01/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "postfix\/local\[8013\]:?")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "812F1252C46:?")/"
assertRegex "$line" "/$(re_tok $T_KV "to=<<EMAIL>>")/"
assertRegex "$line" "/$(re_tok $T_KV "status=sent")/"
assertRegex "$line" "/$(re_tok $T_INFO "\(delivered to mailbox\)")/"
# processing of the DSN status codes is done by the printing module:
dsn_color_success=32 # green
dsn_color_bounce=33 # yellow
dsn_color_error=31 # red
dsn_colors="*=0:h2=${dsn_color_success}:h3=${dsn_color_bounce}:h4=${dsn_color_error}" # ...and nothing else!
line_dsn_success="$(logline "$logfile" 1 | HX_COLORS="$dsn_colors" "$HX" )"
line_dsn_error="$(logline "$logfile" 2 | HX_COLORS="$dsn_colors" "$HX" )"
assertRegex "$line_dsn_success" "/$(re_col $dsn_color_success)[\d\.]+$(re_col 0)/"
assertRegex "$line_dsn_error" "/$(re_col $dsn_color_error)[\d\.]+$(re_col 0)/"
line_dsn_error="$(logline "$logfile" 4 | HX_COLORS="$dsn_colors" "$HX" )"
assertRegex "$line_dsn_error" "/$(re_col $dsn_color_error)[\d\.]+$(re_col 0)/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# The --ecma option enables simplifies color output.
#
# This test depends on test-basic-colors.
allowed_codes='(?:0|1|2|22|3[1-7])'
re_allowed_sequences="\x1b\[$allowed_codes(?:;$allowed_codes)*m"
assertContainsOnlyAllowedAnsiSequences () {
local logfile="$1"
local output="$(HX --ecma48 < "$logfile")"
local outputWithoutAllowedSequences="$(printf '%s\n' "$output" | perl -pe "s/${re_allowed_sequences}//g" )"
assertContainsNoAnsiSequences "$outputWithoutAllowedSequences" \
"\"hx --ecma48 < $(basename -- "$logfile")\" still produced unexpected ANSI sequences!"
}
assertContainsOnlyAllowedAnsiSequences "$HERE/samples/syslog.log"
assertContainsOnlyAllowedAnsiSequences "$HERE/samples/apache2.log"
assertContainsOnlyAllowedAnsiSequences "$HERE/samples/mysqld.log"
assertContainsOnlyAllowedAnsiSequences "$HERE/samples/syslog-postfix.log"
success
<file_sep>.PHONY : all install test dep
BIN=src/hx
DEST=/usr/local/bin/hx
MOD=src/*.pm
MODDEST=/usr/local/lib/hx-modules/
CHOWN=root:root
all: ;
README.md: doc/hx.1 doc/*.md
git submodule update --init doc/man-to-md/
perl doc/man-to-md.pl \
--formatted-code --comment \
--word hx --word HX_COLORS --word HX_SETTINGS \
--paste-after HEADLINE:'Badges.md' \
--paste-after SYNOPSIS:'Some Screenshots.md' \
--paste-section-after DESCRIPTION:'Installation.md' \
<$< >$@
dep:
install: $(BIN) dep
cp $(BIN) $(DEST)
chown $(CHOWN) $(DEST)
mkdir -p $(MODDEST)
cp $(MOD) $(MODDEST)
chown $(CHOWN) $(MODDEST) $(MODDEST)/*.pm
mkdir -p /usr/local/share/man/man1/
cp doc/hx.1 /usr/local/share/man/man1/
chmod 0644 /usr/local/share/man/man1/hx.1
gzip -f /usr/local/share/man/man1/hx.1
test:
git submodule update --init test/framework/
test/run-all-tests.sh
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests RFC-5424 syslog messages.
#
# This test depends on test-syslog-logs.
logfile="$HERE/samples/syslog-rfc5424.log"
re_backslash='(?:\\)'
# Jun 16 11:31:52 hostname5 1 2019-06-16T11:31:52.892601+02:00 hostname5 user5 - - [timeQuality tzKnown="1" isSynced="1" syncAccuracy="280500"][zoo@123 tiger="hungry"] this is message
line="$(logline "$logfile" 1 | LEX)"
reDate="$(re_tok $T_DATE "Jun 16 11:31:52")"
reHost="$(re_tok $T_HOST "hostname5")"
reVers="$(re_tok $T_INFO "1")"
reTime="$(re_tok $T_DATE "2019-06-16T11:31:52\.892601\+02:00")"
reTag="$(re_tok $T_APP "user5")"
rePid="$(re_tok $T_APP "-")"
reMsgid="$(re_tok $T_INFO "-")"
assertRegex "$line" "/${reDate}${reHost}${reVers}${reTime}${reHost}${reTag}${rePid}${reMsgid}/"
assertRegex "$line" "/$(re_tok $T_INFO "\[timeQuality tzKnown=\"1\" isSynced=\"1\" syncAccuracy=\"280500\"\].*")/"
assertRegex "$line" "/$(re_tok $T_INFO ".*\[zoo@123 tiger=\"hungry\"\]")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "this is message")/"
# Jun 16 11:45:54 hostname5 1 2019-06-16T11:45:54.360888+02:00 hostname5 MYTAG 31247 4X44 [zoo@123 tiger="hungry" zebra="running"][manager@123 qu'otes="ab\c"] this is message.
line="$(logline "$logfile" 3 | LEX)"
reHost="$(re_tok $T_HOST "hostname5")"
reTag="$(re_tok $T_APP "MYTAG")"
rePid="$(re_tok $T_APP "31247")"
reMsgid="$(re_tok $T_INFO "4X44")"
assertRegex "$line" "/${reHost}${reTag}${rePid}${reMsgid}/"
assertRegex "$line" "/$(re_tok $T_INFO "\[zoo@123 tiger=\"hungry\" zebra=\"running\"\].*")/"
assertRegex "$line" "/$(re_tok $T_INFO ".*\[manager@123 qu'otes=\"ab${re_backslash}c\"\]")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "this is message\.")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
re_backslash='(?:\\)'
logfile="$HERE/samples/brk.hxt"
# L M(linebrk\nok ) M(backslash\\ok ) M(escaped-n\\nok ) M(backslash-and-linebrk\\\nok ) Z
line="$(HX --printer < "$logfile")"
assertRegex "$line" "/linebrk\nok/"
assertRegex "$line" "/backslash${re_backslash}ok/"
assertRegex "$line" "/escaped-n${re_backslash}nok/" \
"Regression: escaped backslash-N in serialized tokens was unserialized/unescaped incorrectly!"
assertRegex "$line" "/backslash-and-linebrk${re_backslash}\nok/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/redis.log"
# 1:M 02 Aug 2021 12:34:56.194 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
line="$(logline "$logfile" 3 | LEX)"
reLine=
reLine="${reLine}$(re_tok "$T_APP|$T_INFO" "1:M")"
reLine="${reLine}$(re_tok $T_DATE "02 Aug 2021 12:34:56\.194 ")"
reLine="${reLine}(?:$(re_tok $T_LOGLEVEL "# WARNING")|$(re_tok $T_LOGLEVEL "#")$(re_tok $T_LOGLEVEL "WARNING"))"
reLine="${reLine}$(re_tok $T_MESSAGE "overcommit_memory .*")"
assertRegex "$line" "/$reLine/"
# 57162:M 12 Aug 12:34:56.635 * DB saved on disk
line="$(logline "$logfile" 4 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "57162:M")/"
assertRegex "$line" "/$(re_tok $T_DATE "12 Aug 12:34:56.635")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "\*")/"
# 57162:signal-handler (1563336793) Received SIGTERM scheduling shutdown...
line="$(logline "$logfile" 5 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "57162:signal-handler")/"
assertRegex "$line" "/$(re_tok $T_DATE "\(1563336793\)")/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/other.log"
# 07-Jun-2019 11:36:20.106 INFORMATION [localhost-startStop-2] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.register Mapped "{[/reload],methods=[POST]}" onto public org.springframework.http.ResponseEntity com.project.testController.reloadConfi(com.project.data)
line="$(logline "$logfile" 1 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "07-Jun-2019 11:36:20\.106")/"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "INFORMATION")/"
assertRegex "$line" "/$(re_tok $T_APP "\[localhost-startStop-2\]")/"
assertRegex "$line" "/$(re_tok $T_INFO "org\.springframework\.web\.servlet\.mvc\.method\.annotation\.RequestMappingHandlerMapping\.register")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Mapped .*")/"
# [2019.06.07 12:16:21] Opened '/home/user1/snap/telegram-desktop/753/.local/share/TelegramDesktop/tdata/working' for reading, the previous Telegram Desktop launch was not finished properly :( Crash log size: 0
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "\[2019\.06\.07 12:16:21\]")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Opened .*")/"
# Apr 1 10:00:00 mysys org.gnome.Shell.desktop[4600]: #2 0x7ffd00007d22 I resource:///org/gnome/gjs/modules/_legacy.js:82 (0x7ffd00007d30 @ 71)
line="$(logline "$logfile" 3 | LEX)"
reStack="$(re_tok $T_INFO "#2 0x7ffd00007d22 I +")"
reMsg="(?:$(re_tok $T_MESSAGE)|$(re_tok $T_MESSAGE " +"))"
reSource="$(re_tok $T_TRACE " *resource:\/\/\/org\/gnome\/gjs\/modules\/_legacy.js:82")"
reInfo="$(re_tok $T_INFO "\(0x7ffd00007d30 @ 71\)")"
assertRegex "$line" "/${reStack}${reMsg}${reSource}${reInfo}/"
# [So, Apr 26th, 13:49:59 2020] msg
line="$(logline "$logfile" 4 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "\[So, Apr 26th, 13:49:59 2020\]")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "msg")/"
# 2020-10-14 12:45:23 Platform HTTP 500: array_key_exists() expects parameter 2 to be array, null given [:, Import.php:300, Application.php:200, index.php:33]
line="$(logline "$logfile" 5 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "Platform( HTTP)?")/"
assertRegex "$line" "/$(re_tok $T_HTTP_STATUS "(HTTP )?500")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "array_key_exists\(\) expects parameter 2 to be array, null given")/"
assertRegex "$line" "/$(re_tok "$T_TRACE|$T_INFO" "\[.*33\](\\\\n)?")/"
# [myapp] (0.262733) init.c:105 | Start-up complete
line="$(logline "$logfile" 6 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "\[myapp\]")/"
assertRegex "$line" "/$(re_tok $T_DATE "\(?0\.262733\)?")/"
assertRegex "$line" "/$(re_tok "$T_TRACE|$T_INFO" "init\.c:105\s*")/"
assertRegex "$line" "/$(re_tok $T_MESSAGE "Start-up complete")/"
# 12:00:00 ERROR [app] message
line="$(logline "$logfile" 7 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "12:00:00")\s*$(re_tok $T_LOGLEVEL "ERROR\s*")\s*$(re_tok $T_APP '\[app\]')\s*$(re_tok $T_MESSAGE)/"
# ERROR: app (pid 1000) Mon Jul 26 16:00:00 2021: message
line="$(logline "$logfile" 8 | LEX)"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "ERROR:?")\s*$(re_tok $T_APP "app \(pid 1000\)")\s*$(re_tok $T_DATE 'Mon Jul 26 16:00:00 2021:?')\s*$(re_tok $T_MESSAGE)/"
# update-alternatives 2021-07-03 13:05:40: run with --install ...
line="$(logline "$logfile" 9 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "update-alternatives")\s*$(re_tok $T_DATE "2021-07-03 13:05:40:?")\s*$(re_tok $T_MESSAGE)/"
# /usr/bin/script.sh:50: Warning: Message
line="$(logline "$logfile" 10 | LEX)"
assertRegex "$line" "/$(re_tok "$T_TRACE|$T_APP" "\\/usr\\/bin\\/script.sh:50:")\s*$(re_tok $T_LOGLEVEL "Warning:")\s*$(re_tok $T_MESSAGE)/"
# 2021-07-26 15:00:00,000 INFO Starting unattended upgrades script
line="$(logline "$logfile" 11 | LEX)"
assertRegex "$line" "/$(re_tok "$T_DATA" "2021-07-26 15:00:00,000")\s*$(re_tok $T_LOGLEVEL "INFO")\s*$(re_tok $T_MESSAGE)/"
# E [01/Aug/2021:12:00:00 +0200] [cups-deviced] message
line="$(logline "$logfile" 12 | LEX)"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "E")\s*$(re_tok $T_DATE "\[01/Aug/2021:12:00:00 \+0200\]")\s*$(re_tok "$T_MESSAGE|$T_INFO" "\[cups.*")/"
# Aug 1 12:00:00 hostname kernel: *ERROR* message
line="$(logline "$logfile" 13 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "kernel:")$(re_tok $T_LOGLEVEL "\*ERROR\*")$(re_tok $T_MESSAGE "message")/"
# 2021-08-12 11:00:00,000 UTC: message
line="$(logline "$logfile" 14 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "2021-08-12 11:00:00,000 UTC:")$(re_tok $T_LOGLEVEL "FATAL:")$(re_tok $T_MESSAGE)/"
# 1622215601080 app::helper INFO Listening on port 34830
line="$(logline "$logfile" 15 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "1622215601080\t")$(re_tok $T_APP "app::helper\t")$(re_tok $T_LOGLEVEL "INFO\t")$(re_tok $T_MESSAGE)/"
# console.warn: message
line="$(logline "$logfile" 16 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "console\.?")$(re_tok $T_LOGLEVEL "\.?warn:?").*$(re_tok $T_MESSAGE ".*message")/"
# (/usr/bin/program:1234): GLib-GObject-CRITICAL **: 12:00:00.123: g_object_set: assertion 'G_IS_OBJECT (object)' failed
line="$(logline "$logfile" 17 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "\(\/usr/bin/program:1234\):")$(re_tok $T_LOGLEVEL "GLib-GObject-CRITICAL \*\*:")$(re_tok $T_DATE "12:00:00.123:")$(re_tok $T_MESSAGE)/"
# (script:1) MyWarning: message...
line="$(logline "$logfile" 18 | LEX)"
assertRegex "$line" "/$(re_tok $T_APP "\(script:1\)")$(re_tok $T_ERROR "MyWarning:?").*$(re_tok $T_MESSAGE "message.*")/"
# Sat Oct 09 2021 14:30:00 GMT+0200 (Central European Summer Time): message
line="$(logline "$logfile" 19 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "Sat Oct 09 2021 14:30:00 GMT\+0200 \(Central European Summer Time\):?")$(re_tok $T_MESSAGE)/"
# [Fri 08 Sep 2021 22:00:00 CEST] Crash report submitted successfully
line="$(logline "$logfile" 20 | LEX)"
assertRegex "$line" "/$(re_tok $T_DATE "\[Fri 08 Sep 2021 22:00:00 CEST\]")$(re_tok $T_MESSAGE)/"
# Nov 21 12:00:00 myhost myapp[10000]: GDBus.Error:org.freedesktop.portal.Error.NotAllowed: This call is not allowed
# L D[format=syslog](Nov 21 12:00:00 ) H(myhost ) A(myapp[10000]: ) G[level=30](GDBus.Error:) X(org.freedesktop.portal.Error.NotAllowed: ) M(This call is not allowed) Z
line="$(logline "$logfile" 21 | LEX)"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "GDBus\.Error:?").*$(re_tok $T_ERROR "org\.freedesktop\.portal\.Error\.NotAllowed:?").*$(re_tok $T_MESSAGE)/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# Tests parsing of dmesg/kernel messages.
logfile="$HERE/samples/dmesg.log"
# [ 0.244585] kernel: rcu: Hierarchical SRCU implementation.
line="$(logline "$logfile" 1 | LEX)"
reDate="$(re_tok $T_DATE "\[ 0\.244585\]")"
reApp="(?:$(re_tok $T_APP "kernel:")$(re_tok $T_APP "rcu:")|$(re_tok $T_APP "kernel: rcu:"))"
reMsg="$(re_tok $T_MESSAGE "Hierarchical.*")"
assertRegex "$line" "/$reDate$reApp$reMsg/"
# [ 0.247623] kernel: #2 #3 #4 #5 #6 #7 #8 #9 #10 #11 #12 #13 #14 #15
line="$(logline "$logfile" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_CONTLINE).*$(re_tok $T_INFO " *#2 #3.*")/"
# <6>[1604743.627189] ata1.00: configured for UDMA/133
line="$(logline "$logfile" 3 | LEX)"
assertRegex "$line" "/$(re_tok $T_LOGLEVEL "<6>")$(re_tok $T_DATE)$(re_tok $T_APP "ata1.00:")$(re_tok $T_MESSAGE)/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile1="$HERE/samples/bug-pkl-brk.log"
logfile2="$HERE/samples/apache2-php-packed.log"
re_backslash='(?:\\)'
re_brk="(?:${re_backslash}n)" # \n
# ... #0 /proj/db.php(8): PDO->__construct()\n#1 /proj/save.php(9): ...
# FNCALL(PDO->__construct()) INFO(\n) PKL INFO(#1) TRACE(/proj/save.php)
# FNCALL(PDO->__construct()) PKL INFO(\n) INFO(#1) TRACE(/proj/save.php)
# FNCALL(PDO->__construct()) PKL(\n) INFO(#1) TRACE(/proj/save.php)
line="$(logline "$logfile2" 1 | LEX)"
reBreak1="$(re_tok $T_PACKEDLINE)$(re_tok $T_INFO "$re_brk")$(re_tok $T_INFO "#1")"
reBreak2="$(re_tok $T_INFO "$re_brk")$(re_tok $T_PACKEDLINE)$(re_tok $T_INFO "#1")"
reBreak3="$(re_tok $T_PACKEDLINE "$re_brk")$(re_tok $T_INFO "#1")"
reBreak="(?:$reBreak1|$reBreak2|$reBreak3)"
reLine="$(re_tok "$T_FNCALL" "PDO->__construct\(\)")${reBreak}$(re_tok $T_TRACE "\\/proj\\/save.php.*")"
assertRegex "$line" "/$reLine/"
# [2021-09-30T12:00:00.000000+02:00] app.ERROR: ErrorException: fwrite(): send failed Broken pipe in /proj/io.php:10 Stack trace: #0 proj/io.php(10): IO->connect() #1 /proj/init.php(2): init() #2 {main} Next IOException: Broken pipe in /proj/io.php:14 Stack trace: #0 /proj/conn.php(30): IO->write() #1 {main} {"exception":"[object] (IOException(code: 32): Broken pipe at io.php:14)\n[previous exception] [object] (ErrorException(code: 0): fwrite(): send failed Broken pipe at /proj/io.php:10)"} []
line="$(logline "$logfile1" 1 | LEX)"
assertRegex "$line" "/$(re_tok "$T_JSON" "\{\"exception.*${re_brk}.*\}")$(re_tok $T_INFO "\[\]")/"
# A second bug also relating to packed lines:
# [2022-11-27T18:56:00] Fatal Error: Class "Helper" not found in ErrorHandler.php:100 Stack trace: #0 in src/ErrorHandler.php:100\nStack trace:\n#0 src/ErrorHandler.php(200): ErrorHandler->handleException()\n#1 [internal function]: ErrorHandler->handleException()\n#2 {main}\n thrown at /proj/src/ErrorHandler.php:100)"} []
line="$(logline "$logfile1" 2 | LEX)"
assertRegex "$line" "/$(re_tok $T_LINE).*$(re_tok $T_TRACE).*$(re_tok $T_PACKEDLINE).*$(re_tok $T_INFO "Stack trace:").*$(re_tok $T_PACKEDLINE).*$(re_tok $T_INFO "Stack trace:(${re_backslash}n)?").*$(re_tok $T_EOL).*/"
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
# The logs' plain text content should not change at all!
# We will now redirect ALL log file samples to hx, line for line,
# and compare its output (sans ansi sequences and line symbol) with the original input.
strip_linesym () { perl -pe "s/^● //"; }
assertSameTextContent () {
local inputLine="$1"
local source="$2"
local strippedOutput="$(
printf '%s' "$inputLine" |
"$HX" |
strip_ansi | strip_linesym )"
assertEq "$strippedOutput" "$inputLine" \
"hx changed its plain text input! (source: $source)"
}
for logfile in "$HERE/samples/"*.log; do
lineno=0
while IFS= read -r line; do
lineno="$((lineno + 1))"
assertSameTextContent "$line" "$logfile:$lineno"
done <<Z
$(cat -- "$logfile")
Z
done
success
<file_sep>#!/bin/sh
. $(dirname "$0")/init.sh
logfile="$HERE/samples/php.log"
# PHP Warning: Uncaught CustomException: exception message in /proj/source.php:10
line="$(logline "$logfile" 1 | LEX)"
re_line=
re_line="${re_line}$(re_tok $T_LOGLEVEL "PHP Warning:")\s*"
re_line="${re_line}$(re_tok $T_MESSAGE "Uncaught")\s*"
re_line="${re_line}$(re_tok $T_ERROR "CustomException:?")\s*"
re_line="${re_line}$(re_tok $T_MESSAGE ":")?\s*"
re_line="${re_line}$(re_tok $T_MESSAGE "(?:: )?exception message")\s*"
re_line="${re_line}$(re_tok $T_TRACE "in \/proj\/source.php:10")\s*"
assertRegex "$line" "/$re_line/"
# PHP message: 2022-03-26T18:00:00+01:00 [critical] Uncaught Error: Call to undefined method MyClass::build()
line="$(logline "$logfile" 2 | LEX)"
re_line=
re_line="${re_line}$(re_tok $T_APP "PHP message:")\s*"
re_line="${re_line}$(re_tok $T_DATE "2022-03-26T18:00:00\+01:00 ")\s*"
re_line="${re_line}$(re_tok $T_LOGLEVEL "\[critical\]")\s*"
re_line="${re_line}$(re_tok $T_MESSAGE "Uncaught")\s*"
re_line="${re_line}$(re_tok $T_ERROR "Error:?")\s*"
re_line="${re_line}$(re_tok $T_MESSAGE ":? ?Call to.*")"
assertRegex "$line" "/$re_line/"
success
| fbd1dba770451b1f8bef1a4d515ea84852370e8d | [
"Markdown",
"Makefile",
"Shell"
] | 50 | Shell | mle86/hx | 521f9bb1df0d35778eea98240bc0cdeeba8178f1 | 6553aafc770f4e5b140b785d0bcb4d0a472178e3 |
refs/heads/main | <repo_name>M-Coder-3920/Quiz<file_sep>/script.js
let title = document.querySelector("#title");
let title2 = document.querySelector("#title2");
let aa1 = document.querySelector("#Aanswer1");
let aa2 = document.querySelector("#Aanswer2");
let aa3 = document.querySelector("#Aanswer3");
let ba1 = document.querySelector("#Banswer1");
let ba2 = document.querySelector("#Banswer2");
let ba3 = document.querySelector("#Banswer3");
let ca1 = document.querySelector("#Canswer1");
let ca2 = document.querySelector("#Canswer2");
let ca3 = document.querySelector("#Canswer3");
let da1 = document.querySelector("#Danswer1");
let da2 = document.querySelector("#Danswer2");
let da3 = document.querySelector("#Danswer3");
let ea1 = document.querySelector("#Eanswer1");
let ea2 = document.querySelector("#Eanswer2");
let ea3 = document.querySelector("#Eanswer3");
let fa1 = document.querySelector("#Fanswer1");
let fa2 = document.querySelector("#Fanswer2");
let fa3 = document.querySelector("#Fanswer3");
let ga1 = document.querySelector("#Ganswer1");
let ga2 = document.querySelector("#Ganswer2");
let ga3 = document.querySelector("#Ganswer3");
let ha1 = document.querySelector("#Hanswer1");
let ha2 = document.querySelector("#Hanswer2");
let ha3 = document.querySelector("#Hanswer3");
let ia1 = document.querySelector("#Ianswer1");
let ia2 = document.querySelector("#Ianswer2");
let ia3 = document.querySelector("#Ianswer3");
let ja1 = document.querySelector("#Janswer1");
let ja2 = document.querySelector("#Janswer2");
let ja3 = document.querySelector("#Janswer3");
let next = document.querySelector("#next");
let next2 = document.querySelector("#next2");
let next3 = document.querySelector("#next3");
let next4 = document.querySelector("#next4");
let next5 = document.querySelector("#next5");
let next6 = document.querySelector("#next6");
let next7 = document.querySelector("#next7");
let next8 = document.querySelector("#next8");
let next9 = document.querySelector("#next9");
let next10 = document.querySelector("#next10");
const youScored = document.querySelector("#yours");
let all = document.querySelector("#all");
const scoreDisplay = document.querySelector(".correct");
let score = 0;
title.innerHTML = "1. Which American president appears on a one dollar bill?";
aa1.innerHTML = "<NAME>";
aa2.innerHTML = "<NAME>";
aa3.innerHTML = "<NAME>";
aa1.onclick = function(){
aa1.style.color = 'green';
aa2.style.color = 'red';
aa3.style.color = 'red';
next.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
aa2.onclick = function(){
aa1.style.color = 'green';
aa2.style.color = 'red';
aa3.style.color = 'red';
next.style.visibility = 'visible';
}
aa3.onclick = function(){
aa1.style.color = 'green';
aa2.style.color = 'red';
aa3.style.color = 'red';
next.style.visibility = 'visible';
}
title2.innerHTML = "2. What color is the \"Ex\" in FedEx Ground?";
ba1.innerHTML = "Orange";
ba2.innerHTML = "Green";
ba3.innerHTML = "Purple";
ba1.onclick = function(){
ba2.style.color = 'green';
ba1.style.color = 'red';
ba3.style.color = 'red';
next2.style.visibility = 'visible';
}
ba2.onclick = function(){
ba2.style.color = 'green';
ba1.style.color = 'red';
ba3.style.color = 'red';
next2.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
ba3.onclick = function(){
ba2.style.color = 'green';
ba1.style.color = 'red';
ba3.style.color = 'red';
next2.style.visibility = 'visible';
}
title3.innerHTML = "3. Of what is Cynophobia the fear?";
ca1.innerHTML = "Snakes";
ca2.innerHTML = "Cats";
ca3.innerHTML = "Dogs";
ca1.onclick = function(){
ca3.style.color = 'green';
ca1.style.color = 'red';
ca2.style.color = 'red';
next3.style.visibility = 'visible';
}
ca2.onclick = function(){
ca3.style.color = 'green';
ca1.style.color = 'red';
ca2.style.color = 'red';
next3.style.visibility = 'visible';
}
ca3.onclick = function(){
ca3.style.color = 'green';
ca1.style.color = 'red';
ca2.style.color = 'red';
next3.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
title4.innerHTML = "4. When did the website \"Facebook\" launch?";
da1.innerHTML = "2002";
da2.innerHTML = "2003";
da3.innerHTML = "2004";
da1.onclick = function(){
da3.style.color = 'green';
da1.style.color = 'red';
da2.style.color = 'red';
next4.style.visibility = 'visible';
}
da2.onclick = function(){
da3.style.color = 'green';
da1.style.color = 'red';
da2.style.color = 'red';
next4.style.visibility = 'visible';
}
da3.onclick = function(){
da3.style.color = 'green';
da1.style.color = 'red';
da2.style.color = 'red';
next4.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
title5.innerHTML = "5. Where did the pineapple plant originate?";
ea1.innerHTML = "South America";
ea2.innerHTML = "North America";
ea3.innerHTML = "Africa";
ea1.onclick = function(){
ea1.style.color = 'green';
ea2.style.color = 'red';
ea3.style.color = 'red';
next5.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
ea2.onclick = function(){
ea1.style.color = 'green';
ea2.style.color = 'red';
ea3.style.color = 'red';
next5.style.visibility = 'visible';
}
ea3.onclick = function(){
ea1.style.color = 'green';
ea2.style.color = 'red';
ea3.style.color = 'red';
next5.style.visibility = 'visible';
}
title6.innerHTML = "6. What year was Queen Elizabeth II born?";
fa1.innerHTML = "1924";
fa2.innerHTML = "1926";
fa3.innerHTML = "1928";
fa1.onclick = function(){
fa2.style.color = 'green';
fa1.style.color = 'red';
fa3.style.color = 'red';
next6.style.visibility = 'visible';
}
fa2.onclick = function(){
fa2.style.color = 'green';
fa1.style.color = 'red';
fa3.style.color = 'red';
next6.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
fa3.onclick = function(){
fa2.style.color = 'green';
fa1.style.color = 'red';
fa3.style.color = 'red';
next6.style.visibility = 'visible';
}
title7.innerHTML = "7. Nephelococcygia is the practice of doing what?";
ga1.innerHTML = "Finding shapes in clouds";
ga2.innerHTML = "Searching for mushrooms";
ga3.innerHTML = "Running for long distances";
ga1.onclick = function(){
ga1.style.color = 'green';
ga2.style.color = 'red';
ga3.style.color = 'red';
next7.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
ga2.onclick = function(){
ga1.style.color = 'green';
ga2.style.color = 'red';
ga3.style.color = 'red';
next7.style.visibility = 'visible';
}
ga3.onclick = function(){
ga1.style.color = 'green';
ga2.style.color = 'red';
ga3.style.color = 'red';
next7.style.visibility = 'visible';
}
title8.innerHTML = "8. Which of these characters turned 40 years old in 1990?";
ha1.innerHTML = "<NAME>";
ha2.innerHTML = "<NAME>";
ha3.innerHTML = "<NAME>";
ha1.onclick = function(){
ha3.style.color = 'green';
ha1.style.color = 'red';
ha2.style.color = 'red';
next8.style.visibility = 'visible';
}
ha2.onclick = function(){
ha3.style.color = 'green';
ha1.style.color = 'red';
ha2.style.color = 'red';
next8.style.visibility = 'visible';
}
ha3.onclick = function(){
ha3.style.color = 'green';
ha1.style.color = 'red';
ha2.style.color = 'red';
next8.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
title9.innerHTML = "9. In 1985, five percent of U.S. households had telephone answering machines. By 1990 what percentage of homes had answering machines?";
ia1.innerHTML = "31%";
ia2.innerHTML = "50%";
ia3.innerHTML = "67%";
ia1.onclick = function(){
ia1.style.color = 'green';
ia2.style.color = 'red';
ia3.style.color = 'red';
next9.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
ia2.onclick = function(){
ia1.style.color = 'green';
ia2.style.color = 'red';
ia3.style.color = 'red';
next9.style.visibility = 'visible';
}
ia3.onclick = function(){
ia1.style.color = 'green';
ia2.style.color = 'red';
ia3.style.color = 'red';
next9.style.visibility = 'visible';
}
title10.innerHTML = "10. What is the voltage of a D battery?";
ja1.innerHTML = "0.5";
ja2.innerHTML = "1.0";
ja3.innerHTML = "1.5";
ja1.onclick = function(){
ja3.style.color = 'green';
ja1.style.color = 'red';
ja2.style.color = 'red';
next10.style.visibility = 'visible';
}
ja2.onclick = function(){
ja3.style.color = 'green';
ja1.style.color = 'red';
ja2.style.color = 'red';
next10.style.visibility = 'visible';
}
ja3.onclick = function(){
ja3.style.color = 'green';
ja1.style.color = 'red';
ja2.style.color = 'red';
next10.style.visibility = 'visible';
score++;
scoreDisplay.innerHTML = score;
}
next.onclick = function(){
all.style.zIndex = '-1';
next.style.visibility = 'hidden';
all.style.visibility = 'hidden';
all2.style.visibility = 'visible';
}
next2.onclick = function(){
all2.style.zIndex = '1';
next2.style.visibility = 'hidden';
all2.style.visibility = 'hidden';
all3.style.visibility = 'visible';
}
next3.onclick = function(){
all3.style.zIndex = '-1';
next3.style.visibility = 'hidden';
all3.style.visibility = 'hidden';
all4.style.visibility = 'visible';
}
next4.onclick = function(){
all4.style.zIndex = '1';
next4.style.visibility = 'hidden';
all4.style.visibility = 'hidden';
all5.style.visibility = 'visible';
}
next5.onclick = function(){
all5.style.zIndex = '1';
next5.style.visibility = 'hidden';
all5.style.visibility = 'hidden';
all6.style.visibility = 'visible';
}
next6.onclick = function(){
all6.style.zIndex = '1';
next6.style.visibility = 'hidden';
all6.style.visibility = 'hidden';
all7.style.visibility = 'visible';
}
next7.onclick = function(){
all7.style.zIndex = '1';
next7.style.visibility = 'hidden';
all7.style.visibility = 'hidden';
all8.style.visibility = 'visible';
}
next8.onclick = function(){
all8.style.zIndex = '1';
next8.style.visibility = 'hidden';
all8.style.visibility = 'hidden';
all9.style.visibility = 'visible';
}
next9.onclick = function(){
all9.style.zIndex = '1';
next9.style.visibility = 'hidden';
all9.style.visibility = 'hidden';
all10.style.visibility = 'visible';
}
next10.onclick = function(){
all10.style.zIndex = '1';
next10.style.visibility = 'hidden';
all10.style.visibility = 'hidden';
youScored.style.visibility = 'visible';
scoreDisplay.style.right = '300px';
scoreDisplay.style.top = '200px';
}<file_sep>/README.md
# Quiz
Bible Quiz
| 04598728d82bf9f634e045eaa2d91e61ee7a045a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | M-Coder-3920/Quiz | 2eff937d43a18dad7c13941a958a382f3b896e08 | ee97477eca461ba1e45c53dc81189390c8903e44 |
refs/heads/master | <repo_name>theja-vanka/CiT-v1<file_sep>/app/src/main/assets/www/ap9.html
<html>
<body>
<center>
<header class="entry-header">
<h3>M.Tech in Signal Processing</h3>
</header>
<div class="entry-content">
<img src="ap2.jpg" alt="11" width="300" height="199" class="alignleft size-medium wp-image-2333" />
<p> </p>
<p style="color: #000000;"><span style="font-weight: 700 !important; font-style: inherit;"><NAME><br />
</span></p>
<p style="color: #000000;"><span style="font-weight: 700 !important; font-style: inherit;">B.E., M.Tech Ph.D</span></p>
<p style="color: #000000;">Professor & Head</p>
<p style="color: #000000;">Email: <EMAIL></p></center>
<p align=justify><br><br>The College has started offering M.Tech in Signal Processing from Sep 2012 with an intake of 18. Signal processing one of the most important Post graduation course of Electronics and Communication Engineering. This program introduces the basic concepts and techniques for processing signals on acomputer.The program emphasizes intuitive understanding and practical implementations of the theoreticalconcepts.</p>
<p align=justify>The department is supported by well experienced and qualified faculties. The department emphasizes on high quality teaching and training in the laboratory. The department houses state of the art laboratory equipped with sophisticated equipment as stipulated by university.<br />
<ul>
<li>Program Duration: 2 years (4 semesters)<br /></li>
<li>Eligibility Criteria for Admission<br /></li></ul>
1. Admission to the Master of Technology Course shall be open to all the candidates who have passed B.E. / B.Tech. Examinations (in relevant field) of VTU or any other University /Institution or any other examinations recognized as equivalent thereof.<br />
2. AMIE qualification in respective branches shall be equivalent to B.E./B.Tech. Courses of VTU for admission to M.Tech.<br />
3. However, the candidate seeking admission to M.Tech. Courses on the basis of AMIE shall also take the Common Entrance Test.<br />
4. Admission to M.Tech. Course shall be open to the candidates who have passed the prescribed qualifying examinations with not less than 50% of the marks in the aggregate of all the years of the degree examinations. However, in the case of candidates belonging to SC/ST and Group I, the aggregate percentage of marks in the qualifying examinations shall not be less than 45%.</p>
</div>
</body>
</html><file_sep>/app/src/main/java/com/citech/vanka_sangashetty/proto1/fragment/AcademicFragment.java
package com.citech.vanka_sangashetty.proto1.fragment;
/**
* Created by Vanka on 24-04-2016.
*/
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import com.citech.vanka_sangashetty.proto1.R;
public class AcademicFragment extends Fragment {
private ImageButton bcse, bise, bece, beee, bmech, bciv,mcse,mcne,mmba,msig,mmd,mmca;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_academic, container, false);
bcse = (ImageButton) view.findViewById(R.id.mb_cse);
bise = (ImageButton) view.findViewById(R.id.mb_ise);
bece = (ImageButton) view.findViewById(R.id.mb_ece);
beee = (ImageButton) view.findViewById(R.id.mb_eee);
bmech = (ImageButton) view.findViewById(R.id.mb_mec);
bciv = (ImageButton) view.findViewById(R.id.mb_civ);
mcse = (ImageButton) view.findViewById(R.id.mb_pcse);
mcne = (ImageButton) view.findViewById(R.id.mb_pcne);
mmca = (ImageButton) view.findViewById(R.id.mb_pmca);
msig = (ImageButton) view.findViewById(R.id.mb_psig);
mmd = (ImageButton) view.findViewById(R.id.mb_pmd);
mmba = (ImageButton) view.findViewById(R.id.mb_mba);
final FragmentManager fm = getFragmentManager();
bcse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragDeptCse());
transaction.addToBackStack(null);
transaction.commit();
}
});
bise.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragDeptIse());
transaction.addToBackStack(null);
transaction.commit();
}
});
bece.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragDeptEce());
transaction.addToBackStack(null);
transaction.commit();
}
});
beee.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragDeptEee());
transaction.addToBackStack(null);
transaction.commit();
}
});
bmech.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragDeptMech());
transaction.addToBackStack(null);
transaction.commit();
}
});
bciv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragDeptCiv());
transaction.addToBackStack(null);
transaction.commit();
}
});
mcse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragPostCse());
transaction.addToBackStack(null);
transaction.commit();
}
});
mcne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragPostCne());
transaction.addToBackStack(null);
transaction.commit();
}
});
mmca.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragPostMca());
transaction.addToBackStack(null);
transaction.commit();
}
});
msig.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragPostSig());
transaction.addToBackStack(null);
transaction.commit();
}
});
mmd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragPostMmd());
transaction.addToBackStack(null);
transaction.commit();
}
});
mmba.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame2, new FragPostMba());
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
<file_sep>/app/src/main/assets/www/ap2.html
<html>
<body>
<header class="entry-header"><center>
<h3>Electronics & Communications Engineering</h3>
</header>
<div class="entry-content">
<img src="ap2.jpg" alt="11" width="300" height="199" class="alignleft size-medium wp-image-2333" />
<p><strong><NAME></strong></br></p>
<p><strong>B.E., M.Tech Ph.D</strong></strong></p>
<p>Professor & Head</p>
<p>Email: <EMAIL></p></center>
<p><strong>Course offered:</strong> B.E. Degree in Electronics and Communication& Engineering</p>
<p><strong>Established:</strong> 2007</p>
<p><strong>Current Intake:</strong> 120</p>
<p align=justify>The Department of Electronics and Communication Engineering was established at the Cambridge Institute of Technology in 2007 with an approved intake of 60 students. The department runs under graduate programme Electronics and Communication Engineering. The department is recognized by AICTE and affiliated to Visvesvaraya Technological University (VTU) Belgaum, with current intake of 120. It has a broad based UG curriculum, which offers a unique mix of electrical, electronics and computer related courses enabling the students to take-up a professional career / higher studies in any of these areas.</p>
<p align=justify>The main focus of the department is to evolve as a Centre of excellence in the field of electronics and communication engineering and to contribute towards the betterment of society. The Vision of our department is to impart high quality academic and research programs in the field of electronics and communication engineering by regular updating of research and development skills among the faculty members & students to meet the requirements of industry and society. The department is doing its best efforts to meet the objective of achieving technical excellence in all areas of Electronics and Communication Engineering.</p>
<p style="text-align: right;"> ——- <strong>Dr. <NAME></strong></p>
<br><br>
<p><b><u>VISION</b></u><br>
To evolve as a Centre of Excellence in the field of Electronics and Communication Engineering and to contribute towards the betterment of society.
<br><br>
<b><u>MISSION</b></u><br>
<p align=justify>M1: To impart quality education and research programs in the field of Electronics and Communication Engineering.
<br>
M2: To prepare students towards innovation & research.
<br>
M3: Continuous enhancement of professional skills among the faculty members & students to meet the requirements of industry and society.
</p></body>
</html><file_sep>/app/src/main/java/com/citech/vanka_sangashetty/proto1/fragment/ContactFragment.java
package com.citech.vanka_sangashetty.proto1.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.citech.vanka_sangashetty.proto1.R;
/**
* Created by Vanka on 24-04-2016.
*/
public class ContactFragment extends Fragment {
WebView myWebView;
static String myBlogAddr = "file:///android_asset/www/contact.html";
String myUrl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact, container, false);
myWebView = (WebView)view.findViewById(R.id.contact_frag);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
if(myUrl == null){
myUrl = myBlogAddr;
}
myWebView.loadUrl(myUrl);
return view;
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
myUrl = url;
view.loadUrl(url);
return true;
}
}
}
<file_sep>/app/src/main/java/com/citech/vanka_sangashetty/proto1/Main4Activity.java
package com.citech.vanka_sangashetty.proto1;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
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.view.View;
import com.citech.vanka_sangashetty.proto1.fragment.AcademicFragment;
import com.citech.vanka_sangashetty.proto1.fragment.FacultyFragment;
public class Main4Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.content_frame3, new FacultyFragment());
transaction.addToBackStack("demicfac");
transaction.commit();
}
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if(count ==1){
super.onBackPressed();
}
else
{
getFragmentManager().popBackStack();
}
}
}
| 713ec4632cee7c541381226c639e9254b46cf9e8 | [
"Java",
"HTML"
] | 5 | HTML | theja-vanka/CiT-v1 | 176e5f989a8c469ce32833efbeaa5b046645fcdc | 7c1c092e75ef6c5f8894b4255b0a6b69029bc8ed |
refs/heads/master | <file_sep>package com.interfacetest.mapper;
import com.interfacetest.entry.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from user")
public List< User > queryUser();
}
| 295b24b1ffede5cd227704faca1583667b14c332 | [
"Java"
] | 1 | Java | CuiZhongyuan/spingboot-mybatis | 7358977969e622b661a1b900e3096674bafa4737 | 29f2dbe85f3472c1e1d9e7dc97b3b472a686d5cd |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Terraria;
using TShockAPI;
using TShockAPI.DB;
namespace CommandRecipes
{
public class Utils
{
public static List<string> ListIngredients(List<Ingredient> actIngs)
{
List<string> lActIngs = new List<string>();
List<int> groups = new List<int>();
foreach (Ingredient item in actIngs)
if (item.group == 0)
lActIngs.Add(FormatItem((Item)item));
else if(!groups.Contains(item.group))
groups.Add(item.group);
for (int i = 0; i < groups.Count; i++)
{
List<string> lGrIng = new List<string>();
foreach (Ingredient item in actIngs)
{
if (groups[i] == item.group)
lGrIng.Add(FormatItem((Item)item));
}
lActIngs.Add(String.Join(" or ", lGrIng));
}
return lActIngs;
}
public static List<Product> DetermineProducts(List<Product> actPros)
{
List<Product> lActPros = new List<Product>();
List<int> groups = new List<int>();
foreach (Product pro in actPros)
{
if (pro.group == 0)
lActPros.Add(pro);
else if (!groups.Contains(pro.group))
groups.Add(pro.group);
}
for (int i = 0; i < groups.Count; i++)
{
List<Product> proPool = new List<Product>();
foreach (Product pro in actPros)
{
if (groups[i] == pro.group)
proPool.Add(pro);
}
Random r = new Random();
double diceRoll = r.Next(100);
int cumulative = 0;
for (int j = 0; j < proPool.Count; j++)
{
cumulative += (proPool[j].weight);
if (diceRoll < cumulative)
{
lActPros.Add(proPool[j]);
break;
}
}
}
return lActPros;
}
public static bool CheckIfInRegion(TSPlayer plr, List<string> region)
{
if (region.Contains(""))
return true;
Region r;
foreach (var reg in region)
{
r = TShock.Regions.GetRegionByName(reg);
if (r != null && r.InArea((int)plr.X, (int)plr.Y))
return true;
}
return false;
}
// I stole this code from my AutoRank plugin - with a few changes. It worked, so.
public static string ParseCommand(TSPlayer player, string text)
{
if (player == null || string.IsNullOrEmpty(text))
return "";
var replacements = new Dictionary<string, object>();
replacements.Add("$group", player.Group.Name);
replacements.Add("$ip", player.IP);
replacements.Add("$playername", player.Name);
replacements.Add("$username", player.User.Name);
foreach (var word in replacements)
{
// Quotes are automatically added - no more self-imposed quotes with $playername!
text = text.Replace(word.Key, "\"{0}\"".SFormat(word.Value.ToString()));
}
return text;
}
// ^ Such ditto, many IVs.
public static List<string> ParseParameters(string text)
{
text = text.Trim();
var args = new List<string>();
StringBuilder sb = new StringBuilder();
bool quote = false;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (char.IsWhiteSpace(c) && !quote)
{
args.Add(sb.ToString());
sb.Clear();
}
else if (c == '"')
{
quote = !quote;
}
else
{
sb.Append(c);
}
}
args.Add(sb.ToString());
return args;
}
#region SetUpConfig
public static void SetUpConfig()
{
try
{
if (!Directory.Exists(CmdRec.configDir))
Directory.CreateDirectory(CmdRec.configDir);
if (File.Exists(CmdRec.configPath))
CmdRec.config = RecConfig.Read(CmdRec.configPath);
else
CmdRec.config.Write(CmdRec.configPath);
foreach (Recipe rec in CmdRec.config.Recipes)
{
if (!CmdRec.recs.Contains(rec.name.ToLower()))
CmdRec.recs.Add(rec.name.ToLower());
rec.categories.ForEach((item) =>
{
CmdRec.cats.Add(item.ToLower());
});
}
}
catch (Exception ex)
{
// Why were you using this instead of Log.ConsoleError?
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine("Error in recConfig.json!");
//Console.ResetColor();
TShock.Log.ConsoleError("Error in recConfig.json!");
TShock.Log.ConsoleError(ex.ToString());
}
}
#endregion
#region GetPrefixById
// Required until everyone gets their TShock updated
public static string GetPrefixById(int id)
{
return id < 1 || id > 83 ? "" : Lang.prefix[id].Value ?? "";
}
#endregion
#region FormatItem
// Though it would be an interesting addition
public static string FormatItem(Item item, int stacks = 0)
{
string prefix = GetPrefixById(item.prefix);
if (prefix != "")
{
prefix += " ";
}
return String.Format("{0} {1}{2}(s)",
(stacks == 0) ? Math.Abs(item.stack) : stacks,
prefix,
item.Name);
}
public static string LogFormatItem(Item item, int stacks = 0)
{
string str = GetPrefixById(item.prefix);
string prefix = str == "" ? "" : "[" + str + "] ";
return String.Format("{0} {1}{2}(s)",
(stacks == 0) ? Math.Abs(item.stack) : stacks,
prefix,
item.Name);
}
#endregion
#region AddToPrefixes(old)
//public static void AddToPrefixes()
//{
// #region Prefixes
// CmdRec.prefixes.Add(1, "Large");
// CmdRec.prefixes.Add(2, "Massive");
// CmdRec.prefixes.Add(3, "Dangerous");
// CmdRec.prefixes.Add(4, "Savage");
// CmdRec.prefixes.Add(5, "Sharp");
// CmdRec.prefixes.Add(6, "Pointy");
// CmdRec.prefixes.Add(7, "Tiny");
// CmdRec.prefixes.Add(8, "Terrible");
// CmdRec.prefixes.Add(9, "Small");
// CmdRec.prefixes.Add(10, "Dull");
// CmdRec.prefixes.Add(11, "Unhappy");
// CmdRec.prefixes.Add(12, "Bulky");
// CmdRec.prefixes.Add(13, "Shameful");
// CmdRec.prefixes.Add(14, "Heavy");
// CmdRec.prefixes.Add(15, "Light");
// CmdRec.prefixes.Add(16, "Sighted");
// CmdRec.prefixes.Add(17, "Rapid");
// CmdRec.prefixes.Add(18, "Hasty");
// CmdRec.prefixes.Add(19, "Intimidating");
// CmdRec.prefixes.Add(20, "Deadly");
// CmdRec.prefixes.Add(21, "Staunch");
// CmdRec.prefixes.Add(22, "Awful");
// CmdRec.prefixes.Add(23, "Lethargic");
// CmdRec.prefixes.Add(24, "Awkward");
// CmdRec.prefixes.Add(25, "Powerful");
// CmdRec.prefixes.Add(26, "Mystic");
// CmdRec.prefixes.Add(27, "Adept");
// CmdRec.prefixes.Add(28, "Masterful");
// CmdRec.prefixes.Add(29, "Inept");
// CmdRec.prefixes.Add(30, "Ignorant");
// CmdRec.prefixes.Add(31, "Deranged");
// CmdRec.prefixes.Add(32, "Intense");
// CmdRec.prefixes.Add(33, "Taboo");
// CmdRec.prefixes.Add(34, "Celestial");
// CmdRec.prefixes.Add(35, "Furious");
// CmdRec.prefixes.Add(36, "Keen");
// CmdRec.prefixes.Add(37, "Superior");
// CmdRec.prefixes.Add(38, "Forceful");
// CmdRec.prefixes.Add(39, "Broken");
// CmdRec.prefixes.Add(40, "Damaged");
// CmdRec.prefixes.Add(41, "Shoddy");
// CmdRec.prefixes.Add(42, "Quick");
// CmdRec.prefixes.Add(43, "Deadly");
// CmdRec.prefixes.Add(44, "Agile");
// CmdRec.prefixes.Add(45, "Nimble");
// CmdRec.prefixes.Add(46, "Murderous");
// CmdRec.prefixes.Add(47, "Slow");
// CmdRec.prefixes.Add(48, "Sluggish");
// CmdRec.prefixes.Add(49, "Lazy");
// CmdRec.prefixes.Add(50, "Annoying");
// CmdRec.prefixes.Add(51, "Nasty");
// CmdRec.prefixes.Add(52, "Manic");
// CmdRec.prefixes.Add(53, "Hurtful");
// CmdRec.prefixes.Add(54, "Strong");
// CmdRec.prefixes.Add(55, "Unpleasant");
// CmdRec.prefixes.Add(56, "Weak");
// CmdRec.prefixes.Add(57, "Ruthless");
// CmdRec.prefixes.Add(58, "Frenzying");
// CmdRec.prefixes.Add(59, "Godly");
// CmdRec.prefixes.Add(60, "Demonic");
// CmdRec.prefixes.Add(61, "Zealous");
// CmdRec.prefixes.Add(62, "Hard");
// CmdRec.prefixes.Add(63, "Guarding");
// CmdRec.prefixes.Add(64, "Armored");
// CmdRec.prefixes.Add(65, "Warding");
// CmdRec.prefixes.Add(66, "Arcane");
// CmdRec.prefixes.Add(67, "Precise");
// CmdRec.prefixes.Add(68, "Lucky");
// CmdRec.prefixes.Add(69, "Jagged");
// CmdRec.prefixes.Add(70, "Spiked");
// CmdRec.prefixes.Add(71, "Angry");
// CmdRec.prefixes.Add(72, "Menacing");
// CmdRec.prefixes.Add(73, "Brisk");
// CmdRec.prefixes.Add(74, "Fleeting");
// CmdRec.prefixes.Add(75, "Hasty");
// CmdRec.prefixes.Add(76, "Quick");
// CmdRec.prefixes.Add(77, "Wild");
// CmdRec.prefixes.Add(78, "Rash");
// CmdRec.prefixes.Add(79, "Intrepid");
// CmdRec.prefixes.Add(80, "Violent");
// CmdRec.prefixes.Add(81, "Legendary");
// CmdRec.prefixes.Add(82, "Unreal");
// CmdRec.prefixes.Add(83, "Mythical");
// #endregion
//}
#endregion
}
}
<file_sep>using System.Collections.Generic;
namespace CommandRecipes
{
public class RecipeData
{
public const string KEY = "CommandRecipes_Data";
public Recipe activeRecipe;
public List<Ingredient> activeIngredients;
public List<RecItem> droppedItems = new List<RecItem>();
public RecipeData()
{
activeIngredients = new List<Ingredient>();
droppedItems = new List<RecItem>();
}
public RecipeData Clone()
{
RecipeData newData = new RecipeData();
newData.activeRecipe = activeRecipe.Clone();
newData.activeIngredients = new List<Ingredient>(activeIngredients);
newData.droppedItems = new List<RecItem>(droppedItems);
return newData;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Streams;
using System.Linq;
using System.Reflection;
using Terraria;
using Terraria.Localization;
using TerrariaApi.Server;
using TShockAPI;
using TShockAPI.Hooks;
namespace CommandRecipes
{
[ApiVersion(2, 1)]
public class CmdRec : TerrariaPlugin
{
public static List<string> cats = new List<string>();
public static List<string> recs = new List<string>();
public static RecipeDataManager Memory { get; private set; }
public static RecConfig config { get; set; }
public static string configDir { get { return Path.Combine(TShock.SavePath, "PluginConfigs"); } }
public static string configPath { get { return Path.Combine(configDir, "AllRecipes.json"); } }
public RecipeLog Log { get; set; }
#region Info
public override string Name
{
get { return "CommandRecipes"; }
}
public override string Author
{
get { return "aMoka & Enerdy"; }
}
public override string Description
{
get { return "Recipes through commands and chat."; }
}
public override Version Version
{
get { return Assembly.GetExecutingAssembly().GetName().Version; }
}
#endregion
#region Initialize
public override void Initialize()
{
PlayerHooks.PlayerPostLogin += OnLogin;
PlayerHooks.PlayerLogout += OnLogout;
ServerApi.Hooks.GameInitialize.Register(this, OnInitialize);
ServerApi.Hooks.NetGetData.Register(this, OnGetData);
}
#endregion
#region Dispose
protected override void Dispose(bool disposing)
{
if (disposing)
{
PlayerHooks.PlayerPostLogin -= OnLogin;
PlayerHooks.PlayerLogout -= OnLogout;
ServerApi.Hooks.GameInitialize.Deregister(this, OnInitialize);
ServerApi.Hooks.NetGetData.Deregister(this, OnGetData);
Log.Dispose();
}
}
#endregion
public CmdRec(Main game)
: base(game)
{
// Why did we need a lower order again?
Order = -10;
config = new RecConfig();
Log = new RecipeLog();
}
#region OnInitialize
void OnInitialize(EventArgs args)
{
Commands.ChatCommands.Add(new Command("cmdrec.player.craft", Craft, "craft")
{
HelpText = "Allows the player to craft items via command from config-defined recipes."
});
Commands.ChatCommands.Add(new Command("cmdrec.admin.reload", RecReload, "recrld")
{
HelpText = "Reloads AllRecipes.json"
});
Memory = new RecipeDataManager();
//Utils.AddToPrefixes();
Utils.SetUpConfig();
Log.Initialize();
}
#endregion
#region OnGetData
void OnGetData(GetDataEventArgs args)
{
if (config.CraftFromInventory)
return;
if (args.MsgID == PacketTypes.ItemDrop)
{
if (args.Handled)
return;
using (var data = new MemoryStream(args.Msg.readBuffer, args.Index, args.Length))
{
Int16 id = data.ReadInt16();
float posx = data.ReadSingle();
float posy = data.ReadSingle();
float velx = data.ReadSingle();
float vely = data.ReadSingle();
Int16 stacks = data.ReadInt16();
int prefix = data.ReadByte();
bool nodelay = data.ReadBoolean();
Int16 netid = data.ReadInt16();
Item item = new Item();
item.SetDefaults(netid);
if (id != 400)
return;
TSPlayer tsplayer = TShock.Players[args.Msg.whoAmI];
RecipeData recData;
if (tsplayer != null && tsplayer.Active && (recData = tsplayer.GetRecipeData()) != null && recData.activeRecipe != null)
{
List<Ingredient> fulfilledIngredient = new List<Ingredient>();
foreach (Ingredient ing in recData.activeIngredients)
{
//ing.prefix == -1 means accepts any prefix
if (ing.name == item.Name && (ing.prefix == -1 || ing.prefix == prefix))
{
ing.stack -= stacks;
if (ing.stack > 0)
{
tsplayer.SendInfoMessage("Drop another {0}.", Utils.FormatItem((Item)ing));
if (recData.droppedItems.Exists(i => i.name == ing.name))
recData.droppedItems.Find(i => i.name == ing.name).stack += stacks;
else
recData.droppedItems.Add(new RecItem(item.Name, stacks, prefix));
args.Handled = true;
return;
}
else if (ing.stack < 0)
{
tsplayer.SendInfoMessage("Giving back {0}.", Utils.FormatItem((Item)ing));
tsplayer.GiveItem(item.type, item.Name, item.width, item.height, Math.Abs(ing.stack), prefix);
if (recData.droppedItems.Exists(i => i.name == ing.name))
recData.droppedItems.Find(i => i.name == ing.name).stack += (stacks + ing.stack);
else
recData.droppedItems.Add(new RecItem(item.Name, stacks + ing.stack, prefix));
foreach (Ingredient ingr in recData.activeIngredients)
if ((ingr.group == 0 && ingr.name == ing.name) || (ingr.group != 0 && ingr.group == ing.group))
fulfilledIngredient.Add(ingr);
args.Handled = true;
}
else
{
tsplayer.SendInfoMessage("Dropped {0}.", Utils.FormatItem((Item)ing, stacks));
if (recData.droppedItems.Exists(i => i.name == ing.name))
recData.droppedItems.Find(i => i.name == ing.name).stack += stacks;
else
recData.droppedItems.Add(new RecItem(item.Name, stacks, prefix));
foreach (Ingredient ingr in recData.activeIngredients)
if ((ingr.group == 0 && ingr.name == ing.name) || (ingr.group != 0 && ingr.group == ing.group))
fulfilledIngredient.Add(ingr);
args.Handled = true;
}
}
}
if (fulfilledIngredient.Count < 1)
return;
recData.activeIngredients.RemoveAll(i => fulfilledIngredient.Contains(i));
foreach (Ingredient ing in recData.activeRecipe.ingredients)
{
if (ing.name == item.Name && ing.prefix == -1)
ing.prefix = prefix;
}
if (recData.activeIngredients.Count < 1)
{
List<Product> lDetPros = Utils.DetermineProducts(recData.activeRecipe.products);
foreach (Product pro in lDetPros)
{
Item product = new Item();
product.SetDefaults(TShock.Utils.GetItemByIdOrName(pro.name).First().netID);
//itm.Prefix(-1) means at least a 25% chance to hit prefix = 0. if < -1, even chances.
product.Prefix(pro.prefix);
pro.prefix = product.prefix;
tsplayer.GiveItem(product.type, product.Name, product.width, product.height, pro.stack, product.prefix);
tsplayer.SendSuccessMessage("Received {0}.", Utils.FormatItem((Item)pro));
}
List<RecItem> prods = new List<RecItem>();
lDetPros.ForEach(i => prods.Add(new RecItem(i.name, i.stack, i.prefix)));
Log.Recipe(new LogRecipe(recData.activeRecipe.name, recData.droppedItems, prods), tsplayer.Name);
// Commands :o (NullReferenceException-free :l)
recData.activeRecipe.Clone().ExecuteCommands(tsplayer);
recData.activeRecipe = null;
recData.droppedItems.Clear();
tsplayer.SendInfoMessage("Finished crafting.");
}
}
}
}
}
#endregion
void OnLogin(PlayerPostLoginEventArgs args)
{
// Note to self: During login, TSPlayer.Active is set to False
if (args.Player == null)
return;
if (Memory.Contains(args.Player.Name))
args.Player.SetData(RecipeData.KEY, Memory.Pop(args.Player.Name));
}
void OnLogout(PlayerLogoutEventArgs args)
{
if (args.Player == null || !args.Player.Active)
return;
RecipeData data = args.Player.GetRecipeData();
if (data != null && data.activeRecipe != null)
Memory.Save(args.Player);
}
#region Commands
#region Craft
static readonly Item dummyItem = new Item();
const int CursorSlot = 58;
void Craft(CommandArgs args)
{
Item item;
var recData = args.Player.GetRecipeData(true);
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /craft <recipe/-quit/-list/-allcats/-cat{0}>",
(config.CraftFromInventory) ? "/-confirm" : "");
return;
}
var subcmd = args.Parameters[0].ToLower();
switch (subcmd)
{
case "-list":
int page;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out page))
return;
List<string> allRec = new List<string>();
// Add any recipe that isn't invisible kappa
foreach (Recipe rec in CmdRec.config.Recipes.FindAll(r => !r.invisible))
allRec.Add(rec.name);
PaginationTools.SendPage(args.Player, page, PaginationTools.BuildLinesFromTerms(allRec),
new PaginationTools.Settings
{
HeaderFormat = "Recipes ({0}/{1}):",
FooterFormat = "Type /craft -list {0} for more.",
NothingToDisplayString = "There are currently no recipes defined!"
});
return;
case "-allcats":
int pge;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pge))
return;
List<string> allCat = new List<string>();
// Another ditto from -list
foreach (Recipe rec in CmdRec.config.Recipes.FindAll(r => !r.invisible))
rec.categories.ForEach(i =>
{
if (!allCat.Contains(i))
allCat.Add(i);
});
PaginationTools.SendPage(args.Player, 1, PaginationTools.BuildLinesFromTerms(allCat),
new PaginationTools.Settings
{
HeaderFormat = "Recipe Categories ({0}/{1}):",
FooterFormat = "Type /craft -cat {0} for more.",
NothingToDisplayString = "There are currently no categories defined!"
});
return;
case "-cat":
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid category!");
return;
}
args.Parameters.RemoveAt(0);
string cat = string.Join(" ", args.Parameters);
if (!cats.Contains(cat.ToLower()))
{
args.Player.SendErrorMessage("Invalid category!");
return;
}
else
{
List<string> catrec = new List<string>();
// Keep bringing them!
foreach (Recipe rec in config.Recipes.FindAll(r => !r.invisible))
{
rec.categories.ForEach(i =>
{
if (cat.ToLower() == i.ToLower())
catrec.Add(rec.name);
});
}
args.Player.SendInfoMessage("Recipes in this category:");
args.Player.SendInfoMessage("{0}", String.Join(", ", catrec));
}
return;
case "-quit":
if (recData.activeRecipe == null)
{
args.Player.SendErrorMessage("You aren't crafting anything!");
}
else
{
args.Player.SendInfoMessage("Returning dropped items...");
foreach (RecItem itm in recData.droppedItems)
{
item = new Item();
item.SetDefaults(TShock.Utils.GetItemByIdOrName(itm.name).First().netID);
args.Player.GiveItem(item.type, itm.name, item.width, item.height, itm.stack, itm.prefix);
args.Player.SendInfoMessage("Returned {0}.", Utils.FormatItem((Item)itm));
}
recData.activeRecipe = null;
recData.droppedItems.Clear();
args.Player.SendInfoMessage("Successfully quit crafting.");
}
return;
case "-confirm":
if (!config.CraftFromInventory)
{
args.Player.SendErrorMessage("Crafting from inventory is disabled!");
return;
}
int count = 0;
Dictionary<int, bool> finishedGroup = new Dictionary<int, bool>();
Dictionary<int, int> slots = new Dictionary<int, int>();
int ingredientCount = recData.activeIngredients.Count;
foreach (Ingredient ing in recData.activeIngredients)
{
if (!finishedGroup.ContainsKey(ing.group))
{
finishedGroup.Add(ing.group, false);
}
else if (ing.group != 0)
ingredientCount--;
}
foreach (Ingredient ing in recData.activeIngredients)
{
if (ing.group == 0 || !finishedGroup[ing.group])
{
Dictionary<int, RecItem> ingSlots = new Dictionary<int, RecItem>();
for (int i = 58; i >= 0; i--)
{
item = args.TPlayer.inventory[i];
if (ing.name == item.Name && (ing.prefix == -1 || ing.prefix == item.prefix))
{
ingSlots.Add(i, new RecItem(item.Name, item.stack, item.prefix));
}
}
if (ingSlots.Count == 0)
continue;
int totalStack = 0;
foreach (var key in ingSlots.Keys)
totalStack += ingSlots[key].stack;
if (totalStack >= ing.stack)
{
foreach (var key in ingSlots.Keys)
slots.Add(key, (ingSlots[key].stack < ing.stack) ? args.TPlayer.inventory[key].stack : ing.stack);
if (ing.group != 0)
finishedGroup[ing.group] = true;
count++;
}
}
}
if (count < ingredientCount)
{
args.Player.SendErrorMessage("Insufficient ingredients!");
return;
}
if (!args.Player.InventorySlotAvailable)
{
args.Player.SendErrorMessage("Insufficient inventory space!");
return;
}
foreach (var slot in slots)
{
item = args.TPlayer.inventory[slot.Key];
var ing = recData.activeIngredients.GetIngredient(item.Name, item.prefix);
if (ing.stack > 0)
{
int stack;
if (ing.stack < slot.Value)
stack = ing.stack;
else
stack = slot.Value;
item.stack -= stack;
ing.stack -= stack;
NetMessage.SendData((int)PacketTypes.PlayerSlot, -1, -1, NetworkText.Empty, args.Player.Index, slot.Key);
args.Player.TPlayer.inventory[CursorSlot] = dummyItem;
NetMessage.SendData((int)PacketTypes.PlayerSlot, -1, -1, NetworkText.Empty, args.Player.Index, CursorSlot);
if (!recData.droppedItems.ContainsItem(item.Name, item.prefix))
recData.droppedItems.Add(new RecItem(item.Name, stack, item.prefix));
else
recData.droppedItems.GetItem(item.Name, item.prefix).stack += slot.Value;
}
}
List<Product> lDetPros = Utils.DetermineProducts(recData.activeRecipe.products);
foreach (Product pro in lDetPros)
{
Item product = new Item();
product.SetDefaults(TShock.Utils.GetItemByIdOrName(pro.name).First().netID);
product.Prefix(pro.prefix);
pro.prefix = product.prefix;
args.Player.GiveItem(product.type, product.Name, product.width, product.height, pro.stack, product.prefix);
args.Player.SendSuccessMessage("Received {0}.", Utils.FormatItem((Item)pro));
}
List<RecItem> prods = new List<RecItem>();
lDetPros.ForEach(i => prods.Add(new RecItem(i.name, i.stack, i.prefix)));
Log.Recipe(new LogRecipe(recData.activeRecipe.name, recData.droppedItems, prods), args.Player.Name);
recData.activeRecipe.Clone().ExecuteCommands(args.Player);
recData.activeRecipe = null;
recData.droppedItems.Clear();
args.Player.SendInfoMessage("Finished crafting.");
return;
default:
if (recData.activeRecipe != null)
{
args.Player.SendErrorMessage("You must finish crafting or quit your current recipe!");
return;
}
string str = string.Join(" ", args.Parameters);
if (!recs.Contains(str.ToLower()))
{
args.Player.SendErrorMessage("Invalid recipe!");
return;
}
foreach (Recipe rec in config.Recipes)
{
if (str.ToLower() == rec.name.ToLower())
{
if (!rec.permissions.Contains("") && !args.Player.CheckPermissions(rec.permissions))
{
args.Player.SendErrorMessage("You do not have the required permission to craft the recipe: {0}!", rec.name);
return;
}
if (!Utils.CheckIfInRegion(args.Player, rec.regions))
{
args.Player.SendErrorMessage("You are not in a valid region to craft the recipe: {0}!", rec.name);
return;
}
recData.activeIngredients = new List<Ingredient>(rec.ingredients.Count);
rec.ingredients.ForEach(i =>
{
recData.activeIngredients.Add(i.Clone());
});
recData.activeRecipe = rec.Clone();
break;
}
}
if (recData.activeRecipe != null)
{
List<string> inglist = Utils.ListIngredients(recData.activeRecipe.ingredients);
if (!args.Silent)
{
args.Player.SendInfoMessage("The {0} recipe requires {1} to craft. {2}",
recData.activeRecipe.name,
(inglist.Count > 1) ? String.Join(", ", inglist.ToArray(), 0, inglist.Count - 1) + ", and " + inglist.LastOrDefault() : inglist[0],
(config.CraftFromInventory) ? "Type \"/craft -confirm\" to craft." : "Please drop all required items.");
}
}
break;
}
}
#endregion
#region RecConfigReload
public static void RecReload(CommandArgs args)
{
Utils.SetUpConfig();
args.Player.SendInfoMessage("Attempted to reload the config file");
}
#endregion
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Terraria;
using TShockAPI;
namespace CommandRecipes
{
public class RecipeLog
{
public RecipeLog()
{
}
private static string path = Path.Combine(CmdRec.configDir, "CraftLog.txt");
private FileStream _ostream;
private FileStream _istream;
public StreamReader Reader { get; protected set; }
public StreamWriter Writer { get; protected set; }
public Dictionary<string, List<LogRecipe>> CompletedRecipes { get; protected set; }
#region Initialize
public void Initialize()
{
_ostream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
_istream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
Writer = new StreamWriter(_ostream);
Reader = new StreamReader(_istream);
//Task.Factory.StartNew(() => Load());
//Load();
CompletedRecipes = new Dictionary<string, List<LogRecipe>>();
}
#endregion
#region Dispose
public void Dispose()
{
Writer.Close();
Reader.Close();
}
#endregion
#region Load
/// <summary>
/// Reloads the CompletedRecipes property
/// </summary>
public void Load()
{
try
{
CompletedRecipes = LoadRecipes();
}
catch (Exception ex)
{
TShock.Log.ConsoleError(ex.ToString());
}
}
#endregion
#region LogRecipe
/// <summary>
/// Logs a crafted recipe to the log file.
/// </summary>
public void Recipe(LogRecipe recipe, string player)
{
try
{
var list = new List<string>();
recipe.ingredients.ForEach(i => list.Add(Utils.LogFormatItem((Item)i, i.stack)));
var ingredients = String.Join(",", list);
list.Clear();
recipe.products.ForEach(i => list.Add(Utils.LogFormatItem((Item)i, i.stack)));
var products = String.Join(",", list);
var str = String.Format("Player ({0}) crafted recipe ({1}), using ({2}) and obtaining ({3}).",
player,
recipe.name,
ingredients,
products);
Writer.WriteLine(str);
Writer.Flush();
//CompletedRecipes.AddToList(new KeyValuePair<string, LogRecipe>(player, recipe));
}
catch (Exception ex)
{
TShock.Log.ConsoleError(ex.ToString());
}
}
#endregion
#region LoadRecipes
/// <summary>
/// Returns the list of crafted recipes directly from the log.
/// </summary>
public Dictionary<string, List<LogRecipe>> LoadRecipes()
{
var dic = new Dictionary<string, List<LogRecipe>>();
KeyValuePair<string, LogRecipe> pair;
while (!Reader.EndOfStream)
{
pair = ParseLine(Reader.ReadLine());
if (!dic.ContainsKey(pair.Key))
{
dic.Add(pair.Key, new List<LogRecipe>());
}
dic[pair.Key].Add(pair.Value);
}
Reader.DiscardBufferedData();
return dic;
}
#endregion
#region GetRecipes
/// <summary>
/// Returns a list of Recipes crafted by player name
/// </summary>
public List<LogRecipe> GetRecipes(string player)
{
return CompletedRecipes[player];
}
#endregion
#region Helper Methods
#region ParseToString
List<string> FormatItems(List<RecItem> items)
{
var list = new List<string>();
string prefix;
foreach (var item in items)
{
prefix = item.prefix > 0 ? String.Format("[{0}] ",
Utils.GetPrefixById(item.prefix)) : "";
list.Add(String.Format("{0} {1}{2}",
item.stack,
prefix,
item.name));
}
return list;
}
#endregion
#region ParseItems
List<RecItem> ParseItems(string items)
{
var list = new List<RecItem>();
string name = String.Empty;
string stack = String.Empty;
string prefix = String.Empty;
ReadMode pos = ReadMode.Stack;
foreach (char ch in items)
{
switch (ch)
{
case ',':
name = name.Replace("(s)", String.Empty);
list.Add(new RecItem(
name.Trim(),
Int32.Parse(stack),
prefix == "" ? 0 : TShock.Utils.GetPrefixByName(prefix.Trim()).First()));
break;
case '[':
pos = ReadMode.Prefix;
break;
case ']':
pos = ReadMode.Name;
break;
default:
if (Char.IsWhiteSpace(ch) && pos != ReadMode.Name)
{
pos = ReadMode.Name;
break;
}
switch (pos)
{
case ReadMode.Stack:
stack += ch;
break;
case ReadMode.Prefix:
prefix += ch;
break;
case ReadMode.Name:
name += ch;
break;
}
break;
}
}
// Additional one for the last item
name = name.Replace("(s)", String.Empty);
list.Add(new RecItem(
name.Trim(),
Int32.Parse(stack.Trim()),
prefix == "" ? 0 : TShock.Utils.GetPrefixByName(prefix.Trim()).First()));
return list;
}
#endregion
#region ParseLine
KeyValuePair<string, LogRecipe> ParseLine(string line)
{
bool reading = false;
int pos = 0;
var reader = new[]
{
String.Empty,
String.Empty,
String.Empty,
String.Empty
};
foreach (char ch in line)
{
switch (ch)
{
case '(':
reading = true;
break;
case ')':
reading = false;
pos++;
break;
default:
if (reading)
{
reader[pos] += ch;
}
break;
}
}
return new KeyValuePair<string, LogRecipe>(
reader[0],
new LogRecipe(reader[1], ParseItems(reader[2]), ParseItems(reader[3])));
}
#endregion
#endregion
enum ReadMode
{
Stack,
Prefix,
Name
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Terraria;
using TShockAPI;
namespace CommandRecipes
{
public class RecItem
{
public string name;
public int stack;
public int prefix;
public RecItem(string name, int stack, int prefix = -1)
{
this.name = name;
this.stack = stack;
this.prefix = prefix;
}
public RecItem Clone()
{
return MemberwiseClone() as RecItem;
}
// Operators for explicit conversions
public static explicit operator Item(RecItem item)
{
var titem = new Item();
titem.SetDefaults(TShock.Utils.GetItemByIdOrName(item.name).First().netID);
titem.stack = item.stack;
titem.prefix = (byte)item.prefix;
return titem;
}
public static explicit operator RecItem(Item item)
{
return new RecItem(item.Name, item.stack, item.prefix);
}
}
public class Ingredient
{
public string name;
public int stack;
public int prefix;
public int group;
public Ingredient(string name, int stack, int prefix, int group)
{
// Can now obtain the item from its netID. Yay!
int id;
if (int.TryParse(name, out id))
{
Item item = TShock.Utils.GetItemById(id);
this.name = item != null ? item.Name : name;
}
else
this.name = name;
this.stack = stack;
this.prefix = prefix;
this.group = group;
}
public Ingredient Clone()
{
return MemberwiseClone() as Ingredient;
}
public static explicit operator Item(Ingredient item)
{
var titem = new Item();
titem.SetDefaults(TShock.Utils.GetItemByIdOrName(item.name).First().netID);
titem.stack = item.stack;
titem.prefix = (byte)item.prefix;
return titem;
}
}
public class Product
{
public string name;
public int stack;
public int prefix;
public int group;
public int weight;
public Product(string name, int stack, int prefix, int group, int weight)
{
// Ditto Ingredient
int id;
if (int.TryParse(name, out id))
{
Item item = TShock.Utils.GetItemById(id);
this.name = item != null ? item.Name : name;
}
else
this.name = name;
this.stack = stack;
this.prefix = prefix;
this.group = group;
this.weight = weight;
}
public Product Clone()
{
return MemberwiseClone() as Product;
}
public static explicit operator Item(Product item)
{
var titem = new Item();
titem.SetDefaults(TShock.Utils.GetItemByIdOrName(item.name).First().netID);
titem.stack = item.stack;
titem.prefix = (byte)item.prefix;
return titem;
}
}
public class LogRecipe
{
public string name;
public List<RecItem> ingredients;
public List<RecItem> products;
public LogRecipe(string name, List<RecItem> ingredients, List<RecItem> products)
{
this.name = name;
this.ingredients = ingredients;
this.products = products;
}
}
public abstract class RecipeFactory
{
public abstract Recipe Clone();
}
public class Recipe : RecipeFactory
{
public string name;
public List<Ingredient> ingredients;
public List<Product> products;
public List<string> categories = new List<string>();
public List<string> permissions = new List<string>();
public List<string> regions = new List<string>();
public bool invisible = false;
public string[] commands;
public Recipe(string name, List<Ingredient> ingredients, List<Product> products, List<string> categories = null, List<string> permissions = null, List<string> regions = null, bool invisible = false, string[] commands = null)
{
this.name = name;
this.ingredients = ingredients;
this.products = products;
this.categories = categories;
this.permissions = permissions;
this.regions = regions;
this.invisible = invisible;
this.commands = commands;
}
public override Recipe Clone()
{
var clone = MemberwiseClone() as Recipe;
clone.ingredients = new List<Ingredient>(ingredients.Count);
clone.products = new List<Product>(products.Count);
ingredients.ForEach(i => clone.ingredients.Add(i.Clone()));
products.ForEach(i => clone.products.Add(i.Clone()));
return clone;
}
/// <summary>
/// Runs associated commands. Returns -1 if an exception occured.
/// </summary>
public int ExecuteCommands(TSPlayer player)
{
int cmdCount = 0;
try
{
if (commands == null || commands.Length < 1)
return 0;
List<string> args;
Command cmd;
string text;
for (int i = 0; i < commands.Length; i++)
{
text = Utils.ParseCommand(player, commands[i]);
text = text.Remove(0, 1);
args = Utils.ParseParameters(text);
cmd = Commands.ChatCommands.Find(c => c.HasAlias(args[0]));
// Found the command, may remove its alias.
args.RemoveAt(0);
if (cmd != null)
{
try
{
// Execute the command without checking for permissions (?)
cmd.CommandDelegate(new CommandArgs(text, player, args));
cmdCount++;
}
catch (Exception)
{
// Swallow (and shall the rest conclude). Delicious.
}
}
}
}
catch (Exception)
{
return -1;
}
return cmdCount;
}
}
public class RecConfig
{
public bool CraftFromInventory = false;
public List<Recipe> Recipes;
public static RecConfig Read(string path)
{
if (!File.Exists(path))
return new RecConfig();
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return Read(fs);
}
}
public static RecConfig Read(Stream stream)
{
using (var sr = new StreamReader(stream))
{
var cf = JsonConvert.DeserializeObject<RecConfig>(sr.ReadToEnd());
if (ConfigRead != null)
ConfigRead(cf);
return cf;
}
}
public void Write(string path)
{
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write))
{
Write(fs);
}
}
public void Write(Stream stream)
{
{
Recipes = new List<Recipe>();
Recipes.Add(new Recipe("Copper Broadsword",
new List<Ingredient>() {
new Ingredient("Copper Bar", 8, 0, 1),
new Ingredient("Iron Bar", 8, 0, 1),
new Ingredient("Stone Block", 20, 0, 0),
new Ingredient("Wooden Hammer", 1, 0, 0) },
new List<Product>() {
new Product("Copper Broadsword", 1, 41, 1, 50),
new Product("Copper Shortsword", 1, 41, 1, 50),
new Product("Wooden Hammer", 1, 39, 0, 100) },
new List<string> { "Example" },
new List<string> { "" },
new List<string> { "" }));
Recipes.Add(new Recipe("Iron Broadsword",
new List<Ingredient>() {
new Ingredient("Iron Bar", 8, 0, 0),
new Ingredient("Stone Block", 20, 0, 0),
new Ingredient("Wooden Hammer", 1, -1, 0) },
new List<Product>() {
new Product("Iron Broadsword", 1, 41, 0, 100),
new Product("Wooden Hammer", 1, 39, 0, 100) },
new List<string> { "Example", "Example2" },
new List<string> { "cmdrec.craft.example", "craft" },
new List<string> { "" }));
}
var str = JsonConvert.SerializeObject(this, Formatting.Indented);
using (var sw = new StreamWriter(stream))
{
sw.Write(str);
}
}
public static Action<RecConfig> ConfigRead;
}
}
<file_sep>CommandRecipes
==============
Definable recipes in command-based crafting for TShock servers.
<file_sep>using System.Collections.Generic;
using TShockAPI;
namespace CommandRecipes
{
public static class Extensions
{
public static RecipeData GetRecipeData(this TSPlayer player, bool createIfNotExists = false)
{
if (!player.ContainsData(RecipeData.KEY) && createIfNotExists)
{
player.SetData(RecipeData.KEY, new RecipeData());
}
return player.GetData<RecipeData>(RecipeData.KEY);
}
public static void AddToList(this Dictionary<string, List<Recipe>> dic, KeyValuePair<string, Recipe> pair)
{
if (dic.ContainsKey(pair.Key))
{
dic[pair.Key].Add(pair.Value);
}
else
{
dic.Add(pair.Key, new List<Recipe>() { pair.Value });
}
}
public static bool CheckPermissions(this TShockAPI.TSPlayer player, List<string> perms)
{
foreach (var perm in perms)
{
if (player.HasPermission(perm))
return true;
}
return false;
}
public static Ingredient GetIngredient(this List<Ingredient> lItem, string name, int prefix)
{
foreach (var ing in lItem)
if (ing.name == name && (ing.prefix == prefix || ing.prefix == -1))
return ing;
return null;
}
public static bool ContainsItem(this List<RecItem> lItem, string name, int prefix)
{
foreach (var item in lItem)
if (item.name == name && (item.prefix == prefix || item.prefix == -1))
return true;
return false;
}
public static RecItem GetItem(this List<RecItem> lItem, string name, int prefix)
{
foreach (var item in lItem)
if (item.name == name & (item.prefix == prefix || item.prefix == -1))
return item;
return null;
}
}
}
<file_sep>using System.Collections.Generic;
using TShockAPI;
namespace CommandRecipes
{
public class RecipeDataManager
{
private Dictionary<string, RecipeData> memory;
public RecipeDataManager()
{
memory = new Dictionary<string, RecipeData>();
}
public bool Contains(string playerName)
{
return memory.ContainsKey(playerName);
}
public RecipeData Pop(string playerName)
{
RecipeData data = memory[playerName]?.Clone();
memory.Remove(playerName);
return data;
}
public bool Save(TSPlayer player)
{
if (player == null)
return false;
RecipeData data;
return (data = player.GetRecipeData()) != null && SaveSlot(player.Name, data);
}
public bool SaveSlot(string playerName, RecipeData data)
{
if (Contains(playerName))
return false;
memory[playerName] = data.Clone();
return true;
}
}
}
| fe66215d24fd3e2d4d8685926f3360246b75116c | [
"Markdown",
"C#"
] | 8 | C# | aylinni-empyrea/CommandRecipes | b877b1d79ce3237e37cdb62a5842b181e7cef2e7 | f9967ca38aaa2154b99ef856dded96ae11ae48a5 |
refs/heads/master | <file_sep>package com.mybareskinph.theBareskinApp.sale.implementations;
import com.mybareskinph.theBareskinApp.home.pojos.OrderUnit;
import com.mybareskinph.theBareskinApp.sale.pojos.RegisterSaleRequest;
import com.mybareskinph.theBareskinApp.sale.viewinterfaces.RegisterSalePresenter;
import com.mybareskinph.theBareskinApp.sale.viewinterfaces.RegisterSaleView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by paulolosbanos on 9/3/17.
*/
public class RegisterSaleInfoImpl implements RegisterSalePresenter {
RegisterSaleView mView;
public RegisterSaleRequest request;
public List<String> getPriceBreakdown() {
List<String> breakdown = new ArrayList<>();
int subtotal = 0;
//shipping = 5000;
for (OrderUnit unit : request.getPurchases()) {
int value = unit.getProduct().getProductSrpUnit() * unit.getQuantity();
breakdown.add(unit.getProduct().getProductName() + " ( × " + unit.getQuantity() + " )" + ";" + value);
subtotal += value;
}
breakdown.add("line");
breakdown.add("boldTotal Sale;" + (subtotal));
return breakdown;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.viewInterfaces;
import com.mybareskinph.theBareskinApp.home.pojos.StoreItem;
import com.mybareskinph.theBareskinApp.home.pojos.UserCredential;
import java.util.ArrayList;
public interface HomeView {
void showFutureEarning(ArrayList<StoreItem> items);
void hideFutureEarning();
void showSupplyWorth(ArrayList<StoreItem> items);
void hideSupplyWorth();
void showInviteCode(UserCredential credential);
void hideInviteCode();
void goToSuppliesPage();
void goToRegisterSalesPage();
}
<file_sep>package com.mybareskinph.theBareskinApp.widgets;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jakewharton.rxbinding.view.RxView;
import com.mybareskinph.theBareskinApp.R;
import rx.subjects.PublishSubject;
/**
* Created by paulolosbanos on 8/7/17.
*/
public class Tags extends LinearLayout {
PublishSubject<String> subject;
public Tags(Context context, String text, PublishSubject<String> subject) {
super(context);
this.subject = subject;
init(text);
}
public Tags(Context context, AttributeSet attrs) {
super(context, attrs);
init("");
}
public Tags(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init("");
}
private void init(String text) {
View view = inflate(getContext(), R.layout.view_tags_layout, this);
TextView t = ((TextView) view.findViewById(R.id.tv_tag));
t.setText(text);
RxView.clicks(t).subscribe(aVoid -> subject.onNext(text));
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.pojos;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Item {
@SerializedName("item-id")
@Expose
private String itemId;
@SerializedName("item-name")
@Expose
private String itemName;
@SerializedName("item-cost-unit")
@Expose
private Integer itemCostUnit;
@SerializedName("item-srp-unit")
@Expose
private Integer itemSrpUnit;
@SerializedName("item-qty")
@Expose
private Integer itemQty;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Integer getItemCostUnit() {
return itemCostUnit;
}
public void setItemCostUnit(Integer itemCostUnit) {
this.itemCostUnit = itemCostUnit;
}
public Integer getItemSrpUnit() {
return itemSrpUnit;
}
public void setItemSrpUnit(Integer itemSrpUnit) {
this.itemSrpUnit = itemSrpUnit;
}
public Integer getItemQty() {
return itemQty;
}
public void setItemQty(Integer itemQty) {
this.itemQty = itemQty;
}
}<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.base.BaseActivity;
import com.mybareskinph.theBareskinApp.home.pojos.StoreItem;
import com.mybareskinph.theBareskinApp.home.pojos.StoreOrder;
import com.mybareskinph.theBareskinApp.util.Constants;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class HomeActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
NavigationView navView;
@BindView(R.id.toolbar_title)
TextView toolbarTitle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navView = (NavigationView) findViewById(R.id.nav_view);
navView.setNavigationItemSelectedListener(this);
navView.setCheckedItem(R.id.nav_home);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, R.color.darkerBrown));
}
initHome();
}
private void initHome() {
HomeFragment fragment = HomeFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
.commit();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
final Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f == null) {
finish();
}
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
fragment = HomeFragment.newInstance();
toolbarTitle.setText("Home");
break;
case R.id.nav_inventory:
fragment = SupplyFragment.newInstance((ArrayList<StoreItem>) getGlobalObjects().get(Constants.SUPPLIES));
toolbarTitle.setText("Supplies");
break;
case R.id.nav_order:
fragment = OrderFragment.newInstance((ArrayList<StoreOrder>) getGlobalObjects().get(Constants.ORDERS));
toolbarTitle.setText("Orders");
break;
case R.id.nav_about:
break;
case R.id.nav_log_out:
break;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void changeCheckedNavTitle(int id) {
navView.setCheckedItem(id);
}
public void changeToolbarTitle(String title) {
toolbarTitle.setText(title);
}
}
<file_sep>package com.mybareskinph.theBareskinApp.base;
public interface BaseService {
}
<file_sep>package com.mybareskinph.theBareskinApp.home.viewInterfaces;
/**
* Created by paulolosbanos on 7/9/17.
*/
public interface PaymentInfoView {
}
<file_sep>package com.mybareskinph.theBareskinApp.home.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;
import com.mybareskinph.theBareskinApp.home.views.CustomerInfoFragment;
import com.mybareskinph.theBareskinApp.home.views.FormFragments;
import com.mybareskinph.theBareskinApp.home.views.OrderInfoFragment;
import com.mybareskinph.theBareskinApp.home.views.OrderPlacementSuccessFragment;
import com.mybareskinph.theBareskinApp.home.views.PaymentInfoFragment;
import com.mybareskinph.theBareskinApp.home.views.ProductOrdersFragment;
import com.mybareskinph.theBareskinApp.util.LoggerUtil;
import rx.subjects.PublishSubject;
public class NewOrderPagerAdapter extends FragmentStatePagerAdapter {
private static final int PAGES = 5;
SparseArray<Fragment> pages = new SparseArray<>();
PublishSubject<Object> orderPayload;
public NewOrderPagerAdapter(FragmentManager fm, PublishSubject<Object> orderPayload) {
super(fm);
this.orderPayload = orderPayload;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
pages.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
pages.remove(position);
super.destroyItem(container, position, object);
}
public FormFragments getRegisteredFragment(int position) {
return ((FormFragments) pages.get(position));
}
@Override
public Fragment getItem(int position) {
FormFragments fragment;
LoggerUtil.log(position);
switch (position) {
case 0:
fragment = ProductOrdersFragment.newInstance(ProductOrdersFragment.NEW_ORDER_MODE);
((ProductOrdersFragment) fragment)
.orderListWatcher()
.subscribe(orderUnits -> {
fragment.setAnswered(orderUnits.size() > 0);
orderPayload.onNext(orderUnits);
});
break;
case 1:
fragment = PaymentInfoFragment.newInstance();
((PaymentInfoFragment) fragment)
.paymentInformation()
.subscribe(s -> {
fragment.setAnswered(s != null && !s.isEmpty());
orderPayload.onNext(s);
});
break;
case 2:
fragment = CustomerInfoFragment.newInstance();
((CustomerInfoFragment) fragment)
.customerInfo()
.subscribe(ss -> {
fragment.setAnswered(ss != null && !ss.isEmpty());
orderPayload.onNext(ss);
});
break;
case 3:
fragment = OrderInfoFragment.newInstance();
fragment.setAnswered(true);
break;
case 4:
fragment = OrderPlacementSuccessFragment.newInstance();
fragment.setAnswered(true);
break;
default:
fragment = CustomerInfoFragment.newInstance();
}
return fragment;
}
@Override
public int getCount() {
return PAGES;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.util;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
public class LoggerUtil {
public static void log(Object o) {
Logger.d(new Gson().toJson(o));
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.viewInterfaces;
/**
* Created by paulolosbanos on 8/29/17.
*/
public interface OrderPlacementSuccessView {
}
<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.base.BaseFragment;
import com.mybareskinph.theBareskinApp.home.adapters.OrderAdapter;
import com.mybareskinph.theBareskinApp.home.implementations.OrderPresenterImpl;
import com.mybareskinph.theBareskinApp.home.pojos.StoreOrder;
import com.mybareskinph.theBareskinApp.home.pojos.UserCredential;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.OrderView;
import com.mybareskinph.theBareskinApp.util.CalendarDate;
import com.mybareskinph.theBareskinApp.util.Constants;
import com.mybareskinph.theBareskinApp.util.DateFormats;
import java.util.ArrayList;
import java.util.Date;
import butterknife.BindView;
import butterknife.OnClick;
public class OrderFragment extends BaseFragment implements OrderView {
@BindView(R.id.rv_supplies)
RecyclerView orderList;
@BindView(R.id.tv_username)
TextView username;
@BindView(R.id.tv_subtext)
TextView subtext;
ArrayList<StoreOrder> items;
OrderPresenterImpl presenter;
OrderAdapter adapter;
public OrderFragment() {
}
public static OrderFragment newInstance(ArrayList<StoreOrder> orders) {
OrderFragment fragment = new OrderFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(Constants.ORDERS, orders);
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_order, container, false);
bindView(this, view);
if (getArguments() != null) {
items = getArguments().getParcelableArrayList(Constants.ORDERS);
}
presenter = new OrderPresenterImpl(this, getGlobalObjects(), getRetrofit());
init();
return view;
}
private void init() {
((HomeActivity) getActivity()).changeToolbarTitle("Orders");
subtext.setText(getString(R.string.label_x_report_date, "orders", DateFormats.DATE_FORMAT_EMDYYYY.format(CalendarDate.fromDate(new Date()).toJavaDate())));
}
@OnClick(R.id.fab_add_order)
public void addOrder(View view) {
startActivity(new Intent(getContext(), NewOrderActivity.class));
}
@Override
public void loadUsername(UserCredential credential) {
username.setText(getString(R.string.label_greet_user, credential.getUsername()));
}
@Override
public void loadOrderDetails(ArrayList<StoreOrder> orders) {
adapter = new OrderAdapter(getContext(), items);
orderList.setLayoutManager(new LinearLayoutManager(getContext()));
orderList.setAdapter(adapter);
}
}
<file_sep>package com.mybareskinph.theBareskinApp;
import com.mybareskinph.theBareskinApp.base.BaseActivity;
import com.mybareskinph.theBareskinApp.base.BaseFragment;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
void inject(BaseActivity activity);
void inject(BaseFragment fragment);
}
<file_sep>package com.mybareskinph.theBareskinApp.sale.pojos;
import com.google.gson.annotations.SerializedName;
import com.mybareskinph.theBareskinApp.home.pojos.OrderUnit;
import java.io.Serializable;
import java.util.List;
/**
* Created by paulolosbanos on 9/1/17.
*/
public class RegisterSaleRequest implements Serializable {
@SerializedName("buyer-name")
String buyerName;
@SerializedName("buyer-number")
String buyerNumber;
List<OrderUnit> purchases;
public String getBuyerName() {
return buyerName;
}
public void setBuyerName(String buyerName) {
this.buyerName = buyerName;
}
public String getBuyerNumber() {
return buyerNumber;
}
public void setBuyerNumber(String buyerNumber) {
this.buyerNumber = buyerNumber;
}
public List<OrderUnit> getPurchases() {
return purchases;
}
public void setPurchases(List<OrderUnit> purchases) {
this.purchases = purchases;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.sale.viewinterfaces;
/**
* Created by paulolosbanos on 9/3/17.
*/
public interface RegisterSaleInfoView {
}
<file_sep>package com.mybareskinph.theBareskinApp.sale.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;
import com.mybareskinph.theBareskinApp.home.views.FormFragments;
import com.mybareskinph.theBareskinApp.home.views.ProductOrdersFragment;
import com.mybareskinph.theBareskinApp.sale.views.RegisterSaleFragment;
import com.mybareskinph.theBareskinApp.sale.views.RegisterSaleInfoFragment;
import com.mybareskinph.theBareskinApp.sale.views.RegisterSaleSuccessFragment;
import rx.android.schedulers.AndroidSchedulers;
import rx.subjects.PublishSubject;
/**
* Created by paulolosbanos on 8/31/17.
*/
public class RegisterSaleAdapter extends FragmentStatePagerAdapter {
private static final int PAGES = 4;
SparseArray<Fragment> pages = new SparseArray<>();
PublishSubject<Object> requestPayload;
public RegisterSaleAdapter(FragmentManager fm, PublishSubject<Object> requestPayload) {
super(fm);
this.requestPayload = requestPayload;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
pages.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
pages.remove(position);
super.destroyItem(container, position, object);
}
public FormFragments getRegisteredFragment(int position) {
return ((FormFragments) pages.get(position));
}
@Override
public Fragment getItem(int position) {
FormFragments fragment;
switch (position) {
case 0:
fragment = RegisterSaleFragment.newInstance();
((RegisterSaleFragment) fragment).getBuyerInfoObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s -> {
fragment.setAnswered(s != null);
requestPayload.onNext(s);
});
break;
case 1:
fragment = ProductOrdersFragment.newInstance(ProductOrdersFragment.REGISTER_SALE_MODE);
((ProductOrdersFragment) fragment)
.orderListWatcher()
.subscribe(orderUnits -> {
fragment.setAnswered(orderUnits.size() > 0);
requestPayload.onNext(orderUnits);
});
break;
case 2:
fragment = RegisterSaleInfoFragment.newInstance();
fragment.setAnswered(true);
break;
case 3:
fragment = RegisterSaleSuccessFragment.newInstance();
fragment.setAnswered(true);
break;
default:
fragment = RegisterSaleFragment.newInstance();
}
return fragment;
}
@Override
public int getCount() {
return PAGES;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.pojos;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class LoginResponse {
@SerializedName("status")
@Expose
private String status;
@SerializedName("user-credential")
@Expose
private UserCredential userCredential;
@SerializedName("store-points")
@Expose
private Integer storePoints;
@SerializedName("store-value")
@Expose
private Long storeValue;
@SerializedName("store-inventory")
@Expose
private ArrayList<StoreItem> storeInventory = null;
@SerializedName("store-orders")
@Expose
private ArrayList<StoreOrder> storeOrders = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public UserCredential getUserCredential() {
return userCredential;
}
public void setUserCredential(UserCredential userCredential) {
this.userCredential = userCredential;
}
public Integer getStorePoints() {
return storePoints;
}
public void setStorePoints(Integer storePoints) {
this.storePoints = storePoints;
}
public Long getStoreValue() {
return storeValue;
}
public void setStoreValue(Long storeValue) {
this.storeValue = storeValue;
}
public ArrayList<StoreItem> getStoreInventory() {
return storeInventory;
}
public void setStoreInventory(ArrayList<StoreItem> storeInventory) {
this.storeInventory = storeInventory;
}
public ArrayList<StoreOrder> getStoreOrders() {
return storeOrders;
}
public void setStoreOrders(ArrayList<StoreOrder> storeOrders) {
this.storeOrders = storeOrders;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.sale;
import com.mybareskinph.theBareskinApp.sale.pojos.RegisterSaleRequest;
import com.mybareskinph.theBareskinApp.sale.pojos.RegisterSaleResponse;
import retrofit2.http.Body;
import retrofit2.http.POST;
import rx.Observable;
/**
* Created by paulolosbanos on 9/3/17.
*/
public interface SaleService {
@POST("/sale/submit")
Observable<RegisterSaleResponse> registerSale(@Body RegisterSaleRequest request);
}
<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import com.mybareskinph.theBareskinApp.base.BaseFragment;
/**
* Created by paulolosbanos on 8/11/17.
*/
public class FormFragments extends BaseFragment {
private boolean answered = false;
public void setAnswered(boolean answered) {
this.answered = answered;
}
public boolean isAnswered() {
return answered;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.sale.implementations;
import com.mybareskinph.theBareskinApp.home.pojos.OrderUnit;
import com.mybareskinph.theBareskinApp.home.views.FormFragments;
import com.mybareskinph.theBareskinApp.sale.SaleService;
import com.mybareskinph.theBareskinApp.sale.pojos.RegisterSaleRequest;
import com.mybareskinph.theBareskinApp.sale.viewinterfaces.RegisterSalePresenter;
import com.mybareskinph.theBareskinApp.sale.viewinterfaces.RegisterSaleView;
import com.mybareskinph.theBareskinApp.sale.views.RegisterSaleInfoFragment;
import java.util.List;
import retrofit2.Retrofit;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class RegisterSaleImpl implements RegisterSalePresenter {
RegisterSaleView mView;
RegisterSaleRequest request = new RegisterSaleRequest();
Retrofit mRetrofit;
public RegisterSaleImpl(RegisterSaleView mView, Retrofit retrofit) {
this.mView = mView;
this.mRetrofit = retrofit;
}
public boolean saveRequestInfo(int page, Object payload) {
switch (page) {
case 0:
String[] payloadString = ((String) payload).split(":");
switch (payloadString[0]) {
case "name":
request.setBuyerName(payloadString.length < 2 ? null : payloadString[1]);
break;
case "number":
request.setBuyerNumber(payloadString.length < 2 ? null : payloadString[1]);
break;
}
return true;
case 1:
if (payload instanceof List)
request.setPurchases((List<OrderUnit>) payload);
return !request.getPurchases().isEmpty();
}
return false;
}
public void updateView(FormFragments currentFragment) {
if (currentFragment instanceof RegisterSaleInfoFragment) {
((RegisterSaleInfoFragment) currentFragment).requestObservable().onNext(request);
}
}
public void submitSale() {
mView.enableLoading(request != null);
SaleService service = mRetrofit.create(SaleService.class);
service
.registerSale(request)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(registerSaleResponse -> {
if (registerSaleResponse.getStatus().equals("success")) {
mView.onSuccess();
mView.enableLoading(false);
mView.setFinalButton();
}
});
}
public void updateNavigationButtons(boolean answered) {
mView.enableNextButton(answered);
mView.enableBackButton(answered);
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.viewInterfaces;
import com.mybareskinph.theBareskinApp.home.pojos.OrderUnit;
import rx.subjects.PublishSubject;
public interface ProductOrderPresenter {
void loadProducts();
void updateOrder(OrderUnit unit, PublishSubject<Integer> subject);
}
<file_sep>package com.mybareskinph.theBareskinApp.home.viewInterfaces;
/**
* Created by paulolosbanos on 8/12/17.
*/
public interface NewOrderPresenter {
void submitOrder();
}
<file_sep>package com.mybareskinph.theBareskinApp.home.pojos;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by paulolosbanos on 7/6/17.
*/
public class Product {
@SerializedName("product-id")
@Expose
private String productId;
@SerializedName("product-name")
@Expose
private String productName;
@SerializedName("product-cost-unit")
@Expose
private Integer productCostUnit;
@SerializedName("product-srp-unit")
@Expose
private Integer productSrpUnit;
@Expose
private List<String> tags;
public String getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
public Integer getProductCostUnit() {
return productCostUnit;
}
public Integer getProductSrpUnit() {
return productSrpUnit;
}
public List<String> getTags() {
return tags;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.util;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Currency;
public class Money implements Serializable {
public static final String PHILIPPINE_PESO = "PHP";
private static final String PLUS = "+";
private static final String MINUS = "-";
private static final String NON_BREAKING_SPACE = "\u00a0";
private static final String CURRENCY_SIGN_PESO = "\u20b1 ";
private static final String CURRENCY_SIGN_PESO_SIMPLE = "PhP ";
private static final String EMPTY = "";
/**
* Money in its lowest unit.
* E.g.
* 10000 in PHP means 100 peso.
* 10000 in INDO means 10000 rp
*/
private long normalizedAmount;
private Currency currency;
public Money(long normalizedAmount, Currency currency) {
this.normalizedAmount = normalizedAmount;
this.currency = currency;
}
public static NumberFormat getCurrencyFormat(@Nullable final String currency,
final boolean isSimpleFormatting) {
return getCurrencyFormat(currency, isSimpleFormatting, false);
}
public static NumberFormat getCurrencyFormat(@Nullable final String currency,
final boolean isSimpleFormatting,
final boolean isSigned) {
NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
try {
numberFormat.setCurrency(Currency.getInstance(currency));
} catch (NullPointerException | IllegalArgumentException e) {
DecimalFormat f = (DecimalFormat) numberFormat;
final String currencySymbol = getCurrencySymbolByCode(currency);
f.setPositivePrefix(isSigned ? PLUS + currencySymbol : currencySymbol);
f.setNegativePrefix(MINUS + currencySymbol);
f.setPositiveSuffix(EMPTY);
f.setNegativeSuffix(EMPTY);
f.setMaximumFractionDigits(2);
return numberFormat;
}
if (PHILIPPINE_PESO.equals(currency)) {
DecimalFormat f = (DecimalFormat) numberFormat;
final String currencySymbol;
if (isSimpleFormatting) {
currencySymbol = CURRENCY_SIGN_PESO_SIMPLE;
} else {
currencySymbol = getCurrencySymbolByCode(currency);
}
f.setPositivePrefix(isSigned ? PLUS + currencySymbol : currencySymbol);
f.setNegativePrefix(MINUS + currencySymbol);
f.setPositiveSuffix(EMPTY);
f.setNegativeSuffix(EMPTY);
f.setMaximumFractionDigits(2);
}
return numberFormat;
}
public static String formatPrice(@Nullable final String currency, double normalizedAmount) {
if (PHILIPPINE_PESO.equals(currency)) {
normalizedAmount = normalizedAmount / 100d;
}
return getCurrencyFormat(currency, false).format(normalizedAmount);
}
@NonNull
public static String getCurrencySymbolByCode(@Nullable final String currencyCode) {
if (currencyCode.equals(PHILIPPINE_PESO)) {
return CURRENCY_SIGN_PESO;
} else if (currencyCode.length() <= 3) {
return currencyCode;
} else {
return EMPTY;
}
}
public enum CurrencySymbolPosition {LEFT, RIGHT}
public static CurrencySymbolPosition getCurrencySymbolPosition(@NonNull final String currency) {
switch (currency) {
case PHILIPPINE_PESO:
return CurrencySymbolPosition.LEFT;
default:
return CurrencySymbolPosition.LEFT;
}
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.implementations;
import com.mybareskinph.theBareskinApp.home.pojos.OrderRequest;
import com.mybareskinph.theBareskinApp.home.pojos.OrderUnit;
import com.mybareskinph.theBareskinApp.home.pojos.UserCredential;
import com.mybareskinph.theBareskinApp.home.services.MainService;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.NewOrderPresenter;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.NewOrderView;
import com.mybareskinph.theBareskinApp.home.views.FormFragments;
import com.mybareskinph.theBareskinApp.home.views.OrderInfoFragment;
import java.util.List;
import retrofit2.Retrofit;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by paulolosbanos on 8/12/17.
*/
public class NewOrderPresenterImpl implements NewOrderPresenter {
private OrderRequest orderRequest = new OrderRequest();
private NewOrderView mView;
private Retrofit mRetrofit;
private UserCredential userCredential;
public static final int PRODUCT_ORDERS = 0;
public static final int PAYMENT_INFO = 1;
public static final int CUSTOMER_INFO = 2;
public NewOrderPresenterImpl() {
}
public NewOrderPresenterImpl(NewOrderView mView, Retrofit retrofit, UserCredential userCredentials) {
this.mView = mView;
this.mRetrofit = retrofit;
this.userCredential = userCredentials;
}
public void setOrderList(List<OrderUnit> orderList) {
orderRequest.setOrderUnitList(orderList);
}
public boolean saveOrderInfo(int page, Object payload) {
switch (page) {
case PRODUCT_ORDERS:
orderRequest.setOrderUnitList((List<OrderUnit>) payload);
return !orderRequest.getOrderUnitList().isEmpty();
case PAYMENT_INFO:
String[] payment_info = ((String) payload).split(":");
orderRequest.setPaymentChannel(payment_info[0]);
orderRequest.setPaymentDate(payment_info[1]);
return !orderRequest.getPaymentChannel().isEmpty() && !orderRequest.getPaymentDate().isEmpty();
case CUSTOMER_INFO:
String[] customer_info = ((String) payload).split(";");
orderRequest.setName(customer_info[0]);
orderRequest.setAddress(customer_info[1]);
orderRequest.setMobile(customer_info[2]);
return !orderRequest.getAddress().isEmpty() && !orderRequest.getMobile().isEmpty();
}
return false;
}
@Override
public void submitOrder() {
mView.enableLoading(orderRequest != null);
MainService service = mRetrofit.create(MainService.class);
service
.submitOrder(userCredential.getUid(),orderRequest)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(newOrderResponse -> {
mView.orderPlacementSuccess(newOrderResponse);
mView.enableLoading(false);
mView.setFinalButton();
});
}
public void updateView(FormFragments currentFragment) {
if (currentFragment instanceof OrderInfoFragment) {
((OrderInfoFragment) currentFragment).requestObservable().onNext(orderRequest);
}
}
public void updateNavigationButtons(boolean answered) {
mView.enableNextButton(answered);
mView.enableBackButton(answered);
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.home.adapters.PriceBreakdownAdapter;
import com.mybareskinph.theBareskinApp.home.implementations.OrderPlacementSuccessPresenterImpl;
import com.mybareskinph.theBareskinApp.home.pojos.NewOrderResponse;
import butterknife.BindView;
import rx.subjects.PublishSubject;
/**
* Created by paulolosbanos on 8/28/17.
*/
public class OrderPlacementSuccessFragment extends FormFragments {
@BindView(R.id.rv_price_breakdown)
RecyclerView priceBreakdown;
public static OrderPlacementSuccessFragment newInstance() {
OrderPlacementSuccessFragment fragment = new OrderPlacementSuccessFragment();
return fragment;
}
PublishSubject<NewOrderResponse> responseSubject = PublishSubject.create();
OrderPlacementSuccessPresenterImpl presenter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order_placement_success, container, false);
bindView(this, view);
presenter = new OrderPlacementSuccessPresenterImpl();
responseSubject
.asObservable()
.subscribe(response -> {
presenter.response = response;
PriceBreakdownAdapter priceBreakdownAdapter = new PriceBreakdownAdapter(getContext(), presenter.getPriceBreakdown());
priceBreakdown.setAdapter(priceBreakdownAdapter);
priceBreakdown.setLayoutManager(new LinearLayoutManager(getContext()));
});
return view;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.jakewharton.rxbinding.view.RxView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.base.BaseFragment;
import com.mybareskinph.theBareskinApp.home.implementations.HomePresenterImpl;
import com.mybareskinph.theBareskinApp.home.pojos.StoreItem;
import com.mybareskinph.theBareskinApp.home.pojos.UserCredential;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.HomeView;
import com.mybareskinph.theBareskinApp.sale.views.RegisterSaleActivity;
import com.mybareskinph.theBareskinApp.util.Constants;
import com.mybareskinph.theBareskinApp.util.Money;
import com.mybareskinph.theBareskinApp.util.StoreComputationUtil;
import java.util.ArrayList;
import butterknife.BindView;
public class HomeFragment extends BaseFragment implements HomeView {
@BindView(R.id.tv_current_supply_worth)
TextView currentSupplyWorth;
@BindView(R.id.tv_future_earning)
TextView futureEarning;
@BindView(R.id.ll_invite_code)
LinearLayout inviteCodeContainer;
@BindView(R.id.tv_invite_code)
TextView inviteCode;
@BindView(R.id.pb_loading_invite)
ProgressBar loadingInvite;
@BindView(R.id.pb_loading_current_supply_worth)
ProgressBar loadingCurrentSupply;
@BindView(R.id.pb_loading_future_earning)
ProgressBar loadingFutureEarning;
@BindView(R.id.tv_sales_history)
TextView salesHistory;
@BindView(R.id.tv_sell_now)
TextView sellNow;
@BindView(R.id.tv_details)
TextView details;
@BindView(R.id.tv_order_now)
TextView orderNow;
HomePresenterImpl presenter;
public HomeFragment() {
}
public static HomeFragment newInstance() {
return new HomeFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_home, container, false);
bindView(this, view);
presenter = new HomePresenterImpl(this, getGlobalObjects());
details.setOnClickListener(view1 -> presenter.onDetailsClick());
RxView.clicks(orderNow).subscribe(aVoid -> startActivity(new Intent(getContext(), NewOrderActivity.class)));
RxView.clicks(sellNow).subscribe(aVoid -> presenter.onRegisterSalesClick());
return view;
}
@Override
public void onResume() {
super.onResume();
getGlobalObjects();
changeToolbarTitle("Home");
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void showFutureEarning(ArrayList<StoreItem> items) {
loadingFutureEarning.setVisibility(View.GONE);
futureEarning.setVisibility(View.VISIBLE);
futureEarning.setText(Money.formatPrice(Money.PHILIPPINE_PESO, StoreComputationUtil.computeEarningTrajectory(items)));
salesHistory.setEnabled(true);
sellNow.setEnabled(true);
}
@Override
public void hideFutureEarning() {
loadingFutureEarning.setVisibility(View.VISIBLE);
futureEarning.setVisibility(View.GONE);
salesHistory.setEnabled(false);
sellNow.setEnabled(false);
}
@Override
public void showSupplyWorth(ArrayList<StoreItem> items) {
loadingCurrentSupply.setVisibility(View.GONE);
currentSupplyWorth.setVisibility(View.VISIBLE);
currentSupplyWorth.setText(Money.formatPrice(Money.PHILIPPINE_PESO, StoreComputationUtil.computeInventoryWorth(items)));
details.setEnabled(true);
orderNow.setEnabled(true);
}
@Override
public void hideSupplyWorth() {
loadingCurrentSupply.setVisibility(View.VISIBLE);
currentSupplyWorth.setVisibility(View.GONE);
details.setEnabled(false);
orderNow.setEnabled(false);
}
@Override
public void showInviteCode(UserCredential credential) {
loadingInvite.setVisibility(View.GONE);
inviteCodeContainer.setVisibility(View.VISIBLE);
inviteCode.setText(credential.getInviteCode());
}
@Override
public void hideInviteCode() {
loadingInvite.setVisibility(View.VISIBLE);
inviteCodeContainer.setVisibility(View.GONE);
}
@Override
public void goToSuppliesPage() {
SupplyFragment fragment = SupplyFragment.newInstance((ArrayList<StoreItem>) getGlobalObjects().get(Constants.SUPPLIES));
((HomeActivity) getActivity()).changeCheckedNavTitle(R.id.nav_inventory);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
}
@Override
public void goToRegisterSalesPage() {
startActivity(new Intent(getContext(), RegisterSaleActivity.class));
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jakewharton.rxbinding.support.v4.view.RxViewPager;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.base.BaseActivity;
import com.mybareskinph.theBareskinApp.home.adapters.NewOrderPagerAdapter;
import com.mybareskinph.theBareskinApp.home.implementations.NewOrderPresenterImpl;
import com.mybareskinph.theBareskinApp.home.pojos.NewOrderResponse;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.NewOrderView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.subjects.PublishSubject;
public class NewOrderActivity extends BaseActivity implements NewOrderView {
@BindView(R.id.vp_new_order)
ViewPager newOrderPager;
@BindView(R.id.iv_back)
ImageView back;
@BindView(R.id.ll_next)
LinearLayout next;
@BindView(R.id.ll_loading)
LinearLayout loading;
@BindView(R.id.tv_fwd_btn)
TextView forwardButton;
@BindView(R.id.iv_right_done)
ImageView rightDone;
@BindView(R.id.iv_right)
ImageView right;
NewOrderPresenterImpl presenter;
PublishSubject<Object> answerWatcher = PublishSubject.create();
NewOrderPagerAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
ButterKnife.bind(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, R.color.darkerBrown));
}
presenter = new NewOrderPresenterImpl(this, getRetrofit(), getUserCredentials());
adapter = new NewOrderPagerAdapter(getSupportFragmentManager(), answerWatcher);
newOrderPager.setAdapter(adapter);
enableNextButton(false);
enableBackButton(false);
RxViewPager
.pageSelections(newOrderPager)
.map(pos -> (adapter.getRegisteredFragment(pos)))
.filter(formFragments -> formFragments != null)
.subscribe(currentFragment -> {
presenter.updateNavigationButtons(currentFragment.isAnswered());
presenter.updateView(currentFragment);
});
answerWatcher
.asObservable()
.subscribe(payload -> presenter.updateNavigationButtons(presenter.saveOrderInfo(newOrderPager.getCurrentItem(), payload)));
}
@OnClick(R.id.ll_next)
public void next(View view) {
if (newOrderPager.getCurrentItem() == 3) {
presenter.submitOrder();
} else {
newOrderPager.setCurrentItem(newOrderPager.getCurrentItem() + 1);
}
}
@OnClick(R.id.iv_back)
public void back(View view) {
newOrderPager.setCurrentItem(newOrderPager.getCurrentItem() - 1);
}
@OnClick(R.id.iv_right_done)
public void finishButton(View view) {
finish();
}
@Override
public void enableBackButton(boolean condition) {
back.setEnabled(newOrderPager.getCurrentItem() > 0 || condition);
back.setClickable(newOrderPager.getCurrentItem() > 0 || condition);
}
@Override
public void enableLoading(boolean condition) {
loading.setVisibility(condition ? View.VISIBLE : View.GONE);
next.setVisibility(condition ? View.GONE : View.VISIBLE);
}
@Override
public void enableNextButton(boolean condition) {
next.setEnabled(condition);
next.setClickable(condition);
}
@Override
public void orderPlacementSuccess(NewOrderResponse response) {
((OrderPlacementSuccessFragment) adapter.getRegisteredFragment(adapter.getCount() - 1)).responseSubject.onNext(response);
newOrderPager.setCurrentItem(adapter.getCount() - 1);
}
@Override
public void setFinalButton() {
forwardButton.setVisibility(View.GONE);
rightDone.setVisibility(View.VISIBLE);
right.setVisibility(View.GONE);
back.setVisibility(View.GONE);
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.util.Observables;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import rx.Observable;
import rx.subjects.PublishSubject;
public class CustomerInfoFragment extends FormFragments {
@BindView(R.id.et_name)
EditText name;
@BindView(R.id.et_address)
EditText address;
@BindView(R.id.et_number)
EditText number;
PublishSubject<String> customerInfo = PublishSubject.create();
public CustomerInfoFragment() {
}
public static CustomerInfoFragment newInstance() {
CustomerInfoFragment fragment = new CustomerInfoFragment();
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_customer_info, container, false);
bindView(this, view);
name.setText(getUserCredentials().getFullname());
List<Observable<Boolean>> observableList = Arrays.asList(
RxTextView.textChanges(name).map(charSequence -> !charSequence.toString().isEmpty()),
RxTextView.textChanges(address).map(charSequence -> !charSequence.toString().isEmpty()),
RxTextView.textChanges(number).map(charSequence -> !charSequence.toString().isEmpty()));
Observables
.allLatestTrue(observableList)
.subscribe(aBoolean -> {
if(aBoolean)
customerInfo.onNext(name.getText().toString() + ";" + address.getText().toString() + ";" + number.getText().toString());
});
return view;
}
public PublishSubject<String> customerInfo() {
return customerInfo;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.implementations;
import com.mybareskinph.theBareskinApp.home.pojos.LoginRequest;
import com.mybareskinph.theBareskinApp.home.pojos.LoginResponse;
import com.mybareskinph.theBareskinApp.home.pojos.StoreItem;
import com.mybareskinph.theBareskinApp.home.pojos.StoreOrder;
import com.mybareskinph.theBareskinApp.home.pojos.UserCredential;
import com.mybareskinph.theBareskinApp.home.services.MainService;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.LoginPresenter;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.LoginView;
import com.mybareskinph.theBareskinApp.util.Constants;
import com.mybareskinph.theBareskinApp.util.LoggerUtil;
import java.io.IOException;
import java.util.ArrayList;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by paulolosbanos on 7/24/17.
*/
public class LoginPresenterImpl implements LoginPresenter {
private LoginView mView;
private Retrofit mRetrofit;
private LoginRequest request;
public LoginPresenterImpl(LoginView mView, Retrofit mRetrofit) {
this.mView = mView;
this.mRetrofit = mRetrofit;
this.request = new LoginRequest();
}
@Override
public void login() {
MainService svc = mRetrofit.create(MainService.class);
svc.login(request)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<LoginResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onStart() {
super.onStart();
mView.loginLoading();
}
@Override
public void onError(Throwable e) {
if (e instanceof HttpException) {
LoggerUtil.log(((HttpException) e).code());
} else if (e instanceof IOException) {
LoggerUtil.log(e);
}
}
@Override
public void onNext(LoginResponse loginResponse) {
loadOrders(loginResponse.getStoreOrders());
loadSupplies(loginResponse.getStoreInventory());
loadPersonalInfo(loginResponse.getUserCredential());
mView.showHome();
}
});
}
public void setId(String id) {
this.request.setId(id);
}
public void setPassword(String password) {
this.request.setPassword(password);
}
@Override
public void loadSupplies(ArrayList<StoreItem> items) {
mView.getGlobalObjects().put(Constants.SUPPLIES, items);
}
@Override
public void loadOrders(ArrayList<StoreOrder> orders) {
mView.getGlobalObjects().put(Constants.ORDERS, orders);
}
@Override
public void loadPersonalInfo(UserCredential cred) {
mView.getGlobalObjects().put(Constants.USER_INFO, cred);
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.util.LoggerUtil;
import com.mybareskinph.theBareskinApp.util.Money;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by paulolosbanos on 8/23/17.
*/
public class PriceBreakdownAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final LayoutInflater inflater;
private final List<String> pricebreakdown;
private final int BREAKDOWN = 0;
private final int BREAKDOWN_BOLD = 1;
private final int LINE = 2;
public PriceBreakdownAdapter(@NonNull Context context, List<String> pricebreakdown) {
this.inflater = LayoutInflater.from(context);
this.pricebreakdown = pricebreakdown;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == LINE) {
view = inflater.inflate(R.layout.item_layout_line, parent, false);
return new ViewHolderLine(view);
} else if (viewType == BREAKDOWN_BOLD) {
view = inflater.inflate(R.layout.item_layout_bold, parent, false);
return new ViewHolderPriceBreakdown(view);
} else {
view = inflater.inflate(R.layout.item_layout_price_breakdown, parent, false);
return new ViewHolderPriceBreakdown(view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
if (!pricebreakdown.get(position).equals("line") || pricebreakdown.get(position).contains("bold")) {
ViewHolderPriceBreakdown holder = (ViewHolderPriceBreakdown) h;
String[] token = pricebreakdown.get(position).split(";");
String trimmedString = token[0].replace("bold", "");
holder.title.setText(trimmedString);
try {
holder.value.setText(Money.formatPrice(Money.PHILIPPINE_PESO, Double.parseDouble(token[1])));
} catch (NumberFormatException e) {
LoggerUtil.log("token[1] is not numeric. skip parsing");
holder.value.setText(token[1]);
}
}
}
@Override
public int getItemCount() {
return pricebreakdown.size();
}
@Override
public int getItemViewType(int position) {
String x = pricebreakdown.get(position);
if (pricebreakdown.get(position).equals("line")) {
return LINE;
} else if (pricebreakdown.get(position).contains("bold")) {
return BREAKDOWN_BOLD;
} else {
return BREAKDOWN;
}
}
public class ViewHolderPriceBreakdown extends RecyclerView.ViewHolder {
@BindView(R.id.tv_title)
TextView title;
@BindView(R.id.tv_value)
TextView value;
public ViewHolderPriceBreakdown(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
public class ViewHolderLine extends RecyclerView.ViewHolder {
@BindView(R.id.line)
View line;
public ViewHolderLine(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SectionIndexer;
import android.widget.TextView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.home.pojos.StoreItem;
import com.mybareskinph.theBareskinApp.util.Money;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class SupplyAdapter extends RecyclerView.Adapter<SupplyAdapter.ViewHolder> implements SectionIndexer {
private List<StoreItem> itemList;
private final LayoutInflater inflater;
public SupplyAdapter(Context context, List<StoreItem> items) {
this.itemList = items;
inflater = LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.item_supply, viewGroup, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
StoreItem item = itemList.get(i);
viewHolder.itemName.setText(item.getItemName());
viewHolder.itemQty.setText(item.getItemQty() + " pcs in stock");
viewHolder.itemCostPerUnit.setText(Money.formatPrice(Money.PHILIPPINE_PESO, item.getItemCostUnit()));
viewHolder.itemSrpPerUnit.setText(Money.formatPrice(Money.PHILIPPINE_PESO, item.getItemSrpUnit()));
viewHolder.itemTotalCost.setText(Money.formatPrice(Money.PHILIPPINE_PESO, item.getItemCostUnit() * item.getItemQty()));
viewHolder.itemTotalRevenue.setText(Money.formatPrice(Money.PHILIPPINE_PESO, item.getItemSrpUnit() * item.getItemQty()));
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public int getItemCount() {
return itemList.size();
}
@Override
public Object[] getSections() {
return new Object[0];
}
@Override
public int getPositionForSection(int sectionIndex) {
return 0;
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.item_name)
TextView itemName;
@BindView(R.id.item_qty)
TextView itemQty;
@BindView(R.id.item_cost_unit)
TextView itemCostPerUnit;
@BindView(R.id.item_srp_unit)
TextView itemSrpPerUnit;
@BindView(R.id.item_total_cost)
TextView itemTotalCost;
@BindView(R.id.item_total_revenue)
TextView itemTotalRevenue;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.views;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.base.BaseFragment;
import com.mybareskinph.theBareskinApp.home.adapters.SupplyAdapter;
import com.mybareskinph.theBareskinApp.home.implementations.SupplyPresenterImpl;
import com.mybareskinph.theBareskinApp.home.pojos.StoreItem;
import com.mybareskinph.theBareskinApp.home.pojos.UserCredential;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.SupplyView;
import com.mybareskinph.theBareskinApp.util.CalendarDate;
import com.mybareskinph.theBareskinApp.util.Constants;
import com.mybareskinph.theBareskinApp.util.DateFormats;
import java.util.ArrayList;
import java.util.Date;
import butterknife.BindView;
public class SupplyFragment extends BaseFragment implements SupplyView {
@BindView(R.id.rv_supplies)
RecyclerView suppliesList;
@BindView(R.id.tv_username)
TextView username;
@BindView(R.id.tv_subtext)
TextView subtext;
ArrayList<StoreItem> items;
SupplyPresenterImpl presenter;
SupplyAdapter adapter;
public SupplyFragment() {
}
public static SupplyFragment newInstance(ArrayList<StoreItem> items) {
SupplyFragment fragment = new SupplyFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(Constants.ITEMS, items);
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_supply, container, false);
bindView(this, view);
if (getArguments() != null) {
items = getArguments().getParcelableArrayList(Constants.ITEMS);
}
adapter = new SupplyAdapter(getContext(), items);
suppliesList.setLayoutManager(new LinearLayoutManager(getContext()));
suppliesList.setAdapter(adapter);
((HomeActivity) getActivity()).changeToolbarTitle("Supplies");
presenter = new SupplyPresenterImpl(this, getGlobalObjects(), getRetrofit());
subtext.setText(getString(R.string.label_x_report_date, "supplies", DateFormats.DATE_FORMAT_EMDYYYY.format(CalendarDate.fromDate(new Date()).toJavaDate())));
return view;
}
@Override
public void loadUsername(UserCredential credential) {
username.setText(getString(R.string.label_greet_user, credential.getUsername()));
}
@Override
public void loadSupplyDetails(ArrayList<StoreItem> storeItems) {
}
}
<file_sep>package com.mybareskinph.theBareskinApp.sale.views;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mybareskinph.theBareskinApp.R;
import com.mybareskinph.theBareskinApp.home.adapters.PriceBreakdownAdapter;
import com.mybareskinph.theBareskinApp.home.views.FormFragments;
import com.mybareskinph.theBareskinApp.sale.implementations.RegisterSaleInfoImpl;
import com.mybareskinph.theBareskinApp.sale.pojos.RegisterSaleRequest;
import butterknife.BindView;
import rx.subjects.PublishSubject;
/**
* Created by paulolosbanos on 9/1/17.
*/
public class RegisterSaleInfoFragment extends FormFragments {
@BindView(R.id.tv_fullname)
TextView fullname;
@BindView(R.id.tv_number)
TextView number;
@BindView(R.id.rv_price_breakdown)
RecyclerView priceBreakdown;
public static RegisterSaleInfoFragment newInstance() {
return new RegisterSaleInfoFragment();
}
PublishSubject<RegisterSaleRequest> requestObservable = PublishSubject.create();
RegisterSaleInfoImpl presenter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register_sale_info, container, false);
bindView(this, view);
presenter = new RegisterSaleInfoImpl();
requestObservable.subscribe(registerSaleRequest -> {
presenter.request = registerSaleRequest;
if(registerSaleRequest.getBuyerName() != null) {
fullname.setText(registerSaleRequest.getBuyerName());
}
if(registerSaleRequest.getBuyerNumber() != null) {
number.setText(registerSaleRequest.getBuyerNumber());
}
PriceBreakdownAdapter priceBreakdownAdapter = new PriceBreakdownAdapter(getContext(), presenter.getPriceBreakdown());
priceBreakdown.setAdapter(priceBreakdownAdapter);
priceBreakdown.setLayoutManager(new LinearLayoutManager(getContext()));
});
return view;
}
public PublishSubject<RegisterSaleRequest> requestObservable() {
return requestObservable;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.home.implementations;
import com.mybareskinph.theBareskinApp.home.pojos.NewOrderResponse;
import com.mybareskinph.theBareskinApp.home.pojos.OrderUnit;
import com.mybareskinph.theBareskinApp.home.viewInterfaces.OrderPlacementSuccessPresenter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by paulolosbanos on 8/29/17.
*/
public class OrderPlacementSuccessPresenterImpl implements OrderPlacementSuccessPresenter {
public NewOrderResponse response;
public List<String> getPriceBreakdown() {
List<String> breakdown = new ArrayList<>();
int subtotal = 0;
//shipping = 5000;
for (OrderUnit unit : response.getRequest().getOrderUnitList()) {
int value = unit.getProduct().getProductCostUnit() * unit.getQuantity();
// breakdown.add(unit.getProduct().getProductName() + " ( × " + unit.getQuantity() + " )" + ";" + value);
subtotal += value;
}
//breakdown.add("line");
breakdown.add("Subtotal;" + subtotal);
breakdown.add("Shipping Fee;Awaiting Confirmation");
breakdown.add("boldTotal w/o Shipping;" + (subtotal));
return breakdown;
}
}
<file_sep>package com.mybareskinph.theBareskinApp.widgets;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import com.mybareskinph.theBareskinApp.R;
public class TypeFacedTextView extends AppCompatTextView {
String fontString = "Roboto-Regular.ttf";
public TypeFacedTextView(Context context) {
super(context);
init(null);
}
public TypeFacedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public TypeFacedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
public void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontSelector, 0, 0);
if (a.getString(R.styleable.FontSelector_font) != null) {
fontString = a.getString(R.styleable.FontSelector_font);
if ("montserrat_regular".equals(fontString) || "montserrat_thin".equals(fontString)) {
fontString += ".otf";
} else {
fontString += ".ttf";
}
}
Typeface font = Typeface.createFromAsset(getContext().getAssets(), fontString);
setTypeface(font);
a.recycle();
}
}
}
| 6ba38a17730d2cdaad8204853d2053f93736b380 | [
"Java"
] | 35 | Java | paulolosbanos/bareskin | 2314e10188665a0bf06d8fbd2a025aefa097eb0d | d3ff2283700884e9bdbe50f280279bae02eca5ec |
refs/heads/master | <file_sep>#include <QString>
#include <QByteArray>
#include <QXmlSchema>
#include <QXmlSchemaValidator>
#include <QMessageBox>
#include <QDomDocument>
#include <QDomNode>
#include "FileReader.h"
FileReader::FileReader(QString fileName, QAbstractItemModel* d, MyWidget* p) : file(fileName), model(d), parent(p) {
QByteArray data("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
"<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
"<xsd:element name=\"chart\" type=\"chartType\"/>"
" <xsd:complexType name=\"chartType\">"
" <xsd:sequence>"
" <xsd:element name=\"title\" type=\"xsd:string\"/>"
" <xsd:element name=\"xlabel\" type=\"xsd:string\" minOccurs=\"0\"/>"
" <xsd:element name=\"ylabel\" type=\"xsd:string\" minOccurs=\"0\"/>"
" <xsd:element name=\"point\" type=\"pointType\" maxOccurs=\"unbounded\"/>"
" </xsd:sequence>"
" </xsd:complexType>"
" <xsd:complexType name=\"pointType\">"
" <xsd:sequence>"
" <xsd:element name=\"x\" type=\"xsd:string\"/>"
" <xsd:element name=\"y\" type=\"xsd:string\"/>"
" </xsd:sequence>"
" </xsd:complexType>"
"</xsd:schema>");
if(!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(parent, tr("qCharts"), tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString()));
return;
}
QXmlSchema schema;
schema.load(data);
if(schema.isValid()) {
QXmlSchemaValidator validator(schema);
if(validator.validate(&file, QUrl::fromLocalFile(file.fileName()))){
isReadable=true;
}
else {
isReadable=false;
QMessageBox::warning(this, tr("qCharts"), tr("The file that you are trying to open isn't valid."));
}
}
file.close();
}
void FileReader::read() {
if(isReadable) {
file.open(QFile::ReadOnly | QFile::Text);
QDomDocument doc;
if(!doc.setContent(&file, false))
QMessageBox::warning(this, tr("qCharts"), tr("There was an error trying to parse the file."));
QDomElement root = doc.documentElement();
parseDocument(root);
file.close();
}
}
void FileReader::parseDocument(const QDomElement& element) {
model->removeRows(0, model->rowCount());
int row=0;
QDomNode child = element.firstChild();
while(!child.isNull()) {
if(child.toElement().tagName() == "title")
readTitle(child.toElement());
else if(child.toElement().tagName() == "xlabel")
readXLabel(child.toElement());
else if(child.toElement().tagName() == "ylabel")
readYLabel(child.toElement());
else if(child.toElement().tagName() == "point") {
model->insertRow(row);
QDomNode nephew = child.firstChild();
while(!nephew.isNull()) {
if(nephew.toElement().tagName() == "x")
model->setData(model->index(row, 0), nephew.toElement().text());
else if(nephew.toElement().tagName() == "y")
model->setData(model->index(row, 1), nephew.toElement().text());
nephew = nephew.nextSibling();
}
row++;
}
child = child.nextSibling();
}
}
void FileReader::readTitle(const QDomElement& element) {
parent->setTitle(element.text());
}
void FileReader::readXLabel(const QDomElement& element) {
parent->setXLabel(element.text());
}
void FileReader::readYLabel(const QDomElement& element) {
parent->setYLabel(element.text());
}
<file_sep>#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QApplication>
#include <QWidget>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QLabel>
#include <QLineEdit>
#include <QFrame>
#include <QTableView>
#include <QPushButton>
#include <QGroupBox>
#include <QRadioButton>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QAbstractItemModel>
#include <QItemSelectionModel>
#include <QQueue>
#include <QPointF>
#include "MyCanvas.h"
class MyWidget : public QWidget {
Q_OBJECT
public:
MyWidget(QWidget* parent=0);
void setTitle(QString);
void setXLabel(QString);
void setYLabel(QString);
QString getTitle();
QString getXLabel();
QString getYLabel();
private slots:
void newChart();
void open();
bool save();
bool saveAs();
void about();
void add();
void remove();
void changingModel();
void beforeDraw();
private:
QMenuBar* menuBar;
QMenu* fileMenu;
QMenu* helpMenu;
QAction* newAct;
QAction* openAct;
QAction* saveAct;
QAction* saveAsAct;
QAction* exitAct;
QAction* aboutAct;
QAction* aboutQtAct;
MyCanvas* canvas;
QLabel* titleLabel;
QLabel* xLabel;
QLabel* yLabel;
QLineEdit* titleEdit;
QLineEdit* xEdit;
QLineEdit* yEdit;
QFrame* separator1;
QFrame* separator2;
QFrame* separator3;
QTableView* table;
QPushButton* addRow;
QPushButton* removeRow;
QPushButton* draw;
QGroupBox* chartBox;
QRadioButton* line;
QRadioButton* bar;
QRadioButton* pie;
QVBoxLayout* vBox;
QGridLayout* desk;
QAbstractItemModel* model;
QItemSelectionModel* selectionModel;
QQueue<QPointF> qPoint;
QString fileName;
bool modelIsChanged;
int typeData;
void createActions();
void createMenus();
void createModel();
void createDataWidget();
void createView();
void createDxBar();
void connectSignalSlot();
bool maybeSave();
void resetModified();
void showRadioButton();
};
#endif
<file_sep>#include <QAbstractItemModel>
#include <QMessageBox>
#include "CheckData.h"
#include <iostream>
using namespace std;
CheckData::CheckData(QAbstractItemModel* model, int &type) {
bool xString=false, yString=false;
if(model) {
for(int i=0; i<model->rowCount(); i++) {
bool canConvert=false;
(model->data(model->index(i, 0))).toDouble(&canConvert);
if(!canConvert)
xString=true;
(model->data(model->index(i, 1))).toDouble(&canConvert);
if(!canConvert)
yString=true;
}
if(!xString && yString)
type=0;
else if(xString && !yString)
type=1;
else if(!xString && !yString)
type=2;
else
type=-1;
}
}
<file_sep>#ifndef FILEWRITER_H
#define FILEWRITER_H
#include <QWidget>
#include <QFile>
#include <QAbstractItemModel>
#include "MyWidget.h"
class FileWriter : public QWidget {
public:
FileWriter(QString, QAbstractItemModel*, MyWidget*);
private:
QFile file;
QAbstractItemModel* model;
MyWidget* parent;
};
#endif
<file_sep>#ifndef LINECHART_H
#define LINECHART_H
class LineChart {
public:
LineChart(QPainter&, QQueue<QPointF>*);
};
#endif
<file_sep>#ifndef NORMVALUE_H
#define NORMVALUE_H
#include <QAbstractItemModel>
#include <QQueue>
#include <QPointF>
class NormValue {
public:
NormValue(QQueue<QPointF>*, QAbstractItemModel*, int);
};
#endif
<file_sep>#include <QPainter>
#include "MyCanvas.h"
#include "NormValue.h"
#include "LineChart.h"
MyCanvas::MyCanvas(QWidget* parent) : QWidget(parent) {
model=0;
radio="";
}
void MyCanvas::draw() {
update();
}
void MyCanvas::setVariable(QQueue<QPointF>* q, QString r, int t, QAbstractItemModel* d) {
model=d;
radio=r;
typeData=t;
qPoint=q;
}
void MyCanvas::paintEvent(QPaintEvent*) {
QPainter p(this);
if(model) {
if(typeData==0 || typeData==1) {
if(radio=="bar") {
//TODO disegno il grafico a barre
}
else if(radio=="pie") {
//TODO disegno il grafico a torta
}
}
else if(typeData==2 && radio=="line") {
LineChart(p, qPoint);
}
}
}
<file_sep>#ifndef MYCANVAS_H
#define MYCANVAS_H
#include <QWidget>
#include <QAbstractItemModel>
#include <QQueue>
#include <QPointF>
class MyCanvas : public QWidget {
Q_OBJECT
public:
MyCanvas(QWidget* parent=0);
void setVariable(QQueue<QPointF>*, QString, int, QAbstractItemModel*);
public slots:
void draw();
protected:
void paintEvent(QPaintEvent*);
private:
QQueue<QPointF>* qPoint;
QAbstractItemModel* model;
QString radio;
int typeData;
};
#endif
<file_sep>#ifndef FILEREADER_H
#define FILEREADER_H
#include <QWidget>
#include <QFile>
#include <QAbstractItemModel>
#include <QDomElement>
#include "MyWidget.h"
class FileReader : public QWidget {
public:
FileReader(QString, QAbstractItemModel*, MyWidget*);
void read();
private:
bool isReadable;
QFile file;
QAbstractItemModel* model;
MyWidget* parent;
void parseDocument(const QDomElement&);
void readTitle(const QDomElement&);
void readXLabel(const QDomElement&);
void readYLabel(const QDomElement&);
};
#endif
<file_sep>#include <QApplication>
#include <QTranslator>
#include <QString>
#include <QLocale>
#include "MyWidget.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QTranslator translator;
QString locale = QLocale::system().name();
translator.load(QString("qCharts_") + locale, "/");
app.installTranslator(&translator);
MyWidget widget;
widget.showMaximized();
return app.exec();
}
<file_sep>#include "NormValue.h"
NormValue::NormValue(QQueue<QPointF>* qPoint, QAbstractItemModel* model, int typeData) {
int dim=500;
if(typeData==0 || typeData==1) {
double max=(model->data(model->index(0, typeData))).toDouble();
for(int i=1; i<model->rowCount(); i++) {
double value=(model->data(model->index(i, typeData))).toDouble();
if(max<value)
max=value;
}
for(int i=0; i<model->rowCount(); i++) {
double value=(model->data(model->index(i, typeData))).toDouble();
qPoint->enqueue(QPointF(dim*i/model->rowCount(), dim-(dim*value/max)));
}
}
if(typeData==2) {
double max0=(model->data(model->index(0, 0))).toDouble();
double max1=(model->data(model->index(0, 1))).toDouble();
for(int i=1; i<model->rowCount(); i++) {
double value0=(model->data(model->index(i, 0))).toDouble();
double value1=(model->data(model->index(i, 1))).toDouble();
if(max0<value0)
max0=value0;
if(max1<value1)
max1=value1;
}
for(int i=0; i<model->rowCount(); i++) {
double value0=(model->data(model->index(i, 0))).toDouble();
double value1=(model->data(model->index(i, 1))).toDouble();
qPoint->enqueue(QPointF(dim*value0/max0, dim-(dim*value1/max1)));
}
}
}
<file_sep>#include <QMessageBox>
#include <QDomDocument>
#include <QTextStream>
#include "FileWriter.h"
FileWriter::FileWriter(QString fileName, QAbstractItemModel* d, MyWidget* p) : file(fileName), model(d), parent(p) {
if(!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(parent, tr("qCharts"), tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString()));
return;
}
QDomDocument doc;
QDomElement root = doc.createElement("chart");
doc.appendChild(root);
QDomElement title = doc.createElement("title");
root.appendChild(title);
QDomText titleText = doc.createTextNode(parent->getTitle());
title.appendChild(titleText);
QDomElement xlabel = doc.createElement("xlabel");
root.appendChild(xlabel);
QDomText xText = doc.createTextNode(parent->getXLabel());
xlabel.appendChild(xText);
QDomElement ylabel = doc.createElement("ylabel");
root.appendChild(ylabel);
QDomText yText = doc.createTextNode(parent->getYLabel());
ylabel.appendChild(yText);
int row = model->rowCount();
for(int i=0; i<row; i++) {
QDomElement point = doc.createElement("point");
root.appendChild(point);
QDomElement x = doc.createElement("x");
point.appendChild(x);
QDomText xValue = doc.createTextNode((model->data(model->index(i, 0))).toString());
x.appendChild(xValue);
QDomElement y = doc.createElement("y");
point.appendChild(y);
QDomText yValue = doc.createTextNode((model->data(model->index(i, 1))).toString());
y.appendChild(yValue);
}
QTextStream out(&file);
out << doc.toString();
}
<file_sep>#include <QPainter>
#include <QQueue>
#include <QPointF>
#include "LineChart.h"
LineChart::LineChart(QPainter &p, QQueue<QPointF>* queue) {
p.setPen(QColor(Qt::black));
p.drawLine(QPoint(0,0), QPoint(0,500));
p.drawLine(QPoint(0,500), QPoint(500,500));
for(int i=0; i<(queue->size())-1; i++) {
p.setPen(QColor(Qt::blue));
p.drawLine(queue->value(i), queue->value(i+1));
}
queue->clear();
}
<file_sep>#include <QMessageBox>
#include <QString>
#include <QFileDialog>
#include <QFile>
#include <QHeaderView>
#include <QStandardItemModel>
#include "MyWidget.h"
#include "FileReader.h"
#include "FileWriter.h"
#include "CheckData.h"
#include "NormValue.h"
MyWidget::MyWidget(QWidget* parent) : QWidget(parent) {
modelIsChanged=false;
typeData=-1;
createActions();
createMenus();
createModel();
createDataWidget();
createView();
createDxBar();
connectSignalSlot();
}
void MyWidget::newChart() {
if(maybeSave()) {
titleEdit->clear();
xEdit->clear();
yEdit->clear();
createModel();
createView();
canvas->setVariable(0, "", typeData, 0);
canvas->draw();
resetModified();
showRadioButton();
}
}
void MyWidget::open() {
if(maybeSave()) {
fileName = QFileDialog::getOpenFileName(this, tr("Open qCharts File"), QDir::currentPath(), tr("qCharts Files (*.xml)"));
if(!fileName.isEmpty()) {
FileReader reader(fileName, model, this);
reader.read();
}
changingModel();
resetModified();
}
}
bool MyWidget::save() {
if(fileName.isEmpty())
return saveAs();
else {
FileWriter writer(fileName, model, this);
resetModified();
return true;
}
}
bool MyWidget::saveAs() {
fileName = QFileDialog::getSaveFileName(this, tr("Save qCharts File"), QDir::currentPath(), tr("qCharts Files (*.xml)"));
if(fileName.isEmpty())
return false;
FileWriter writer(fileName, model, this);
resetModified();
return true;
}
void MyWidget::about() { //TODO write something smart for about()
QMessageBox::about(this, tr("About qCharts"), tr("That's all Folks!"));
}
void MyWidget::add() {
model->insertRow(model->rowCount());
}
void MyWidget::remove() {
model->removeRow((model->rowCount())-1);
}
void MyWidget::changingModel() {
modelIsChanged=true;
CheckData data(model, typeData);
if(typeData==-1) {
line->setVisible(false);
bar->setVisible(false);
pie->setVisible(false);
}
else if(typeData==0 || typeData==1) {
line->setVisible(false);
bar->setVisible(true);
pie->setVisible(true);
}
else if(typeData==2) {
line->setVisible(true);
bar->setVisible(false);
pie->setVisible(false);
}
}
void MyWidget::beforeDraw() {
QString radio="";
if(line->isChecked())
radio="line";
else if(bar->isChecked())
radio="bar";
else if(pie->isChecked())
radio="pie";
model->sort(0);
NormValue norm(&qPoint, model, typeData);
canvas->setVariable(&qPoint, radio, typeData, model);
canvas->draw();
}
void MyWidget::createActions() {
newAct = new QAction(tr("&New"), this);
openAct = new QAction(tr("&Open..."), this);
saveAct = new QAction(tr("&Save"), this);
saveAsAct = new QAction(tr("Save &as..."), this);
exitAct = new QAction(tr("&Exit"), this);
aboutAct = new QAction(tr("&About"), this);
aboutQtAct = new QAction(tr("About &Qt"), this);
}
void MyWidget::createMenus() {
fileMenu = new QMenu(tr("&File"));
fileMenu->addAction(newAct);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addAction(saveAsAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
helpMenu = new QMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
menuBar = new QMenuBar();
menuBar->addMenu(fileMenu);
menuBar->addSeparator();
menuBar->addMenu(helpMenu);
}
void MyWidget::createModel() {
model = new QStandardItemModel(1, 2, this);
model->setHeaderData(0, Qt::Horizontal, tr("X"));
model->setHeaderData(1, Qt::Horizontal, tr("Y"));
connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(changingModel()));
}
void MyWidget::createDataWidget() {
canvas = new MyCanvas(this);
titleLabel = new QLabel(tr("Title:"));
xLabel = new QLabel(tr("Label x-axis:"));
yLabel = new QLabel(tr("Label y-axis:"));
titleEdit = new QLineEdit();
xEdit = new QLineEdit();
yEdit = new QLineEdit();
table = new QTableView;
addRow = new QPushButton("+");
removeRow = new QPushButton("-");
draw = new QPushButton(tr("Draw"));
chartBox = new QGroupBox(tr("Chart selection"));
line = new QRadioButton(tr("Line chart"));
bar = new QRadioButton(tr("Bar chart"));
pie = new QRadioButton(tr("Pie chart"));
}
void MyWidget::createView() {
table->setModel(model);
selectionModel = new QItemSelectionModel(model);
table->setSelectionModel(selectionModel);
QHeaderView* headerView = table->horizontalHeader();
headerView->setStretchLastSection(true);
}
void MyWidget::createDxBar() {
separator1 = new QFrame();
separator2 = new QFrame();
separator3 = new QFrame();
separator1->setFrameShape(QFrame::HLine);
separator2->setFrameShape(QFrame::HLine);
separator3->setFrameShape(QFrame::HLine);
vBox = new QVBoxLayout;
vBox->addWidget(line);
vBox->addWidget(bar);
vBox->addWidget(pie);
chartBox->setLayout(vBox);
desk = new QGridLayout();
desk->setColumnStretch(0,1);
desk->addWidget(canvas,0,0,12,1);
desk->addWidget(titleLabel,0,1,1,2);
desk->addWidget(titleEdit,1,1,1,2);
desk->addWidget(separator1,2,1,1,2);
desk->addWidget(xLabel,3,1,1,2);
desk->addWidget(xEdit,4,1,1,2);
desk->addWidget(yLabel,5,1,1,2);
desk->addWidget(yEdit,6,1,1,2);
desk->addWidget(separator2,7,1,1,2);
desk->addWidget(table,8,1,1,2);
desk->addWidget(addRow,9,1);
desk->addWidget(removeRow,9,2);
desk->addWidget(separator3,10,1,1,2);
desk->addWidget(chartBox,11,1,1,2);
desk->addWidget(draw,12,1,1,2);
setLayout(desk);
}
void MyWidget::connectSignalSlot() {
connect(newAct, SIGNAL(triggered()), this, SLOT(newChart()));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(addRow, SIGNAL(clicked()), this, SLOT(add()));
connect(removeRow, SIGNAL(clicked()), this, SLOT(remove()));
connect(draw, SIGNAL(clicked()), this, SLOT(beforeDraw()));
}
bool MyWidget::maybeSave() {
if(titleEdit->isModified() || xEdit->isModified() || yEdit->isModified() || modelIsChanged) {
QMessageBox::StandardButton saveFirst;
saveFirst = QMessageBox::warning(this, tr("qCharts"), tr("Data has been modified.\nDo you want to save changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
if(saveFirst == QMessageBox::Save) {
return save();
}
else if(saveFirst == QMessageBox::Cancel) {
return false;
}
}
return true;
}
void MyWidget::resetModified() {
titleEdit->setModified(false);
xEdit->setModified(false);
yEdit->setModified(false);
modelIsChanged=false;
typeData=-1;
}
void MyWidget::showRadioButton() {
line->setVisible(true);
bar->setVisible(true);
pie->setVisible(true);
}
void MyWidget::setTitle(QString text) {
titleEdit->setText(text);
}
void MyWidget::setXLabel(QString text) {
xEdit->setText(text);
}
void MyWidget::setYLabel(QString text) {
yEdit->setText(text);
}
QString MyWidget::getTitle() {
return titleEdit->text();
}
QString MyWidget::getXLabel() {
return xEdit->text();
}
QString MyWidget::getYLabel() {
return yEdit->text();
}
<file_sep>#ifndef CHECKDATA_H
#define CHECKDATA_H
class CheckData {
public:
CheckData(QAbstractItemModel*, int&);
};
#endif
| 9a1d2773d30861e42a09c919c97a7106f984b9d3 | [
"C++"
] | 15 | C++ | mzilio/qCharts | c91512c004be85a239253f0938a6cb47841e8b58 | e49d9948d83d928c7fe6b0f92c6fb606c2efd417 |
refs/heads/master | <repo_name>tomivs/arduino-usb-vumeter<file_sep>/vu_meter/vu_meter.ino
int ledsConfig[4][2] = {
{2, 100},
{3, 20000},
{4, 200000},
{5, 400000}
};
int ledsCount = sizeof(ledsConfig) / sizeof(int);
void setup() {
Serial.begin(115200);
for (int i = 0; i < ledsCount - 1; i++) {
pinMode(ledsConfig[i][0], OUTPUT);
}
}
void loop() {
while (Serial.available()) {
long int val = Serial.parseInt();
for (int i = 0; i < ledsCount - 1; i++) {
if (val > ledsConfig[i][1])
digitalWrite(ledsConfig[i][0], HIGH);
else
digitalWrite(ledsConfig[i][0], LOW);
}
}
}
<file_sep>/README.md
# arduino-usb-vumeter
Transmite en tiempo real la información del servidor de audio de la computadora y permite visualizarla con un Arduino mediante LEDs.
| 3fc1d87c871053079b643a6d1de0af1343399a52 | [
"Markdown",
"C++"
] | 2 | C++ | tomivs/arduino-usb-vumeter | 304ed5f2bd030ecc222971f721889b3aa074ebd4 | b29d97d8451adcf73ea788859e205a9e4c755386 |
refs/heads/master | <file_sep>calculadora
===========
Calculadora con interfaz gráfica hecha en java
<file_sep>package calculadora.interfaz;
/**
* Ejercicio: Calculadora sencilla - Implementar la Interfaz de usuario -
* Implementar los mtodos siguientes a través de los listeners adecuados: -
* Sumar - Restar - Multiplicar - Dividir
*
* @author: $Author: Omaruiz $
*/
public class CalculadoraInterfaz {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
VentanaCalculadora calculadora = new VentanaCalculadora();
calculadora.setVisible(true);
}
} | 0587014dc396d6acbeb28e1d4e2eaffb2113ea7e | [
"Markdown",
"Java"
] | 2 | Markdown | omaruiz/calculadora | 2a7d5f30d33187a2557801845b7faf543aab3a28 | 81178c62df097e5d57dc4b0b7dc5cf1f208d81d5 |
refs/heads/master | <repo_name>software-kaist/DataScienceContest<file_sep>/src/ManDrill.py
import sys
def process_file(fileName):
input_file = open(fileName, "r")
for line in input_file:
line = line.strip()
print (line)
input_file.close()
import random
def splitDataset(dataset, splitRatio):
trainSize = int(len(dataset) * splitRatio)
trainSet = []
copy = list(dataset)
while len(trainSet) < trainSize:
index = random.randrange(len(copy))
trainSet.append(copy.pop(index))
return [trainSet, copy]
def separateByClass(dataset):
separated = {}
for i in range(len(dataset)):
vector = dataset[i]
if (vector[-1] not in separated):
separated[vector[-1]] = []
separated[vector[-1]].append(vector)
return separated
import math
def mean(numbers):
return sum(numbers)/float(len(numbers))
def stdev(numbers):
avg = mean(numbers)
variance = sum([pow(x-avg,2) for x in numbers])/float(len(numbers)-1)
return math.sqrt(variance)
def summarize(dataset):
summaries = [(mean(attribute), stdev(attribute)) for attribute in zip(*dataset)]
del summaries[-1]
return summaries
def summarizeByClass(dataset):
separated = separateByClass(dataset)
summaries = {}
for classValue, instances in separated.iteritems():
summaries[classValue] = summarize(instances)
return summaries
import math
def calculateProbability(x, mean, stdev):
exponent = math.exp(-(math.pow(x-mean,2)/(2*math.pow(stdev,2))))
return (1 / (math.sqrt(2*math.pi) * stdev)) * exponent
dataset = [[1], [2], [3], [4], [5]]
splitRatio = 0.67
train, test = splitDataset(dataset, splitRatio)
print('Split {0} rows into train with {1} and test with {2}').format(len(dataset), train, test)
dataset = [[1,20,1], [2,21,0], [3,22,1]]
separated = separateByClass(dataset)
print('Separated instances: {0}').format(separated)
numbers = [1,2,3,4,5]
print('Summary of {0}: mean={1}, stdev={2}').format(numbers, mean(numbers), stdev(numbers))
dataset = [[1,20,0], [2,21,1], [3,22,0]]
summary = summarize(dataset)
print('Attribute summaries: {0}').format(summary)
dataset = [[1,20,1], [2,21,0], [3,22,1], [4,22,0]]
summary = summarizeByClass(dataset)
print('Summary by class value: {0}').format(summary)
x = 71.5
mean = 73
stdev = 6.2
probability = calculateProbability(x, mean, stdev)
print('Probability of belonging to this class: {0}').format(probability)
process_file("../FLAT_RCL_Out_14.txt")
# import random
#
# # 게임을 위한 랜덤 숫자 생성
# rn = ["0", "0", "0"]
# rn[0] = str(random.randrange(1, 9, 1))
# rn[1] = rn[0]
# rn[2] = rn[0]
# while (rn[0] == rn[1]):
# rn[1] = str(random.randrange(1, 9, 1))
# while (rn[0] == rn[2] or rn[1] == rn[2]):
# rn[2] = str(random.randrange(1, 9, 1))
#
# #print(rn)
#
# t_cnt = 0 # 시도횟수
# s_cnt = 0 # 스트라이크 갯수
# b_cnt = 0 # 볼 갯수
#
# print("숫자야구게임을 시작합니다 !!!")
# print("---------------------------")
# while ( s_cnt < 3 ):
#
# num = str(input("숫자 3자리를 입력하세요 : "))
#
# s_cnt = 0
# b_cnt = 0
#
# for i in range(0, 3):
# for j in range(0, 3):
# if(num[i] == str(rn[j]) and i == j):
# s_cnt += 1
# elif(num[i] == str(rn[j]) and i != j):
# b_cnt += 1
# print("결과 : [", s_cnt, "] Strike [", b_cnt, "] Ball")
# t_cnt += 1
# print("---------------------------")
# print(t_cnt, "번 만에 정답을 맞추셨습니다.")<file_sep>/src/main.py
'''
Created on 2015. 10. 24.
@author: SUNgHOOn
'''
from numpy import ones
from numpy import log
import nltk # stop words를 제거해도 영향이 미미함! 속도만 느려지므로 삭제
#import array
# 정규식으로 단어별 파싱 함수
def textParse(bigString): #input is big string, #output is word list
import re
listOfTokens = re.split(r'\W*', bigString)
return [tok.lower() for tok in listOfTokens if len(tok) > 0]
# 중복을 제거한 단어 모음 함수
def createVocabList(dataSet):
vocabSet = set([]) #create empty set 중복 허용 안함!!
for document in dataSet:
print(document)
vocabSet = vocabSet | set(document) #union of the two sets
vocabSet.remove("hwt")
vocabSet.remove("swt")
vocabSet.remove("etc")
return list(vocabSet)
def whiteVocabList():
vocabSet = set([]) #create empty set 중복 허용 안함!!
vocabSet.add('update')
vocabSet.add('software')
vocabSet.add('ecm')
vocabSet.add('upload')
vocabSet.add('calibration')
vocabSet.add('tpms')
vocabSet.add('westport')
vocabSet.add('reprogram')
vocabSet.add('disabled')
vocabSet.add('monitoring')
vocabSet.add('programming')
vocabSet.add('pscm')
vocabSet.add('sdm')
vocabSet.add('ecu')
vocabSet.add('bcm')
vocabSet.add('ecx')
vocabSet.add('pcm')
vocabSet.add('vim')
vocabSet.add('esc')
vocabSet.add('eco')
vocabSet.add('ewps')
vocabSet.add('dbna')
vocabSet.add('pim')
vocabSet.add('tps')
vocabSet.add('sccm')
vocabSet.add('controlling')
vocabSet.add('version')
vocabSet.add('recalibrate')
vocabSet.add('reflash')
vocabSet.add('re-flash')
vocabSet.add('receives')
vocabSet.add('algorithm')
vocabSet.add('interface')
vocabSet.add('diagnostics')
vocabSet.add('calibrations')
vocabSet.add('recalibrated')
vocabSet.add('reprogrammed')
vocabSet.add('conditions')
vocabSet.add('electronic')
vocabSet.add('updated')
vocabSet.add('module')
vocabSet.add('unit')
vocabSet.add('program')
vocabSet.add('control')
vocabSet.add('rcm')
vocabSet.add('abs')
vocabSet.add('electric')
vocabSet.add('system')
vocabSet.add('eps')
vocabSet.add('fmvss')
vocabSet.add('systems')
vocabSet.add('affected')
vocabSet.add('dasm')
vocabSet.add('ebcm')
vocabSet.add('ipm')
vocabSet.add('tcm')
vocabSet.add('detected')
vocabSet.add('enhanced')
vocabSet.add('interfere')
vocabSet.add('authorized')
vocabSet.add('alerted')
vocabSet.add('warned')
vocabSet.add('deactivated')
vocabSet.add('associated')
vocabSet.add('notified')
# # vocabSet.add('leak')
# # vocabSet.add('inspect')
# # vocabSet.add('damaged')
# # vocabSet.add('detaches')
# # vocabSet.add('locked')
# # vocabSet.add('corrected')
# # vocabSet.add('installed')
# # vocabSet.add('melting')
# # vocabSet.add('install')
# vocabSet.add('causing')
# vocabSet.add('impact')
# vocabSet.add('incorrect')
# vocabSet.add('event')
# vocabSet.add('repair')
# vocabSet.add('overloaded')
# vocabSet.add('affected')
# vocabSet.add('remove')
# vocabSet.add('protected')
# vocabSet.add('disengaged')
# vocabSet.add('misaligned')
# vocabSet.add('fmvss')
# vocabSet.add('eps')
# vocabSet.add('system')
# vocabSet.add('control')
# vocabSet.add('unit')
# vocabSet.add('module')
# vocabSet.add('updated')
# vocabSet.add('electronic')
# vocabSet.add('version')
# vocabSet.add('recalibrate')
# vocabSet.add('reflash')
# vocabSet.add('receives')
# vocabSet.add('algorithm')
# vocabSet.add('interface')
# vocabSet.add('diagnostics')
# vocabSet.add('calibrations')
# vocabSet.add('recalibrated')
# vocabSet.add('reprogrammed')
# vocabSet.add('controlling')
# vocabSet.add('dbna')
# vocabSet.add('esc')
# vocabSet.add('eco')
# vocabSet.add('ewps')
# vocabSet.add('bcm')
# vocabSet.add('ecx')
# vocabSet.add('pcm')
# vocabSet.add('vim')
# vocabSet.add('ecu')
# vocabSet.add('programming')
# vocabSet.add('monitoring')
# vocabSet.add('disabled')
# vocabSet.add('reprogram')
# # vocabSet.add('westport')
# vocabSet.add('tpms')
# vocabSet.add('upload')
# vocabSet.add('calibration')
# vocabSet.add('ecm')
# vocabSet.add('software')
# vocabSet.add('update')
# vocabSet.add('dasm')
# vocabSet.add('manifold')
# vocabSet.add('wesport')
# vocabSet.add('free')
# vocabSet.add('charge')
# vocabSet.add('manifold')
# # 1차 Contest Result
# # vocabSet.add("refresh")
# # vocabSet.add("reprogramming")
# # vocabSet.add("reprogrammed")
# # vocabSet.add("reprogram")
# # vocabSet.add("repair")
# # vocabSet.add("repairs") ##
# # vocabSet.add("replace") ##
# # vocabSet.add("replaced")
# # vocabSet.add("replacement")
# vocabSet.add("steering") ##
# # vocabSet.add("gears")
# # vocabSet.add("telescopic")
# # vocabSet.add("escort")
# # vocabSet.add("abs")
# # vocabSet.add("cabs")
# # vocabSet.add("escalade")
# vocabSet.add("automatic") ##
# vocabSet.add("automatically")
# vocabSet.add("inspect") ##
# vocabSet.add("inspection")
# vocabSet.add("inspections")
# vocabSet.add("inspecting")
# vocabSet.add("inspected")
# vocabSet.add("units") ##
# vocabSet.add("unit")
# vocabSet.add("bolts") ##
# vocabSet.add("coolant") ##
# vocabSet.add("lines") ##
# vocabSet.add("line") ##
# vocabSet.add("door") ##
# vocabSet.add("software")
# vocabSet.add("crack") ##
# vocabSet.add("cracks")
# vocabSet.add("cracking") ##
# vocabSet.add("cracked") ##
# vocabSet.add("insulation")
# vocabSet.add("gunite")
# vocabSet.add("insulation") ##
# vocabSet.add("calibration")
# vocabSet.add("absorber") ##
# vocabSet.add("absorbers") ##
# vocabSet.add("absorb") ##
# # vocabSet.add("ecu")
# # vocabSet.add("tpms")
# vocabSet.add("absolute") ##
# vocabSet.add("monitoring")
# # vocabSet.add("hecu")
# vocabSet.add("absence") ##
# vocabSet.add("remove") ##
# vocabSet.add("overheated")
# vocabSet.add("exhoust")
# vocabSet.add("components") ##
# vocabSet.add("component")
# vocabSet.add("melt") ##
# vocabSet.add("attach") ##
# vocabSet.add("attachment") ##
# # vocabSet.add("illuminates")
# # vocabSet.add("illuminate")
# vocabSet.add("update")
# vocabSet.add("updated")
# vocabSet.add("absorption")
# # vocabSet.add("Tire pressure monitoring systems")
# # vocabSet.add("esc")
# # vocabSet.add("escape")
# # vocabSet.add("escapes")
# vocabSet.add("upload")
# vocabSet.add("rescue")
# vocabSet.add("describing")
return list(vocabSet)
# 단어별 빈도수 구하기
def bagOfWords2VecMN(vocabList, inputSet):
returnVec = [0]*len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] += 1
return returnVec
def bagOfWords2VecMN_Tot(vocabList, inputSet, totCntList):
returnVec = [0]*len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] += 1
totCntList[vocabList.index(word)] += 1
return returnVec
# 나이브 베이지안
def trainNB0(trainMatrix,trainCategory):
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
print(numTrainDocs, numWords)
# print(sum(trainCategory))
# pAbusive = sum(trainCategory)/float(numTrainDocs)
p0Num = ones(numWords); p1Num = ones(numWords) #change to ones()
# print(p0Num, len(p0Num))
# print(p1Num, len(p1Num))
p0Denom = 2.0; p1Denom = 2.0
abus = 0 #change to 2.0
for i in range(numTrainDocs):
if trainCategory[i] == "hwt":
p1Num += trainMatrix[i]
p1Denom += sum(trainMatrix[i])
elif trainCategory[i] == "swt":
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
abus += 1
pAbusive = abus/float(numTrainDocs)
print(p0Num, len(p0Num))
print(p0Denom)
print(p1Num, len(p1Num))
print(p1Denom)
p1Vect = log(p1Num/p1Denom) #change to log()
p0Vect = log(p0Num/p0Denom) #change to log()
return p0Vect,p1Vect,pAbusive,p0Num,p1Num
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
# p1 = sum(vec2Classify * p1Vec) + log(pClass1) #element-wise mult
# p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
p1 = sum(vec2Classify * p1Vec) + log(1.0 - pClass1) #element-wise mult
p0 = sum(vec2Classify * p0Vec) + log(pClass1)
#print(p1, p0)
if p1 > p0:
return "hwt"
else:
return "swt"
if __name__ == '__main__':
'''
학습
'''
docList=[];
recall_2014_file = open("../new_rcl_out_14.txt", "r", encoding='utf8')
#recall_2014_file = open("../test_set.txt", "r", encoding='utf8')
from nltk.corpus import stopwords # Import the stop word list
print(stopwords.words("english"))
for line in recall_2014_file:
line = line.strip()
# wordList = textParse(line)
wordList = nltk.word_tokenize(line)
wordList = [tok.lower() for tok in wordList if len(tok) > 0]
# 영향도 없고 느려지므로 주석 처리!!!
# wordList = [w for w in wordList if not w in stopwords.words("english")] # remove stop words
print(wordList)
docList.append(wordList)
# 중복 제거하여 단어 리스트 만듬
# vocabList = createVocabList(docList)
vocabList = whiteVocabList()
print(vocabList)
print("VOCA CNT=%d" %(len(vocabList)))
trainMat = []; trainClasses = []; totCntList = [0]*len(vocabList)
for docIndex in range(len(docList)):
# 등장 빈도 수 체크 vocabList trainMat 같은 인덱스로 묶임!!
#trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
trainMat.append(bagOfWords2VecMN_Tot(vocabList, docList[docIndex], totCntList))
trainClasses.append(docList[docIndex][0])
# print(trainMat[docIndex])
# print(trainClasses)
print(totCntList)
# # 빈도수 낮은 것 삭제 ###################################################
# delList = []
# for i in range(len(totCntList)):
# if totCntList[i] <= 15:
# delList.append(vocabList[i])
#
# for item in delList:
# vocabList.remove(item)
#
# print(vocabList)
# print("VOCA CNT=%d" %(len(vocabList)))
#
# trainMat = []; totCntList = [0]*len(vocabList)
# for docIndex in range(len(docList)):
# trainMat.append(bagOfWords2VecMN_Tot(vocabList, docList[docIndex], totCntList))
# trainClasses.append(docList[docIndex][0])
#
# print(totCntList)
# ###############################################################
# 학습된 테이블
p0V,p1V,pSpam,p0Num,p1Num = trainNB0((trainMat), (trainClasses))
#print(p0V)
#print(p1V)
print(pSpam)
# Feature Select를 위한 데이터 추출
word_cnt_2014 = open("../2014_word_cnt.txt", "w", encoding='utf8')
for i in range(len(vocabList)):
# wordCntLine = "%s %d %f %f\n" %(vocabList[i], totCntList[i], p0V[i], p1V[i])
wordCntLine = "%s %d %f %f\n" %(vocabList[i], totCntList[i], p0Num[i], p1Num[i])
word_cnt_2014.write(wordCntLine)
word_cnt_2014.close()
'''
테스트 할 파일 로딩
'''
recall_2014_file_test = open("../new_rcl_out_15.txt", "r", encoding='utf8')
# recall_2014_file_test = open("../FLAT_RCL_Out_15_new.txt", "r", encoding='utf8')
# recall_2014_file_test = open("../test_set.txt", "r", encoding='utf8')
# 학습된 테이블 검증
testDocList=[];
for line in recall_2014_file_test:
line = line.strip()
wordList = textParse(line)
testDocList.append(wordList)
swt_error_cnt = 0; swt_cnt = 0; hwt_error_cnt = 0; hwt_cnt = 0; predic_swt_cnt = 0;
for i in range(len(testDocList)):
wordVector = bagOfWords2VecMN(vocabList, testDocList[i])
predic = classifyNB(wordVector,p0V,p1V,pSpam)
# kList = ['15e011000', '15v013000', '15v043000', '15v064000', '15v075000']
# if testDocList[i][0] in kList:
# print(wordVector)
if predic == "swt":
predic_swt_cnt += 1
print("SWT Classfication", testDocList[i][1], testDocList[i][0], predic)
if testDocList[i][0] == "swt":
swt_cnt += 1
if predic != testDocList[i][0]:
swt_error_cnt += 1
print ("SWT classification error", testDocList[i][1], testDocList[i][0], predic)
# else:
# print ("swt classification OK", testDocList[i][1], testDocList[i][0], predic)
elif testDocList[i][0] == "hwt":
hwt_cnt += 1
if predic != testDocList[i][0]:
hwt_error_cnt += 1
print ("HWT classification error", testDocList[i][1], testDocList[i][0], predic)
# else:
# print ("hwt classification OK", testDocList[i][1], testDocList[i][0], predic)
print("SW Recall classification CNT=%d" %(predic_swt_cnt))
swt_recall = (swt_cnt - swt_error_cnt) / swt_cnt
print("SW Recall(True Positive Rate)=%f, FP=%d, SW CNT=%d" %(swt_recall, swt_error_cnt, swt_cnt))
hwt_recall = (hwt_cnt - hwt_error_cnt) / hwt_cnt
print("HW Recall(True Positive Rate)=%f, FP=%d, HW CNT=%d" %(hwt_recall, hwt_error_cnt, hwt_cnt))
accuracy = ((swt_cnt - swt_error_cnt) + (hwt_cnt - hwt_error_cnt)) / (swt_cnt + hwt_cnt)
print("Accuracy=%f" %(accuracy))
<file_sep>/src/Merge.py
'''
Created on 2015. 10. 24.
@author: SUNgHOOn
트레이닝셋에 리콜타입 머지
old_rcl_out_14.txt 파일을 읽어
software.txt
hardware.txt
etc.txt
의 ID와 비교하여
new_rcl_out_14.txt 파일 생성
'''
# recall_2014_file = open("../old_rcl_out_14.txt", "r", encoding='utf8')
# recall_2014_outfile = open("../new_rcl_out_14.txt", "w", encoding='utf8')
recall_2014_file = open("../FLAT_RCL_Out_15_new.txt", "r", encoding='utf8')
recall_2014_outfile = open("../new_rcl_out_15.txt", "w", encoding='utf8')
for line in recall_2014_file:
line = line.strip()
rcl_id = line[0:9]
#print(rcl_id)
search_id = ""
# sw_file = open("../software.txt", "r")
sw_file = open("../software2015.txt", "r")
for sw_id in sw_file:
sw_id = sw_id.strip()
if rcl_id == sw_id:
search_id = sw_id
line = "SWT " + line
recall_2014_outfile.write(line)
recall_2014_outfile.write("\n")
break
# if search_id == "":
# hw_file = open("../hardware.txt", "r")
# for hw_id in hw_file:
# hw_id = hw_id.strip()
# if rcl_id == hw_id:
# search_id = hw_id
# line = "HWT " + line
# break
#
# if search_id == "":
# hw_file = open("../etc.txt", "r")
# for hw_id in hw_file:
# hw_id = hw_id.strip()
# if rcl_id == hw_id:
# search_id = hw_id
# line = "ETC " + line
# break
if search_id == "":
line = "HWT " + line
recall_2014_outfile.write(line)
recall_2014_outfile.write("\n")
# recall_2014_outfile.write(line)
# recall_2014_outfile.write("\n")
print (line)
recall_2014_outfile.close()
| 36efe7a8cf4efddf5721276ffa77d69fb1980d5a | [
"Python"
] | 3 | Python | software-kaist/DataScienceContest | df36cefd98f95603ada8aba6bca95d2fd332eef4 | 63e916950ab50c1f9e9e33e423aab824d8c689e8 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MusicSearch
{
public class SongRequestLocal
{
public static string MusicDir = Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%") + "\\Music\\";
public struct SmallFileInfo
{
public string Name;
public string Dir;
public string Path;
public string Extension;
}
private static SmallFileInfo[] MusicFiles = new SmallFileInfo[0];
private static DateTime LastEdit = new DateTime(0);
public static SmallFileInfo[] GetFiles()
{
try
{
var DirInfo = new DirectoryInfo(MusicDir);
if (DirInfo.LastAccessTime > LastEdit)
{
LastEdit = DirInfo.LastAccessTime;
//Console.WriteLine($"Reloading local music library, last detected change at {DirInfo.LastAccessTime.ToLongTimeString()}");
MusicFiles = AddFiles(new List<SmallFileInfo>(), DirInfo).OrderBy(x => x.Name).ToArray();
}
}
catch //(Exception ex)
{
//Console.WriteLine(ex);
}
return MusicFiles;
}
private static string[] Exts = new[]
{
"FLAC", "WAV", "MP3", "M4A", "ALAC", "OGG", "APE"
};
private static List<SmallFileInfo> AddFiles(List<SmallFileInfo> List, DirectoryInfo Dir)
{
foreach (var File in Dir.GetFiles())
{
var Extention = File.Extension.Substring(1).ToUpper();
if (Exts.Contains(Extention) && !File.Attributes.HasFlag(FileAttributes.System))
{
List.Add(new SmallFileInfo
{
Name = File.Name.Substring(0, File.Name.Length - File.Extension.Length),
Dir = Dir.FullName,
Path = File.FullName,
Extension = Extention
});
}
}
foreach (var SubDir in Dir.GetDirectories())
{
AddFiles(List, SubDir);
}
return List;
}
}
}
<file_sep>using Newtonsoft.Json;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class SentMessageAck
{
/// <summary>Required, string
/// <para>This parameter specifies who sent this response.</para>
/// <para>The value is the registration token of the client app.</para>
/// </summary>
[JsonProperty("from", Required = Required.Always)]
public string From { get; set; }
/// <summary>Required, string
/// <para>This parameter uniquely identifies a message in an XMPP connection. The value is a string that uniquely identifies the associated message.</para>
/// </summary>
[JsonProperty("message_id", Required = Required.Always)]
public string MessageId { get; set; }
/// <summary>Required, string
/// <para>This parameter specifies an ack or nack message from the XMPP connection server to the app server.</para>
/// <para>If the value is set to nack, the app server should look at error and error_description to get failure information.</para>
/// </summary>
[JsonProperty("message_type", Required = Required.Always)]
public string MessageType { get; set; }
/// <summary>Optional, string
/// <para>This parameter specifies the canonical registration token for the client app that the message was processed and sent to. Sender should replace the registration token with this value on future requests; otherwise, the messages might be rejected.</para>
/// </summary>
[JsonProperty("registration_id", Required = Required.Default)]
public string RegistrationId { get; set; }
/// <summary>Optional, string
/// <para>This parameter specifies an error related to the downstream message. It is set when the message_type is nack. See table 4 for details.</para>
/// </summary>
[JsonProperty("error", Required = Required.Default)]
public string Error { get; set; }
/// <summary>Optional, string
/// <para>This parameter provides descriptive information for the error. It is set when the message_type is nack.</para>
/// </summary>
[JsonProperty("error_description", Required = Required.Default)]
public string ErrorDesc { get; set; }
}
}
<file_sep>using Newtonsoft.Json;
namespace CaiqueServer.Cloud.Json
{
/// <summary>
/// <para>This is a message sent from the XMPP connection server to an app server. Here are the primary types of messages that the XMPP connection server sends to the app server:</para>
/// <para>Delivery Receipt: If the app server included delivery_receipt_requested in the downstream message, the XMPP connection server sends a delivery receipt when it receives confirmation that the device received the message.</para>
/// <para>Control: These CCS-generated messages indicate that action is required from the app server.</para>
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
class ServerMessage
{
#region Common field
/// <summary>Required, string
/// <para>This parameter specifies the type of the CCS message: either delivery receipt or control.</para>
/// <para>When it is set to receipt, the message includes from, message_id, category, and data fields to provide additional information.</para>
/// <para>When it is set to control, the message includes control_type to indicate the type of control message.</para>
/// </summary>
[JsonProperty("message_type", Required = Required.Always)]
public string MessageType { get; set; }
#endregion
#region Delivery receipt-specific
/// <summary>Required, string
/// <para>This parameter is set to gcm.googleapis.com, indicating that the message is sent from CCS.</para>
/// </summary>
[JsonProperty("from", Required = Required.Always)]
public string From { get; set; }
/// <summary>Required, string
/// <para>This parameter specifies the original message ID that the receipt is intended for, prefixed with dr2: to indicate that the message is a delivery receipt. An app server must send an ack message with this message ID to acknowledge that it received this delivery receipt. See table 6 for the ack message format.</para>
/// </summary>
[JsonProperty("message_id", Required = Required.Always)]
public string MessageId { get; set; }
/// <summary>Optional, string
/// <para>This parameter specifies the application package name of the client app that receives the message that this delivery receipt is reporting. This is available when message_type is receipt.</para>
/// </summary>
[JsonProperty("category", Required = Required.Default)]
public string Category { get; set; }
[JsonObject(MemberSerialization.OptIn)]
public class DataPayload
{
/// <summary>This parameter specifies the status of the receipt message. It is set to MESSAGE_SENT_TO_DEVICE to indicate the device has confirmed its receipt of the original message.</summary>
[JsonProperty("message_status", Required = Required.Always)]
public string MessageStatus { get; set; }
/// <summary>This parameter specifies the ID of the original message that the app server sent to the client app.</summary>
[JsonProperty("original_message_id", Required = Required.Always)]
public string OriginalMessageId { get; set; }
/// <summary>This parameter specifies the registration token of the client app to which the original message was sent.</summary>
[JsonProperty("device_registration_id", Required = Required.Always)]
public string DeviceRegistrationId { get; set; }
}
/// <summary>Optional, string
/// <para>This parameter specifies the key-value pairs for the delivery receipt message. This is available when the message type is receipt.</para>
/// </summary>
[JsonProperty("data", Required = Required.Default)]
public DataPayload Data { get; set; }
#endregion
#region Control-specific
/// <summary>Optional, string
/// <para>This parameter specifies the type of control message sent from CCS.</para>
/// <para>Currently, only CONNECTION_DRAINING is supported. The XMPP connection server sends this control message before it closes a connection to perform load balancing. As the connection drains, no more messages are allowed to be sent to the connection, but existing messages in the pipeline continue to be processed.</para>
/// </summary>
[JsonProperty("control_type", Required = Required.Default)]
public string ControlType { get; set; }
#endregion
}
}<file_sep>using CaiqueServer.Music;
using MusicSearch;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace CaiqueServer
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Caique Server";
SongRequest.YouTube = "AIzaSyAVrXiAHfLEbQbNJP80zbTuW2jL0wuEigQ";
SongRequest.SoundCloud = "5c28ed4e5aef8098723bcd665d09041d";
var ProcessStartInfo = new ProcessStartInfo
{
FileName = "Includes/icecast.exe",
Arguments = "-c Includes/icecast.xml",
UseShellExecute = false,
RedirectStandardOutput = false
};
var IcecastProcess = Process.Start(ProcessStartInfo);
IcecastProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
Console.WriteLine("Icecast server started");
if (!Cloud.Messaging.Start().Result)
{
Console.WriteLine("Auth Error!");
}
ConsoleEvents.SetHandler(delegate
{
Console.WriteLine("Shutting down..");
var StopFCM = Cloud.Messaging.Stop();
Cloud.Database.Stop();
Streamer.Shutdown();
IcecastProcess.Dispose();
StopFCM.Wait();
});
Console.WriteLine("Boot");
while (true)
{
Console.Title = "Caique " + Cloud.Messaging.Acks + " " + Cloud.Messaging.WaitAck.Count + " " + Cloud.Messaging.Saves;
Task.Delay(100).Wait();
}
}
}
}
<file_sep>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class SendMessage
{
/// <summary>Optional, string
/// <para>This parameter specifies the recipient of a message.</para>
/// <para>The value must be a registration token, notification key, or topic. Do not set this field when sending to multiple topics. See condition.</para>
/// </summary>
[JsonProperty("to", Required = Required.Default)]
public string To { get; set; }
/// <summary>Optional, string
/// <para>This parameter specifies a logical expression of conditions that determines the message target.</para>
/// <para>Supported condition: Topic, formatted as "'yourTopic' in topics". This value is case-insensitive.</para>
/// <para>Supported operators: &&, ||. Maximum two operators per topic message supported.</para>
/// </summary>
[JsonProperty("condition", Required = Required.Default)]
public string Condition { get; set; }
#region Options
/// <summary>Required, string
/// <para>This parameter uniquely identifies a message in an XMPP connection.</para>
/// </summary>
[JsonProperty("message_id", Required = Required.Always)]
public string MessageId { get; set; }
/// <summary>Optional, string
/// <para>This parameter identifies a group of messages (e.g., with collapse_key: "Updates Available") that can be collapsed so that only the last message gets sent when delivery is resumed. This is intended to avoid sending too many of the same messages when the device comes back online or becomes active (see DelayIdle).</para>
/// <para>There is no guarantee of the order in which messages get sent.</para>
/// <para>Note: A maximum of 4 different collapse keys is allowed at any given time. This means an FCM connection server can simultaneously store 4 different send-to-sync messages per client app. If you exceed this number, there is no guarantee which 4 collapse keys the FCM connection server will keep. </para>
/// </summary>
[JsonProperty("collapse_key", Required = Required.Default)]
public string CollapseKey { get; set; }
/// <summary>Optional, string
/// <para>Sets the priority of the message. Valid values are "normal" and "high." On iOS, these correspond to APNs priorities 5 and 10.</para>
/// <para>By default, messages are sent with normal priority. Normal priority optimizes the client app's battery consumption and should be used unless immediate delivery is required. For messages with normal priority, the app may receive the message with unspecified delay.</para>
/// <para>When a message is sent with high priority, it is sent immediately, and the app can wake a sleeping device and open a network connection to your server.</para>
/// <para>For more information, see Setting the priority of a message.</para>
/// </summary>
[JsonProperty("priority", Required = Required.Default)]
public string Priority { get; set; }
/// <summary>Optional, JSON boolean
/// <para>On iOS, use this field to represent content-available in the APNs payload. When a notification or message is sent and this is set to true, an inactive client app is awakened. On Android, data messages wake the app by default. On Chrome, this parameter is currently not supported.</para>
/// </summary>
[JsonProperty("content_available", Required = Required.Default)]
public bool ContentAvailable { get; set; }
/// <summary>Optional, JSON boolean
/// <para>When this parameter is set to true, it indicates that the message should not be sent until the device becomes active.</para>
/// <para>The default value is false.</para>
/// </summary>
[JsonProperty("delay_while_idle", Required = Required.Default)]
public bool DelayIdle { get; set; }
/// <summary>Optional, JSON number
/// <para>This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks. For more information, see Setting the lifespan of a message. </para>
/// </summary>
[JsonProperty("time_to_live", Required = Required.Default)]
public string TTL { get; set; }
/// <summary>Optional, JSON boolean
/// <para>This parameter lets the app server request confirmation of message delivery.</para>
/// <para>When this parameter is set to true, CCS sends a delivery receipt when the device confirms that it received the message.</para>
/// <para>Note: this parameter is not supported for messages sent to iOS devices. The default value is false.</para>
/// </summary>
[JsonProperty("delivery_receipt_requested", Required = Required.Default)]
public bool ReceiptRequested { get; set; }
/// <summary>Optional, JSON boolean
/// <para>This parameter, when set to true, allows developers to test a request without actually sending a message.</para>
/// <para>The default value is false.</para>
/// </summary>
[JsonProperty("dry_run", Required = Required.Default)]
public bool DryRun { get; set; }
#endregion
#region Payload
/// <summary>Optional, JSON object
/// <para>This parameter specifies the key-value pairs of the message's payload.</para>
/// <para>For example, with data:{"score":"3x1"}:</para>
/// <para>On iOS, if the message is sent via APNs, it represents the custom data fields. If it is sent via the FCM connection server, it is represented as a key value dictionary in AppDelegate application:didReceiveRemoteNotification:.</para>
/// <para>On Android, this results in an intent extra named score with the string value 3x1.</para>
/// <para>The key should not be a reserved word ("from" or any word starting with "google" or "gcm"). Do not use any of the words defined in this table (such as collapse_key).</para>
/// <para>Values in string types are recommended. You have to convert values in objects or other non-string data types (e.g., integers or booleans) to string.</para>
/// </summary>
[JsonProperty("data", Required = Required.Default)]
//public JObject Data { get; set; }
public object Data { get; set; }
[JsonObject(MemberSerialization.OptIn)]
public class NotificationPayload
{
/// <summary>Optional, string
/// <para>Indicates notification title.</para>
/// </summary>
[JsonProperty("title", Required = Required.Default)]
public string Title { get; set; }
/// <summary>Optional, string
/// <para>Indicates notification body text. </para>
/// </summary>
[JsonProperty("text", Required = Required.Default)]
public string Text { get; set; }
/// <summary>Optional, string
/// <para>Indicates notification icon. Sets value to myicon for drawable resource myicon.</para>
/// </summary>
[JsonProperty("icon", Required = Required.Default)]
public string Icon { get; set; }
/// <summary>Optional, string
/// <para>Indicates a sound to play when the device receives a notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.</para>
/// </summary>
[JsonProperty("sound", Required = Required.Default)]
public string Sound { get; set; }
/// <summary>Optional, string
/// <para>Indicates whether each notification results in a new entry in the notification drawer on Android. </para>
/// <para>If not set, each request creates a new notification.</para>
/// <para>If set, and a notification with the same tag is already being shown, the new notification replaces the existing one in the notification drawer.</para>
/// </summary>
[JsonProperty("tag", Required = Required.Default)]
public string Tag { get; set; }
/// <summary>Optional, string
/// <para>Indicates color of the icon, expressed in #rrggbb format</para>
/// </summary>
[JsonProperty("color", Required = Required.Default)]
public string Color { get; set; }
/// <summary>Optional, string
/// <para>Indicates the action associated with a user click on the notification. When this is set, an activity with a matching intent filter is launched when user clicks the notification.</para>
/// </summary>
[JsonProperty("click_action", Required = Required.Default)]
public string ClickAction { get; set; }
/// <summary>Optional, string
/// <para>Indicates the key to the body string for localization. Use the key in the app's string resources when populating this value.</para>
/// </summary>
[JsonProperty("body_loc_key", Required = Required.Default)]
public string BodyLocKey { get; set; }
/// <summary>Optional, JSON array as string
/// <para>Indicates the string value to replace format specifiers in the body string for localization. For more information, see Formatting and Styling.</para>
/// </summary>
[JsonProperty("body_loc_args", Required = Required.Default)]
public JArray BodyLocArgs { get; set; }
/// <summary>Optional, string
/// <para>Indicates the key to the title string for localization. Use the key in the app's string resources when populating this value.</para>
/// </summary>
[JsonProperty("title_loc_key", Required = Required.Default)]
public string TitleLocKey { get; set; }
/// <summary>Optional, JSON array as string
/// <para>Indicates the string value to replace format specifiers in the title string for localization. For more information, see Formatting strings.</para>
/// </summary>
[JsonProperty("title_loc_args", Required = Required.Default)]
public JArray TitleLocArgs { get; set; }
}
/// <summary>Optional, JSON object
/// <para>This parameter specifies the key-value pairs of the notification payload. See Notification payload support for detail. For more information about notification message and data message options, see message types.</para>
/// </summary>
[JsonProperty("notification", Required = Required.Default)]
public NotificationPayload Notification { get; set; }
#endregion
}
}
<file_sep>using CaiqueServer.Cloud.Json;
using MusicSearch;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace CaiqueServer.Cloud
{
class MessagingHandlers
{
private static ConcurrentDictionary<string, string> TokenCache = new ConcurrentDictionary<string, string>();
private static async Task SendChatList(string Id, string Token)
{
var Chats = (await Database.Client.GetAsync($"user/{Id}/member")).ResultAs<Dictionary<string, bool>>();
if (Chats != null)
{
Messaging.Send(new SendMessage
{
To = Token,
Data = new { type = "list", chats = Chats.Keys }
});
}
}
public static async Task Upstream(UpstreamMessage In)
{
var Event = In.Data.ToObject<Event>();
if (!TokenCache.TryGetValue(In.From, out Event.Sender))
{
Event.Sender = Database.Client.Get($"token/{In.From}/key").ResultAs<string>();
if (Event.Sender != null)
{
TokenCache.TryAdd(In.From, Event.Sender);
}
}
if (Event.Sender == null)
{
Console.WriteLine("Not registered - " + In.Data.ToString());
if (Event.Type == "reg" && Event.Text != null)
{
var Userdata = await Authentication.UserdataFromToken(Event.Text);
if (Userdata.Email == null)
{
Console.WriteLine("Can't register device");
}
else
{
Console.WriteLine("Register with " + Userdata.Email);
await Database.Client.SetAsync($"token/{In.From}", new { key = Userdata.Sub });
//await SendChatList(Userdata.Sub, In.From);
if ((await Database.Client.GetAsync($"user/{Userdata.Sub}/data")).ResultAs<DatabaseUser>() == null)
{
await Database.Client.SetAsync($"user/{Userdata.Sub}/data", new DatabaseUser
{
Name = Userdata.Name
});
await new Firebase.Storage.FirebaseStorage("firebase-caique.appspot.com").Child("users").Child(Userdata.Sub).PutAsync(File.Open("Includes/emptyUser.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
await Database.Client.SetAsync($"user/{Userdata.Sub}/member/-KSqbu0zMurmthzBE7GF", true);
Messaging.Send(new SendMessage
{
To = In.From,
Data = new
{
type = "regcomplete"
}
});
}
}
}
else
{
Messaging.Send(new SendMessage
{
To = In.From,
Data = new Event
{
Type = "reg"
}
});
}
}
else
{
switch (Event.Type)
{
case "text":
Chat.Home.ById(Event.Chat).Distribute(Event, "high");
break;
case "typing":
Chat.Home.ById(Event.Chat).Distribute(Event);
break;
case "madd":
if (await Music.Streamer.Get(Event.Chat).Enqueue(Event.Text, Event.Sender))
{
Messaging.Send(new SendMessage
{
To = In.From,
Data = new Event
{
Chat = Event.Chat,
Type = "play",
Text = Music.Streamer.Serialize(Event.Chat)
}
});
}
break;
case "msearch":
Messaging.Send(new SendMessage
{
To = In.From,
Data = new
{
chat = Event.Chat,
type = "mres",
r = await SongRequest.Search(Event.Text)
}
});
break;
case "mskip":
Music.Streamer.Get(Event.Chat).Skip();
break;
case "mremove":
ushort ToRemove;
if (ushort.TryParse(Event.Text, out ToRemove) && ToRemove-- != 0)
{
if (Music.Streamer.Get(Event.Chat).Queue.TryRemove(ToRemove, out Song Song))
{
Event.Text = Song.Title;
Event.Sender = null;
Messaging.Send(new SendMessage
{
To = In.From,
Data = Event
});
}
}
break;
case "mplaying":
Messaging.Send(new SendMessage
{
To = In.From,
Data = new Event
{
Chat = Event.Chat,
Type = "play",
Text = Music.Streamer.Serialize(Event.Chat)
}
});
break;
case "newchat":
var ChatData = JsonConvert.DeserializeObject<DatabaseChat>(Event.Text);
var Id = await Database.Client.PushAsync("chat", new
{
data = ChatData
});
var ChatId = Id.Result.Name.ToString();
await new Firebase.Storage.FirebaseStorage("firebase-caique.appspot.com").Child("chats").Child(ChatId).PutAsync(File.Open("Includes/emptyChat.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
await Database.Client.SetAsync($"user/{Event.Sender}/member/{ChatId}", true);
foreach (var Tag in ChatData.Tags)
{
await Database.Client.SetAsync($"tags/{Tag}/{ChatId}", true);
}
break;
case "joinchat":
if ((await Database.Client.GetAsync($"chat/{Event.Chat}/data/title")).ResultAs<string>() != null)
{
await Database.Client.SetAsync($"user/{Event.Sender}/member/{Event.Chat}", true);
}
break;
case "leavechat":
await Database.Client.DeleteAsync($"user/{Event.Sender}/member/{Event.Chat}");
break;
case "searchtag":
var Split = Event.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (Split.Length != 0)
{
Messaging.Send(new SendMessage
{
To = In.From,
Data = new { type = "tagres", r = await Chat.Home.ByTags(Split) }
});
}
break;
case "update":
(await Chat.Home.ById(Event.Chat).Update(JsonConvert.DeserializeObject<DatabaseChat>(Event.Text))).Distribute(Event);
break;
case "name":
await Database.Client.SetAsync($"user/{Event.Sender}/data", new DatabaseUser
{
Name = Event.Text
});
break;
}
var User = Database.Client.Get($"user/{Event.Sender}/data").ResultAs<DatabaseUser>();
Console.WriteLine($"{DateTime.Now.ToLongTimeString()} -- Upstream from {User.Name} {Event.Type} {Event.Text}");
}
}
public static void Server(ServerMessage Info)
{
if (Info.MessageType == "receipt")
{
Console.WriteLine("-- Receipt " + Info.MessageId);
}
else
{
Console.WriteLine("-- CCS " + Info.ControlType);
}
}
}
}
<file_sep>namespace MusicSearch
{
public enum SongType
{
File,
YouTube,
SoundCloud,
Telegram,
Uploaded
}
}
<file_sep>using Newtonsoft.Json;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class ReceivedMessageAck
{
/// <summary>Required, string
/// <para>This parameter specifies the recipient of a response message.</para>
/// <para>The value must be a registration token of the client app that sent the upstream message.</para>
/// </summary>
[JsonProperty("to", Required = Required.Always)]
public string To { get; set; }
/// <summary>Required, string
/// <para>This parameter specifies which message the response is intended for. The value must be the message_id value from the corresponding upstream message.</para>
/// <para>The value must be a registration token of the client app that sent the upstream message.</para>
/// </summary>
[JsonProperty("message_id", Required = Required.Always)]
public string MessageId { get; set; }
/// <summary>Required, string
/// <para>This parameter specifies an ack message from an app server to CCS. For upstream messages, it should always be set to ack.</para>
/// </summary>
[JsonProperty("message_type", Required = Required.Always)]
public string MessageType { get; set; }
}
}
<file_sep>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class UpstreamMessage
{
/// <summary>Required, string
/// <para>This parameter specifies who sent this response.</para>
/// <para>The value is the registration token of the client app.</para>
/// </summary>
[JsonProperty("from", Required = Required.Always)]
public string From { get; set; }
/// <summary>Required, string
/// <para>This parameter specifies the application package name of the client app that receives the message that this delivery receipt is reporting.</para>
/// </summary>
[JsonProperty("category", Required = Required.Always)]
public string Category { get; set; }
/// <summary>Required, string
/// <para>This parameter specifies the unique ID of the message.</para>
/// </summary>
[JsonProperty("message_id", Required = Required.Always)]
public string MessageId { get; set; }
/// <summary> Optional, string
/// <para>This parameter specifies the key-value pairs of the message's payload</para>
/// </summary>
[JsonProperty("data", Required = Required.Default)]
public JObject Data { get; set; }
}
}
<file_sep>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright (c) 2003-2012 by AG-Software *
* All Rights Reserved. *
* Contact information for AG-Software is available at http://www.ag-software.de *
* *
* Licence: *
* The agsXMPP SDK is released under a dual licence *
* agsXMPP can be used under either of two licences *
* *
* A commercial licence which is probably the most appropriate for commercial *
* corporate use and closed source projects. *
* *
* The GNU Public License (GPL) is probably most appropriate for inclusion in *
* other open source projects. *
* *
* See README.html for details. *
* *
* For general enquiries visit our website at: *
* http://www.ag-software.de *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
using System;
using System.Collections;
using System.Threading;
using agsXMPP.protocol.client;
//using agsXMPP.protocol.component;
using agsXMPP.Xml;
namespace agsXMPP
{
public class IqGrabber : PacketGrabber
{
/// <summary>
///
/// </summary>
/// <param name="conn"></param>
public IqGrabber(XmppClientConnection conn)
{
m_connection = conn;
conn.OnIq += OnIq;
}
public IqGrabber(XmppComponentConnection conn)
{
m_connection = conn;
conn.OnIq += OnIq;
}
#if !CF
private IQ synchronousResponse = null;
private int m_SynchronousTimeout = 5000;
/// <summary>
/// Timeout for synchronous requests, default value is 5000 (5 seconds)
/// </summary>
public int SynchronousTimeout
{
get { return m_SynchronousTimeout; }
set { m_SynchronousTimeout = value; }
}
#endif
/// <summary>
/// An IQ Element is received. Now check if its one we are looking for and
/// raise the event in this case.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnIq(object sender, IQEventArgs e)
{
// the tracker handles on iq responses, which are either result or error
if (e.IQ.Type != IqType.error && e.IQ.Type != IqType.result)
return;
string id = e.IQ.Id;
if(id == null)
return;
IqHandler td;
lock (m_grabbing)
{
td = (IqHandler) m_grabbing[id];
if (td == null)
{
return;
}
m_grabbing.Remove(id);
}
td(this, e);
}
/// <summary>
/// Send an IQ Request and store the object with callback in the Hashtable
/// </summary>
/// <param name="iq">The iq to send</param>
/// <param name="cb">the callback function which gets raised for the response</param>
public void SendIq(IQ iq, IqHandler cb)
{
// check if the callback is null, in case of wrong usage of this class
if (cb == null) {
throw new ArgumentNullException("cb");
}
if (iq == null) {
throw new ArgumentNullException("cb");
}
m_grabbing[iq.Id] = cb;
m_connection.Send(iq);
}
#if !CF
/// <summary>
/// Sends an Iq synchronous and return the response or null on timeout
/// </summary>
/// <param name="iq">The IQ to send</param>
/// <param name="timeout"></param>
/// <returns>The response IQ or null on timeout</returns>
public IQ SendIq(agsXMPP.protocol.client.IQ iq, int timeout)
{
synchronousResponse = null;
AutoResetEvent are = new AutoResetEvent(false);
SendIq(iq,
delegate (object sender, IQEventArgs e)
{
e.Handled = true;
are.Set();
}
);
if (!are.WaitOne(timeout, true))
{
// Timed out
lock (m_grabbing)
{
if (m_grabbing.ContainsKey(iq.Id))
m_grabbing.Remove(iq.Id);
}
return null;
}
return synchronousResponse;
}
/// <summary>
/// Sends an Iq synchronous and return the response or null on timeout.
/// Timeout time used is <see cref="SynchronousTimeout"/>
/// </summary>
/// <param name="iq">The IQ to send</param>
/// <returns>The response IQ or null on timeout</returns>
public IQ SendIq(IQ iq)
{
return SendIq(iq, m_SynchronousTimeout);
}
#endif
}
}<file_sep>using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MusicSearch
{
static class Extensions
{
internal static StringBuilder UcWords(this object In)
{
var Output = new StringBuilder();
var Pieces = In.ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var piece in Pieces)
{
var Chars = piece.ToCharArray();
Chars[0] = char.ToUpper(Chars[0]);
Output.Append(' ');
Output.Append(Chars);
}
return Output;
}
public static async Task<string> WebResponse(this string Url, WebHeaderCollection Headers = null)
{
try
{
for (int i = 0; i < 5; i++)
{
try
{
var Request = WebRequest.Create(Url);
if (Headers != null)
{
Request.Headers = Headers;
}
return await new StreamReader(
(await Request.GetResponseAsync())
.GetResponseStream()
)
.ReadToEndAsync();
}
catch (Exception Ex2)
{
if (i == 4)
{
throw Ex2;
}
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex);
}
return string.Empty;
}
}
}
<file_sep>using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MusicSearch
{
public class SongQueue
{
[JsonIgnore]
public int MaxQueued = 25;
public Song Playing
{
get
{
return mPlaying;
}
}
[JsonIgnore]
public bool IsPlaying
{
get
{
return !string.IsNullOrEmpty(mPlaying.Url) && !string.IsNullOrEmpty(mPlaying.FullName);
}
}
[JsonIgnore]
public bool CanAdd
{
get
{
return Queue.Count <= MaxQueued;
}
}
[JsonIgnore]
public int Count
{
get
{
return Queue.Count;
}
}
public string[] Titles
{
get
{
return Queue.Select(x => x.Title).ToArray();
}
}
private Song mPlaying;
private ConcurrentQueue<Song> Queue = new ConcurrentQueue<Song>();
public int Enqueue(Song Song)
{
if (CanAdd)
{
Queue.Enqueue(Song);
return Queue.Count;
}
return 0;
}
public bool Next()
{
Invalidate();
if (!Queue.TryDequeue(out mPlaying))
{
return false;
}
return true;
}
public void Invalidate()
{
mPlaying = default(Song);
}
public int Repeat(int Count)
{
if (IsPlaying)
{
var Songs = ToArray();
if (Count + Songs.Length > MaxQueued)
{
Count = MaxQueued - Songs.Length;
}
var NewQueue = new ConcurrentQueue<Song>();
for (int i = 0; i < Count; i++)
{
NewQueue.Enqueue(Playing);
}
foreach (var Song in Queue)
{
NewQueue.Enqueue(Song);
}
Queue = NewQueue;
return Count;
}
return 0;
}
public bool TryPush(int Place, int ToPlace, out Song Pushed)
{
Pushed = default(Song);
var NewQueue = new ConcurrentQueue<Song>();
var Songs = ToList();
if (Place >= 0 && ToPlace >= 0 && Place != ToPlace && Songs.Count > Place && Songs.Count > ToPlace)
{
Pushed = Songs[Place];
Songs.Remove(Pushed);
Songs.Insert(ToPlace, Pushed);
foreach (var Song in Songs)
{
NewQueue.Enqueue(Song);
}
Queue = NewQueue;
return true;
}
return false;
}
public bool TryRemove(ushort Index, out Song Song)
{
Song = default(Song);
var List = ToList();
if (List.Count <= Index)
{
return false;
}
Song = List[Index];
List.RemoveAt(Index);
Queue = new ConcurrentQueue<Song>(List);
return true;
}
public Song[] ToArray()
=> Queue.ToArray();
public List<Song> ToList()
=> Queue.ToList();
public Task<string> StreamUrl(bool AllFormats = true)
=> SongRequest.StreamUrl(Playing, AllFormats);
}
}
<file_sep>using CaiqueServer.Cloud;
using CaiqueServer.Cloud.Json;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CaiqueServer.Chat
{
class Room
{
private string Topic;
private int Roulette = 0;
private int MaxRoulette = 32;
internal Room(string Id)
{
Topic = Id;
}
internal async Task<Room> Update(DatabaseChat New)
{
var Current = (await Database.Client.GetAsync($"chat/{Topic}/data")).ResultAs<DatabaseChat>();
if (Current.Tags == null)
{
Current.Tags = new string[0];
}
foreach (var Tag in New.Tags)
{
if (!Current.Tags.Contains(Tag))
{
await Database.Client.SetAsync($"tags/{Tag}/{Topic}", true);
}
}
foreach (var Tag in Current.Tags)
{
if (!New.Tags.Contains(Tag))
{
await Database.Client.DeleteAsync($"tags/{Tag}/{Topic}");
}
}
await Database.Client.SetAsync($"chat/{Topic}/data", New);
return this;
}
internal void Distribute(Event Event, string Priority = "normal")
{
var SubTopic = Interlocked.Increment(ref Roulette) % MaxRoulette;
Messaging.Send(new SendMessage
{
To = $"/topics/%{Topic}%{SubTopic}",
Data = Event,
Priority = Priority
});
}
}
}
<file_sep>using Newtonsoft.Json;
using MusicSearch;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace CaiqueServer.Music
{
class Streamer
{
private const string IcecastPass = "<PASSWORD>";
private static ConcurrentDictionary<string, Streamer> Streamers = new ConcurrentDictionary<string, Streamer>();
private static CancellationTokenSource Stop = new CancellationTokenSource();
private static ConcurrentBag<ManualResetEvent> ShutdownCompleted = new ConcurrentBag<ManualResetEvent>();
internal static Streamer Get(string Chat)
{
return Streamers.GetOrAdd(Chat, delegate (string Id)
{
return new Streamer(Id);
});
}
internal static bool TryGetSong(string Chat, out Song Out)
{
Streamer Streamer;
if (Streamers.TryGetValue(Chat, out Streamer) && Streamer.Queue.IsPlaying)
{
Out = Streamer.Queue.Playing;
return true;
}
Out = new Song();
return false;
}
internal static string Serialize(string Chat)
{
if (Streamers.TryGetValue(Chat, out Streamer Streamer))
{
return JsonConvert.SerializeObject(Streamer.Queue);
}
return string.Empty;
}
internal static void Shutdown()
{
Stop.Cancel();
Parallel.ForEach(Streamers, (KVP, s) =>
{
KVP.Value.Skip();
});
var Shutdown = ShutdownCompleted.ToArray();
if (Shutdown.Length != 0)
{
WaitHandle.WaitAll(Shutdown);
}
}
internal Process Ffmpeg { get; private set; }
internal SongQueue Queue = new SongQueue();
private TaskCompletionSource<bool> ProcessWaiter;
private SemaphoreSlim WaitAdd = new SemaphoreSlim(0);
private string Id;
internal Streamer(string Chat)
{
Queue.MaxQueued = 16;
Id = Chat;
var Reset = new ManualResetEvent(false);
ShutdownCompleted.Add(Reset);
BackgroundStream().ContinueWith(delegate
{
Reset.Set();
});
}
private async Task BackgroundStream()
{
Console.WriteLine("Started background stream for " + Id);
DataReceivedEventHandler Handler = null;
var ProcessStartInfo = new ProcessStartInfo
{
FileName = "Includes/ffmpeg",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardError = true
};
while (!Stop.IsCancellationRequested)
{
try
{
await WaitAdd.WaitAsync(Stop.Token);
Queue.Next();
using (Ffmpeg = new Process())
{
ProcessStartInfo.Arguments = $"-re -i \"{await Queue.StreamUrl(false)}\" -vn -content_type audio/aac -f adts ";
if (Queue.Playing.Type == SongType.YouTube || Queue.Playing.Type == SongType.Uploaded)
{
ProcessStartInfo.Arguments += "-c:a copy ";
}
else
{
ProcessStartInfo.Arguments += $"-c:a aac -b:a 128k -ac 2 -ar 48k ";
}
ProcessStartInfo.Arguments += $"icecast://source:{IcecastPass}@localhost:80/{Id}";
ProcessWaiter = new TaskCompletionSource<bool>();
Ffmpeg.StartInfo = ProcessStartInfo;
Ffmpeg.EnableRaisingEvents = true;
Ffmpeg.Exited += (s, e) =>
{
ProcessWaiter.TrySetResult(true);
};
Handler = async (s, e) =>
{
Console.WriteLine(e.Data ?? "");
if (e.Data?.StartsWith("size=") ?? false)
{
Ffmpeg.ErrorDataReceived -= Handler;
await Task.Delay(250).ContinueWith(delegate
{
Chat.Home.ById(Id).Distribute(new Cloud.Json.Event
{
Chat = Id,
Type = "start",
Text = Serialize(Id)
});
});
}
};
Ffmpeg.ErrorDataReceived += Handler;
Ffmpeg.Start();
Ffmpeg.BeginErrorReadLine();
Ffmpeg.PriorityClass = ProcessPriorityClass.BelowNormal;
await ProcessWaiter.Task;
Ffmpeg.CancelErrorRead();
await Ffmpeg.StandardInput.WriteAsync("q");
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
finally
{
Queue.Invalidate();
Console.WriteLine("Stopped Playing");
}
if (Queue.Count == 0)
{
Chat.Home.ById(Id).Distribute(new Cloud.Json.Event
{
Chat = Id,
Type = "start"
});
}
}
}
internal async Task<bool> Enqueue(string Song, string Adder)
{
var Results = await SongRequest.Search(Song, false);
if (Results.Count == 0)
{
return false;
}
return Enqueue(Results[0], Adder);
}
internal bool Enqueue(Song Song, string Adder)
{
Song.Adder = Adder;
if (Queue.Enqueue(Song) != 0)
{
WaitAdd.Release();
return true;
}
return false;
}
internal void Skip()
{
ProcessWaiter?.TrySetResult(false);
}
}
}
<file_sep>using CaiqueServer.Cloud.Json;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CaiqueServer.Chat
{
class Home
{
private struct RoomScore
{
internal Room Room;
internal int Score;
}
private static ConcurrentDictionary<string, Room> Rooms = new ConcurrentDictionary<string, Room>();
internal static Room ById(string Chat)
{
return Rooms.GetOrAdd(Chat, delegate (string Id)
{
return new Room(Id);
});
}
internal static async Task<string[]> ByTags(string[] Tags)
{
List<string> Chats = null;
var Relevancy = new Dictionary<string, int>();
foreach (var Tag in Tags)
{
var TagResults = (await Cloud.Database.Client.GetAsync($"tags/{Tag}")).ResultAs<Dictionary<string, bool>>();
if (TagResults == null)
{
return new string[0];
}
if (Chats == null)
{
Chats = TagResults.Keys.ToList();
}
else
{
Chats = TagResults.Keys.Where(x => Chats.Contains(x)).ToList();
}
}
foreach (var Chat in Chats)
{
var TagsChatRes = await Cloud.Database.Client.GetAsync($"chat/{Chat}/data/tags");
var TagsChat = TagsChatRes.ResultAs<object[]>();
Relevancy.Add(Chat, TagsChat.Length);
}
return Chats.OrderBy(x => Relevancy[x]).ToArray();
}
}
}
<file_sep>using Newtonsoft.Json;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class DatabaseChat
{
[JsonProperty("title", Required = Required.Always)]
public string Title;
[JsonProperty("tags", Required = Required.Default)]
public string[] Tags;
}
}
<file_sep>using Newtonsoft.Json;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class Event
{
[JsonProperty("type", Required = Required.Always)]
public string Type;
[JsonProperty("chat", Required = Required.Default)]
public string Chat;
[JsonProperty("sender", Required = Required.Default)]
public string Sender;
[JsonProperty("date", Required = Required.Default)]
public int Date;
[JsonProperty("text", Required = Required.AllowNull)]
public string Text;
[JsonProperty("attach", Required = Required.Default)]
public string Attachment;
}
}
<file_sep>using agsXMPP;
using agsXMPP.Net;
using agsXMPP.protocol.client;
using agsXMPP.Xml.Dom;
using CaiqueServer.Cloud.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace CaiqueServer.Cloud
{
class Messaging
{
static XmppClientConnection Xmpp;
static Messaging()
{
Xmpp = new XmppClientConnection
{
UseSSL = true,
UseStartTLS = false,
Server = "gcm.googleapis.com",
Port = 5235,
Username = "420728598029",
Password = "<PASSWORD>",
AutoResolveConnectServer = true,
SocketConnectionType = SocketConnectionType.Direct,
AutoAgents = false,
KeepAlive = true,
AutoRoster = false,
AutoPresence = false,
UseCompression = false,
Show = ShowType.chat
};
Xmpp.OnMessage += OnMessage;
Xmpp.OnError += OnError;
}
internal static async Task<bool> Start()
{
var T = new TaskCompletionSource<bool>();
Xmpp.OnLogin += (s) => T.TrySetResult(true);
Xmpp.OnAuthError += (s, e) => T.TrySetResult(false);
Xmpp.Open();
return await T.Task;
}
internal static async Task Stop()
{
var T = new TaskCompletionSource<bool>();
Xmpp.OnClose += (s) => T.TrySetResult(true);
Xmpp.Close();
await T.Task;
}
internal static ConcurrentDictionary<long, SendMessage> WaitAck = new ConcurrentDictionary<long, SendMessage>();
internal static int Acks = 0;
internal static int Saves = 0;
private static async void OnMessage(object s, Message msg)
{
try
{
var JData = JObject.Parse(msg.FirstChild.Value);
if (JData["message_type"] == null)
{
var Message = JData.ToObject<UpstreamMessage>();
Send(new ReceivedMessageAck
{
To = Message.From,
MessageId = Message.MessageId,
MessageType = "ack"
});
await MessagingHandlers.Upstream(Message);
}
else if (JData["message_type"].ToString().EndsWith("ack"))
{
var SentAck = JData.ToObject<SentMessageAck>();
if (int.TryParse(SentAck.MessageId, out int MessageId) && WaitAck.ContainsKey(MessageId))
{
SendMessage Out;
if (SentAck.MessageType == "ack")
{
Interlocked.Increment(ref Acks);
if (WaitAck.TryRemove(MessageId, out Out))
{
if (Out.Priority == "high")
{
await Database.Client.PushAsync($"chat/{Out.To.Split('%')[1]}/message", Out.Data);
Interlocked.Increment(ref Saves);
}
}
}
else
{
Console.WriteLine("Message " + MessageId + " status " + SentAck.Error + " " + SentAck.ErrorDesc);
if (WaitAck.TryGetValue(MessageId, out Out))
{
Console.WriteLine(Out.ToString());
if (SentAck.Error != "INVALID_REQUEST" && SentAck.Error != "DEVICE_UNREGISTERED")
{
await Task.Delay(1500);
Resend(Out);
}
}
else
{
Console.WriteLine("Message " + MessageId + " couldn't be resent");
}
}
}
}
else
{
var Message = JData.ToObject<ServerMessage>();
Send(new ReceivedMessageAck
{
To = Message.From,
MessageId = Message.MessageId,
MessageType = "ack"
});
MessagingHandlers.Server(Message);
}
}
catch (Exception Ex)
{
Console.WriteLine("Message Handler Exception\r\n" + msg + "\r\n" + Ex);
}
}
private static void OnError(object s, Exception ex)
{
Console.WriteLine(ex.ToString());
}
private static long Unique = 0;
internal static void Send(SendMessage ToSend)
{
var UniqueId = Interlocked.Increment(ref Unique);
ToSend.MessageId = UniqueId.ToString();
WaitAck.TryAdd(UniqueId, ToSend);
Send((object)ToSend);
//Console.WriteLine("Sending " + JsonConvert.SerializeObject(ToSend));
}
internal static void Resend(SendMessage ToSend)
{
//WaitAck.TryAdd(long.Parse(ToSend.MessageId), ToSend);
Send((object)ToSend);
}
private static void Send(object JsonObject)
{
var Gcm = new Element
{
TagName = "gcm",
Value = JsonObject.ToJson()
};
Gcm.Attributes["xmlns"] = "google:mobile:data";
var Msg = new Element("message");
Msg.AddChild(Gcm);
Msg.Attributes["id"] = string.Empty;
Xmpp.Send(Msg);
}
}
}
<file_sep>using FireSharp;
using FireSharp.Config;
using FireSharp.Exceptions;
using System;
namespace CaiqueServer.Cloud
{
class Database
{
public static FirebaseClient Client;
static Database()
{
Client = new FirebaseClient(new FirebaseConfig
{
AuthSecret = "<KEY>",
BasePath = "https://fir-caique.firebaseio.com",
RequestTimeout = new TimeSpan(0, 5, 0)
});
Client.OnException += OnException;
}
private static void OnException(FirebaseException ex)
{
Console.WriteLine(ex.ToString());
}
public static void Stop()
{
Client.Dispose();
}
}
}
<file_sep>using Newtonsoft.Json;
namespace MusicSearch
{
[JsonObject(MemberSerialization.OptIn)]
public struct Song
{
public static int MaxLength = 100;
[JsonProperty("name", Required = Required.AllowNull)]
public string FullName;
[JsonProperty("desc", Required = Required.AllowNull)]
public string Desc
{
get
{
return mDesc;
}
set
{
mDesc = value;
if (mDesc.Length > MaxLength)
{
mDesc = mDesc.Substring(0, MaxLength - 3) + "...";
}
}
}
private string mDesc;
[JsonProperty("url", Required = Required.AllowNull)]
public string Url;
[JsonProperty("adder", Required = Required.AllowNull)]
public string Adder;
[JsonProperty("type", Required = Required.AllowNull)]
public SongType Type;
[JsonProperty("tn", Required = Required.AllowNull)]
public string ThumbNail;
public string GetThumbnail(string Replacement)
=> ThumbNail != null && ThumbNail != string.Empty ? ThumbNail : Replacement;
[JsonIgnore]
public string Title
{
get
{
if (FullName.Length < 192)
{
return FullName;
}
return FullName.Substring(0, 192);
}
}
}
}
<file_sep>using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
//using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace CaiqueServer
{
static class Extentions
{
public static string SafePath(this string In)
{
return In.Replace("\\", "\\\\").Replace("\"", "\\\"");
}
public static string Md5(this string In)
{
var InBytes = Encoding.Unicode.GetBytes(In);
var Result = new StringBuilder();
byte[] Hash;
using (var Md5 = MD5.Create())
{
Hash = Md5.ComputeHash(InBytes);
}
for (int i = 0; i < Hash.Length; i++)
{
Result.Append(Hash[i].ToString("x2"));
}
return Result.ToString();
}
public static string ToJson(this object In)
{
return JsonConvert.SerializeObject(In, Formatting.None, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
});
}
/*public static Task ConnectAsync(this Socket Connection, IPEndPoint EndPoint)
{
return Task.Factory.FromAsync(Connection.BeginConnect(EndPoint, null, null), Connection.EndConnect);
}
public static Task SendAsync(this Socket Connection, byte[] Data)
{
return Task.Factory.FromAsync(Connection.BeginSend(Data, 0, Data.Length, SocketFlags.None, null, null), Connection.EndSend);
}
public static Task DisconnectAsync(this Socket Connection)
{
return Task.Factory.FromAsync(Connection.BeginDisconnect(false, null, null), Connection.EndDisconnect);
}*/
public static bool IsValidUrl(this string Text)
{
Uri WebRes;
return Uri.TryCreate(Text, UriKind.Absolute, out WebRes);
}
public static async Task<string> WebResponse(this string Url, WebHeaderCollection Headers = null)
{
try
{
for (int i = 0; i < 5; i++)
{
try
{
WebRequest Request = WebRequest.Create(Url);
if (Headers != null)
{
Request.Headers = Headers;
}
return await new StreamReader(
(await Request.GetResponseAsync())
.GetResponseStream()
)
.ReadToEndAsync();
}
catch (Exception Ex2)
{
if (i == 4)
{
throw Ex2;
}
}
await Task.Delay(i * 500);
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex);
}
return string.Empty;
}
public static StringBuilder UcWords(this object theString)
{
var output = new StringBuilder();
var pieces = theString.ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var piece in pieces)
{
var theChars = piece.ToCharArray();
theChars[0] = char.ToUpper(theChars[0]);
output.Append(' ');
output.Append(new string(theChars));
}
return output;
}
}
}
<file_sep>using Newtonsoft.Json;
using System.Threading.Tasks;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class Authentication
{
internal static async Task<Authentication> UserdataFromToken(string IdToken)
{
var Res = await $"https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={IdToken}".WebResponse();
return JsonConvert.DeserializeObject<Authentication>(Res);
}
[JsonProperty("iss", Required = Required.Default)]
public string ISS;
[JsonProperty("aud", Required = Required.Default)]
public string Aud;
// Google Account ID
[JsonProperty("sub", Required = Required.Always)]
public string Sub;
[JsonProperty("email_verified", Required = Required.Default)]
public bool EmailVerified;
[JsonProperty("azp", Required = Required.Default)]
public string Azp;
[JsonProperty("email", Required = Required.Default)]
public string Email;
[JsonProperty("iat", Required = Required.Default)]
public int Iat;
[JsonProperty("exp", Required = Required.Default)]
public int Expiration;
// Full Name
[JsonProperty("name", Required = Required.Always)]
public string Name;
[JsonProperty("picture", Required = Required.Always)]
public string Picture;
[JsonProperty("given_name", Required = Required.Default)]
public string FirstName;
[JsonProperty("family_name", Required = Required.Default)]
public string FamilyName;
[JsonProperty("locale", Required = Required.Default)]
public string Locale;
[JsonProperty("alg", Required = Required.Default)]
public string Alg;
[JsonProperty("kid", Required = Required.Default)]
public string KId;
}
}
<file_sep>using Newtonsoft.Json;
namespace CaiqueServer.Cloud.Json
{
[JsonObject(MemberSerialization.OptIn)]
class DatabaseUser
{
[JsonProperty("name", Required = Required.Always)]
public string Name;
}
}
<file_sep>using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using VideoLibrary;
namespace MusicSearch
{
public class SongRequest
{
private static YouTubeService YTHolder = null;
internal static YouTubeService YT
{
get
{
if (YTHolder == null)
{
YTHolder = new YouTubeService(new BaseClientService.Initializer
{
ApiKey = YouTube
});
}
return YTHolder;
}
}
public static string YouTube;
public static string SoundCloud = null;
private static readonly Regex YoutubeRegex = new Regex(@"youtu(?:\.be|be\.com)/(?:(.*)v(/|=)|(.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);
public static Func<string, Task<string>> GetTelegramUrl;
public static async Task<string> StreamUrl(Song Song, bool AllFormats = true)
{
if (Song.Type == SongType.YouTube)
{
var Videos = VideoLibrary.YouTube.Default.GetAllVideos(Song.Url);
YouTubeVideo MaxVid = null;
foreach (var Vid in Videos)
{
if (MaxVid == null || (Vid.AudioBitrate >= MaxVid.AudioBitrate && (AllFormats || Vid.AudioFormat == AudioFormat.Aac)))
{
MaxVid = Vid;
}
}
if (MaxVid == null)
{
return string.Empty;
}
return await MaxVid.GetUriAsync();
}
else if (Song.Type == SongType.SoundCloud)
{
var SC = await($"http://api.soundcloud.com/resolve?url={Song.Url}&client_id={SoundCloud}").WebResponse();
if (SC != string.Empty && SC.StartsWith("{\"kind\":\"track\""))
{
return $"{JObject.Parse(SC)["stream_url"]}?client_id={SoundCloud}";
}
}
else if (Song.Type == SongType.Telegram)
{
return await GetTelegramUrl(Song.Url);
}
return Song.Url;
}
public static async Task<List<Song>> Search(object ToSearch, bool ReturnAtOnce = false)
{
var Query = ((string)ToSearch).Trim();
var Results = new List<Song>();
var Match = YoutubeRegex.Match(Query);
if (Match.Success)
{
var ResultData = await YouTubeParse(Match.Groups[4].Value);
if (ResultData != null)
{
Results.Add((Song)ResultData);
}
}
else if (SoundCloud != null && Regex.IsMatch(Query, "(.*)(soundcloud.com|snd.sc)(.*)"))
{
var SC = await ($"http://api.soundcloud.com/resolve?url={Query}&client_id={SoundCloud}").WebResponse();
if (SC != string.Empty && SC.StartsWith("{\"kind\":\"track\""))
{
Results.Add(SoundCloudParse(JToken.Parse(SC)));
}
}
else if (Uri.TryCreate(Query, UriKind.Absolute, out Uri Url))
{
Results.Add(new Song
{
FullName = Path.GetFileNameWithoutExtension(Url.LocalPath),
Desc = $"Remote {Path.GetExtension(Url.LocalPath)} file",
Url = Query,
Type = SongType.File
});
}
if (Query.Length >= 3)
{
var SplitQuery = Query.Split(' ');
var Range = SongRequestLocal.GetFiles()
.Where(
x => x.Name.Length >= Query.Length && SplitQuery.All(y => x.Name.IndexOf(y, StringComparison.OrdinalIgnoreCase) >= 0)
)
.Select(x => new Song
{
FullName = x.Name,
Desc = $"{x.Extension} file at {x.Dir}",
Url = x.Path,
Type = SongType.File
});
if (Range.Count() > 3)
{
Range = Range.Take(3);
}
Results.AddRange(Range);
}
if (!ReturnAtOnce || Results.Count == 0)
{
var SC = $"http://api.soundcloud.com/tracks/?client_id={SoundCloud}&q={System.Text.Encodings.Web.UrlEncoder.Default.Encode(Query)}".WebResponse();
var ListRequest = YT.Search.List("snippet");
ListRequest.Q = Query;
ListRequest.MaxResults = 3;
ListRequest.Type = "video";
foreach (var Result in (await ListRequest.ExecuteAsync()).Items)
{
var ResultData = await YouTubeParse(Result.Id.VideoId);
if (ResultData != null)
{
Results.Add((Song)ResultData);
}
}
var SCResponse = JArray.Parse(await SC);
int i = 0;
foreach (var Response in SCResponse)
{
if (++i > 3)
{
break;
}
Results.Add(SoundCloudParse(Response));
}
}
return Results;
}
private static async Task<Song?> YouTubeParse(string VideoId)
{
var Search = YT.Videos.List("contentDetails,snippet");
Search.Id = VideoId;
var Videos = await Search.ExecuteAsync();
var Result = Videos.Items.FirstOrDefault();
if (Result != null)
{
var Desc = Result.Snippet.Description;
if (Desc.Length == 0)
{
Desc = "No description";
}
return new Song
{
FullName = Result.Snippet.Title,
Desc = $"{TimeSpanToString(XmlConvert.ToTimeSpan(Result.ContentDetails.Duration))} on YouTube | {Desc}",
Url = $"http://www.youtube.com/watch?v={Search.Id}",
Type = SongType.YouTube,
ThumbNail = Result.Snippet.Thumbnails.Maxres?.Url ?? Result.Snippet.Thumbnails.Default__?.Url
};
}
return null;
}
private static string StripHtml(string In)
{
return Regex.Replace(In, @"<[^>]*>", string.Empty);
}
private static Song SoundCloudParse(JToken Response)
{
var Desc = Response["description"].ToString().Replace("\n", " ");
if (Desc.Length == 0)
{
Desc = Response["genre"].UcWords().ToString();
}
var Thumb = Response["artwork_url"].ToString();
if (Thumb == string.Empty)
{
Thumb = "http://i.imgur.com/eRaxycY.png";
}
return new Song
{
FullName = Response["title"].ToString(),
Desc = $"{TimeSpanToString(new TimeSpan(0, 0, 0, 0, Response["duration"].ToObject<int>()))} on SoundCloud | {StripHtml(Desc.Trim())}",
Url = Response["uri"].ToString(),
Type = SongType.SoundCloud,
ThumbNail = Thumb
};
}
private static string TimeSpanToString(TimeSpan Span)
{
var TimeStr = $"{Span.Minutes.ToString().PadLeft(2, '0')}:{Span.Seconds.ToString().PadLeft(2, '0')}";
var Hours = Span.Days * 24 + Span.Hours;
if (Hours != 0)
{
TimeStr = $"{Hours}:{TimeStr}";
}
return TimeStr;
}
}
}
| db94c19bc665396b6c139a18543f0ae45293fe1e | [
"C#"
] | 24 | C# | amirzaidi/CaiqueServer | e78923491045e78093cdd1d76c914036e2753bda | 65b5dea62b824e9b956d5560afd9af5ebc041cf6 |
refs/heads/master | <repo_name>fatema-binbytes/photographer<file_sep>/src/screens/Profile/index.js
// @flow
import React, {Component} from "react";
import {Image, ImageBackground, TouchableOpacity, Dimensions,Platform,FlatList} from "react-native";
import {
Container,
Content,
Text,
Thumbnail,
View,
List,
ListItem,
Button,
Icon
} from "native-base";
import {inject,observer} from 'mobx-react'
import {Grid, Col} from "react-native-easy-grid";
import CustomHeader from "../../components/CustomHeader";
import ProfileTab from '../Photographer/ProfileTabs/tabOne'
import styles from "./styles";
@inject("User")
@observer
class Profile extends Component {
render() {
const navigation = this.props.navigation;
return (
<Container>
<ImageBackground
source={require("../../../assets/bg-transparent.png")}
style={styles.container}
>
<CustomHeader hasTabs navigation={navigation} />
<Content
showsVerticalScrollIndicator={false}
style={{backgroundColor: "#fff"}}
>
{!this.props.User.imageData
? <View style={styles.linkTabs}>
<ListItem
style={{
backgroundColor: "#fff",
justifyContent: "center"
}}
>
<Text style={styles.textNote}>Empty List</Text>
</ListItem>
</View>
: <View>
<ProfileTab navigation={navigation}/>
</View>}
</Content>
</ImageBackground>
</Container>
);
}
}
export default Profile;
<file_sep>/src/App.js
import React from "react";
import { StackNavigator, DrawerNavigator ,TabNavigator,createMaterialTopTabNavigator} from "react-navigation";
import { Root } from "native-base";
import Splash from './screens/Splash/splash'
import Login from "./screens/Login/";
import ForgotPassword from "./screens/ForgotPassword";
import SignUp from "./screens/SignUp/";
import Walkthrough from "./screens/Walkthrough/";
import Comments from "./screens/Comments/";
import Channel from "./screens/Channel";
import Story from "./screens/Story";
import Sidebar from "./screens/Sidebar";
import Profile from "./screens/Profile/";
import EditProfile from "./screens/EditProfile";
import ImageUpload from "./screens/ImageUpload";
import Explore from './screens/Explore'
import ProfileTabs from './screens/Photographer/ProfileTabs'
import Friend from './screens/Settings/inviteFriends'
import Contact from './screens/Settings/contactUs'
import Terms from './screens/Settings/termServices'
import Payment from './screens/Settings/payment'
import ZoomImage from './screens/ZoomImage/zoomImage'
const TabNavigation = TabNavigator({
// Friend:{
// screen:Friend
// },
Contact:{
screen:Contact
},
Terms:{
screen:Terms
},
Payment :{
screen:Payment
}
},{
lazy:true,
tabBarOptions:{
scrollEnabled:true,
style: {
backgroundColor: '#01cca1',
},
tabStyle: {
width:95
},}
})
const Drawer = DrawerNavigator(
{
Explore:{screen:Explore},
Profile: { screen: Profile },
ProfileTabs :{screen:ProfileTabs},
Settings: { screen: TabNavigation }
},
{
initialRouteName:'Explore',
contentComponent: props => <Sidebar {...props} />
}
);
const App = StackNavigator(
{
Splash:{screen:Splash},
Login: { screen: Login },
SignUp: { screen: SignUp },
ForgotPassword: { screen: ForgotPassword },
Walkthrough: { screen: Walkthrough },
Story: { screen: Story },
Comments: { screen: Comments },
Channel: { screen: Channel },
Drawer: { screen: Drawer },
ZoomImage:{screen:ZoomImage},
EditProfile: { screen: EditProfile },
Friend:{ screen:Friend },
ImageUpload:{ screen: ImageUpload }
},
{
index: 0,
initialRouteName: "Splash",
headerMode: "none"
}
);
export default () =>
<Root>
<App />
</Root>;
<file_sep>/src/components/FlateList/explorComponent.js
import React,{Component} from 'react'
import {TouchableHighlight,ImageBackground,Text,View,Dimensions,Platform} from 'react-native'
const deviceHeight = Dimensions.get("window").height;
export default class ExploreComponent extends Component{
render(){
return(
<TouchableHighlight
underlayColor={'transparent'}
onPress={()=>this.props.navigation.navigate(this.props.navi)}
>
<ImageBackground transparent style={{
height:Dimensions.get("window").height/ 4 + 10,
width:Dimensions.get("window").width / 2 + 2,
}} source={this.props.item.image}>
{this.props.text ?
<View transparent style={{backgroundColor:'#33333399',}}><Text transparent
style={{fontSize: 12,
fontWeight: "900",
marginLeft: 100,
bottom:10,
marginTop: deviceHeight / 4 - 6,
color:'white'
}}
>
{this.props.text}
</Text></View>:<View/>}
</ImageBackground>
</TouchableHighlight>
)
}
}
<file_sep>/src/screens/Sidebar/index.js
// @flow
import React, {Component} from "react";
import {ImageBackground, TouchableOpacity} from "react-native";
import { NavigationActions } from "react-navigation";
import {
Container,
Content,
Text,
ListItem,
Thumbnail,
View
} from "native-base";
import Icon from "react-native-vector-icons/MaterialIcons";
import{ inject,observer }from "mobx-react";
import { Grid, Col } from "react-native-easy-grid";
import { remove } from "../../utils/db";
import styles from "./style";
@inject("User")
class SideBar extends Component {
logout() {
remove(err => {
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Login'})
]
})
this.props.navigation.dispatch(resetAction)
})
}
render() {
const navigation = this.props.navigation;
return (
<Container>
<ImageBackground
source={require("../../../assets/sidebar-transparent.png")}
style={styles.background}
>
<Content style={styles.drawerContent}>
<ListItem
button
onPress={() => {
navigation.navigate("Explore");
}}
iconLeft
style={styles.links}
>
<Icon name="explore" size={26} color={"#fff"} />
<Text style={styles.linkText}> EXPLORE</Text>
</ListItem>
<ListItem
button
onPress={() => {
navigation.navigate("ProfileTabs");
}}
iconLeft
style={styles.links}
>
<Icon name="person" size={26} color={"#fff"} />
<Text style={styles.linkText}> PROFILE</Text>
</ListItem>
<ListItem
button
onPress={() => {
navigation.navigate("Settings");
}}
iconLeft
style={styles.links}
>
<Icon name="settings" size={26} color={"#fff"} />
<Text style={styles.linkText}>SETTINGS</Text>
</ListItem>
</Content>
<View style={styles.logoutContainer}>
<View style={styles.logoutbtn} foregroundColor={"white"}>
<Grid>
<Col>
<TouchableOpacity
onPress={() => this.logout()}
style={{
alignSelf: "flex-start",
backgroundColor: "transparent"
}}
>
<Text style={{fontWeight: "bold", color: "#fff"}}>
Logout
</Text>
<Text note style={{color: "#fff"}}>
{this.props.User.displayName}
</Text>
</TouchableOpacity>
</Col>
<Col>
<TouchableOpacity
style={{alignSelf: "flex-end"}}
onPress={() => {
navigation.navigate("Profile");
}}
>
<Thumbnail
source={require("../../../assets/Contacts/user.png")}
style={styles.profilePic}
/>
</TouchableOpacity>
</Col>
</Grid>
</View>
</View>
</ImageBackground>
</Container>
);
}
}
export default SideBar;
<file_sep>/src/screens/Photographer/ProfileTabs/tabThree.js
// @flow
import React, {Component} from "react";
import {Image, ImageBackground,Dimensions,Platform, View,TouchableOpacity,FlatList, ListView} from "react-native";
import {
Container,
Content,
Text,
Thumbnail,
Left,
Right,
Body,
Header,
List,
ListItem,
Button,
Icon
} from "native-base";
import {Grid, Col} from "react-native-easy-grid";
import { inject, observer } from 'mobx-react'
import styles from "./styles";
@inject('User')
@observer
class TabThree extends Component {
componentDidMount(){
this.props.User.imageData
}
render() {
const navigation = this.props.navigation;
return (
<View style={{flex:1}}>
<FlatList
data={this.props.User.imageData}
numColumns={2}
renderItem={(item) => {
return<TouchableOpacity
onPress={()=>navigation.navigate('Channel')}
>
<ImageBackground style={{margin:1,
height:Dimensions.get("window").height/ 4 + 10,
width:Dimensions.get("window").width / 2 + 2,
}} source={item.item.image}>
{/* <Text
style={
Platform.OS === "android"
? styles.achannelImgText
: styles.ioschannelImgText
}
>
{item.item.name}
</Text> */}
</ImageBackground></TouchableOpacity>
}}
keyExtractor={(item,index )=> `${index}`}/>
</View>
);
}
}
export default TabThree
<file_sep>/src/screens/Splash/splash.js
import React, { Component } from "react";
import { Dimensions, ImageBackground} from "react-native";
import { inject, observer } from "mobx-react";
import { load } from "../../utils/db";
@inject("User")
@observer
export default class Splash extends Component {
componentDidMount(){
load((err, result) => {
console.log(result, err);
if(result){
this.props.User.set(JSON.parse(result));
this.props.navigation.replace("Drawer");
} else {
this.props.navigation.replace("Login");
}
});
}
render(){
return(
<ImageBackground
style={{height:Dimensions.get("window").height,
width:Dimensions.get("window").width}}
source={require('../../../assets/launch-screen.png')} />
)
}
}<file_sep>/src/screens/Photographer/ProfileTabs/tabOne.js
// @flow
import React, {Component} from "react";
import {Image, ImageBackground,ScrollView, View,TouchableOpacity,FlatList, ListView} from "react-native";
import {
Container,
Content,
Text,
Thumbnail,
Left,
Right,
Body,
Header,
List,
ListItem,
Button,
Icon
} from "native-base";
import {Grid, Col} from "react-native-easy-grid";
import { inject, observer } from 'mobx-react'
import styles from "./styles";
import ImageComponent from '../../../components/FlateList/imageComponent'
const headerLogo = require("../../../../assets/header-logo.png");
@inject('User')
@observer
class TabOne extends Component {
componentDidMount(){
this.props.User.imageData
}
render() {
return (
<ScrollView>
<View style={{flex:1}}>
<View style={styles.profileInfoContainer}>
<View style={{alignSelf: "center"}}>
<Thumbnail
source={require("../../../../assets/Contacts/user.png")}
style={styles.profilePic}
/>
</View>
<View style={styles.profileInfo}>
<Text style={styles.profileUser}>{this.props.User.userName}</Text>
<Text note style={styles.profileUserInfo}>
{this.props.User.aboutUser}
</Text>
</View>
</View>
<FlatList
data={this.props.User.imageData}
numColumns={2}
renderItem={(item) => {
return<ImageComponent navi={"Profile"} navigation={this.props.navigation}item={item.item}/>
}}
keyExtractor={(item,index )=> `${index}`}/>
</View>
</ScrollView>
);
}
}
export default TabOne
<file_sep>/src/screens/ImageUpload/index.js
import React, { Component } from "react";
import { ScrollView } from "react-native";
import {
Container,
Button,
Content,
Text,
View
} from "native-base";
import { inject } from "mobx-react";
import { NavigationActions } from "react-navigation";
import PickImage from "./PickImage"
import styles from "./styles";
@inject("User")
export default class EditProfile extends Component {
constructor(props) {
super(props);
this.state = {
images: []
}
}
async componentDidMount() {
const user = await this.props.User.getById(this.props.navigation.state.params.uid);
if(user) {
this.setState({ images: user.images });
}
}
render() {
return (
<ScrollView>
<Container style={styles.container}>
<Content contentContainerStyle={styles.contentContainer}>
<Text style={{fontSize: 26, fontWeight: "bold", alignSelf: "center", marginBottom: 16}}>Add Portfolio</Text>
<View style={{flexGrow: 1, flexDirection: "row", flexWrap: "wrap", justifyContent: "space-between"}}>
{
Array.apply(0, Array(6)).map((x, i) => {
const uri = this.state.images[i] ? this.state.images[i].downloadURL : null
console.log(this.state.images[i]);
return <PickImage uri={uri} onFilePick={(path, filename) => this.state.images[i] = { path, filename }} key={i} />
})
}
</View>
<Button onPress={this.onNext} style={{marginTop: 16}} light full>
<Text> Done </Text>
</Button>
</Content>
</Container>
</ScrollView>
);
}
onNext = () => {
this.props.User.createOrUpdate(this.props.navigation.state.params, this.state.images, () => {
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: "Drawer"})
]
});
this.props.navigation.dispatch(resetAction);
})
}
}<file_sep>/src/utils/str.js
export default {
getFormattedTime() {
var today = new Date()
var y = today.getFullYear()
var m = today.getMonth()
var d = today.getDate()
var h = today.getHours()
var m = today.getMinutes()
var s = today.getSeconds()
return '_' + y + '-' + m + '-' + d + '-' + h + '-' + m + '-' + s
},
getRandom(length) {
var text = ''
var possible =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length))
return text
},
getFileName() {
return this.getRandom(4) + this.getFormattedTime()
}
}
<file_sep>/src/screens/Photographer/ProfileTabs/tabTwo.js
// @flow
import React, {Component} from "react";
import {View} from "react-native";
import { Calendar as MonthCalendar } from "react-native-calendars";
type Props = {
navigation: () => void,
day: string
};
class TabTwo extends Component {
state: {
date: Object,
selected: string
};
props: Props;
constructor(props: Props) {
super(props);
this.state = {
date: new Date(),
selected: ""
};
}
onDateChange(date: Object) {
this.setState({ date });
}
onDayPress(day: any) {
this.setState({
selected: day.dateString
});
}
render() {
return (
<View style={{flex:1}}>
<MonthCalendar
onDayPress={e => this.onDayPress(e)}
disableMonthChange={true}
markedDates={{ [this.state.selected]: { selected: true } }}
theme={{
calendarBackground: "#ffffff",
textSectionTitleColor: "#01cca1",
selectedDayBackgroundColor: "#01cca1",
selectedDayTextColor: "#ffffff",
todayTextColor: "#01cca1",
dayTextColor: "#2d4150",
textDisabledColor: "#d9e1e8",
dotColor: "#00adf5",
selectedDotColor: "#ffffff",
arrowColor: "#01cca1",
monthTextColor: "#000"
}}
/>
</View>
);
}
}
export default TabTwo
<file_sep>/src/utils/db.js
import { AsyncStorage } from "react-native";
const USER_KEY = "USER_KEY";
export function save(key) {
return AsyncStorage.setItem(USER_KEY, JSON.stringify(key));
}
export function load(callback) {
return AsyncStorage.getItem(USER_KEY, callback);
}
export function remove(callback) {
return AsyncStorage.removeItem(USER_KEY, callback);
}<file_sep>/src/screens/ImageUpload/styles.js
const React = require("react-native");
const { Dimensions, Platform } = React;
const commonColor = require("../../theme/variables/commonColor");
const deviceHeight = Dimensions.get("window").height;
export default {
container: {
flex: 1
},
contentContainer: {
flex: 1,
justifyContent: "center",
margin: 16
},
label: {
fontSize: 26,
fontWeight: "bold"
},
subLabel: {
fontSize: 16
},
pickerContainer: {
borderWidth: 1,
borderColor: "#fff",
marginTop: 16,
borderRadius: 10,
paddingHorizontal: 4
}
};
| 499de00f31cb4022013d02a278c0c75984d67651 | [
"JavaScript"
] | 12 | JavaScript | fatema-binbytes/photographer | 17ebdf9c36fc60e3c1c0c95fba1f64aad350b9e5 | 160f48f505ade9391bece001c6cea3d8b5d6f6e6 |
refs/heads/master | <repo_name>ilsediaz/Salary-API<file_sep>/README.md
# REST API
## what is this?
simple api example using flask. a flask api object contains one or more functionalities (GET, POST, etc).
## install
```
pip install -r requirements.txt
```
## run
```
python app.py
```
then go to http://localhost:5000/departments
you could drill down by deparments too!
try http://localhost:5000/dept/police<file_sep>/app.py
'''
12/23/16 (bolbs in ny; we walked to barclay center/fulton mall last night and ate at pizzeria; hes still a boy in many ways; 1st week back after two weeks of offsites and leadership training; watching david attenboruoughs trials of life - one of the best series ive seen; doing a lot of random things at work - perch/smartthings, marketing spend, lotik modeling, etc. i actually like it; walked to office todya and picked up turtlebot; want to spend more time with ros and robotics; bay fell asleep at 6ish - shes been through a lot after fran and lydia both left; coding at maple now - bolbs/laura/lurm went ice skating; will go to peter luger later; bay is feeling a bit disconnected since ive been gone for so long but i think we're both tired and busy with work; reviewing restful apis so i can actually have a convo with adrian)
3/18/17 (emily to be gone for two weeks; lurm is back from sxsw; trying to hire yukuan but shana is getting in the way; in a good space with bay right now as long as we talk; long week for both of us due to work; trying to bring stae over the finish line; at lpq now there are so many screaming babies; <NAME> got a new job; bolbs laura in thailand for edisons wedding; did a metis presentation yesterday; saw ben yesterday; angela is moving to paris; juyoung is imploding and will move to lotik; mike park in town for spring break - itll be nice to see him and talk abotu science; thinking about going to copahagen with my beautiful wife; reviewing api's because im researching api fortress as a potential investment)
'''
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
# Assuming salaries.db is in your app root folder
e = create_engine('sqlite:///salaries.db') # loads db into memory
app = Flask(__name__)
api = Api(app) # api is a collection of objects, where each object contains a specific functionality (GET, POST, etc)
class Departments_Meta(Resource):
def get(self):
conn = e.connect() # open connection to memory data
query = conn.execute("select distinct DEPARTMENT from salaries") # query
return {'departments': [i[0] for i in query.cursor.fetchall()]} # format results in dict format
class Departmental_Salary(Resource):
def get(self, department_name): # param is pulled from url string
conn = e.connect()
query = conn.execute("select * from salaries where Department='%s'"%department_name.upper())
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
return result
class multiply(Resource):
'''dummy function to test apis'''
def get(self, number): # param must match uri identifier
return number * 2
# once we've defined our api functionalities, add them to the master API object
api.add_resource(Departments_Meta, '/departments') # bind url identifier to class
api.add_resource(Departmental_Salary, '/dept/<string:department_name>') # bind url identifier to class; also make it querable
api.add_resource(multiply, '/multiply/<int:number>') # whatever the number is, multiply by 2
if __name__ == '__main__':
app.run(debug=True) | 43bc12b46fa9f9e315294ddde9d745e410c5ba39 | [
"Markdown",
"Python"
] | 2 | Markdown | ilsediaz/Salary-API | 2b56db9c266cd72ac144e6a4530112594df98112 | b1165bfb9783d2a7584f46d0e569b8d1384663be |
refs/heads/master | <file_sep>import { Equal, Expect, ExpectFalse, NotEqual } from '@type-challenges/utils'
interface Model {
name: string;
age: number;
locations: string[] | null;
}
type ModelEntries = ['name', string] | ['age', number] | ['locations', string[] | null];
type cases = [
Expect<Equal<ObjectFromEntries<ModelEntries>,Model>>,
]
<file_sep>import { Equal, Expect, ExpectFalse, NotEqual } from '@type-challenges/utils'
interface Model {
name: string;
age: number;
locations: string[] | null;
}
type ModelEntries = ['name', string] | ['age', number] | ['locations', string[] | null];
type cases = [
Expect<Equal<ObjectEntries<Model>,ModelEntries>>,
Expect<Equal<ObjectEntries<Partial<Model>>,ModelEntries>>,
]
| aecbe04fb3d1dbd8289da5dcefb67d310e9002c0 | [
"TypeScript"
] | 2 | TypeScript | im-codebreaker/type-challenges | 659d205bb234e8e2eb507030a545fa90297afb9a | dc9c68cd6ef079d080eae28ef0b7728bd6848cd2 |
refs/heads/master | <file_sep>newBZhgt
========
A new version of bzhgt written in C++11 and supporting more image formats thanks to SFML.
<file_sep>#include <iostream>
#include <string>
#include <memory>
#include <functional>
#include <fstream>
#include <sstream>
#include "stb_image.h"
struct StbImageFree
{
void operator()(std::uint8_t* ptr)
{
stbi_image_free(ptr);
}
};
using StbSmartPtr = std::unique_ptr<std::uint8_t[], StbImageFree>;
bool saveHGT(const std::string& file, const std::uint8_t* img, std::size_t heightModifier, std::size_t width, std::size_t height);
int main(int argc, char** argv) try
{
if(!(argc == 2 || argc == 3))
throw std::runtime_error("Incorrect # of args, must be 1 (filename of image)");
std::string file = argv[1];
std::string fileName = file.substr(0, file.find_last_of('.'));
std::string fileExt = file.substr(file.find_last_of('.') + 1);
// if second arg is given, it is the heightMod, otherwise, make it 0
auto heightMod = argv[2] ? std::stoi(argv[2]) : 0;
// check for supported file types via extension
if(!(fileExt == "bmp" || fileExt == "png" || fileExt == "tga" || fileExt == "jpg" || fileExt == "gif" || fileExt == "psd" || fileExt == "hdr" || fileExt == "pic"))
throw std::runtime_error("Unsupported image format");
int width = 0;
int height = 0;
StbSmartPtr image(stbi_load(file.c_str(), &width, &height, nullptr, 4));
std::cout << "This image will create a " << width * 10 << " x " << height * 10 << " height map.\n";
bool result = saveHGT(fileName + ".hgt", image.get(), heightMod, width, height);
if(result)
std::cout << "HGT successfully created as " << fileName << ".hgt!\n";
else
throw std::runtime_error("Failed creating HGT");
return 0;
}
catch(const std::runtime_error& re)
{
std::cerr << re.what() << '\n';
return 1;
}
bool saveHGT(const std::string& file, const std::uint8_t* img, std::size_t heightModifier, std::size_t width, std::size_t height)
{
// write to memory...
std::stringstream ss(std::ios::binary);
// total chunks in map
auto xChunks = width / 128;
auto yChunks = height / 128;
// decide how we're writing bytes before we loop
std::function<std::pair<std::uint8_t, std::uint8_t>(int)> byteWrite;
if(heightModifier == 0)
{
// math mode
byteWrite = [&](int pos)
{
// store top 4 bits in the high byte
std::uint8_t high = (img[pos + 1] & 240) >> 4;
// and store the next 8 bits in the low byte
std::uint8_t low = ((img[pos + 1] & 15) << 4) + (img[pos + 2] & 15);
return std::make_pair(low, high);
};
}
else
{
// normal greyscale mode
byteWrite = [&](int pos)
{
std::uint16_t val = static_cast<std::uint16_t>(heightModifier * (img[pos] + img[pos + 1] + img[pos + 2]));
std::uint8_t low = val & 255;
std::uint8_t high = val >> 8;
return std::make_pair(low, high);
};
}
for(auto y = yChunks - 1; y >= 0; --y)
{
for(auto x = 0u; x < xChunks; ++x)
{
auto basePos = 128 * 4 * (x + y * 128 * xChunks);
for(auto yi = 127u; yi >= 0; --yi)
{
for(auto xi = 0u; xi < 128; ++xi)
{
auto pos = (yi * width + xi) * 4 + basePos;
auto pair = byteWrite(pos);
ss.put(pair.first);
ss.put(pair.second);
}
}
}
}
// ...then to disk, once
std::ofstream fout(file, std::ios::binary);
if(!fout)
return false;
std::string out = ss.str();
fout.write(out.c_str(), out.length());
return true;
} | 7df1b5a0d53d38e3f9f265c1923da592bc538444 | [
"Markdown",
"C++"
] | 2 | Markdown | dabbertorres/newBZhgt | 8ea21d6c328fef6045f1f26574dca097ddc42038 | 7894c1ceedf4747481fa155a3696808cb4c82309 |
refs/heads/master | <file_sep>/*
* Configuration file support for sample IPP server implementation.
*
* Copyright © 2015-2018 by the IEEE-ISTO Printer Working Group
* Copyright © 2015-2018 by Apple Inc.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more
* information.
*/
#include "ippserver.h"
#include <cups/file.h>
#include <cups/dir.h>
#include <fnmatch.h>
#include <cups/ipp-private.h>
/*
* Local globals...
*/
static _cups_mutex_t printer_mutex = _CUPS_MUTEX_INITIALIZER;
/*
* Local functions...
*/
static int attr_cb(_ipp_file_t *f, server_pinfo_t *pinfo, const char *attr);
static int compare_lang(server_lang_t *a, server_lang_t *b);
static int compare_printers(server_printer_t *a, server_printer_t *b);
static server_lang_t *copy_lang(server_lang_t *a);
#ifdef HAVE_AVAHI
static void dnssd_client_cb(AvahiClient *c, AvahiClientState state, void *userdata);
#endif /* HAVE_AVAHI */
static int error_cb(_ipp_file_t *f, server_pinfo_t *pinfo, const char *error);
static void free_lang(server_lang_t *a);
static int load_system(const char *conf);
static int token_cb(_ipp_file_t *f, _ipp_vars_t *vars, server_pinfo_t *pinfo, const char *token);
/*
* 'serverCleanAllJobs()' - Clean old jobs for all printers...
*/
void
serverCleanAllJobs(void)
{
server_printer_t *printer; /* Current printer */
serverLog(SERVER_LOGLEVEL_DEBUG, "Cleaning old jobs.");
_cupsMutexLock(&printer_mutex);
for (printer = (server_printer_t *)cupsArrayFirst(Printers); printer; printer = (server_printer_t *)cupsArrayNext(Printers))
serverCleanJobs(printer);
_cupsMutexUnlock(&printer_mutex);
}
/*
* 'serverDNSSDInit()' - Initialize DNS-SD registrations.
*/
void
serverDNSSDInit(void)
{
#ifdef HAVE_DNSSD
if (DNSServiceCreateConnection(&DNSSDMaster) != kDNSServiceErr_NoError)
{
fputs("Error: Unable to initialize Bonjour.\n", stderr);
exit(1);
}
#elif defined(HAVE_AVAHI)
int error; /* Error code, if any */
if ((DNSSDMaster = avahi_threaded_poll_new()) == NULL)
{
fputs("Error: Unable to initialize Bonjour.\n", stderr);
exit(1);
}
if ((DNSSDClient = avahi_client_new(avahi_threaded_poll_get(DNSSDMaster), AVAHI_CLIENT_NO_FAIL, dnssd_client_cb, NULL, &error)) == NULL)
{
fputs("Error: Unable to initialize Bonjour.\n", stderr);
exit(1);
}
avahi_threaded_poll_start(DNSSDMaster);
#endif /* HAVE_DNSSD */
}
/*
* 'serverFinalizeConfiguration()' - Make final configuration choices.
*/
int /* O - 1 on success, 0 on failure */
serverFinalizeConfiguration(void)
{
char local[1024]; /* Local hostname */
/*
* Default hostname...
*/
if (!ServerName && httpGetHostname(NULL, local, sizeof(local)))
ServerName = strdup(local);
if (!ServerName)
ServerName = strdup("localhost");
#ifdef HAVE_SSL
/*
* Setup TLS certificate for server...
*/
cupsSetServerCredentials(KeychainPath, ServerName, 1);
#endif /* HAVE_SSL */
/*
* Default directories...
*/
if (!DataDirectory)
{
char directory[1024]; /* New directory */
const char *tmpdir; /* Temporary directory */
#ifdef WIN32
if ((tmpdir = getenv("TEMP")) == NULL)
tmpdir = "C:/TEMP";
#elif defined(__APPLE__)
if ((tmpdir = getenv("TMPDIR")) == NULL)
tmpdir = "/private/tmp";
#else
if ((tmpdir = getenv("TMPDIR")) == NULL)
tmpdir = "/tmp";
#endif /* WIN32 */
snprintf(directory, sizeof(directory), "%s/ippserver.%d", tmpdir, (int)getpid());
if (mkdir(directory, 0755) && errno != EEXIST)
{
serverLog(SERVER_LOGLEVEL_ERROR, "Unable to create default data directory \"%s\": %s", directory, strerror(errno));
return (0);
}
serverLog(SERVER_LOGLEVEL_INFO, "Using default data directory \"%s\".", directory);
DataDirectory = strdup(directory);
}
if (!SpoolDirectory)
{
SpoolDirectory = strdup(DataDirectory);
serverLog(SERVER_LOGLEVEL_INFO, "Using default spool directory \"%s\".", DataDirectory);
}
/*
* Initialize Bonjour...
*/
serverDNSSDInit();
/*
* Apply default listeners if none are specified...
*/
if (!Listeners)
{
#ifdef WIN32
/*
* Windows is almost always used as a single user system, so use a default port
* number of 8631.
*/
if (!DefaultPort)
DefaultPort = 8631;
#else
/*
* Use 8000 + UID mod 1000 for the default port number...
*/
if (!DefaultPort)
DefaultPort = 8000 + ((int)getuid() % 1000);
#endif /* WIN32 */
serverLog(SERVER_LOGLEVEL_INFO, "Using default listeners for %s:%d.", ServerName, DefaultPort);
if (!serverCreateListeners(strcmp(ServerName, "localhost") ? NULL : "localhost", DefaultPort))
return (0);
}
return (1);
}
/*
* 'serverFindPrinter()' - Find a printer by resource...
*/
server_printer_t * /* O - Printer or NULL */
serverFindPrinter(const char *resource) /* I - Resource path */
{
server_printer_t key, /* Search key */
*match = NULL; /* Matching printer */
_cupsMutexLock(&printer_mutex);
if (cupsArrayCount(Printers) == 1 || !strcmp(resource, "/ipp/print"))
{
/*
* Just use the first printer...
*/
match = cupsArrayFirst(Printers);
if (strcmp(match->resource, resource) && strcmp(resource, "/ipp/print"))
match = NULL;
}
else
{
key.resource = (char *)resource;
match = (server_printer_t *)cupsArrayFind(Printers, &key);
}
_cupsMutexUnlock(&printer_mutex);
return (match);
}
/*
* 'serverLoadAttributes()' - Load printer attributes from a file.
*
* Syntax is based on ipptool format:
*
* ATTR value-tag name value
* ATTR value-tag name value,value,...
* AUTHTYPE "scheme"
* COMMAND "/path/to/command"
* DEVICE-URI "uri"
* MAKE "manufacturer"
* MODEL "model name"
* PROXY-USER "username"
* STRINGS lang filename.strings
*
* AUTH schemes are "none" for no authentication or "basic" for HTTP Basic
* authentication.
*
* DEVICE-URI values can be "socket", "ipp", or "ipps" URIs.
*/
int /* O - 1 on success, 0 on failure */
serverLoadAttributes(
const char *filename, /* I - File to load */
server_pinfo_t *pinfo) /* I - Printer information */
{
_ipp_vars_t vars; /* IPP variables */
_ippVarsInit(&vars, (_ipp_fattr_cb_t)attr_cb, (_ipp_ferror_cb_t)error_cb, (_ipp_ftoken_cb_t)token_cb);
pinfo->attrs = _ippFileParse(&vars, filename, (void *)pinfo);
_ippVarsDeinit(&vars);
return (pinfo->attrs != NULL);
}
/*
* 'serverLoadConfiguration()' - Load the server configuration file.
*/
int /* O - 1 if successful, 0 on error */
serverLoadConfiguration(
const char *directory) /* I - Configuration directory */
{
cups_dir_t *dir; /* Directory pointer */
cups_dentry_t *dent; /* Directory entry */
char filename[1024], /* Configuration file/directory */
iconname[1024], /* Icon file */
resource[1024], /* Resource path */
*ptr; /* Pointer into filename */
server_printer_t *printer; /* Printer */
server_pinfo_t pinfo; /* Printer information */
/*
* First read the system configuration file, if any...
*/
snprintf(filename, sizeof(filename), "%s/system.conf", directory);
if (!load_system(filename))
return (0);
if (!serverFinalizeConfiguration())
return (0);
/*
* Then see if there are any print queues...
*/
snprintf(filename, sizeof(filename), "%s/print", directory);
if ((dir = cupsDirOpen(filename)) != NULL)
{
serverLog(SERVER_LOGLEVEL_INFO, "Loading printers from \"%s\".", filename);
while ((dent = cupsDirRead(dir)) != NULL)
{
if ((ptr = dent->filename + strlen(dent->filename) - 5) >= dent->filename && !strcmp(ptr, ".conf"))
{
/*
* Load the conf file, with any associated icon image.
*/
serverLog(SERVER_LOGLEVEL_INFO, "Loading printer from \"%s\".", dent->filename);
snprintf(filename, sizeof(filename), "%s/print/%s", directory, dent->filename);
*ptr = '\0';
memset(&pinfo, 0, sizeof(pinfo));
snprintf(iconname, sizeof(iconname), "%s/print/%s.png", directory, dent->filename);
if (!access(iconname, R_OK))
pinfo.icon = strdup(iconname);
if (serverLoadAttributes(filename, &pinfo))
{
snprintf(resource, sizeof(resource), "/ipp/print/%s", dent->filename);
if ((printer = serverCreatePrinter(resource, dent->filename, &pinfo)) == NULL)
continue;
if (!Printers)
Printers = cupsArrayNew((cups_array_func_t)compare_printers, NULL);
cupsArrayAdd(Printers, printer);
}
}
else if (!strstr(dent->filename, ".png"))
serverLog(SERVER_LOGLEVEL_INFO, "Skipping \"%s\".", dent->filename);
}
cupsDirClose(dir);
}
/*
* Finally, see if there are any 3D print queues...
*/
snprintf(filename, sizeof(filename), "%s/print3d", directory);
if ((dir = cupsDirOpen(filename)) != NULL)
{
serverLog(SERVER_LOGLEVEL_INFO, "Loading 3D printers from \"%s\".", filename);
while ((dent = cupsDirRead(dir)) != NULL)
{
if ((ptr = dent->filename + strlen(dent->filename) - 5) >= dent->filename && !strcmp(ptr, ".conf"))
{
/*
* Load the conf file, with any associated icon image.
*/
serverLog(SERVER_LOGLEVEL_INFO, "Loading 3D printer from \"%s\".", dent->filename);
snprintf(filename, sizeof(filename), "%s/print3d/%s", directory, dent->filename);
*ptr = '\0';
memset(&pinfo, 0, sizeof(pinfo));
snprintf(iconname, sizeof(iconname), "%s/print3d/%s.png", directory, dent->filename);
if (!access(iconname, R_OK))
pinfo.icon = strdup(iconname);
if (serverLoadAttributes(filename, &pinfo))
{
snprintf(resource, sizeof(resource), "/ipp/print3d/%s", dent->filename);
if ((printer = serverCreatePrinter(resource, dent->filename, &pinfo)) == NULL)
continue;
if (!Printers)
Printers = cupsArrayNew((cups_array_func_t)compare_printers, NULL);
cupsArrayAdd(Printers, printer);
}
}
else if (!strstr(dent->filename, ".png"))
serverLog(SERVER_LOGLEVEL_INFO, "Skipping \"%s\".", dent->filename);
}
cupsDirClose(dir);
}
return (1);
}
/*
* 'attr_cb()' - Determine whether an attribute should be loaded.
*/
static int /* O - 1 to use, 0 to ignore */
attr_cb(_ipp_file_t *f, /* I - IPP file */
server_pinfo_t *pinfo, /* I - Printer information */
const char *attr) /* I - Attribute name */
{
int i, /* Current element */
result; /* Result of comparison */
static const char * const ignored[] =
{ /* Ignored attributes */
"attributes-charset",
"attributes-natural-language",
"charset-configured",
"charset-supported",
"device-service-count",
"device-uuid",
"document-format-varying-attributes",
"job-settable-attributes-supported",
"printer-alert",
"printer-alert-description",
"printer-camera-image-uri",
"printer-charge-info",
"printer-charge-info-uri",
"printer-config-change-date-time",
"printer-config-change-time",
"printer-current-time",
"printer-detailed-status-messages",
"printer-dns-sd-name",
"printer-fax-log-uri",
"printer-get-attributes-supported",
"printer-icons",
"printer-id",
"printer-is-accepting-jobs",
"printer-message-date-time",
"printer-message-from-operator",
"printer-message-time",
"printer-more-info",
"printer-service-type",
"printer-settable-attributes-supported",
"printer-state",
"printer-state-message",
"printer-state-reasons",
"printer-static-resource-directory-uri",
"printer-static-resource-k-octets-free",
"printer-static-resource-k-octets-supported",
"printer-strings-languages-supported",
"printer-strings-uri",
"printer-supply-info-uri",
"printer-up-time",
"printer-uri-supported",
"printer-xri-supported",
"queued-job-count",
"uri-authentication-supported",
"uri-security-supported",
"xri-authentication-supported",
"xri-security-supported",
"xri-uri-scheme-supported"
};
(void)f;
(void)pinfo;
for (i = 0, result = 1; i < (int)(sizeof(ignored) / sizeof(ignored[0])); i ++)
{
if ((result = strcmp(attr, ignored[i])) <= 0)
break;
}
return (result != 0);
}
/*
* 'compare_lang()' - Compare two languages.
*/
static int /* O - Result of comparison */
compare_lang(server_lang_t *a, /* I - First localization */
server_lang_t *b) /* I - Second localization */
{
return (strcmp(a->lang, b->lang));
}
/*
* 'compare_printers()' - Compare two printers.
*/
static int /* O - Result of comparison */
compare_printers(server_printer_t *a, /* I - First printer */
server_printer_t *b) /* I - Second printer */
{
return (strcmp(a->resource, b->resource));
}
/*
* 'copy_lang()' - Copy a localization.
*/
static server_lang_t * /* O - New localization */
copy_lang(server_lang_t *a) /* I - Localization to copy */
{
server_lang_t *b; /* New localization */
if ((b = calloc(1, sizeof(server_lang_t))) != NULL)
{
b->lang = strdup(a->lang);
b->filename = strdup(a->filename);
}
return (b);
}
#ifdef HAVE_AVAHI
/*
* 'dnssd_client_cb()' - Client callback for Avahi.
*
* Called whenever the client or server state changes...
*/
static void
dnssd_client_cb(
AvahiClient *c, /* I - Client */
AvahiClientState state, /* I - Current state */
void *userdata) /* I - User data (unused) */
{
(void)userdata;
if (!c)
return;
switch (state)
{
default :
fprintf(stderr, "Ignore Avahi state %d.\n", state);
break;
case AVAHI_CLIENT_FAILURE:
if (avahi_client_errno(c) == AVAHI_ERR_DISCONNECTED)
{
fputs("Avahi server crashed, exiting.\n", stderr);
exit(1);
}
break;
}
}
#endif /* HAVE_AVAHI */
/*
* 'error_cb()' - Log an error message.
*/
static int /* O - 1 to continue, 0 to stop */
error_cb(_ipp_file_t *f, /* I - IPP file data */
server_pinfo_t *pinfo, /* I - Printer information */
const char *error) /* I - Error message */
{
(void)f;
(void)pinfo;
serverLog(SERVER_LOGLEVEL_ERROR, "%s", error);
return (1);
}
/*
* 'free_lang()' - Free a localization.
*/
static void
free_lang(server_lang_t *a) /* I - Localization */
{
free(a->lang);
free(a->filename);
free(a);
}
/*
* 'load_system()' - Load the system configuration file.
*/
static int /* O - 1 on success, 0 on failure */
load_system(const char *conf) /* I - Configuration file */
{
cups_file_t *fp; /* File pointer */
int status = 1, /* Return value */
linenum = 0; /* Current line number */
char line[1024], /* Line from file */
*value; /* Pointer to value on line */
if ((fp = cupsFileOpen(conf, "r")) == NULL)
return (errno == ENOENT);
while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
{
if (!value)
{
fprintf(stderr, "ippserver: Missing value on line %d of \"%s\".\n", linenum, conf);
status = 0;
break;
}
if (!_cups_strcasecmp(line, "DataDirectory"))
{
if (access(value, R_OK))
{
fprintf(stderr, "ippserver: Unable to access DataDirectory \"%s\": %s\n", value, strerror(errno));
status = 0;
break;
}
DataDirectory = strdup(value);
}
else if (!_cups_strcasecmp(line, "DefaultPrinter"))
{
if (DefaultPrinter)
{
fprintf(stderr, "ippserver: Extra DefaultPrinter seen on line %d of \"%s\".\n", linenum, conf);
status = 0;
break;
}
DefaultPrinter = strdup(value);
}
else if (!_cups_strcasecmp(line, "Encryption"))
{
if (!_cups_strcasecmp(value, "always"))
Encryption = HTTP_ENCRYPTION_ALWAYS;
else if (!_cups_strcasecmp(value, "ifrequested"))
Encryption = HTTP_ENCRYPTION_IF_REQUESTED;
else if (!_cups_strcasecmp(value, "never"))
Encryption = HTTP_ENCRYPTION_NEVER;
else if (!_cups_strcasecmp(value, "required"))
Encryption = HTTP_ENCRYPTION_REQUIRED;
else
{
fprintf(stderr, "ippserver: Bad Encryption value \"%s\" on line %d of \"%s\".\n", value, linenum, conf);
status = 0;
break;
}
}
else if (!_cups_strcasecmp(line, "KeepFiles"))
{
KeepFiles = !strcasecmp(value, "yes") || !strcasecmp(value, "true") || !strcasecmp(value, "on");
}
else if (!_cups_strcasecmp(line, "Listen"))
{
char *ptr; /* Pointer into host value */
int port; /* Port number */
if ((ptr = strrchr(value, ':')) != NULL && !isdigit(ptr[1] & 255))
{
fprintf(stderr, "ippserver: Bad Listen value \"%s\" on line %d of \"%s\".\n", value, linenum, conf);
status = 0;
break;
}
if (ptr)
{
*ptr++ = '\0';
port = atoi(ptr);
}
else
port = 8000 + ((int)getuid() % 1000);
if (!serverCreateListeners(value, port))
{
status = 0;
break;
}
}
else if (!_cups_strcasecmp(line, "LogFile"))
{
if (!_cups_strcasecmp(value, "stderr"))
LogFile = NULL;
else
LogFile = strdup(value);
}
else if (!_cups_strcasecmp(line, "LogLevel"))
{
if (!_cups_strcasecmp(value, "error"))
LogLevel = SERVER_LOGLEVEL_ERROR;
else if (!_cups_strcasecmp(value, "info"))
LogLevel = SERVER_LOGLEVEL_INFO;
else if (!_cups_strcasecmp(value, "debug"))
LogLevel = SERVER_LOGLEVEL_DEBUG;
else
{
fprintf(stderr, "ippserver: Bad LogLevel value \"%s\" on line %d of \"%s\".\n", value, linenum, conf);
status = 0;
break;
}
}
else if (!_cups_strcasecmp(line, "MaxCompletedJobs"))
{
if (!isdigit(*value & 255))
{
fprintf(stderr, "ippserver: Bad MaxCompletedJobs value \"%s\" on line %d of \"%s\".\n", value, linenum, conf);
status = 0;
break;
}
MaxCompletedJobs = atoi(value);
}
else if (!_cups_strcasecmp(line, "MaxJobs"))
{
if (!isdigit(*value & 255))
{
fprintf(stderr, "ippserver: Bad MaxJobs value \"%s\" on line %d of \"%s\".\n", value, linenum, conf);
status = 0;
break;
}
MaxJobs = atoi(value);
}
else if (!_cups_strcasecmp(line, "SpoolDirectory"))
{
if (access(value, R_OK))
{
fprintf(stderr, "ippserver: Unable to access SpoolDirectory \"%s\": %s\n", value, strerror(errno));
status = 0;
break;
}
SpoolDirectory = strdup(value);
}
else
{
fprintf(stderr, "ippserver: Unknown directive \"%s\" on line %d.\n", line, linenum);
}
}
cupsFileClose(fp);
return (status);
}
/*
* 'token_cb()' - Process ippserver-specific config file tokens.
*/
static int /* O - 1 to continue, 0 to stop */
token_cb(_ipp_file_t *f, /* I - IPP file data */
_ipp_vars_t *vars, /* I - IPP variables */
server_pinfo_t *pinfo, /* I - Printer information */
const char *token) /* I - Current token */
{
char temp[1024], /* Temporary string */
value[1024]; /* Value string */
if (!token)
{
/*
* NULL token means do the initial setup - create an empty IPP message and
* return...
*/
f->attrs = ippNew();
return (1);
}
else if (!_cups_strcasecmp(token, "AUTHTYPE"))
{
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing AuthType value on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
pinfo->auth_type = strdup(value);
}
else if (!_cups_strcasecmp(token, "COMMAND"))
{
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing Command value on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
pinfo->command = strdup(value);
}
else if (!_cups_strcasecmp(token, "DEVICEURI"))
{
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing DeviceURI value on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
pinfo->device_uri = strdup(value);
}
else if (!_cups_strcasecmp(token, "OUTPUTFORMAT"))
{
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing OutputFormat value on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
pinfo->output_format = strdup(value);
}
else if (!_cups_strcasecmp(token, "MAKE"))
{
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing Make value on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
pinfo->make = strdup(value);
}
else if (!_cups_strcasecmp(token, "MODEL"))
{
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing Model value on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
pinfo->model = strdup(value);
}
else if (!_cups_strcasecmp(token, "PROXYUSER"))
{
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing ProxyUser value on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
pinfo->proxy_user = strdup(value);
}
else if (!_cups_strcasecmp(token, "STRINGS"))
{
server_lang_t lang; /* New localization */
char stringsfile[1024]; /* Strings filename */
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing STRINGS language on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, value, temp, sizeof(value));
if (!_ippFileReadToken(f, temp, sizeof(temp)))
{
serverLog(SERVER_LOGLEVEL_ERROR, "Missing STRINGS filename on line %d of \"%s\".", f->linenum, f->filename);
return (0);
}
_ippVarsExpand(vars, stringsfile, temp, sizeof(stringsfile));
lang.lang = value;
lang.filename = stringsfile;
if (!pinfo->strings)
pinfo->strings = cupsArrayNew3((cups_array_func_t)compare_lang, NULL, NULL, 0, (cups_acopy_func_t)copy_lang, (cups_afree_func_t)free_lang);
cupsArrayAdd(pinfo->strings, &lang);
serverLog(SERVER_LOGLEVEL_DEBUG, "Added strings file \"%s\" for language \"%s\".", stringsfile, value);
}
else
{
serverLog(SERVER_LOGLEVEL_ERROR, "Unknown directive \"%s\" on line %d of \"%s\".", token, f->linenum, f->filename);
return (0);
}
return (1);
}
<file_sep>/*
* IPP Proxy implementation for HP PCL and IPP Everywhere printers.
*
* Copyright 2016-2017 by the IEEE-ISTO Printer Working Group.
* Copyright 2014-2017 by Apple Inc.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more
* information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <cups/cups.h>
#include <cups/thread-private.h>
/*
* Local types...
*/
typedef struct proxy_info_s
{
const char *printer_uri,
*device_uri,
*device_uuid;
} proxy_info_t;
typedef struct proxy_job_s
{
ipp_jstate_t local_job_state; /* Local job-state value */
int local_job_id, /* Local job-id value */
remote_job_id, /* Remote job-id value */
remote_job_state; /* Remote job-state value */
} proxy_job_t;
/*
* Local globals...
*/
static cups_array_t *jobs; /* Local jobs */
static _cups_cond_t jobs_cond = _CUPS_COND_INITIALIZER;
/* Condition for jobs array */
static _cups_mutex_t jobs_mutex = _CUPS_MUTEX_INITIALIZER;
/* Mutex for jobs array */
static const char * const printer_attrs[] =
{ /* Printer attributes we care about */
"copies-supported",
"document-format-supported",
"jpeg-k-octets-supported",
"media-bottom-margin-supported",
"media-col-database",
"media-col-default",
"media-col-ready",
"media-col-supported",
"media-default",
"media-left-margin-supported",
"media-ready",
"media-right-margin-supported",
"media-size-supported",
"media-source-supported",
"media-supported",
"media-top-margin-supported",
"media-type-supported",
"pdf-k-octets-supported",
"print-color-mode-default",
"print-color-mode-supported",
"print-quality-default",
"print-quality-supported",
"printer-resolution-default",
"printer-resolution-supported",
"printer-state",
"printer-state-message",
"printer-state-reasons",
"pwg-raster-document-resolution-supported",
"pwg-raster-document-sheet-back",
"pwg-raster-document-type-supported",
"sides-default",
"sides-supported",
"urf-supported"
};
static int stop_running = 0;
static int verbosity = 0;
/*
* Local functions...
*/
static int attrs_are_equal(ipp_attribute_t *a, ipp_attribute_t *b);
static int compare_jobs(proxy_job_t *a, proxy_job_t *b);
static proxy_job_t *copy_job(proxy_job_t *src);
static ipp_t *create_media_col(const char *media, const char *source, const char *type, int width, int length, int margins);
static ipp_t *create_media_size(int width, int length);
static void deregister_printer(http_t *http, const char *printer_uri, const char *resource, int subscription_id, const char *device_uuid);
static int fetch_job(http_t *http, const char *printer_uri, const char *resource, int job_id, const char *device_uri, const char *device_uuid, ipp_t *device_attrs);
static ipp_t *get_device_attrs(const char *device_uri);
static void make_uuid(const char *device_uri, char *uuid, size_t uuidsize);
static const char *password_cb(const char *prompt, http_t *http, const char *method, const char *resource, void *user_data);
static void *proxy_jobs(proxy_info_t *info);
static int register_printer(http_t *http, const char *printer_uri, const char *resource, const char *device_uri, const char *device_uuid);
static void run_printer(http_t *http, const char *printer_uri, const char *resource, int subscription_id, const char *device_uri, const char *device_uuid);
static void sighandler(int sig);
static int update_device_attrs(http_t *http, const char *printer_uri, const char *resource, const char *device_uuid, ipp_t *old_attrs, ipp_t *new_attrs);
static void usage(int status) __attribute__((noreturn));
/*
* 'main()' - Main entry for ippproxy.
*/
int /* O - Exit status */
main(int argc, /* I - Number of command-line arguments */
char *argv[]) /* I - Command-line arguments */
{
int i; /* Looping var */
char *opt, /* Current option */
*device_uri = NULL, /* Device URI */
*password = <PASSWORD>, /* Password, if any */
*printer_uri = NULL; /* Infrastructure printer URI */
cups_dest_t *dest; /* Destination for printer URI */
http_t *http; /* Connection to printer */
char resource[1024]; /* Resource path */
int subscription_id; /* Event subscription ID */
char device_uuid[45]; /* Device UUID URN */
/*
* Parse command-line...
*/
for (i = 1; i < argc; i ++)
{
if (argv[i][0] == '-' && argv[i][1] != '-')
{
for (opt = argv[i] + 1; *opt; opt ++)
{
switch (*opt)
{
case 'd' : /* -d device-uri */
i ++;
if (i >= argc)
{
fputs("ippproxy: Missing device URI after '-d' option.\n", stderr);
usage(1);
}
device_uri = argv[i];
break;
case 'p' : /* -p password */
i ++;
if (i >= argc)
{
fputs("ippproxy: Missing password after '-p' option.\n", stderr);
usage(1);
}
password = argv[i];
break;
case 'u' : /* -u user */
i ++;
if (i >= argc)
{
fputs("ippproxy: Missing username after '-u' option.\n", stderr);
usage(1);
}
cupsSetUser(argv[i]);
break;
case 'v' : /* Be verbose */
verbosity ++;
break;
default :
fprintf(stderr, "ippproxy: Unknown option '-%c'.\n", *opt);
usage(1);
break;
}
}
}
else if (!strcmp(argv[i], "--help"))
usage(0);
else if (printer_uri)
{
fprintf(stderr, "ippproxy: Unexpected option '%s'.\n", argv[i]);
usage(1);
}
else
printer_uri = argv[i];
}
if (!printer_uri)
usage(1);
if (!device_uri)
{
fputs("ippproxy: Must specify '-d device-uri'.\n", stderr);
usage(1);
}
if (!password)
password = getenv("IPPPROXY_PASSWORD");
if (password)
cupsSetPasswordCB2(password_cb, password);
make_uuid(device_uri, device_uuid, sizeof(device_uuid));
/*
* Connect to the infrastructure printer...
*/
dest = cupsGetDestWithURI("infra", printer_uri);
while ((http = cupsConnectDest(dest, CUPS_DEST_FLAGS_NONE, 30000, NULL, resource, sizeof(resource), NULL, NULL)) == NULL)
{
fprintf(stderr, "ippproxy: Infrastructure printer at '%s' is not responding, retrying in 30 seconds...\n", printer_uri);
sleep(30);
}
cupsFreeDests(1, dest);
/*
* Register the printer and wait for jobs to process...
*/
signal(SIGHUP, sighandler);
signal(SIGINT, sighandler);
signal(SIGTERM, sighandler);
if ((subscription_id = register_printer(http, printer_uri, resource, device_uri, device_uuid)) == 0)
{
httpClose(http);
return (1);
}
run_printer(http, printer_uri, resource, subscription_id, device_uri, device_uuid);
deregister_printer(http, printer_uri, resource, subscription_id, device_uuid);
httpClose(http);
return (0);
}
/*
* 'attrs_are_equal()' - Compare two attributes for equality.
*/
static int /* O - 1 if equal, 0 otherwise */
attrs_are_equal(ipp_attribute_t *a, /* I - First attribute */
ipp_attribute_t *b) /* I - Second attribute */
{
int i, /* Looping var */
count; /* Number of values */
ipp_tag_t tag; /* Type of value */
/*
* Check that both 'a' and 'b' point to something first...
*/
if ((a != NULL) != (b != NULL))
return (0);
if (a == NULL && b == NULL)
return (1);
/*
* Check that 'a' and 'b' are of the same type with the same number
* of values...
*/
if ((tag = ippGetValueTag(a)) != ippGetValueTag(b))
return (0);
if ((count = ippGetCount(a)) != ippGetCount(b))
return (0);
/*
* Compare values...
*/
switch (tag)
{
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
for (i = 0; i < count; i ++)
if (ippGetInteger(a, i) != ippGetInteger(b, i))
return (0);
break;
case IPP_TAG_BOOLEAN :
for (i = 0; i < count; i ++)
if (ippGetBoolean(a, i) != ippGetBoolean(b, i))
return (0);
break;
case IPP_TAG_KEYWORD :
for (i = 0; i < count; i ++)
if (strcmp(ippGetString(a, i, NULL), ippGetString(b, i, NULL)))
return (0);
break;
default :
return (0);
}
/*
* If we get this far we must be the same...
*/
return (1);
}
/*
* 'compare_jobs()' - Compare two jobs.
*/
static int
compare_jobs(proxy_job_t *a, /* I - First job */
proxy_job_t *b) /* I - Second job */
{
return (a->remote_job_id - b->remote_job_id);
}
/*
* 'copy_job()' - Create a job of a job.
*/
static proxy_job_t * /* O - New job */
copy_job(proxy_job_t *src) /* I - Original job */
{
proxy_job_t *dst; /* New job */
if ((dst = malloc(sizeof(proxy_job_t))) != NULL)
memcpy(dst, src, sizeof(proxy_job_t));
return (dst);
}
/*
* 'create_media_col()' - Create a media-col value.
*/
static ipp_t * /* O - media-col collection */
create_media_col(const char *media, /* I - Media name */
const char *source, /* I - Media source */
const char *type, /* I - Media type */
int width, /* I - x-dimension in 2540ths */
int length, /* I - y-dimension in 2540ths */
int margins) /* I - Value for margins */
{
ipp_t *media_col = ippNew(), /* media-col value */
*media_size = create_media_size(width, length);
/* media-size value */
char media_key[256]; /* media-key value */
if (type && source)
snprintf(media_key, sizeof(media_key), "%s_%s_%s%s", media, source, type, margins == 0 ? "_borderless" : "");
else if (type)
snprintf(media_key, sizeof(media_key), "%s__%s%s", media, type, margins == 0 ? "_borderless" : "");
else if (source)
snprintf(media_key, sizeof(media_key), "%s_%s%s", media, source, margins == 0 ? "_borderless" : "");
else
snprintf(media_key, sizeof(media_key), "%s%s", media, margins == 0 ? "_borderless" : "");
ippAddString(media_col, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-key", NULL,
media_key);
ippAddCollection(media_col, IPP_TAG_PRINTER, "media-size", media_size);
ippAddString(media_col, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-size-name", NULL, media);
ippAddInteger(media_col, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"media-bottom-margin", margins);
ippAddInteger(media_col, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"media-left-margin", margins);
ippAddInteger(media_col, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"media-right-margin", margins);
ippAddInteger(media_col, IPP_TAG_PRINTER, IPP_TAG_INTEGER,
"media-top-margin", margins);
if (source)
ippAddString(media_col, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-source", NULL, source);
if (type)
ippAddString(media_col, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-type", NULL, type);
ippDelete(media_size);
return (media_col);
}
/*
* 'create_media_size()' - Create a media-size value.
*/
static ipp_t * /* O - media-col collection */
create_media_size(int width, /* I - x-dimension in 2540ths */
int length) /* I - y-dimension in 2540ths */
{
ipp_t *media_size = ippNew(); /* media-size value */
ippAddInteger(media_size, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "x-dimension",
width);
ippAddInteger(media_size, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "y-dimension",
length);
return (media_size);
}
/*
* 'deregister_printer()' - Unregister the output device and cancel the printer subscription.
*/
static void
deregister_printer(
http_t *http, /* I - Connection to printer */
const char *printer_uri, /* I - Printer URI */
const char *resource, /* I - Resource path */
int subscription_id, /* I - Subscription ID */
const char *device_uuid) /* I - Device UUID */
{
ipp_t *request; /* IPP request */
/*
* Deregister the output device...
*/
request = ippNewRequest(IPP_OP_DEREGISTER_OUTPUT_DEVICE);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "output-device-uuid", NULL, device_uuid);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippDelete(cupsDoRequest(http, request, resource));
/*
* Then cancel the subscription we are using...
*/
request = ippNewRequest(IPP_OP_CANCEL_SUBSCRIPTION);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-subscription-id", subscription_id);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippDelete(cupsDoRequest(http, request, resource));
}
/*
* 'fetch_job()' - Fetch and print a job.
*/
static int /* O - 1 on success, 0 on failure */
fetch_job(http_t *http, /* I - Connection to printer */
const char *printer_uri, /* I - Printer URI */
const char *resource, /* I - Resource path */
int job_id, /* I - Job ID */
const char *device_uri, /* I - Device URI */
const char *device_uuid, /* I - Device UUID */
ipp_t *device_attrs) /* I - Device attributes */
{
(void)http;
(void)printer_uri;
(void)resource;
(void)job_id;
(void)device_uri;
(void)device_uuid;
(void)device_attrs;
return (0);
}
/*
* 'get_device_attrs()' - Get current attributes for a device.
*/
static ipp_t * /* O - IPP attributes */
get_device_attrs(const char *device_uri)/* I - Device URI */
{
ipp_t *response = NULL; /* IPP attributes */
if (!strncmp(device_uri, "ipp://", 6) || !strncmp(device_uri, "ipps://", 7))
{
/*
* Query the IPP printer...
*/
cups_dest_t *dest; /* Destination for printer URI */
http_t *http; /* Connection to printer */
char resource[1024]; /* Resource path */
ipp_t *request; /* Get-Printer-Attributes request */
/*
* Connect to the printer...
*/
dest = cupsGetDestWithURI("device", device_uri);
while ((http = cupsConnectDest(dest, CUPS_DEST_FLAGS_NONE, 30000, NULL, resource, sizeof(resource), NULL, NULL)) == NULL)
{
fprintf(stderr, "ippproxy: Device at '%s' is not responding, retrying in 30 seconds...\n", device_uri);
sleep(30);
}
cupsFreeDests(1, dest);
/*
* Get the attributes...
*/
request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, device_uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", (int)(sizeof(printer_attrs) / sizeof(printer_attrs[0])), NULL, printer_attrs);
response = cupsDoRequest(http, request, resource);
if (cupsLastError() >= IPP_STATUS_ERROR_BAD_REQUEST)
{
fprintf(stderr, "ippproxy: Device at '%s' returned error: %s\n", device_uri, cupsLastErrorString());
ippDelete(response);
response = NULL;
}
httpClose(http);
}
else
{
/*
* Must be a socket-based HP PCL laser printer, report just
* standard size information...
*/
int i; /* Looping var */
ipp_attribute_t *media_col_database,
/* media-col-database value */
*media_size_supported;
/* media-size-supported value */
ipp_t *media_col; /* media-col-default value */
static const int media_col_sizes[][2] =
{ /* Default media-col sizes */
{ 21590, 27940 }, /* Letter */
{ 21590, 35560 }, /* Legal */
{ 21000, 29700 } /* A4 */
};
static const char * const media_col_supported[] =
{ /* media-col-supported values */
"media-bottom-margin",
"media-left-margin",
"media-right-margin",
"media-size",
"media-size-name",
"media-top-margin"
};
static const char * const media_supported[] =
{ /* Default media sizes */
"na_letter_8.5x11in", /* Letter */
"na_legal_8.5x14in", /* Legal */
"iso_a4_210x297mm" /* A4 */
};
static const int quality_supported[] =
{ /* print-quality-supported values */
IPP_QUALITY_DRAFT,
IPP_QUALITY_NORMAL,
IPP_QUALITY_HIGH
};
static const int resolution_supported[] =
{ /* printer-resolution-supported values */
300,
600
};
static const char * const sides_supported[] =
{ /* sides-supported values */
"one-sided",
"two-sided-long-edge",
"two-sided-short-edge"
};
response = ippNew();
ippAddRange(response, IPP_TAG_PRINTER, "copies-supported", 1, 1);
ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_MIMETYPE, "document-format-supported", NULL, "application/vnd.hp-pcl");
ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-bottom-margin-supported", 635);
media_col_database = ippAddCollections(response, IPP_TAG_PRINTER, "media-col-database", (int)(sizeof(media_col_sizes) / sizeof(media_col_sizes[0])), NULL);
for (i = 0; i < (int)(sizeof(media_col_sizes) / sizeof(media_col_sizes[0])); i ++)
{
media_col = create_media_col(media_supported[i], NULL, NULL, media_col_sizes[i][0], media_col_sizes[i][1], 635);
ippSetCollection(response, &media_col_database, i, media_col);
ippDelete(media_col);
}
media_col = create_media_col(media_supported[0], NULL, NULL, media_col_sizes[0][0], media_col_sizes[0][1], 635);
ippAddCollection(response, IPP_TAG_PRINTER, "media-col-default", media_col);
ippDelete(media_col);
media_col = create_media_col(media_supported[0], NULL, NULL, media_col_sizes[0][0], media_col_sizes[0][1], 635);
ippAddCollection(response, IPP_TAG_PRINTER, "media-col-ready", media_col);
ippDelete(media_col);
ippAddStrings(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-col-supported", (int)(sizeof(media_col_supported) / sizeof(media_col_supported[0])), NULL, media_col_supported);
ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-default", NULL, media_supported[0]);
ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-left-margin-supported", 635);
ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-ready", NULL, media_supported[0]);
ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-right-margin-supported", 635);
media_size_supported = ippAddCollections(response, IPP_TAG_PRINTER, "media-size-supported", (int)(sizeof(media_col_sizes) / sizeof(media_col_sizes[0])), NULL);
for (i = 0;
i < (int)(sizeof(media_col_sizes) / sizeof(media_col_sizes[0]));
i ++)
{
ipp_t *size = create_media_size(media_col_sizes[i][0], media_col_sizes[i][1]);
ippSetCollection(response, &media_size_supported, i, size);
ippDelete(size);
}
ippAddStrings(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "media-supported", (int)(sizeof(media_supported) / sizeof(media_supported[0])), NULL, media_supported);
ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "media-top-margin-supported", 635);
ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "print-color-mode-default", NULL, "monochrome");
ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "print-color-mode-supported", NULL, "monochrome");
ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "print-quality-default", IPP_QUALITY_NORMAL);
ippAddIntegers(response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "print-quality-supported", (int)(sizeof(quality_supported) / sizeof(quality_supported[0])), quality_supported);
ippAddResolution(response, IPP_TAG_PRINTER, "printer-resolution-default", IPP_RES_PER_INCH, 300, 300);
ippAddResolutions(response, IPP_TAG_PRINTER, "printer-resolution-supported", (int)(sizeof(resolution_supported) / sizeof(resolution_supported[0])), IPP_RES_PER_INCH, resolution_supported, resolution_supported);
ippAddInteger(response, IPP_TAG_PRINTER, IPP_TAG_ENUM, "printer-state", IPP_PSTATE_IDLE);
ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "printer-state-reasons", NULL, "none");
ippAddString(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "sides-default", NULL, "two-sided-long-edge");
ippAddStrings(response, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "sides-supported", (int)(sizeof(sides_supported) / sizeof(sides_supported[0])), NULL, sides_supported);
}
return (response);
}
/*
* 'make_uuid()' - Make a RFC 4122 URN UUID from the device URI.
*
* NULL device URIs are (appropriately) mapped to "file://hostname/dev/null".
*/
static void
make_uuid(const char *device_uri, /* I - Device URI or NULL */
char *uuid, /* I - UUID string buffer */
size_t uuidsize) /* I - Size of UUID buffer */
{
char nulluri[1024]; /* NULL URI buffer */
unsigned char sha256[32]; /* SHA-256 hash */
/*
* Use "file://hostname/dev/null" if the device URI is NULL...
*/
if (!device_uri)
{
char host[1024]; /* Hostname */
httpGetHostname(NULL, host, sizeof(host));
httpAssembleURI(HTTP_URI_CODING_ALL, nulluri, sizeof(nulluri), "file", NULL, host, 0, "/dev/null");
device_uri = nulluri;
}
/*
* Build a version 3 UUID conforming to RFC 4122 based on the
* SHA-256 hash of the device URI
*/
cupsHashData("sha-256", device_uri, strlen(device_uri), sha256, sizeof(sha256));
snprintf(uuid, uuidsize, "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", sha256[0], sha256[1], sha256[2], sha256[3], sha256[4], sha256[5], (sha256[6] & 15) | 0x30, sha256[7], (sha256[8] & 0x3f) | 0x40, sha256[9], sha256[10], sha256[11], sha256[12], sha256[13], sha256[14], sha256[15]);
fprintf(stderr, "ippproxy: UUID for '%s' is '%s'.\n", device_uri, uuid);
}
/*
* 'password_cb()' - Password callback.
*/
static const char * /* O - Password string */
password_cb(const char *prompt, /* I - Prompt (unused) */
http_t *http, /* I - Connection (unused) */
const char *method, /* I - Method (unused) */
const char *resource, /* I - Resource path (unused) */
void *user_data) /* I - Password string */
{
(void)prompt;
(void)http;
(void)method;
(void)resource;
return ((char *)user_data);
}
/*
* 'proxy_jobs()' - Relay jobs to the local printer.
*/
static void * /* O - Thread exit status */
proxy_jobs(proxy_info_t *info) /* I - Printer and device info */
{
(void)info;
for (;;)
{
_cupsMutexLock(&jobs_mutex);
_cupsCondWait(&jobs_cond, &jobs_mutex, 0.0);
_cupsMutexUnlock(&jobs_mutex);
}
return (NULL);
}
/*
* 'register_printer()' - Register the printer (output device) with the Infrastructure Printer.
*/
static int /* O - Subscription ID */
register_printer(
http_t *http, /* I - Connection to printer */
const char *printer_uri, /* I - Printer URI */
const char *resource, /* I - Resource path */
const char *device_uri, /* I - Device URI, if any */
const char *device_uuid) /* I - Device UUID */
{
ipp_t *request, /* IPP request */
*response; /* IPP response */
ipp_attribute_t *attr; /* Attribute in response */
int subscription_id = 0; /* Subscription ID */
static const char * const events[] = /* Events to monitor */
{
"document-config-change",
"document-state-change",
"job-config-change",
"job-state-change",
"printer-config-change",
"printer-state-change"
};
(void)device_uri;
(void)device_uuid;
/*
* Create a printer subscription to monitor for events...
*/
request = ippNewRequest(IPP_OP_CREATE_PRINTER_SUBSCRIPTION);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippAddString(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD, "notify-pull-method", NULL, "ippget");
ippAddStrings(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD, "notify-events", (int)(sizeof(events) / sizeof(events[0])), NULL, events);
ippAddInteger(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER, "notify-lease-duration", 0);
response = cupsDoRequest(http, request, resource);
if (cupsLastError() != IPP_STATUS_OK)
{
fprintf(stderr, "ippproxy: Unable to monitor events on '%s': %s\n", printer_uri, cupsLastErrorString());
return (0);
}
if ((attr = ippFindAttribute(response, "notify-subscription-id", IPP_TAG_INTEGER)) != NULL)
{
subscription_id = ippGetInteger(attr, 0);
}
else
{
fprintf(stderr, "ippproxy: Unable to monitor events on '%s': No notify-subscription-id returned.\n", printer_uri);
}
ippDelete(response);
return (subscription_id);
}
/*
* 'run_printer()' - Run the printer until no work remains.
*/
static void
run_printer(
http_t *http, /* I - Connection to printer */
const char *printer_uri, /* I - Printer URI */
const char *resource, /* I - Resource path */
int subscription_id, /* I - Subscription ID */
const char *device_uri, /* I - Device URI, if any */
const char *device_uuid) /* I - Device UUID */
{
ipp_t *device_attrs, /* Device attributes */
*request, /* IPP request */
*response; /* IPP response */
ipp_attribute_t *attr; /* IPP attribute */
const char *name, /* Attribute name */
*event; /* Current event */
int job_id; /* Job ID, if any */
ipp_jstate_t job_state; /* Job state, if any */
int seq_number = 1; /* Current event sequence number */
int get_interval; /* How long to sleep */
proxy_info_t info; /* Information for proxy thread */
_cups_thread_t jobs_thread; /* Job proxy processing thread */
/*
* Initialize the local jobs array...
*/
jobs = cupsArrayNew3((cups_array_func_t)compare_jobs, NULL, NULL, 0, (cups_acopy_func_t)copy_job, (cups_afree_func_t)free);
info.printer_uri = printer_uri;
info.device_uri = device_uri;
info.device_uuid = device_uuid;
jobs_thread = _cupsThreadCreate((_cups_thread_func_t)proxy_jobs, &info);
/*
* Query the printer...
*/
device_attrs = get_device_attrs(device_uri);
/*
* Register the output device...
*/
if (!update_device_attrs(http, printer_uri, resource, device_uuid, NULL, device_attrs))
return;
while (!stop_running)
{
/*
* See if we have any work to do...
*/
request = ippNewRequest(IPP_OP_GET_NOTIFICATIONS);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-subscription-ids", subscription_id);
ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-sequence-numbers", seq_number);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippAddBoolean(request, IPP_TAG_OPERATION, "notify-wait", 1);
response = cupsDoRequest(http, request, resource);
if ((attr = ippFindAttribute(response, "notify-get-interval", IPP_TAG_INTEGER)) != NULL)
get_interval = ippGetInteger(attr, 0);
else
get_interval = 30;
for (attr = ippFirstAttribute(response); attr; attr = ippNextAttribute(response))
{
if (ippGetGroupTag(attr) != IPP_TAG_EVENT_NOTIFICATION || !ippGetName(attr))
continue;
event = NULL;
job_id = 0;
job_state = IPP_JSTATE_PENDING;
while (ippGetGroupTag(attr) == IPP_TAG_EVENT_NOTIFICATION && (name = ippGetName(attr)) != NULL)
{
if (!strcmp(name, "notify-subscribed-event") && ippGetValueTag(attr) == IPP_TAG_KEYWORD)
event = ippGetString(attr, 0, NULL);
else if (!strcmp(name, "notify-job-id") && ippGetValueTag(attr) == IPP_TAG_INTEGER)
job_id = ippGetInteger(attr, 0);
else if (!strcmp(name, "job-state") && ippGetValueTag(attr) == IPP_TAG_ENUM)
job_state = (ipp_jstate_t)ippGetInteger(attr, 0);
else if (!strcmp(name, "notify-sequence-number") && ippGetValueTag(attr) == IPP_TAG_INTEGER)
{
int new_seq = ippGetInteger(attr, 0);
if (new_seq > seq_number)
seq_number = new_seq;
}
attr = ippNextAttribute(response);
}
if (event)
{
if (!strcmp(event, "job-fetchable") && job_id)
{
/* TODO: queue up fetches */
fetch_job(http, printer_uri, resource, job_id, device_uri, device_uuid, device_attrs);
}
else if (!strcmp(event, "job-state-changed") && job_id)
{
/* TODO: Support cancellation */
if (job_state == IPP_JSTATE_CANCELED || job_state == IPP_JSTATE_ABORTED)
{
/* Cancel job locally if it is printing... */
}
}
}
}
/*
* Pause before our next poll of the Infrastructure Printer...
*/
if (get_interval > 0 && get_interval < 3600)
sleep((unsigned)get_interval);
else
sleep(30);
}
/*
* Stop the job proxy thread...
*/
_cupsThreadCancel(jobs_thread);
_cupsThreadWait(jobs_thread);
}
/*
* 'sighandler()' - Handle termination signals so we can clean up...
*/
static void
sighandler(int sig) /* I - Signal */
{
(void)sig;
stop_running = 1;
}
/*
* 'update_device_attrs()' - Update device attributes on the server.
*/
static int /* O - 1 on success, 0 on failure */
update_device_attrs(
http_t *http, /* I - Connection to server */
const char *printer_uri, /* I - Printer URI */
const char *resource, /* I - Resource path */
const char *device_uuid, /* I - Device UUID */
ipp_t *old_attrs, /* I - Old attributes */
ipp_t *new_attrs) /* I - New attributes */
{
int i, /* Looping var */
result; /* Result of comparison */
ipp_t *request; /* IPP request */
ipp_attribute_t *attr; /* New attribute */
const char *name; /* New attribute name */
/*
* Update the configuration of the output device...
*/
request = ippNewRequest(IPP_OP_UPDATE_OUTPUT_DEVICE_ATTRIBUTES);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "output-device-uuid", NULL, device_uuid);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
for (attr = ippFirstAttribute(new_attrs); attr; attr = ippNextAttribute(new_attrs))
{
/*
* Add any attributes that have changed...
*/
if (ippGetGroupTag(attr) != IPP_TAG_PRINTER || (name = ippGetName(attr)) == NULL)
continue;
for (i = 0, result = 1; i < (int)(sizeof(printer_attrs) / sizeof(printer_attrs[0])) && result > 0; i ++)
{
if ((result = strcmp(name, printer_attrs[i])) == 0)
{
/*
* This is an attribute we care about...
*/
if (!attrs_are_equal(ippFindAttribute(old_attrs, name, ippGetValueTag(attr)), attr))
ippCopyAttribute(request, attr, 1);
}
}
}
ippDelete(cupsDoRequest(http, request, resource));
if (cupsLastError() != IPP_STATUS_OK)
{
fprintf(stderr, "ippproxy: Unable to update the output device with '%s': %s\n", printer_uri, cupsLastErrorString());
return (0);
}
return (1);
}
/*
* 'usage()' - Show program usage and exit.
*/
static void
usage(int status) /* O - Exit status */
{
puts("Usage: ippproxy [options] printer-uri");
puts("Options:");
puts(" -d device-uri Specify local printer device URI.");
puts(" -p password Password for authentication.");
puts(" (Also IPPPROXY_PASSWORD environment variable)");
puts(" -u username Username for authentication.");
puts(" -v Be verbose.");
puts(" --help Show this help.");
exit(status);
}
| 82275ca2fa42f8a5f7c72ff4198aa14ad2d07370 | [
"C"
] | 2 | C | lzpfmh/ippsample | 3af49524afdd5d9c9f107fbb9e500cd6cda305a2 | f659d4cf2cc314679351be067cd5d02c3034506e |
refs/heads/master | <repo_name>CUBoulder-2017-IML4HCI/Tentacle<file_sep>/tentacle-stop-script.sh
#
pkill -9 -f TentacleControl
pkill -9 -f own_with_weki
<file_sep>/tentacle-start-script.sh
# NOTE: Wekinator must already be running
read -p "Confirm that wekinator is already running."
# java -jar ~/Downloads/weki/WekiMini.jar &
# Start Tentacle Control (Stepper)
python ./control/TentacleControl.py &
# Myo Interface (Requires wekinator)
python ./myo-raw/own.py &
python ./myo-raw/own_with_weki.py &
<file_sep>/myo-raw/own.py
from __future__ import print_function
from common import *
from myo_raw import MyoRaw
import OSC
wek = OSC.OSCClient()
wek.connect(('127.0.0.1', 6448))
tenta = OSC.OSCClient()
tenta.connect(('127.0.0.1', 12000))
def send(data, dest, address):
oscmsg = OSC.OSCMessage()
oscmsg.setAddress(address)
for elem in data:
oscmsg.append(float(elem))
dest.send(oscmsg)
#if dest == wek:
#print(oscmsg)
#print(data)
def imu(quat,acc,gyro):
#print(quat,acc,gyro)
#print ("quat: ", quat, " type: ", type(quat))
send(quat, wek, "/wek/inputs")
def pose(p):
print(p)
def emg(emg, moving):
emgdat = (sum(emg)/float(len(emg)),)
#print ("emgdat: ", emgdat, " type: ", type(emgdat))
send(emgdat, tenta, "/tenta_emg")
if __name__ == '__main__':
m = MyoRaw()
#m.add_imu_handler(print)
m.add_imu_handler(imu)
#m.add_pose_handler(pose)
m.add_emg_handler(emg)
m.connect()
while True:
m.run()
| a4a57d37793f232da0b6d289aa9f62a3d3c72882 | [
"Python",
"Shell"
] | 3 | Shell | CUBoulder-2017-IML4HCI/Tentacle | c1da8688fd9b1ccf2b37a1a6574cc7edb6c935d5 | fbcfcc8b008616090f8b526be25a64fb5de8c9e8 |
refs/heads/main | <file_sep>import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
isEdit: true,
isLoading: false,
todos: [],
},
actions: {
async fetchTodos({ commit }) {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/todos"
);
commit("setTodos", response.data);
},
async addTodo({ commit }, title) {
commit("setIsLoading", true);
const response = await axios.post(
"https://jsonplaceholder.typicode.com/todos",
{ title, completed: false }
);
console.log(response);
commit("setAddTodo", response.data);
commit("setIsLoading", false);
return response;
},
async deleteTodo({ commit }, id) {
const res = await axios.delete(
`https://jsonplaceholder.typicode.com/todos/${id}`
);
commit("deleteTodo", id);
return res;
},
async updateTodo({ commit }, { title, id }) {
const response = await axios.put(
`https://jsonplaceholder.typicode.com/todos/${id}`,
{
title,
}
);
commit("updateTodo", response.data);
return response;
},
setIsEdit({ commit }) {
commit("setIsEdit");
},
},
mutations: {
setTodos: (state, todos) => {
return (state.todos = todos);
},
setAddTodo: (state, todo) => state.todos.unshift(todo),
deleteTodo: (state, id) =>
(state.todos = state.todos.filter((todo) => todo.id !== id)),
updateTodo: (state, data) => {
// console.log({ title, id });
state.todos = state.todos.map((todo) => {
if (todo.id === data.id) {
todo.title = data.title;
return todo;
} else {
return todo;
}
});
},
setIsLoading: (state, status) => (state.isLoading = status),
// setIsEdit: (state) => (state.isEdit = !state.isEdit),
},
getters: {
allTodos: (state) => state.todos,
isLoading: (state) => state.isLoading,
// isEdit: (state) => state.isEdit,
},
});
| 99aef49553012523c7738b9ad1762391bd8899f7 | [
"JavaScript"
] | 1 | JavaScript | NaemBhuiyan/todo-with-vue | 9c809d6392271b97469f41cd2112805eba9c7058 | 2575d647c7071c77f43a33ac074df95f4154116c |
refs/heads/master | <file_sep>#!/bin/bash
./bluetooth_battery.py 88:D0:39:6C:A8:AF.1
<file_sep>#!/bin/bash
# Note: font awesome icon size is determined by font size
echo "Hello world! | kargos.fa_icon=globe size=16";
<file_sep>#!/bin/bash
temp0=$(sensors | grep 'Tctl:' | cut -c '16-17')
temp_gpu=$(sensors | grep 'edge:' | cut -c '16-17')
# echo "<table><tr><td bgcolor='#ff0000'>CPU</td><td>GPU</td></tr><tr><td>${temp0%%.*}</td><td>${temp_gpu}</td></tr></table>"
# echo "<div><font size='1'>CPU</font><br/><font size='2'>${temp0%%.*}°</font></div><div><font size='1'>GPU</font><br/><font size='2'>${temp_gpu}°</font></div> | font=Inconsolata-Condensed"
echo " <font color='yellow' size='2'>CPU GPU</font> <br><font size='3'> ${temp0%%.*} ${temp_gpu}</font>| font=Inconsolata Condensed"
# echo "---"
# echo ""
# echo " <br><font size='1'>CPU GPU HDD</font><br>${temp0%%.*}° ${gpu_temp}° ${hdd_temp}°| font=Hack-Regular size=10 "
<file_sep>#!/usr/bin/env python
import sys
# sys.setdefaultencoding() does not exist, here!
import urllib2
import xml.etree.ElementTree as ET
reload(sys) # Reload does the trick!
sys.setdefaultencoding('UTF8')
# limit the number of items per url. -1= no limit
MAX=-1
urls = [
# (url,icon). icon maybe empty string
('https://dot.kde.org/rss.xml', 'https://dot.kde.org/sites/all/themes/neverland/logo.png'),
('https://dot.kde.org/rss.xml', '')
]
print "---"
print "Refresh|refresh=true iconName=view-refresh"
for (url, icon) in urls:
response = urllib2.urlopen(url)
html = response.read()
try:
root = ET.fromstring(html)
count = 0
for item in root.findall('.//item'):
if count == MAX:
break
count += 1
title = item.find('title').text
link = item.find('link').text
line = title.replace('|', '/') + '| href=' + link
if (icon !=None and icon != ''):
line+=' imageWidth=22 imageHeight=22 imageURL='+icon
else:
line+=' iconName=application-rss+xml'
print line
print line + ' dropdown=false'
except:
line = 'error fetching '+url+'|'
if (icon !=None and icon != ''):
line+=' imageWidth=22 imageHeight=22 imageURL='+icon
else:
line+=' iconName=application-rss+xml'
print line
print line + ' dropdown=false'
<file_sep>#!/bin/bash
echo "Hello world! | kargos.fa_icon=globe size=16";
echo "---";
echo "Refresh|refresh=true iconName=view-refresh";
| 333fd3a6176d316e88c70955a054f557c7b9a95c | [
"Python",
"Shell"
] | 5 | Shell | aftadizca/MyLinuxScript | c280323706ac9d12d504e12b6bf4e756d9b5eca7 | 69cf0fbe8acfd39ca31084196633ca5e5a1afadb |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import cv2
import numpy as np
import os
import glob
import re
from PIL import Image
import pytesseract
import logging
import aircv as ac
logging.basicConfig(level=1,format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: '
'%(message)s')
#单张图片增加对比度和亮度
def addWeight(img, alpha = 1.3, gamma = 10):
mask = np.zeros(img.shape, dtype=np.uint8)
alpha = alpha
beta = 1 - alpha
gamma = gamma
img_dst = cv2.addWeighted(img, alpha, mask, beta, gamma)
return img_dst
#批量图片增加对比度和亮度
def addWeights(src_path, tgt_path, suffix):
if not os.path.exists(src_path):
logging.error('The path [%s] is not exist' %src_path)
if not os.path.exists(tgt_path):
logging.error('The path [%s] is not exist' %tgt_path)
pic_files = glob.glob(os.path.join(src_path, suffix))
total = len(pic_files)
counter = 1
for pic_file in pic_files:
logging.log(1, "Total of %d/%d" %(counter, total))
img = cv2.imread(pic_file)
img_dst = addWeight(img)
img_dst_file = tgt_path + r'/' + os.path.basename(pic_file)
cv2.imwrite(img_dst_file, img_dst)
counter += 1
#获取证件编码
def getCode(text):
if text is None:
return None
# 去掉text中的引号
text = text.replace('\'', '@@@')
text = text.replace('\"', '@@@')
# 去掉空格
text = text.replace(' ', '')
# print(text)
# 匹配统一社会信用代码
code = re.findall(r'[0-9][0-9]44030[0-9A-Z]{11}', text.upper())
# a匹配食品经营许可证号
if len(code) < 1:
code = re.findall(r'JY[0-9]44030[0-9]{8}', text.upper())
# 匹配餐饮服务许可证
if len(code) < 1:
code = re.findall(r'20[1-2][0-9]44030[0-9]{7}', text.upper())
# 医配食品流通许可证
if len(code) < 1:
code = re.findall(r'SP44030[0-9][1-2][0-9]{9}', text.upper())
# 匹配营业执照号 -注册号
if len(code) < 1:
code = re.findall(r'44030[0-9]{10}', text.upper())
if len(code) > 0:
code = code[0]
else:
code = None
return code
#使用tesserect解析图片
def parsePics(src_path, suffix, tgt_path = None):
if not os.path.exists(src_path):
logging.error('The path [%s] is not exist' %src_path)
pic_files = glob.glob(os.path.join(src_path, suffix))
total = len(pic_files)
counter = 1
for pic_file in pic_files:
img = Image.open(pic_file)
text = pytesseract.image_to_string(img, lang='chi_sim')
code = getCode(text)
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
if code is not None:
mid_path = '/01'
else:
mid_path = '/02'
#照片/添加的文字/左上角坐标/字体/字体大小/颜色/字体粗细
cv2.putText(img, code, (100,100), cv2.FONT_HERSHEY_COMPLEX,2,(0,0,255),2)
if tgt_path is not None:
logging.log(1, "Total of %d/%d" % (counter, total))
img_dst_file = tgt_path + mid_path + r'/' + os.path.basename(pic_file)
cv2.imwrite(img_dst_file, img)
counter += 1
def picMatch(img, templ):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
templ_gray = cv2.cvtColor(templ, cv2.COLOR_BGR2GRAY)
h, w = templ_gray.shape[:2]
res = cv2.matchTemplate(img, templ, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
print(templ.shape)
print(img_gray.shape)
print(top_left, bottom_right)
cv2.rectangle(img, top_left, bottom_right, 0, 2)
cv2.imwrite('./template/1.jpg', img)
# cv2.imshow('test', img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
def resize(img, width = None, height = None, inter = cv2.INTER_AREA):
dim = None
h, w = img.shape[:2]
if width is None and height is None:
return img
if width is None:
r = height / height
dim = (int(w * r), height)
else:
r = width / w
dim = (width, int(h * r))
resized = cv2.resize(img, dim, interpolation= inter)
return resized
if __name__ == '__main__':
src_path = r'E:\work\pingan\05_code\pic_recognition\com\pingan\pic_rec\source'
tgt_path = r'E:\work\pingan\05_code\pic_recognition\com\pingan\pic_rec\target'
parse_path = r'E:\work\pingan\05_code\pic_recognition\com\pingan\pic_rec\parse'
suffix = r'*.jpg'
text = ''
# addWeights(src_path, tgt_path, suffix)
# print(getCode('JY24403000001343'))
# parsePics(tgt_path, suffix, parse_path)
img_file = r'./template/002_bak.jpg'
templ_file = r'./template/template_06.jpg'
queryImage = cv2.imread(img_file)
trainImage = cv2.imread(templ_file)
# img = cv2.circle(queryImage, (460, 120), 2, (0,0,255), 2)
# img = cv2.circle(queryImage, (460+230, 120+230), 2, (0, 0, 255), 2)
# img2 = queryImage[120:120+230, 460:460+230,:]
#
# cv2.imwrite('./template/template_03.jpg', img2)
picMatch(queryImage, trainImage)
# sift = cv2.SIF
# kp1, des1 = sift.detectAndCompute(queryImage, None)
# kp2, des2 = sift.detectAndCompute(trainImage, None)
# FLANN_INDEX_KDTREE = 0
# index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
# search_params = dict(checks=50) # or pass empty dictionary
# flann = cv2.FlannBasedMatcher(index_params, search_params)
# matches = flann.knnMatch(des1, des2, k=2)
# # 找出相匹配的特征点
# for m, n in matches:
# if m.distance < 0.75 * n.distance:
# x1 = kp1[m.queryIdx].pt[0]
# y1 = kp1[m.queryIdx].pt[1]
# x2 = kp2[m.trainIdx].pt[0]
# y2 = kp2[m.trainIdx].pt[1]
# print(x1,y1, x2,y2)
# pos = ac.find_template(queryImage, trainImage)
# print(pos)
#
# pt1 = pos['rectangle'][0]
# pt2 = pos['rectangle'][3]
# print(pt1, pt2)
#
# queryImage = cv2.rectangle(queryImage, pt1, pt2, 255, 2)
# cv2.imwrite('./template/1.jpg', queryImage)
# cv2.imshow('test', queryImage)
cv2.waitKey(0)
cv2.destroyAllWindows()<file_sep># -*- coding: utf-8 -*-
import cv2
import glob
import os
import numpy as np
def imgCrop(img):
h, w = img.shape[:2]
left = int(w//2)
rigth = int(w)
top = int(h//6)
bottom = int(3*h//5)
tgt_img = img[top: bottom, left: rigth]
return tgt_img
if __name__ == '__main__':
# src_path = r'E:\work\pingan_tmp\pic美团\01_食品经营许可证1'
# tgt_path = r'E:\work\pingan_tmp\pic美团\01_食品经营许可证1_1'
src_path = r'E:\work\pingan_tmp\pic美团\01_食品经营许可证2'
tgt_path = r'E:\work\pingan_tmp\pic美团\01_食品经营许可证2_2'
suffix = '*.jpg'
files = glob.glob(os.path.join(src_path, suffix))
total = len(files)
counter = 1
for file in files:
print('total of %d/%d' %(counter, total))
print(file)
# img = cv2.imread(file)
img = cv2.imdecode(np.fromfile(file, dtype=np.uint8), -1)
tgt_img = imgCrop(img)
tgt_img_name = tgt_path + '/' + os.path.basename(file)
# cv2.imwrite(tgt_img_name, tgt_img)
cv2.imencode('.jpg',tgt_img)[1].tofile(tgt_img_name)
counter += 1
#
# img = cv2.imread(pic_file)
# tgt_img = imgCrop(img)
<file_sep>import pytesseract
from PIL import Image
import cv2
def resize(img, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
h, w = img.shape[:2]
if width is None and height is None:
return img
if width is None:
r = height / height
dim = (int(w * r), height)
else:
r = width / w
dim = (width, int(h * r))
resized = cv2.resize(img, dim, interpolation=inter)
return resized
if __name__ == '__main__':
pic_file = r'./template/e24345d5f8df9bb699a817d64a79347d239818.jpg'
img_source = cv2.imread(pic_file)
img_source = resize(img_source, 800)
img_gray = cv2.cvtColor(img_source, cv2.COLOR_BGR2GRAY)
# img_gray = cv2.GaussianBlur(img_gray, (3,3), 1.5)
_, img_threshold = cv2.threshold(img_gray, 140, 255, cv2.THRESH_BINARY)
# img_threshold = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,3,2)
cv2.imshow('source', img_source)
cv2.imshow('img_threshold', img_threshold)
img = Image.fromarray(img_threshold)
# text = pytesseract.image_to_string(img, 'chi_sim')
# print(text)
cv2.waitKey(0)
cv2.destroyAllWindows()<file_sep># -*- coding: utf-8 -*-
import cv2
import tkinter.messagebox as box
import glob
import os
import tkinter as tk
from tkinter import *
import numpy as np
import tkinter.filedialog as fd
import sys
# sys.setdefaultencoding('utf-8')
def resize(img, width = None, height = None, inter = cv2.INTER_AREA):
dim = None
h, w = img.shape[:2]
if width is None and height is None:
return img
if width is None:
r = height / height
dim = (int(w * r), height)
else:
r = width / w
dim = (width, int(h * r))
resized = cv2.resize(img, dim, interpolation= inter)
return resized
def show(event,x,y,flags,param):
global pt1, pt2, img, template_file, template_img, draw_flag, show_flag,coord_flag, calc
if event == cv2.EVENT_LBUTTONDOWN:
pt1 = (x, y)
draw_flag = True
coord_flag = False
elif event == cv2.EVENT_MOUSEMOVE and draw_flag == True:
pt2 = (x, y)
# img = cv2.imread(pics[counter - 1])
# img = resize(img, 800)
img = source_img.copy()
img_msg = '(%dx%d)' % (np.abs(pt2[0] - pt1[0]), np.abs(pt2[1] - pt1[1]))
img = cv2.rectangle(img, (pt1[0] - 2, pt1[1] - 2), (pt2[0] + 2, pt2[1] + 2), (0, 255, 0), 2)
img = cv2.rectangle(img, (pt1[0] - 3, pt1[1] - 30), (pt1[0] + 120, pt1[1]), (0, 255, 0),-1)
img = cv2.putText(img, img_msg, (pt1[0], pt1[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
elif event == cv2.EVENT_MOUSEMOVE and coord_flag == True:
img = source_img.copy()
coord_msg = '(%d,%d)' %(x,y)
img = cv2.putText(img, coord_msg, (x,y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
elif event == cv2.EVENT_LBUTTONDBLCLK:
coord_flag = True
elif event == cv2.EVENT_LBUTTONUP:
draw_flag = False
pt2 = (x, y)
img = source_img.copy()
img = cv2.rectangle(img, (pt1[0], pt1[1]), (pt2[0], pt2[1]), (0, 255, 0), 2)
img_msg = '(%dx%d)' %(np.abs(pt2[0]-pt1[0]), np.abs(pt2[1]-pt1[1]))
if np.abs(pt2[0] - pt1[0]) > 0:
img = cv2.rectangle(img, (pt1[0] - 3, pt1[1] - 30), (pt1[0] + 120, pt1[1]), (0, 255, 0), -1)
img = cv2.putText(img, img_msg, (pt1[0], pt1[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0), 2)
template_img = source_img[pt1[1]:pt2[1], pt1[0]:pt2[0], :]
elif event == cv2.EVENT_RBUTTONDOWN and template_img is not None:
cv2.imwrite(template_file, template_img)
show_flag = False
cv2.destroyAllWindows()
def nextPic(val):
global counter, tgt_path, msg, total,img, draw_flag, show_flag,source_img, template_file, calc
counter += val
show_flag = True
if counter > total:
counter -= val
box.showinfo('系统提示', '没有更多图片')
elif counter <=0:
counter -= val
box.showinfo('系统提示', '已经是第一张')
else:
msg = '图片数量:%d/%d' % (counter, total)
lbl.config(text=msg)
win_name = 'pic_util'
pic_file = os.path.basename(pics[counter - 1])
template_file = tgt_path + '/' + pic_file
img = cv2.imread(pics[counter - 1].encode('gbk').decode())
# img = resize(img, 800)
source_img = np.zeros(img.shape, np.uint8)
source_img = img.copy()
# ims_show = PhotoImage(file=pics[counter - 1])
# cv = Canvas(t_frame3, bg='white', width=200, height=150)
# cv.pack(side=LEFT)
cv2.namedWindow(win_name)
cv2.setMouseCallback(win_name, show)
while show_flag:
cv2.imshow(win_name, img)
k = cv2.waitKey(1) & 0xFF
if k == ord('q') or k == 27:
break
cv2.destroyAllWindows()
def getFilePath(type):
global pic_path, pics,msg, total,var_pic_path,tgt_path,var_pic_tgt_path
path = fd.askdirectory()
if type == 1 and path != '':
if path == tgt_path:
box.showerror('sys info', '图片路径和目标路径不能一致!')
return
pic_path = path
var_pic_path.set(pic_path)
pics = glob.glob(os.path.join(pic_path, suffix))
total = len(pics)
msg = '图片数量:%d/%d' % (counter, total)
lbl.config(text=msg)
elif type == 2 and path != '':
if path == pic_path:
box.showerror('sys info', '目标路径和图片路径不能一致!')
return
tgt_path = path
var_pic_tgt_path.set(tgt_path)
if __name__ == '__main__':
template_file = r'./template/template_06.jpg'
pic_path = r'./source/'
tgt_path = r'./target/'
suffix = '*.jpg'
pt1 = None
pt2 = None
draw_flag = False
show_flag = True
coord_flag = True
counter = 1
calc = [-1, 0, 1]
template_img = None
source_img = None
pics = glob.glob(os.path.join(pic_path, suffix))
total = len(pics)
msg = '图片数量:%d/%d' %(counter, total)
win = tk.Tk()
win.geometry('300x120')
win.title('图片样本制作')
win.resizable(width=False, height=False)
t_frame0 = Frame(win)
t_frame0.pack(side=TOP)
lbl_img = tk.Label(t_frame0, text='图片路径:')
lbl_img.pack(side=LEFT)
var_pic_path = StringVar()
entry_name = tk.Entry(t_frame0, textvariable= var_pic_path)
entry_name.pack(side = LEFT)
var_pic_path.set(pic_path)
btn_file = tk.Button(t_frame0, text='选择文件夹', command = lambda :getFilePath(1))
btn_file.pack(side=LEFT, padx=5)
t_frame0_1 = Frame(win)
t_frame0_1.pack(side=TOP)
lbl_img_1 = tk.Label(t_frame0_1, text='保存路径:')
lbl_img_1.pack(side=LEFT)
var_pic_tgt_path = StringVar()
entry_name_tgt = tk.Entry(t_frame0_1, textvariable= var_pic_tgt_path)
entry_name_tgt.pack(side = LEFT)
var_pic_tgt_path.set(tgt_path)
btn_file_tgt = tk.Button(t_frame0_1, text='选择文件夹', command = lambda :getFilePath(2))
btn_file_tgt.pack(side=LEFT, padx=5)
t_frame1 = Frame(win)
t_frame1.pack(side = TOP)
lbl = tk.Label(t_frame1)
lbl.config(text = msg)
lbl.pack(side = LEFT)
t_frame2 = Frame(win)
t_frame2.pack(side=TOP)
btn = tk.Button(t_frame2, text='上一张', command = lambda val = calc[0]:nextPic(val))
btn.pack(side = LEFT, padx=5)
btn = tk.Button(t_frame2, text='当前张', command = lambda val = calc[1]:nextPic(val))
btn.pack(side=LEFT, padx=5)
btn = tk.Button(t_frame2, text='下一张', command = lambda val = calc[2]:nextPic(val))
btn.pack(side=LEFT, padx=5)
win.mainloop()
| 874cebc16f99fe38115e06e572a181fa96f65e78 | [
"Python"
] | 4 | Python | marc45/pic_recognitioin | 46f9646fd685e87881d972085ec9b4cb423045f3 | bdf82d7637922de4d03882beb4a03e0370f93a6e |
refs/heads/master | <repo_name>jorson-chen/JDBCLogger<file_sep>/src/main/java/com/github/azbh111/jdbclogger/wrappers/PreparedStatementWrapper.java
package com.github.azbh111.jdbclogger.wrappers;
import com.github.azbh111.jdbclogger.SqlLog;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.util.Calendar;
public class PreparedStatementWrapper extends StatementWrapper implements PreparedStatement {
public PreparedStatement pstmt;
public PreparedStatementWrapper(ConnectionWrapper con, PreparedStatement prepareStatement, String sql) {
super(con, prepareStatement, sql);
this.pstmt = prepareStatement;
getSQL();
}
@Override
public ResultSet executeQuery() throws SQLException {
return SqlLog.wrapExecute(queries, () -> this.pstmt.executeQuery());
}
@Override
public int executeUpdate() throws SQLException {
return SqlLog.wrapExecute(queries, () -> this.pstmt.executeUpdate());
}
@Override
public boolean execute() throws SQLException {
return SqlLog.wrapExecute(queries, () -> this.pstmt.execute());
}
// Batch
@Override
public void addBatch() throws SQLException {
query = null;
pstmt.addBatch();
}
@Override
public void clearParameters() throws SQLException {
getSQL().clearParameters();
pstmt.clearParameters();
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
getSQL().setNull(parameterIndex, sqlType);
pstmt.setNull(parameterIndex, sqlType);
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
getSQL().setBoolean(parameterIndex, x);
pstmt.setBoolean(parameterIndex, x);
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
getSQL().setByte(parameterIndex, x);
pstmt.setByte(parameterIndex, x);
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
getSQL().setShort(parameterIndex, x);
pstmt.setShort(parameterIndex, x);
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
getSQL().setInt(parameterIndex, x);
pstmt.setInt(parameterIndex, x);
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
getSQL().setLong(parameterIndex, x);
pstmt.setLong(parameterIndex, x);
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
getSQL().setFloat(parameterIndex, x);
pstmt.setFloat(parameterIndex, x);
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
getSQL().setDouble(parameterIndex, x);
pstmt.setDouble(parameterIndex, x);
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
getSQL().setBigDecimal(parameterIndex, x);
pstmt.setBigDecimal(parameterIndex, x);
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
getSQL().setString(parameterIndex, x);
pstmt.setString(parameterIndex, x);
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
getSQL().setBytes(parameterIndex, x);
pstmt.setBytes(parameterIndex, x);
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
getSQL().setDate(parameterIndex, x);
pstmt.setDate(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
getSQL().setTime(parameterIndex, x);
pstmt.setTime(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
getSQL().setTimestamp(parameterIndex, x);
pstmt.setTimestamp(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
getSQL().setAsciiStream(parameterIndex, x, length);
pstmt.setAsciiStream(parameterIndex, x, length);
}
@SuppressWarnings("deprecation")
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
getSQL().setUnicodeStream(parameterIndex, x, length);
pstmt.setUnicodeStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
getSQL().setBinaryStream(parameterIndex, x, length);
pstmt.setBinaryStream(parameterIndex, x, length);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
getSQL().setObject(parameterIndex, x, targetSqlType);
pstmt.setObject(parameterIndex, x, targetSqlType);
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
getSQL().setObject(parameterIndex, x);
pstmt.setObject(parameterIndex, x);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
getSQL().setCharacterStream(parameterIndex, reader, length);
pstmt.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
getSQL().setRef(parameterIndex, x);
pstmt.setRef(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
getSQL().setBlob(parameterIndex, x);
pstmt.setBlob(parameterIndex, x);
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
getSQL().setClob(parameterIndex, x);
pstmt.setClob(parameterIndex, x);
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
getSQL().setArray(parameterIndex, x);
pstmt.setArray(parameterIndex, x);
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return pstmt.getMetaData();
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
getSQL().setDate(parameterIndex, x, cal);
pstmt.setDate(parameterIndex, x, cal);
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
getSQL().setTime(parameterIndex, x, cal);
pstmt.setTime(parameterIndex, x, cal);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
getSQL().setTimestamp(parameterIndex, x, cal);
pstmt.setTimestamp(parameterIndex, x, cal);
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
getSQL().setNull(parameterIndex, sqlType, typeName);
pstmt.setNull(parameterIndex, sqlType, typeName);
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
getSQL().setURL(parameterIndex, x);
pstmt.setURL(parameterIndex, x);
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
return pstmt.getParameterMetaData();
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
getSQL().setRowId(parameterIndex, x);
pstmt.setRowId(parameterIndex, x);
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
getSQL().setNString(parameterIndex, value);
pstmt.setNString(parameterIndex, value);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
getSQL().setNCharacterStream(parameterIndex, value, length);
pstmt.setNCharacterStream(parameterIndex, value, length);
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
getSQL().setNClob(parameterIndex, value);
pstmt.setNClob(parameterIndex, value);
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
getSQL().setClob(parameterIndex, reader, length);
pstmt.setClob(parameterIndex, reader, length);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
getSQL().setBlob(parameterIndex, inputStream, length);
pstmt.setBlob(parameterIndex, inputStream, length);
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
getSQL().setNClob(parameterIndex, reader, length);
pstmt.setNClob(parameterIndex, reader, length);
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
getSQL().setSQLXML(parameterIndex, xmlObject);
pstmt.setSQLXML(parameterIndex, xmlObject);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
getSQL().setObject(parameterIndex, x);
pstmt.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
getSQL().setAsciiStream(parameterIndex, x, length);
pstmt.setAsciiStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
getSQL().setBinaryStream(parameterIndex, x, length);
pstmt.setBinaryStream(parameterIndex, x, length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader x, long length) throws SQLException {
getSQL().setCharacterStream(parameterIndex, x, length);
pstmt.setCharacterStream(parameterIndex, x, length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
getSQL().setAsciiStream(parameterIndex, x);
pstmt.setAsciiStream(parameterIndex, x);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
getSQL().setBinaryStream(parameterIndex, x);
pstmt.setBinaryStream(parameterIndex, x);
}
@Override
public void setCharacterStream(int parameterIndex, Reader x) throws SQLException {
getSQL().setCharacterStream(parameterIndex, x);
pstmt.setCharacterStream(parameterIndex, x);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader x) throws SQLException {
getSQL().setNCharacterStream(parameterIndex, x);
pstmt.setNCharacterStream(parameterIndex, x);
}
@Override
public void setClob(int parameterIndex, Reader x) throws SQLException {
getSQL().setClob(parameterIndex, x);
pstmt.setClob(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, InputStream x) throws SQLException {
getSQL().setBlob(parameterIndex, x);
pstmt.setBlob(parameterIndex, x);
}
@Override
public void setNClob(int parameterIndex, Reader x) throws SQLException {
getSQL().setNClob(parameterIndex, x);
pstmt.setNClob(parameterIndex, x);
}
@Override
public void close() throws SQLException {
pstmt.close();
}
@Override
public boolean isClosed() throws SQLException {
return pstmt.isClosed();
}
public QueryWrapper getSQL() {
if (query != null) {
return query;
}
if (queries.isEmpty()) {
query = new QueryWrapper(sql);
queries.add(query);
} else {
query = queries.get(queries.size() - 1).copyNew();
queries.add(query);
}
return query;
}
}
<file_sep>/src/main/java/com/github/azbh111/jdbclogger/instrument/transformers/DriverManagerTransformer.java
package com.github.azbh111.jdbclogger.instrument.transformers;
import com.github.azbh111.jdbclogger.JdbcLoggerConfig;
import com.github.azbh111.jdbclogger.SqlLog;
import com.github.azbh111.jdbclogger.wrappers.ConnectionWrapper;
import javassist.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Objects;
import java.util.Properties;
import java.util.WeakHashMap;
/**
* This class is responsible to modify the DriverManager to spawn our own Connection class.
*
* @author HK
*/
public class DriverManagerTransformer implements ClassFileTransformer {
private WeakHashMap cache = new WeakHashMap();
private Object NULL = new Object();
public DriverManagerTransformer() {
importPackage();
}
@Override
public byte[] transform(ClassLoader loader, String rawclassName, Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
String className = rawclassName.replaceAll("/", ".");
loadConfigFromClassPath(); // 如果有新的ClassLoder, 就尝试加载配置
if (JdbcLoggerConfig.sholdProxy(className)) {
return doTransform(className, classfileBuffer);
}
return classfileBuffer;
}
private void importPackage() {
ClassPool cp = ClassPool.getDefault();
cp.importPackage("sun.reflect");
}
private byte[] doTransform(String className, byte[] classfileBuffer) {
try {
SqlLog.log("Instrumenting " + className);
ClassPool cp = ClassPool.getDefault();
CtClass curClass = cp.makeClass(new ByteArrayInputStream(classfileBuffer));
proxyConnectMethod(cp, curClass);
return curClass.toBytecode();
} catch (NotFoundException | CannotCompileException | IOException ex) {
throw new RuntimeException(ex);
}
}
private void loadConfigFromClassPath() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
return;
}
if (!cache.containsKey(classLoader)) {
cache.put(classLoader, NULL);
if (!"sun.misc.Launcher$AppClassLoader".equals(classLoader.getClass().getName())) {
ClassPool.getDefault().appendClassPath(new LoaderClassPath(classLoader));
}
JdbcLoggerConfig.loadConfig(classLoader);
}
}
private void proxyConnectMethod(ClassPool cp, CtClass curClass) throws NotFoundException, CannotCompileException {
String methodName = "connect";
CtClass paramClass1 = cp.get(String.class.getCanonicalName());
CtClass paramClass2 = cp.get(Properties.class.getCanonicalName());
CtClass[] paramArgs = new CtClass[]{paramClass1, paramClass2};
// 搜索目标方法, 可能在父类里面
CtMethod originMethod = findConnectMethod(curClass, methodName, paramArgs);
if (originMethod == null) {
throw new NotFoundException(String.format("can not find method( %s(%s, %s) ) in class: %s", methodName, paramClass1.getName(), paramClass2.getName(), curClass.getName()));
}
// 创建新的方法,复制原来的方法
CtMethod mnew = CtNewMethod.copy(originMethod, methodName, curClass, null);
String wrapperClass = ConnectionWrapper.class.getCanonicalName();
// 代理方法
if (Objects.equals(originMethod.getDeclaringClass().getName(), curClass.getName())) {
// 方法是在当前类定义的, 直接改名
SqlLog.log("proxy connect method in class " + curClass.getName());
originMethod.setName(methodName + "$Impl");
mnew.setBody(String.format("{return new %s(%s$Impl($1, $2));}", wrapperClass, methodName));
} else {
SqlLog.log("add connect method to class " + curClass.getName());
// 方法是在父类定义的, 当前方法直接调用父类方法
mnew.setBody(String.format("{return new %s(super.%s($1, $2));}", wrapperClass, methodName));
}
curClass.addMethod(mnew);
}
private CtMethod findConnectMethod(CtClass curClass, String methodName, CtClass[] paramArgs) throws NotFoundException {
while (true) {
try {
return curClass.getDeclaredMethod(methodName, paramArgs);
} catch (NotFoundException e) {
if (!Object.class.getName().equals(curClass.getName())) {
curClass = curClass.getSuperclass();
} else {
return null;
}
}
}
}
}
<file_sep>/src/main/java/com/github/azbh111/jdbclogger/stacktrace/model/StackTraceInfo.java
package com.github.azbh111.jdbclogger.stacktrace.model;
/**
* @author pyz
* @date 2019/6/13 8:03 PM
*/
public class StackTraceInfo {
/**
* 所在的类
*/
private String fileName = "?";
private int lineNumer = -1;
/**
* 类中的方法
*/
private String methodName = "?";
/**
* 调用的方法
*/
private String invokeMethodName = "?";
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public int getLineNumer() {
return lineNumer;
}
public void setLineNumer(int lineNumer) {
this.lineNumer = lineNumer;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getInvokeMethodName() {
return invokeMethodName;
}
public void setInvokeMethodName(String invokeMethodName) {
this.invokeMethodName = invokeMethodName;
}
@Override
public String toString() {
return fileName + ":" + methodName + ":" + invokeMethodName + ":" + lineNumer;
}
}
<file_sep>/src/main/java/com/github/azbh111/jdbclogger/stacktrace/StackTraceManager.java
package com.github.azbh111.jdbclogger.stacktrace;
import com.github.azbh111.jdbclogger.stacktrace.model.StackTraceInfo;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author pyz
* @date 2019/1/16 11:47 AM
*/
public class StackTraceManager {
/**
* 前缀匹配项目包
*/
private final Set<String> packagePrefixs = new HashSet<>();
/**
* 前缀排除包
*/
private final Set<String> packageExecludes = new HashSet<>();
/**
* 缓存项目包,加快判断速度
*/
private final Map<String, LoggerStackTraceElement> projectStackTraceCache = new ConcurrentHashMap<>();
private static final StackTraceManager instance = new StackTraceManager();
public Set<String> getPackagePrefixs() {
return packagePrefixs;
}
public Set<String> getPackageExecludes() {
return packageExecludes;
}
public static StackTraceManager getInstance() {
return instance;
}
{
// quartz
packagePrefixs.add("org.quartz.");
// 排除jdk包和连接池包
packageExecludes.add("java.");
packageExecludes.add("javax.");
packageExecludes.add("sun.");
packageExecludes.add("com.alibaba.druid.");
}
public StackTraceInfo getStackTraceInfo() {
StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace();
int length = stackTraces.length;
LoggerStackTraceElement preStackTrace = null;
LoggerStackTraceElement currentStackTrace = null;
StackTraceElement stackTrace;
StackTraceInfo info = new StackTraceInfo();
for (int i = 0; i < length; i++) {
stackTrace = stackTraces[i];
preStackTrace = currentStackTrace;
currentStackTrace = toLoggerStackTrace(stackTrace);
if (!currentStackTrace.isProxy() && currentStackTrace.isProjectClass()) {
if (preStackTrace != null) {
info.setInvokeMethodName(stackTraces[i - 1].getMethodName());
}
info.setMethodName(stackTraces[i].getMethodName());
info.setFileName(currentStackTrace.getFileName());
info.setLineNumer(stackTrace.getLineNumber());
return info;
}
}
return info;
}
private LoggerStackTraceElement toLoggerStackTrace(StackTraceElement element) {
LoggerStackTraceElement loggerStackTraceElement = projectStackTraceCache.get(element.getClassName());
if (loggerStackTraceElement == null) {
loggerStackTraceElement = parse(element);
projectStackTraceCache.put(element.getClassName(), loggerStackTraceElement);
}
return loggerStackTraceElement;
}
private boolean isProjectStackTrace(StackTraceElement element) {
if ("<generated>".equals(element.getFileName())) {
return false;
}
String className = element.getClassName();
for (String prefix : packagePrefixs) {
A:
if (className.startsWith(prefix)) {
for (String execlude : packageExecludes) {
if (className.startsWith(execlude)) {
break A;
}
}
return true;
}
}
return false;
}
private LoggerStackTraceElement parse(StackTraceElement element) {
LoggerStackTraceElement ele = new LoggerStackTraceElement();
ele.setProjectClass(element.getClassName().contains("$$") || element.getClassName().startsWith("com.sun.proxy.$Proxy"));
ele.setFileName(trimJavaSuffix(element.getFileName()));
ele.setProjectClass(isProjectStackTrace(element));
return ele;
}
private String trimJavaSuffix(String fileName) {
if (fileName == null) {
return "";
}
return fileName.endsWith(".java") ? fileName.substring(0, fileName.length() - 5) : fileName;
}
private static class LoggerStackTraceElement {
/**
* 是否是代理类
*/
private boolean proxy;
/**
* 是否是项目类
*/
private boolean projectClass;
private String fileName;
public boolean isProxy() {
return proxy;
}
public void setProxy(boolean proxy) {
this.proxy = proxy;
}
public boolean isProjectClass() {
return projectClass;
}
public void setProjectClass(boolean projectClass) {
this.projectClass = projectClass;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
}
<file_sep>/build.gradle
buildscript {
ext {
lombokVersion = "1.18.6"
mapstructVersion = "1.3.0.Final"
autoServiceVersion = "1.0-rc2"
slf4jApi = "1.7.25"
}
repositories {
mavenLocal()
maven {
url "http://maven.aliyun.com/nexus/content/groups/public/"
}
mavenCentral()
}
dependencies {
classpath "com.github.jengelman.gradle.plugins:shadow:2.0.4"
classpath "io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.22.0"
}
}
apply plugin: 'io.codearte.nexus-staging'
apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: "com.github.johnrengelman.shadow"
apply plugin: 'maven-publish'
apply plugin: 'signing'
group 'com.github.azbh111'
version = '0.1.0'
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile 'org.javassist:javassist:3.20.0-GA'
testCompile 'org.springframework.boot:spring-boot-starter:2.1.5.RELEASE'
testCompile "org.springframework.boot:spring-boot-starter-test:2.1.5.RELEASE"
testCompile "org.springframework.boot:spring-boot-starter-jdbc:2.1.5.RELEASE"
testCompile "com.h2database:h2:1.4.192"
testCompile 'uk.org.lidalia:sysout-over-slf4j:1.0.2'
testCompile 'org.slf4j:slf4j-api:1.7.26'
testCompile 'org.projectlombok:lombok:1.18.8'
testCompile 'org.projectlombok:lombok:1.18.8'
testCompile 'com.alibaba:fastjson:1.2.70'
testCompile 'com.baomidou:mybatis-plus-boot-starter:3.3.1'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.8'
}
shadowJar {
manifest {
attributes 'Premain-Class': 'com.github.azbh111.jdbclogger.instrument.Agent'
}
classifier = null
// 改javassist的包路径,防止冲突
relocate 'javassist', 'relocate.javassist'
}
// 关闭java8严格的javadoc检查
if (JavaVersion.current().isJava8Compatible()) {
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
tasks.withType(Javadoc) {
options.encoding = "UTF-8"
}
// 让idea下载源码
idea {
module {
downloadJavadoc = true
downloadSources = true
}
}
repositories {
mavenLocal()
maven {
url "http://maven.aliyun.com/nexus/content/groups/public/"
}
}
compileJava {
// 编译保留参数名字
options.compilerArgs << "-parameters"
// 将apt生成的文件放在源码目录,方便看
options.compilerArgs << "-s"
options.compilerArgs << "$projectDir/src/main/generated"
// 关闭mapstruct生成类注解上的时间戳
options.compilerArgs << "-Amapstruct.suppressGeneratorTimestamp=true"
// 关闭mapstruct生成类注解上的版本信息
options.compilerArgs << "-Amapstruct.suppressGeneratorVersionInfoComment=true"
// mapstruct未映射的字段,不警告
options.compilerArgs << "-Amapstruct.unmappedTargetPolicy=IGNORE"
// 构建之前先删除自动生成的类
doFirst {
file("$projectDir/src/main/generated").deleteDir();
file("$projectDir/src/main/generated").mkdirs();
}
}
sourceSets {
main {
java {
srcDir "$projectDir/src/main/generated"
}
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar) {
from javadoc
classifier = 'javadoc'
}
javadoc {
// <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
// 防止本地打开中文乱码
options.addStringOption("charset", "UTF-8")
}
configurations {
deployerJars
}
// 最主要的是这里
publishing {
publications {
// 这一个推送项目名称,mavenJava 相当于是一个 task name
shadow(MavenPublication) { publication ->
project.shadow.component(publication)
pom {
name = project.group + ":" + project.name
if (project.description == null || project.description.isEmpty()) {
description = project.group + ":" + project.name
} else {
description = project.description
}
url = "https://github.com/azbh111/JDBCLogger.git"
licenses {
license {
name = "The Apache License, Version 2.0"
url = "http://www.apache.org/licenses/LICENSE-2.0.txt"
}
}
developers {
developer {
id = "azbh111"
name = "pan"
}
}
scm {
connection = "scm:git:https://github.com/azbh111/JDBCLogger.git"
developerConnection = "scm:git:https://github.com/azbh111/JDBCLogger.git"
url = "https://github.com/azbh111/JDBCLogger"
}
}
}
mavenJava(MavenPublication) {
groupId project.group
artifactId project.name
version project.version
from components.java
artifact tasks.sourcesJar
artifact tasks.javadocJar
}
}
repositories {
maven {
name 'mavenCenter'
def url_ = null
if (project.version.endsWith("-SNAPSHOT")) {
// snapshot包去这里找
// https://oss.sonatype.org/service/local/repositories/snapshots/content/com/github/azbh111/JDBCLogger/
url_ = 'https://oss.sonatype.org/content/repositories/snapshots/'
} else {
// release包去这里找
// https://oss.sonatype.org/service/local/repositories/releases/content/com/github/azbh111/JDBCLogger/
// https://maven.aliyun.com/nexus/content/groups/public/com/github/azbh111/JDBCLogger/
url_ = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
}
credentials {
username = sonatypeUsername
password = <PASSWORD>
}
url url_
}
}
}
// 签名
signing {
sign publishing.publications.mavenJava
sign publishing.publications.shadow
}
// 自动close/release
nexusStaging {
packageGroup = project.group
username = sonatypeUsername
password = <PASSWORD>
}<file_sep>/README.MD
# JDBCLogger
## 记录的日志例子
java类
```java
@Service
public class CustomerService {
@Resource
private CustoemrMapper customerMapper;
public Customer getCustomerById(Long id) {
return customerMapper.selectById(id); // 假设这里是103行
}
}
```
执行耗时49毫秒, 对应的日志
```
2021-09-18 15:48:51.344 SqlLog.log:19 - CustomerService:getCustomerById:selectById:103 cost 49 select `id`, `name`, `sex`, `age` from customer where id = 3
2021-09-18 15:48:51.344 SqlLog.log:19 - CustomerService:getCustomerById:selectById:103 cost 49 select `id`, `name`, `sex`, `age` from customer where id = 3
2021-09-18 15:48:51.344 SqlLog.log:19 - CustomerService:getCustomerById:selectById:103 cost 49 select `id`, `name`, `sex`, `age` from customer where id = 3
```
## 特性
记录可执行的sql
记录sql执行时长
可以打印执行sql时, 所在的类名, 方法名, 和执行sql的方法名
支持原生jdbc
支持mybatis/hibernate等所有orm框架
对业务无侵入
## 原理
通过javaagent来代理指定的jdbc驱动, 增强connect方法
从而可以干预 connection.createStatement/connection.prepareStatement 流程
能方便的记录sql日志和执行时间
并读取堆栈信息, 分析出执行sql的位置
## 用法
1.1 将 System.out 重定向到日志框架, 比如slf4j
参考 https://blog.csdn.net/qq_31683775/article/details/104940649
1.2 或者 自定义日志输出逻辑
```java
public class Main {
private static final Logger logger = Logger.getLogger("sql");
public static void main(String[] args) {
// 自定义日志输出逻辑
SqlLog.setLogger(str -> logger.info(str));
}
}
```
2. 配置文件 jdbclogger.properties 放在classPath下
```properties
# 修改成自己项目的配置
# 要代理的jdbc驱动类, 多个用逗号分隔
jdbclogger.proxy.driverClass=com.mysql.cj.jdbc.Driver
# 项目包路径前缀, 多个用逗号分隔
jdbclogger.project.packagePrefixs=com.github.azbh111
# 非项目包路径前缀, 多个用逗号分隔, 用来排除 jdbclogger.project.packagePrefixs 中的某些包路径
jdbclogger.project.packageExecludes=com.github.azbh111.common
```
3. 从maven中央仓库中下载JDBCLogger.jar
https://repo1.maven.org/maven2/com/github/azbh111/JDBCLogger/0.1.0/JDBCLogger-0.1.0.jar
4. 添加java启动参数
-Xbootclasspath/p:JDBCLogger.jar的绝对路径 -javaagent:JDBCLogger.jar的绝对路径
<file_sep>/gradle/wrapper/gradle-wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http://nexus.66c.pub:888/repository/gradle/gradle-6.7-bin.zip
<file_sep>/src/main/java/com/github/azbh111/jdbclogger/wrappers/QueryWrapper.java
package com.github.azbh111.jdbclogger.wrappers;
import com.github.azbh111.jdbclogger.SqlLog;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.StringJoiner;
/**
* This class represents a SQL that is going to be executed by a JDBC Statement.
*
* @author <NAME>
*/
public class QueryWrapper {
private static final SimpleDateFormat formatter = new SimpleDateFormat("'yyyy-MM-dd HH:mm:ss'");
public String vars[];
public String query;
public QueryWrapper(String[] vars, String query) {
this.vars = vars;
this.query = query;
}
public QueryWrapper(String query) {
int countVars = countMatches(query, "?");
vars = new String[countVars];
this.query = query.replaceAll("\\?", "%s");
this.query = this.query.toUpperCase();
}
public QueryWrapper copyNew() {
String[] vars = new String[this.vars.length];
return new QueryWrapper(vars, query);
}
public void clearParameters() {
vars = new String[vars.length];
}
public void setString(int i, String x) {
vars[i - 1] = toExecutableString(x);
}
public void setNull(int i, int type) {
vars[i - 1] = "null";
}
@Override
public String toString() {
try {
return String.format(query, this.vars).replaceAll("\n", " ");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
SqlLog.log("convert QueryWrapper to String fail.\n" + sw.toString());
return query + " " + vars.length;
}
}
public void setBoolean(int i, boolean x) {
vars[i - 1] = x ? "1" : "0";
}
public void setByte(int i, byte x) {
vars[i - 1] = String.valueOf(x);
}
public void setShort(int i, short x) {
vars[i - 1] = String.valueOf(x);
}
public void setInt(int i, int x) {
vars[i - 1] = String.valueOf(x);
}
public void setLong(int i, long x) {
vars[i - 1] = String.valueOf(x);
}
public void setFloat(int i, float x) {
vars[i - 1] = String.valueOf(x);
}
public void setDouble(int i, double x) {
vars[i - 1] = String.valueOf(x);
}
public void setBigDecimal(int i, BigDecimal x) {
vars[i - 1] = toExecutableString(x);
}
public void setBytes(int i, byte[] x) {
vars[i - 1] = "[bytes]";
}
public void setDate(int i, Date x) {
vars[i - 1] = x == null ? "null" : formatter.format(x);
}
public void setTime(int i, Time x) {
vars[i - 1] = x == null ? "null" : formatter.format(x);
}
public void setAsciiStream(int i, InputStream x, long length) {
vars[i - 1] = "[input stream]";
}
public void setAsciiStream(int i, InputStream x) {
vars[i - 1] = "[input stream]";
}
public void setTimestamp(int i, Timestamp x) {
vars[i - 1] = x == null ? "null" : formatter.format(x);
}
public void setUnicodeStream(int i, InputStream x, int length) {
vars[i - 1] = "[inputStream]";
}
public void setBinaryStream(int i, InputStream x, long length) {
vars[i - 1] = "[inputStream]";
}
public void setBinaryStream(int i, InputStream x) {
vars[i - 1] = "[inputStream]";
}
public void setObject(int i, Object x, int targetSqlType) {
vars[i - 1] = toExecutableString(x);
}
public void setObject(int i, Object x) {
vars[i - 1] = toExecutableString(x);
}
public void setCharacterStream(int i, Reader reader, long length) {
vars[i - 1] = "[reader]";
}
public void setCharacterStream(int i, Reader reader) {
vars[i - 1] = "[reader]";
}
public void setRef(int i, Ref x) {
vars[i - 1] = "[ref]";
}
public void setBlob(int i, Blob x) {
vars[i - 1] = "[Blob]";
}
public void setBlob(int i, InputStream x) {
vars[i - 1] = "[Blob]";
}
public void setClob(int i, Reader x) {
vars[i - 1] = "[clob]";
}
public void setClob(int i, Clob x) {
vars[i - 1] = "[clob]";
}
public void setArray(int i, Array x) {
vars[i - 1] = "[array]";
}
public void setDate(int i, Date x, Calendar cal) {
vars[i - 1] = x == null ? "null" : formatter.format(x);
}
public void setTime(int i, Time x, Calendar cal) {
vars[i - 1] = x == null ? "null" : formatter.format(x);
}
public void setTimestamp(int i, Timestamp x, Calendar cal) {
vars[i - 1] = x == null ? "null" : formatter.format(x);
}
public void setNull(int i, int sqlType, String typeName) {
vars[i - 1] = "null";
}
public void setURL(int i, URL x) {
vars[i - 1] = toExecutableString(x);
}
public void setRowId(int i, RowId x) {
vars[i - 1] = "[rowId]";
}
public void setNString(int i, String x) {
vars[i - 1] = toExecutableString(x);
}
public void setNCharacterStream(int i, Reader value, long length) {
vars[i - 1] = "[characterStream]";
}
public void setNCharacterStream(int i, Reader value) {
vars[i - 1] = "[characterStream]";
}
public void setNClob(int i, NClob value) {
vars[i - 1] = "[nclob]";
}
public void setNClob(int i, Reader value) {
vars[i - 1] = "[nclob]";
}
public void setClob(int i, Reader reader, long length) {
vars[i - 1] = "[clob]";
}
public void setBlob(int i, InputStream inputStream, long length) {
vars[i - 1] = "[blob]";
}
public void setNClob(int i, Reader reader, long length) {
vars[i - 1] = "[nclob]";
}
public void setSQLXML(int i, SQLXML xmlObject) {
vars[i - 1] = "[sqlxml]";
}
private int countMatches(String str, String sub) {
if (str != null && str.length() > 0) {
int count = 0;
for (int idx = 0; (idx = str.indexOf(sub, idx)) != -1; idx += sub.length()) {
++count;
}
return count;
} else {
return 0;
}
}
public static String toString(List<QueryWrapper> queryWrappers) {
if (queryWrappers.isEmpty()) {
return "";
}
StringJoiner sj = new StringJoiner(";");
for (QueryWrapper queryWrapper : queryWrappers) {
sj.add(queryWrapper.toString());
}
return sj.toString();
}
private String toExecutableString(Object x) {
if (x == null) {
return "null";
}
return "'" + x + "'";
}
}
<file_sep>/src/main/java/com/github/azbh111/jdbclogger/wrappers/SqlCallable.java
package com.github.azbh111.jdbclogger.wrappers;
import java.sql.SQLException;
/**
* @author: zyp
* @since: 2021/11/1 16:00
*/
public interface SqlCallable<T> {
T call() throws SQLException;
}
<file_sep>/settings.gradle
rootProject.name = 'JDBCLogger'
| 190db10f6ac1a9e7a967f6762fec4b79c0969db6 | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 10 | Java | jorson-chen/JDBCLogger | 1eaf3c475a951848f7a35d506f7fe9bf254e1860 | 0182ec3af59f1246a0711ba04b256bdf3306e75f |
refs/heads/master | <repo_name>1046102779/common<file_sep>/rpc/token.go
package rpc
import "github.com/1046102779/common/types"
// 微信开放平台公众号托管
type WxRelayServer struct {
GetOfficialAccountPlatformInfo func() (*types.OfficialAccountPlatform, error)
StoreOfficialAccountInfo func(*types.OfficialAccount) (err error)
GetOfficialAccountInfo func(string) (*types.OfficialAccount, error)
RefreshComponentVerifyTicket func(*types.ComponentVerifyTicket) (string, error)
}
<file_sep>/rpc/official_account.go
package rpc
import "github.com/1046102779/common/types"
type OfficialAccountServer struct {
GetSmsRechargePayJsapiParams func(*types.SmsRechargeInfo) (*types.WechatJSAPIParamInfo, error)
GetSaleOrderPayNativeParams func(*types.ProductPayInfo) (string, error)
GetSmsRechargePayNativeParams func(*types.SmsRechargeInfo) (string, error)
BindingCustomerAndWxInfo func(string, int) error
BindingUserAndWxInfo func(string, int) error
GetOfficialAccountId func(int) (int, error)
SendMessage func(int, int, int16) error
}
<file_sep>/README.md
## 公共组件
该common模块用于official_accounts和wx_relay_servers通信的公共组件, 包括了hprose客户端定义、错误码、类型定义和常用方法
<file_sep>/consts/codes.go
package consts
const (
CODE__SUCCESS = 0
CODE__FIRST = "1"
// position
CODE__POSITION__SELLER = "seller"
CODE__POSITION__CAHIER = "cashier"
CODE__POSITION__TREASURER = "treasurer"
CODE__POSITION__WAREHOUSE_KEEPER = "warehouse_keeper"
CODE__POSITION__SHOP_MANAGER = "shop_manager"
CODE__POSITION__GENERAL_MANAGER = "general_manager"
CODE__POSITION__COMPANY_ADMIN = "company_admin"
// system template message
// 出库提醒
CODE__TEMPLATE_MESSAGE__WAREHOUSE_MANAGER__WAITING_OUTBOUNDS = "出库提醒"
// 销售员或店长-接收已出库提醒 , 销售员或店长-接收已物流提醒
CODE__TEMPLATE_MESSAGE__SALE_OR_SHOPMANAGER__WAITING_OUTBOUNDS_OR_LOGISTAICS = "货物出库提醒"
// 门店订购提醒通知
CODE__TEMPLATE_MESSAGE__CUSTOMER__PLACE_ORDER_SUCCESS = "门店订购提醒通知"
// 客户-总价格确定时接收提醒
CODE__TEMPLATE_MESSAGE__CUSTOMER__PRICE_CLAIM = "订单状态更新通知"
// 客户-待客户验收状态时接收提醒
CODE__TEMPLATE_MESSAGE__CUSTOMER__TO_BE_ACCEPTION = "商品自提通知"
// 总经理-每晚8点接收当天营业额统计情况的提醒
CODE__TEMPLATE_MESSAGE__SHOP_MANAGER__STATISTICS = "营业情况明细通知"
)
<file_sep>/types/official_account.go
package types
// SaaS平台短信充值信息
type SmsRechargeInfo struct {
Money int64 `json:"money"`
TradeNo string `json:"trade_no"`
Openid string `json:"openid"`
Title string `json:"title"`
OfficialAccountId int64 `json:"official_account_id"`
}
// 微信公众号JSAPI支付参数
type WechatJSAPIParamInfo struct {
AppId string `json:"app_id"`
TimeStamp string `json:"timestamp"`
NonceStr string `json:"nonce_str"`
Package string `json:"package"`
SignType string `json:"sign_type"`
PaySign string `json:"pay_sign"`
}
// 商品支付参数信息
type ProductPayInfo struct {
Money int64 `json:"money"`
TradeNo string `json:"trade_no"`
Title string `json:"title"`
OfficialAccountId int64 `json:"official_account_id"`
TransactionId string `json:"transaction_id"`
}
<file_sep>/consts/keys.go
package consts
const (
// header
KEY__HEADER__USER_ID = "Zhibu-Account-User-Id"
KEY__HEADER__USER_CODE = "Zhibu-Account-User-Code"
KEY__HEADER__USER_NAME = "Zhibu-Account-User-Name"
KEY__HEADER__USER_MOBILE = "Zhibu-Account-User-Mobile"
KEY__HEADER__COMPANY_ID = "Zhibu-Account-Company-Id"
KEY__HEADER__COMPANY_NAME = "Zhibu-Account-Company-Name"
KEY__HEADER__POSITIONS = "Zhibu-Account-Positions"
// session
KEY__SESSION__USER_ID = "Zhibu-Account-User-Id"
KEY__SESSION__USER_CODE = "Zhibu-Account-User-Code"
KEY__SESSION__USER_NAME = "Zhibu-Account-User-Name"
KEY__SESSION__USER_MOBILE = "Zhibu-Account-User-Mobile"
KEY__SESSION__COMPANY_ID = "Zhibu-Account-Company-Id"
KEY__SESSION__COMPANY_NAME = "Zhibu-Account-Company-Name"
KEY__SESSION__POSITIONS = "Zhibu-Account-Positions"
// auto complete
KEY__AUTO_COMPLETE__SIZE = 8
)
<file_sep>/rpc/user.go
package rpc
type UserServer struct {
GetWechatBindingUserInfo func(int, int16) (string, error)
}
<file_sep>/consts/types.go
package consts
const (
// login or signin
TYPE_LOGIN_PASSWORD = 10
TYPE_LOGIN_VERIFICATION_CODE = 20
TYPE__SIGN_IN__PASSWORD = 10
TYPE__SIGN_IN__VERIFICATION_CODE = 20
// finance
TYPE__FINANCE_ACCOUNT__CASH = 10
TYPE__FINANCE_ACCOUNT__BANK = 20
TYPE__FINANCE_ACCOUNT__WECHAT_PERSON = 30
TYPE__FINANCE_ACCOUNT__WECHAT_OFFICAL = 31
TYPE__FINANCE_ACCOUNT__ALI_PAY = 40
// org
TYPE__ORG__SHOP = 10
TYPE__ORG__WAREHOUSE = 20
TYPE__ORG__COMPANY = 30
// user
TYPE__USER__SHOP = 10
TYPE__USER__WAREHOUSE = 20
TYPE__USER__COMPANY = 30
TYPE__USER__NORMAL = 70
// sex
TYPE__SEX__MALE = 1
TYPE__SEX__FEMALE = 2
TYPE__SEX__UNKNOWED = 3
// warehouse
TYPE__WAREHOUSE__NORMAL = 10 //普通仓库
// fabric pattern storage place
TYPE__FABRIC_PATTERN_STORAGE__SHOP = 10
TYPE__FABRIC_PATTERN_STORAGE__WAREHOUSE = 20
// official account permission
TYPE_PERMISSION__OFFICIAL_ACCOUNT__MESSAGE_MANAGEMENT = 1 // 消息管理权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__USER_MANAGEMENT = 2 // 用户管理权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__ACCOUNT_SERVICE = 3 // 帐号服务权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__WEB_SERVICE = 4 // 网页服务权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__WECHAT_SHOP = 5 // 微信小店权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__MULTI_CUSTOMER_SERVICE = 6 // 微信多客服权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__NOTIFICATION = 7 // 群发与通知权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__CARDS = 8 // 微信卡券权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__SCANNING = 9 // 微信扫一扫权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__WECHAT_WIFI = 10 // 微信连WIFI权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__MATERIAL_MANAGEMENT = 11 // 素材管理权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__SHAKE_AROUND = 12 // 微信摇周边权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__WECHAT_STORE = 13 // 微信门店权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__WECHAT_PAY = 14 // 微信支付权限
TYPE_PERMISSION__OFFICIAL_ACCOUNT__CUSTOMIZE_MENU = 15 // 自定义菜单权限
// 微信用户类型
TYPE_WECHAT__USER___BUSSINESS = 10 // 微信B端用户
TYPE_WECHAT__USER__PERSONAL = 20 // 微信C端用户
// 手机号码状态
TYPE_STATUS__MOBILE__UNCOMFIRMED = -10
TYPE_STATUS__MOBILE__CONFIRMING = 10
TYPE_STATUS__MOBILE__CONFIRMED = 20
// 邮箱状态
TYPE_STATUS__EMAIL__UNCOMFIRMED = -10
TYPE_STATUS__EMAIL__CONFIRMING = 10
TYPE_STATUS__EMAIL__CONFIRMED = 20
// 邀请码状态
TYPE__INVITATION_CODE__UNUSED = 10
TYPE__INVITATION_CODE__USED = 20
// 面料存储的地点类型
TYPE__INVENTORY__WAREHOUSE = 10 // 仓库
TYPE__INVENTORY__SHOP = 20 // 商铺
// 微信支付方式
TYPE_PAY__WECHAT__JSAPI = "JSAPI"
TYPE_PAY__WECHAT__NATIVE = "NATIVE"
TYPE_PAY__WECHAT__APP = "APP"
// 支付业务场景类型
TYPE_PAY_ENV__WECHAT__SMS_RECHARGE = "101" // 短信充值业务
TYPE_PAY_ENV__WECHAT__FABRIC_ORDER = "102" // SaaS平台商家布匹交易
// 微信是否已经绑定用户/客户账号
TYPE__WECHAT_USER_BINDING__USER = 10 // 绑定B端用户
TYPE__WECHAT_USER_BINDING__CUSTOMER = 11 // 绑定C端用户
TYPE__WECHAT_USER_BINDING__NO = 20
// 库存启用状态: 10: 库存已启用;20:库存未启用
TYPE__STORAGE__ENABLED = 10
TYPE__STORAGE__UNABLED = 20
// 微信支付开启状态
TYPE_PAY_STATUS__WECHAT__STARTED = 10 // 已开启
TYPE_PAY_STATUS__WECHAT__UNSTART = 20 // 未开启
// 模板消息类型
TYPE__MESSAGE_TEMPLATE__WAITING_TO_OUTS__WAREHOUSE_KEEPER = 10 // 仓管员-接收待出库提醒消息
TYPE__MESSAGE_TEMPLATE__OUTS__SALER_OR_SHOP_MANAGER = 20 // 销售员或店长-接收已出库提醒
TYPE__MESSAGE_TEMPLATE__LOGISTICS__SALER_OR_SHOP_MANAGER = 30 // 销售员或店长-接收已物流提醒
TYPE__MESSAGE_TEMPLATE__PLACE_ORDER__CUSTOMER = 40 // 客户-下单成功时提醒
TYPE__MESSAGE_TEMPLATE__PRICE__CUSTOMER = 50 // 客户-总价格确定时接收提醒
TYPE__MESSAGE_TEMPLATE__ACCEPTION__CUSTOMER = 60 // 客户-待客户验收状态时接收提醒
TYPE__MESSAGE_TEMPLATE__STATIS__GENERAL_MANAGER = 70 // 总经理-每晚8点接收当天营业额统计情况的提醒
// Customer mobile sale order's order status
TYPE__CUSTOMER_MOBILE__SALE_ORDER__ORDER_STATUS__TO_BE_RECEIVING = 10 // C端客户待收货
TYPE__CUSTOMER_MOBILE__SALE_ORDER__ORDER_STATUS__RECEIVED = 20 // C端客户已收货
// customer mobile sale order pay status
TYPE_CUSTOMER_MOBILE__SALE_ORDER__PAY_STATUS__TO_BE_PAY = 10 // 待支付
TYPE_CUSTOMER_MOBILE__SALE_ORDER__PAY_STATUS__TO_BE_PAY_BALANCE_AMOUNT = 10 // 待付尾款
TYPE_CUSTOMER_MOBILE__SALE_ORDER__PAY_STATUS__PAYED = 10 // 已支付
)
<file_sep>/consts/errs.go
package consts
const (
SUCCESS = 0 // status 状态
STATUS_VALID = 10 // 账号有效或者已启用
STATUS_INVALID = -10 // 临时
STATUS_INACTIVE = -10 // 账号未启用
STATUS_DELETED = -20 // 账号删除
STATUS_BLOCKED = -30 // 账号冻结
ERROR_CODE__PARAM__ILLEGAL = 1101
WECHAT_MESSAGE_NOT_EXIST = 3021
// etcd相关操作错误码
ETCD_CREATE_DIR_ERROR = 3001
ETCD_CREATE_KEY_ERROR = 3002
ETCD_READ_KEY_ERROR = 3003
// http
ERROR_CODE__SOURCE_DATA__ILLEGAL = 1101 // 外部传入参数错误
ERROR_CODE__GRPC__FAILED = 1102 // grpc 调用失败
ERROR_CODE__HTTP__CALL_FAILD_EXTERNAL = 1103 // http外部调用失败
ERROR_CODE__HTTP__CALL_FAILD_INTERNAL = 1104 // http内部调用失败
ERROR_CODE__JSON__PARSE_FAILED = 1105 // JSON解析失败
ERROR_CODE__HTTP__INPUT_EMPTY = 1106
// database
ERROR_CODE__DB__INSERT = 1001
ERROR_CODE__DB__READ = 1002
ERROR_CODE__DB__UPDATE = 1003
ERROR_CODE__DB__NO_ROW = 1007
ERROR_CODE__DB__UNEXPECTED = 1008
ERROR_CODE__DB__TRANSACTION_BEGIN_FAILED = 1009
ERROR_CODE__DB__TRANSACTION_COMMIT_FAILED = 1010
ERROR_CODE__DB__UPDATE_UNEXPECTED = 1011
ERROR_CODE__DB__TRANSACTION_ROLLBACK_FAILED = 1010
// session
ERROR_CODE__SESSION__START_FAILED = 1404
ERROR_CODE__SESSION__EMPTY_SESSION = 1410
ERROR_CODE__SESSION__SET_FAILED = 1411
// session 相关错误码
SESSION_ERROR_NO_USER_ID = 1401
SESSION_ERROR_NO_COMPANY_ID = 1402
SESSION_ERROR_EMPTY_INPUT = 1403
SESSION_ERROR_START_FAIL = 1404
SESSION_ERROR_NO_USER_NAME = 1405
SESSION_ERROR_NO_COMPANY_NAME = 1406
SESSION_ERROR_EMPTY_SESSION = 1407
SESSION_ERROR_INVALID_USER_ID = 1408
SESSION_ERROR_INVALID_COMPANY_ID = 1409
SESSION_ERROR_NO_SESSION = 1410
// header 相关错误码
ERROR_CODE__HEADER__NO_USER_ID = 1501
ERROR_CODE__HEADER__NO_COMPANY_ID = 1502
ERROR_CODE__HEADER__NO_USER_NAME = 1504
ERROR_CODE__HEADER__NO_COMPANY_NAME = 1505
ERROR_CODE__HEADER__NO_POSITIONS = 1506
ERROR_CODE__HEADER__POSITIONS_FORMAT_ILLEGAL = 1507
ERROR_CODE__HEADER__NO_USER_MOBILE = 1509
ERROR_CODE__HEADER__NO_USER_CODE = 1510
// IO文件解析错误码
FILE_OPEN_FAILED = 4001
FILE_READ_FAILED = 4002
)
<file_sep>/types/token.go
package types
// 微信开放平台
type OfficialAccountPlatform struct {
Appid string `json:"appid"`
ComponentVerifyTicket string `json:"component_verify_ticket"`
EncodingAesKey string `json:"encoding_aes_key"`
AppSecret string `json:"app_secret"`
ComponentAccessToken string `json:"component_access_token"`
PreAuthCode string `json:"pre_auth_code"`
Token string `json:"token"`
}
// 公众号
type OfficialAccount struct {
Appid string `json:"appid"`
AuthorizerAccessToken string `json:"authorizer_access_token"`
AuthorizerAccessTokenExpiresIn int64 `json:"authorizer_access_token_expires_in"`
AuthorizerRefreshToken string `json:"authorizer_refresh_token"`
}
// 授权凭证
type ComponentVerifyTicket struct {
TimeStamp string `json:"timestamp"`
Nonce string `json:"nonce"`
MsgSign string `json:"msg_sign"`
Bts []byte `json:"bts"`
AuthorizationCode string `json:"authorization_code"`
}
| 021040de748781ca00c5d81e0d86b99edff2c191 | [
"Markdown",
"Go"
] | 10 | Go | 1046102779/common | 71242e9534550deb4a9a5040ef978563361c6b90 | e547e07f021278395bf64e61ec73bc8155a23e42 |
refs/heads/master | <file_sep>import os
from os import path
from dal import DAL
from functional_tests import FunctionalTest, ROOT
class TestRegisterPage(FunctionalTest):
def setUp(self):
self.url= ROOT +'/tukker/default/user/register'
get_browser = self.browser.get(self.url)
path_to_database = path.join(path.curdir, "databases")
self.db = DAL('sqlite://storage.sqlite', folder=path_to_database)
self.db.import_table_definitions(path_to_database)
self.db.auth_user.insert(
first_name = 'Duplicate',
last_name = 'Nickname',
email='<EMAIL>',
password = '<PASSWORD>',
nickname = 'duplicate'
)
self.db.commit()
def test_can_view_home_page(self):
response_code = self.get_response_code(self.url)
self.assertEqual(response_code, 200)
def test_has_right_title(self):
title=self.browser.title
self.assertEqual('Tukker.Me Registration', title)
def test_put_values_in_register_form(self):
first_name = self.browser.find_element_by_name('first_name')
first_name.send_keys("John")
last_name = self.browser.find_element_by_name('last_name')
last_name.send_keys("Tukker")
email = self.browser.find_element_by_name('email')
email.send_keys("<EMAIL>")
password = self.browser.find_element_by_name('password')
password.send_keys("pass")
verify_password = self.browser.find_element_by_name('password_two')
verify_password.send_keys("pass")
nickname = self.browser.find_element_by_name('nickname')
nickname.send_keys("john")
image = self.browser.find_element_by_name('image')
path_to_image = path.abspath(path.join(path.curdir, "fts/test_image.png"))
image.send_keys(path_to_image)
register_button = self.browser.find_element_by_xpath("//input[@type='submit']")
register_button.click()
welcome_message = self.browser.find_element_by_css_selector(".alert")
self.assertEqual('Welcome to Tukker.Me', welcome_message.text)
self.url = ROOT + '/tukker/default/user/logout'
get_browser = self.browser.get(self.url)
def test_put_values_in_register_form_with_empty_nickname(self):
first_name = self.browser.find_element_by_name('first_name')
first_name.send_keys("John")
last_name = self.browser.find_element_by_name('last_name')
last_name.send_keys("Tukker")
email = self.browser.find_element_by_name('email')
email.send_keys("<EMAIL>")
password = self.browser.find_element_by_name('password')
password.send_keys("<PASSWORD>")
verify_password = self.browser.find_element_by_name('password_two')
verify_password.send_keys("<PASSWORD>")
# nickname = self.browser.find_element_by_name('nickname')
# nickname.send_keys("john")
image = self.browser.find_element_by_name('image')
path_to_image = path.abspath(path.join(path.curdir, "fts/test_image.png"))
image.send_keys(path_to_image)
register_button = self.browser.find_element_by_xpath("//input[@type='submit']")
register_button.click()
error_message = self.browser.find_element_by_id("nickname__error")
self.assertEqual('enter a value', error_message.text)
def test_put_values_in_register_form_nickname_with_24_chars(self):
first_name = self.browser.find_element_by_name('first_name')
first_name.send_keys("John")
last_name = self.browser.find_element_by_name('last_name')
last_name.send_keys("Tukker")
email = self.browser.find_element_by_name('email')
email.send_keys("<EMAIL>")
password = self.browser.find_element_by_name('password')
password.send_keys("<PASSWORD>")
verify_password = self.browser.find_element_by_name('password_two')
verify_password.send_keys("<PASSWORD>")
nickname = self.browser.find_element_by_name('nickname')
nickname.send_keys("012345678901234567890123")
image = self.browser.find_element_by_name('image')
path_to_image = path.abspath(path.join(path.curdir, "fts/test_image.png"))
image.send_keys(path_to_image)
register_button = self.browser.find_element_by_xpath("//input[@type='submit']")
register_button.click()
error_message = self.browser.find_element_by_id("nickname__error")
self.assertEqual('enter from 0 to 20 characters', error_message.text)
def test_put_values_in_register_form_nickname_unique(self):
first_name = self.browser.find_element_by_name('first_name')
first_name.send_keys("John")
last_name = self.browser.find_element_by_name('last_name')
last_name.send_keys("Tukker")
email = self.browser.find_element_by_name('email')
email.send_keys("<EMAIL>")
password = self.browser.find_element_by_name('password')
password.send_keys("<PASSWORD>")
verify_password = self.browser.find_element_by_name('password_two')
verify_password.send_keys("<PASSWORD>")
nickname = self.browser.find_element_by_name('nickname')
nickname.send_keys("duplicate")
image = self.browser.find_element_by_name('image')
path_to_image = path.abspath(path.join(path.curdir, "fts/test_image.png"))
image.send_keys(path_to_image)
register_button = self.browser.find_element_by_xpath("//input[@type='submit']")
register_button.click()
error_message = self.browser.find_element_by_id("nickname__error")
self.assertEqual('value already in database or empty', error_message.text)
def tearDown(self):
self.db.auth_user.truncate()
self.db.commit()
dirPath = path.join(path.curdir, "uploads")
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
<file_sep>from functional_tests import FunctionalTest, ROOT
class TestHomePage(FunctionalTest):
def setUp(self):
self.url= ROOT +'/tukker/'
get_browser = self.browser.get(self.url)
def test_can_view_home_page(self):
response_code = self.get_response_code(self.url)
self.assertEqual(response_code, 200)
def test_has_right_title(self):
title=self.browser.title
self.assertEqual('Microposts On Steroids', title)
def test_has_right_heading(self):
body = self.browser.find_element_by_tag_name('body')
self.assertIn('Messages With 300 Chars', body.text)
class TestPrivacyPage(FunctionalTest):
def setUp(self):
self.url = ROOT + '/tukker/default/privacy'
get_browser=self.browser.get(self.url)
def test_can_view_privacy_page(self):
response_code = self.get_response_code(self.url)
self.assertEqual(response_code, 200)
def test_has_right_title(self):
title = self.browser.title
self.assertEqual('Tukker.Me Privacy Policy', title)
def test_has_right_heading(self):
heading = self.browser.find_element_by_tag_name('h1')
self.assertIn('Tukker.Me Privacy Policy', heading.text)
class TestAboutPage(FunctionalTest):
def setUp(self):
self.url = ROOT + '/tukker/default/about'
get_browser=self.browser.get(self.url)
def test_can_view_about_page(self):
response_code = self.get_response_code(self.url)
self.assertEqual(response_code, 200)
def test_has_right_title(self):
title = self.browser.title
self.assertEqual('About Tukker.Me', title)
def test_has_right_heading(self):
heading = self.browser.find_element_by_tag_name('h1')
self.assertIn('About Tukker.Me', heading.text) | 0cc1e5d365dfbf1f9b7b04d313115b6a13b6b0e5 | [
"Python"
] | 2 | Python | glennneiger/tukker | f5b65d0d6fb195e431dd5235a11ec5660eadad3c | 54096600e602ad71b8fc912dd463ab1c56399a12 |
refs/heads/master | <repo_name>fberber/handle_rds<file_sep>/Common.java
/**********************************************************************\
© COPYRIGHT 2015 Corporation for National Research Initiatives (CNRI);
All rights reserved.
The HANDLE.NET software is made available subject to the
Handle.Net Public License Agreement, which may be obtained at
http://hdl.handle.net/20.1000/103 or hdl:20.1000/103
\**********************************************************************/
/*----------------------------------------------------------------------*/
/* Added the HS_RDS_URL type */
/* Author: <NAME> */
/* Email: <EMAIL> */
/*----------------------------------------------------------------------*/
package net.handle.hdllib;
/***********************************************************************
* This class holds all of the standard identifiers for the handle
* library.
***********************************************************************/
public abstract class Common {
public static final byte MAJOR_VERSION = 2;
public static final byte MINOR_VERSION = 10;
// If an AbstractRequest doesn't explicitly set a protocol version when contacting an interface directly (without knowing its SiteInfo), this is used.
public static final byte COMPATIBILITY_MAJOR_VERSION = 2;
public static final byte COMPATIBILITY_MINOR_VERSION = 3;
public static final byte EMPTY_BYTE_ARRAY[] = new byte[0];
public static final String TEXT_ENCODING = "UTF8";
public static final byte ST_NONE = 0;
public static final byte ST_ADMIN = 1;
public static final byte ST_RESOLUTION = 2;
public static final byte ST_RESOLUTION_AND_ADMIN = 3;
public static final byte BLANK_HANDLE[] = Util.encodeString("/");
public static final byte GLOBAL_NA_PREFIX[] = Util.encodeString("0.");
public static final byte GLOBAL_NA[] = Util.encodeString("0/");
public static final byte NA_HANDLE_PREFIX_NOSLASH[] = Util.encodeString("0.NA");
public static final byte NA_HANDLE_PREFIX[] = Util.encodeString("0.NA/");
public static final byte TRUST_ROOT_HANDLE[] = Util.encodeString("0.0/0.0");
public static final byte ROOT_HANDLE[] = Util.encodeString("0.NA/0.NA");
public static final byte SPECIAL_DERIVED_MARKER[] = Util.encodeString("0.NA/0.NA/");
public static final byte SERVER_TXN_ID_HANDLE[] = Util.encodeString("0.SITE/NEXT-TXN-ID");
public static final byte SITE_INFO_TYPE[] = Util.encodeString("HS_SITE");
public static final byte SITE_INFO_6_TYPE[] = Util.encodeString("HS_SITE.6");
public static final byte LEGACY_DERIVED_PREFIX_SITE_TYPE[] = Util.encodeString("HS_NA_DELEGATE");
public static final byte DERIVED_PREFIX_SITE_TYPE[] = Util.encodeString("HS_SITE.PREFIX");
public static final byte SERVICE_HANDLE_TYPE[] = Util.encodeString("HS_SERV");
public static final byte DERIVED_PREFIX_SERVICE_HANDLE_TYPE[] = Util.encodeString("HS_SERV.PREFIX");
public static final byte NAMESPACE_INFO_TYPE[] = Util.encodeString("HS_NAMESPACE");
public static final byte RDS_URL_TYPE[] = Util.encodeString("HS_RDS_URL");
@Deprecated public static final byte MD5_SECRET_KEY_TYPE[] = Util.encodeString("HS_SECKEY");
public static final byte SECRET_KEY_TYPE[] = Util.encodeString("HS_SECKEY");
public static final byte PUBLIC_KEY_TYPE[] = Util.encodeString("HS_PUBKEY");
public static final byte ADMIN_TYPE[] = Util.encodeString("HS_ADMIN");
public static final byte ADMIN_GROUP_TYPE[] = Util.encodeString("HS_VLIST");
public static final byte HS_SIGNATURE_TYPE[] = Util.encodeString("HS_SIGNATURE");
public static final byte HS_CERT_TYPE[] = Util.encodeString("HS_CERT");
public static final byte HASH_ALG_MD5[] = Util.encodeString("MD5");
public static final byte HASH_ALG_SHA1[] = Util.encodeString("SHA1");
public static final byte HASH_ALG_SHA1_ALTERNATE[] = Util.encodeString("SHA-1");
public static final byte HASH_ALG_SHA256[] = Util.encodeString("SHA-256");
public static final byte HASH_ALG_SHA256_ALTERNATE[] = Util.encodeString("SHA256");
public static final byte HASH_ALG_HMAC_SHA1[] = Util.encodeString("HMAC-SHA1");
public static final byte HASH_ALG_HMAC_SHA256[] = Util.encodeString("HMAC-SHA256");
public static final byte HASH_ALG_PBKDF2_HMAC_SHA1[] = Util.encodeString("PBKDF2-HMAC-SHA1");
public static final byte HASH_ALG_PBKDF2_HMAC_SHA1_ALTERNATE[] = Util.encodeString("PBKDF2WithHmacSHA1");
public static final byte SITE_INFO_TYPES[][] = { SITE_INFO_TYPE,
SITE_INFO_6_TYPE };
public static final byte DERIVED_PREFIX_SITE_INFO_TYPES[][] = { DERIVED_PREFIX_SITE_TYPE, LEGACY_DERIVED_PREFIX_SITE_TYPE };
public static final byte SITE_INFO_INCL_PREFIX_TYPES[][] = { SITE_INFO_TYPE,
SITE_INFO_6_TYPE,
DERIVED_PREFIX_SITE_TYPE, LEGACY_DERIVED_PREFIX_SITE_TYPE };
public static final byte SITE_INFO_AND_SERVICE_HANDLE_TYPES[][] = { SITE_INFO_TYPE,
SITE_INFO_6_TYPE,
SERVICE_HANDLE_TYPE };
public static final byte SITE_INFO_AND_SERVICE_HANDLE_INCL_PREFIX_TYPES[][] = { SITE_INFO_TYPE,
SITE_INFO_6_TYPE,
SERVICE_HANDLE_TYPE,
DERIVED_PREFIX_SITE_TYPE,
LEGACY_DERIVED_PREFIX_SITE_TYPE,
DERIVED_PREFIX_SERVICE_HANDLE_TYPE };
public static final byte SITE_INFO_AND_SERVICE_HANDLE_AND_NAMESPACE_TYPES[][] = { SITE_INFO_TYPE,
SITE_INFO_6_TYPE,
SERVICE_HANDLE_TYPE,
NAMESPACE_INFO_TYPE };
public static final byte SITE_INFO_AND_SERVICE_HANDLE_AND_NAMESPACE_AND_RDS_URL_TYPES[][] = { SITE_INFO_TYPE,
SITE_INFO_6_TYPE,
SERVICE_HANDLE_TYPE,
NAMESPACE_INFO_TYPE ,
RDS_URL_TYPE};
public static final byte DERIVED_PREFIX_SITE_AND_SERVICE_HANDLE_TYPES[][] = {
DERIVED_PREFIX_SITE_TYPE,
LEGACY_DERIVED_PREFIX_SITE_TYPE,
DERIVED_PREFIX_SERVICE_HANDLE_TYPE };
public static byte[][] HS_SIGNATURE_TYPE_LIST = new byte[][] { Common.HS_SIGNATURE_TYPE };
public static final byte SERVICE_HANDLE_TYPES[][] = { SERVICE_HANDLE_TYPE, DERIVED_PREFIX_SERVICE_HANDLE_TYPE };
public static final byte LOCATION_TYPES[][] = { SITE_INFO_TYPE,
SERVICE_HANDLE_TYPE,
DERIVED_PREFIX_SERVICE_HANDLE_TYPE,
SITE_INFO_6_TYPE,
DERIVED_PREFIX_SITE_TYPE,
LEGACY_DERIVED_PREFIX_SITE_TYPE,
NAMESPACE_INFO_TYPE };
@Deprecated public static final byte MD5_SECRET_KEY_TYPES[][] = { SECRET_KEY_TYPE };
public static final byte SECRET_KEY_TYPES[][] = { SECRET_KEY_TYPE };
public static final byte PUBLIC_KEY_TYPES[][] = { PUBLIC_KEY_TYPE };
public static final byte ADMIN_TYPES[][] = { ADMIN_TYPE };
public static final byte ADMIN_GROUP_TYPES[][] = { ADMIN_GROUP_TYPE };
public static final byte LOCATION_AND_ADMIN_TYPES[][] = { SITE_INFO_TYPE,
SITE_INFO_6_TYPE,
DERIVED_PREFIX_SITE_TYPE,
LEGACY_DERIVED_PREFIX_SITE_TYPE,
SERVICE_HANDLE_TYPE,
DERIVED_PREFIX_SERVICE_HANDLE_TYPE,
NAMESPACE_INFO_TYPE,
ADMIN_TYPE,
ADMIN_GROUP_TYPE,
PUBLIC_KEY_TYPE,
SECRET_KEY_TYPE };
public static final int ADMIN_INDEXES[] = {};
public static final byte STD_TYPE_URL[] = Util.encodeString("URL");
public static final byte STD_TYPE_EMAIL[] = Util.encodeString("EMAIL");
public static final byte STD_TYPE_HSALIAS[] = Util.encodeString("HS_ALIAS");
public static final byte STD_TYPE_HSSITE[] = Util.encodeString("HS_SITE");
public static final byte STD_TYPE_HSSITE6[] = Util.encodeString("HS_SITE.6");
public static final byte STD_TYPE_HSADMIN[] = Util.encodeString("HS_ADMIN");
public static final byte STD_TYPE_HSSERV[] = Util.encodeString("HS_SERV");
// public static final byte STD_TYPE_HOSTNAME[] = Util.encodeString("INET_HOST");
// public static final byte STD_TYPE_URN[] = Util.encodeString("URN");
public static final byte STD_TYPE_HSSECKEY[] = Util.encodeString("HS_SECKEY");
public static final byte STD_TYPE_HSPUBKEY[] = Util.encodeString("HS_PUBKEY");
public static final byte STD_TYPE_HSVALLIST[] = Util.encodeString("HS_VLIST");
public static final byte STD_TYPES[][] = { STD_TYPE_URL,
STD_TYPE_EMAIL,
STD_TYPE_HSADMIN,
STD_TYPE_HSALIAS,
STD_TYPE_HSSITE,
STD_TYPE_HSSITE6,
STD_TYPE_HSSERV,
STD_TYPE_HSSECKEY,
STD_TYPE_HSPUBKEY,
STD_TYPE_HSVALLIST,
// STD_TYPE_HOSTNAME,
// STD_TYPE_URN,
};
// codes identifying hash types (used in request digest encoding)
public static final byte HASH_CODE_MD5_OLD_FORMAT = (byte)0;
public static final byte HASH_CODE_MD5 = (byte)1;
public static final byte HASH_CODE_SHA1 = (byte)2;
public static final byte HASH_CODE_SHA256 = (byte)3;
public static final byte HASH_CODE_HMAC_SHA1 = (byte)0x12;
public static final byte HASH_CODE_HMAC_SHA256 = (byte)0x13;
public static final byte HASH_CODE_PBKDF2_HMAC_SHA1 = (byte)0x22;
// credential type identifier indicating a message signed by a client for session fashion request submit
public static final byte[] CREDENTIAL_TYPE_MAC = Util.encodeString("HS_MAC");
// credential type identifier indicating a message signed by a server, or client for session setup
public static final byte[] CREDENTIAL_TYPE_SIGNED = Util.encodeString("HS_SIGNED");
// credential type identifier indicating a message signed by a server (old style, deprecated)
public static final byte[] CREDENTIAL_TYPE_OLDSIGNED = Util.encodeString("HS_DSAPUBKEY");
// codes identifying file-encryption schemes
@Deprecated
public static final int ENCRYPT_DES_ECB_PKCS5 = 0; // DES with ECB and PKCS5 padding
public static final int ENCRYPT_NONE = 1; // no encryption
public static final int ENCRYPT_DES_CBC_PKCS5 = 2; // DES with CBC and PKCS5 padding
public static final int ENCRYPT_PBKDF2_DESEDE_CBC_PKCS5 = 3; // DESede with CBC and PKCS5 padding and PBKDF2 to derive encryption key
public static final int ENCRYPT_PBKDF2_AES_CBC_PKCS5 = 4; // AES with CBC and PKCS5 padding and PBKDF2 to derive encryption key
public static final int MAX_ENCRYPT = 9; // All file-encryption schemes must be smaller, and all public-key-encoding strings must be longer
// identifier for the DSA private key encoding
public static final byte KEY_ENCODING_DSA_PRIVATE[] = Util.encodeString("DSA_PRIV_KEY");
// identifier for the DSA public key encoding
public static final byte KEY_ENCODING_DSA_PUBLIC[] = Util.encodeString("DSA_PUB_KEY");
// identifier for the DH private key encoding
public static final byte KEY_ENCODING_DH_PRIVATE[] = Util.encodeString("DH_PRIV_KEY");
// identifier for the DH public key encoding
public static final byte KEY_ENCODING_DH_PUBLIC[] = Util.encodeString("DH_PUB_KEY");
// identifier for the RSA private key and private crt key encoding
public static final byte KEY_ENCODING_RSA_PRIVATE[] = Util.encodeString("RSA_PRIV_KEY");
public static final byte KEY_ENCODING_RSACRT_PRIVATE[] = Util.encodeString("RSA_PRIVCRT_KEY");
// identifier for the RSA public key encoding
public static final byte KEY_ENCODING_RSA_PUBLIC[] = Util.encodeString("RSA_PUB_KEY");
// format version number for site records
public static final int SITE_RECORD_FORMAT_VERSION = 1;
// size (in bytes) of the "nonce" sent to clients for authentication
public static final int CHALLENGE_NONCE_SIZE = 16;
// size (in bytes) of an MD5 digest
public static final int MD5_DIGEST_SIZE = 16;
// size (in bytes) of an SHA1 digest
public static final int SHA1_DIGEST_SIZE = 20;
// size (in bytes) of an SHA256 digest
public static final int SHA256_DIGEST_SIZE = 32;
// static size of message header (in bytes)
public static final int MESSAGE_HEADER_SIZE = 24;
// static size of message envelope (in bytes)
public static final int MESSAGE_ENVELOPE_SIZE = 20;
// maximum allowable size (in bytes) of a message
public static final int MAX_MESSAGE_LENGTH = 262144;
// maximum size of udp packets. packets in multi-packet
// messages must be as large as possible equal to or below
// this limit.
public static final int MAX_UDP_PACKET_SIZE = 512;
// the maximum size of the data portion of a UDP packet
// (ie the non-envelope portion)
public static final int MAX_UDP_DATA_SIZE = MAX_UDP_PACKET_SIZE - MESSAGE_ENVELOPE_SIZE;
// the maximum number of handle values which are allowed in a message
public static final int MAX_HANDLE_VALUES = 2048;
// the maximum length of a handle
public static final int MAX_HANDLE_LENGTH = 2048;
// limit all arrays in messages to one million elements max
public static final int MAX_ARRAY_SIZE = 1048576;
// IP address length
public static final int IP_ADDRESS_LENGTH = 16;
public static final String HDL_MIME_TYPE = "application/x-hdl-message";
public static final String XML_MIME_TYPE = "text/xml";
//for session setup request, exchange key type
public static final int KEY_EXCHANGE_NONE = 0; // no session
public static final int KEY_EXCHANGE_CIPHER_CLIENT = 1; // Use client pub key
public static final int KEY_EXCHANGE_CIPHER_SERVER = 2; // Use server pub key
public static final int KEY_EXCHANGE_CIPHER_HDL = 3; // Use key from hdl
public static final int KEY_EXCHANGE_DH = 4; // diffie hellman
// size (in bytes) of the session key sent between client and server
public static final int SESSION_KEY_SIZE = 512;
//default server session time out 24 hours (in seconds)
public static final int DEFAULT_SESSION_TIMEOUT = 24 * 60 * 60;
public static final String READ_ONLY_DB_STORAGE_KEY = "read_only";
}
<file_sep>/README.md
# handle_rds
Handle System with support for HS_RDS_URL type
| a1a321f0b5c7b0c6f85f4d98af99476bd927b410 | [
"Markdown",
"Java"
] | 2 | Java | fberber/handle_rds | 0bdc8be59c862ef1653bd2f71d853b811b40872e | 85709355e8767c185d4e509e78ede28fb18db380 |
refs/heads/main | <repo_name>OrAnge-Lime/JsPr<file_sep>/src/service/dataService.js
import axios from 'C:/Users/orlov/ui/src/axios/ingex.js';
/*
Запрашивает список всех элементов
*/
export async function fetchTodos(){
try{
const response = await axios.get('/todos');
return response.data.todos;
} catch(error){
console.error({error});
throw error;
}
}
/*
Создает новый элемент
*/
export async function createTodo({title, isCompleted}){
try{
const response = await axios.post('/todos', {
title
});
return response.data;
} catch(error){
console.error({error});
throw error;
}
}
/*
Удаляет элеемнт по id
*/
export async function deleteTodoById(id){
try{
const response = await axios.delete('/todos/' + id);
return response.data.todos;
} catch(error){
console.error({error});
throw error;
}
}
/*
Обновление статут элемента с данным id
*/
export async function patchTodo({id, isCompleted}){
try{
const response = await axios.patch('/todos/' + id, {
isCompleted
});
return response.data;
} catch(error){
console.error({error});
throw error;
}
}
/*
Удаляет весь список Todo
*/
export async function deleteAllTodo(){
try{
const response = await axios.delete('/todos');
return response.data.todos;
} catch(error){
console.error({error});
throw error;
}
}
| cfb35f7c0afea3b0e0f5c1006cadaab028096749 | [
"JavaScript"
] | 1 | JavaScript | OrAnge-Lime/JsPr | 61213be472b824e6179186866e173c2ad1cb16a0 | 2d8c62e929b6e68bd7409e4a90d73c0d1d9cdbb4 |
refs/heads/master | <file_sep>package com.company;
public enum RankEnum {
A,
J,
Q,
K,
}
<file_sep>package com.company.models;
import com.company.util.Constants;
import java.io.*;
import java.util.HashMap;
public class Patient extends AbstractPerson{
String gender;
private String fileName = Constants.DATABASE_PATH + "patient.txt";
private HashMap<String, String> patients = new HashMap<>();
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
public Patient(String name, String gender) {
super(name);
this.gender = gender;
}
public Patient() { }
public HashMap<String, String> getPatient() {
return patients;
}
public void load() throws IOException {
bufferedReader = new BufferedReader(new FileReader(fileName));
String line;
while((line = bufferedReader.readLine()) != null) {
if(!line.contains(","))
continue;
String[] values = line.split(",");
patients.put(values[0], values[1]);
}
bufferedReader.close();
}
public void save() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
patients.forEach((k,v) -> {
stringBuilder.append(k + "," + v);
stringBuilder.append(System.getProperty("line.separator"));
});
bufferedWriter = new BufferedWriter(new FileWriter(fileName));
bufferedWriter.write(stringBuilder.toString());
bufferedWriter.close();
}
public void create() throws IOException {
if(patients.containsKey(name)) {
System.out.println("Paciente ya existe...");
return;
}
patients.put(name, gender);
save();
}
}
<file_sep>## Tabla de contenido
* [Informacion general](#informacion-general)
* [Instalacion y configuracion](#instalacion-configuracion)
* [Uso del programa](#uso-del-programa)
* [Creditos](#creditos)
* [Licencia](#licencia)
## Informacion general
Software administrador de citas para un consultorio.
## Instalacion configuracion
Para correr este proyecto es necesario contar con java JDSK v14
## Uso del programa
El producto final será un programa que simulará un sistema de administración de citas con las siguientes funcionalidades:
• Dar de alta doctores: se deberán poder dar de alta los doctores del consultorio médico, los datos básicos serán:
• Identificador único.
• Nombre completo. • Especialidad.
• Dar de alta pacientes: se deberán poder registrar los pacientes que acudan al consultorio médico, los datos básicos serán:
• Identificador único.
• Nombre completo.
• Crear una cita con fecha y hora: se deberán poder crear múltiples citas, los datos básicos serán:
• Identificador único.
• Fecha y hora de la cita.
• Motivo de la cita.
• Relacionar una cita con un doctor y un paciente: cada una de las citas creadas deberá estar relacionada con un doctor y un paciente.
• Tener control de acceso mediante administradores: solo ciertos usuarios podrán acceder al sistema mediante un identificador y una contraseña.
## Creditos
eserna 2020
## Licencia
Open source<file_sep>package com.company.interfaces;
import java.io.IOException;
public interface IActions {
void create() throws IOException;
// void update();
}
<file_sep>package com.company.models;
import com.company.util.Constants;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
public class Appointment {
String idDoctor;
String idPatient;
String description;
String date;
private String fileName = Constants.DATABASE_PATH + "appointment.txt";
private HashMap<String, String> appointments = new HashMap<>();
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
public Appointment(String idDoctor, String idPatient, String description, String date) {
this.idDoctor = idDoctor;
this.idPatient = idPatient;
this.description = description;
this.date = date;
}
public Appointment() { }
public void load() throws IOException {
bufferedReader = new BufferedReader(new FileReader(fileName));
String line;
while((line = bufferedReader.readLine()) != null) {
if(!line.contains(","))
continue;
String[] values = line.split(",");
appointments.put(values[0], values[1]);
}
bufferedReader.close();
}
public void save() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
appointments.forEach((k,v) -> {
stringBuilder.append(k + "," + v);
stringBuilder.append(System.getProperty("line.separator"));
});
bufferedWriter = new BufferedWriter(new FileWriter(fileName));
bufferedWriter.write(stringBuilder.toString());
bufferedWriter.close();
}
public void create() throws IOException {
appointments.put(date, description+","+idDoctor+","+idPatient);
save();
}
public boolean appointmentExits(String username, String password) {
if(!appointments.containsKey(username))
return false;
else if (appointments.get(username).equals(password))
return true;
else
return false;
}
}
<file_sep>package com.company.models;
import java.io.IOException;
public class Auth {
String username;
String password;
public Auth(String username, String password) {
this.username = username;
this.password = password;
}
public boolean userExists() throws IOException {
User users = new User();
users.load();
return users.userExits(username, password);
}
}
<file_sep>package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean exit = false;
Deck deck = new Deck();
Scanner s = new Scanner(System.in);
while(!exit){
System.out.println("Bienvenidos, favor de seleccionar una opcion: \n" +
"1) Shuffle\n" +
"2) Head\n" +
"3) Pick\n" +
"4) Hand\n" +
"5) Exit");
String option = s.nextLine();
switch (option) {
case "1":
deck.Shuffle();
System.out.println("Se mezclo el deck...");
break;
case "2":
System.out.println(deck.Head());
System.out.println("Quedan " + deck.deck.size());
break;
case "3":
System.out.println(deck.Pick());
System.out.println("Quedan " + deck.deck.size());
break;
case "4":
System.out.println(deck.Hand());
System.out.println("Quedan " + deck.deck.size());
break;
case "5":
exit = true;
break;
default:
System.out.println("Opcion incorrecta, intente de nuevo...");
break;
}
}
}
}
<file_sep>package com.company.models;
public abstract class AbstractPerson {
String name;
public AbstractPerson(String name) {
this.name = name;
}
public AbstractPerson() { }
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
| 665bd3ad0440c8f48fb8cb528fd40ed9d829f210 | [
"Markdown",
"Java"
] | 8 | Java | AL02891856/JavaCourse | 28ce5239f7ce35b7a625ba8c941e4687b73281ed | 1ae75c1a03fe55dab3edc21b5686fa5d0cd0cef8 |
refs/heads/master | <repo_name>SamKustin/cs440<file_sep>/assignment3/FuncWrapper/Function.hpp
#ifndef FUNCTION_HPP
#define FUNCTION_HPP
#include <iostream>
#include <exception>
namespace cs540 {
/* ========================== BadFunctionCall Class ======================= */
class BadFunctionCall : public std::exception {
public:
/**
* const char* what() const throw()
* Returns the explanatory string about the error.
*/
virtual const char* what() const throw() {
return "Error: Bad Function Call";
}
}; /* class BadFunctionCall */
/* ========================= CallableInterface Class ====================== */
// Undefined, allows partial specialization.
template <typename>
class CallableInterface;
// A specialization used to parse function signature types.
template <typename ResultType, typename ... ArgumentTypes>
class CallableInterface<ResultType(ArgumentTypes...)> {
public:
virtual ~CallableInterface() = default;
virtual ResultType operator()(ArgumentTypes... args) = 0;
virtual CallableInterface<ResultType(ArgumentTypes...)>* clone() = 0;
}; /* class CallableInterface */
/* ============================ Callable Class ============================ */
template <typename FunctionType, typename ResultType, typename ... ArgumentTypes>
class Callable : public CallableInterface<ResultType(ArgumentTypes...)> {
private:
FunctionType callable_target;
public:
// Value Constructor
Callable(const FunctionType& target) : callable_target(target) {}
// Destructor
virtual ~Callable() override = default;
/**
* ResultType operator()(ArgumentTypes... args)
* Invokes the target function.
*/
virtual ResultType operator()(ArgumentTypes... args) override {
return callable_target(std::forward<ArgumentTypes>(args)...);
}
/**
* CallableInterface<ResultType, ArgumentTypes...>* clone()
* Cloning allows us to easily make a copy of the derived type
* from the base type.
*/
virtual CallableInterface<ResultType(ArgumentTypes...)>* clone() override {
return new Callable<FunctionType, ResultType, ArgumentTypes...>(callable_target);
}
}; /* class Callable */
/* ============================ Function Class ============================ */
// Undefined, allows partial specialization.
template <typename>
class Function;
// A specialization used to parse function signature types.
template <typename ResultType, typename ... ArgumentTypes>
class Function<ResultType(ArgumentTypes...)> {
private:
CallableInterface<ResultType(ArgumentTypes...)> *callable_object;
public:
/* ------ Constructors, Assignment Operators, and Destructor ------ */
/* Default Constructor */
Function();
/* Value Constructor */
template <typename FunctionType> Function(FunctionType);
/* Copy Constructor */
Function(const Function &);
/* Copy Assignment Operator */
Function &operator=(const Function &);
/* Destructor */
~Function();
/* --------------------------- Functionality ---------------------- */
ResultType operator()(ArgumentTypes...);
/* --------------------------- Observers -------------------------- */
/**
* explicit operator bool() const;
* Return true if the cs540::Function references a callable function
* and false otherwise.
*/
explicit operator bool() const {
if (callable_object != nullptr) return true;
return false;
}
}; /* class Function */
/* =============== cs540::Function Function Implementation ================ */
/* ----------- Constructors, Assignment Operators, and Destructor --------- */
// Default Constructor
/**
* Function()
* Constructs a function wrapper that does not yet reference a
* target function.
*/
template <typename ResultType, typename ... ArgumentTypes>
Function<ResultType(ArgumentTypes...)>::Function() :
callable_object(nullptr) {}
// Value Constructor
/**
* Function(FunctionType target)
* Constructs a function wrapper with a function of FunctionType as
* its target.
*/
template <typename ResultType, typename ... ArgumentTypes>
template <typename FunctionType>
Function<ResultType(ArgumentTypes...)>::Function(FunctionType target) {
callable_object = new Callable<FunctionType, ResultType, ArgumentTypes...>(target);
}
// Copy Constructor
/**
* Function(const Function &other)
* Copy construct from an existing cs540::Function.
*/
template <typename ResultType, typename ... ArgumentTypes>
Function<ResultType(ArgumentTypes...)>::Function(const Function &other) {
if (other.callable_object != nullptr) {
callable_object = other.callable_object->clone();
return;
}
callable_object = nullptr;
}
// Copy Assignment Operator
/**
* Function &operator=(const Function &)
* Copy assignment.
* Must handle self assignment.
* Must be able to freely assign between cs540::Function objects that
* contain a free function, lambda, or functor given that they have
* the same function signature.
*/
template <typename ResultType, typename ... ArgumentTypes>
Function<ResultType(ArgumentTypes...)>&
Function<ResultType(ArgumentTypes...)>::operator=(const Function &other){
if (&other == this) return *this;
if (callable_object != nullptr) {
delete callable_object;
}
if (other.callable_object != nullptr) {
callable_object = other.callable_object->clone();
return *this;
}
callable_object = nullptr;
return *this;
}
// Destructor
/**
* ~Function()
* Frees all memory
*/
template <typename ResultType, typename ... ArgumentTypes>
Function<ResultType(ArgumentTypes...)>::~Function(){
if (callable_object != nullptr){
delete callable_object;
}
callable_object = nullptr;
}
/* ------------------------------- Functionality -------------------------- */
/**
* ResultType operator()(ArgumentTypes... args)
* Call the wrapped function target with the given arguments and
* return its result.
* Throw cs540::BadFunctionCall if a callable function is not stored.
*/
template <typename ResultType, typename ... ArgumentTypes>
ResultType Function<ResultType(ArgumentTypes...)>::operator()(ArgumentTypes... args){
if (callable_object == nullptr){
throw BadFunctionCall();
}
return ((*callable_object)(std::forward<ArgumentTypes>(args)...));
}
/* ============== Non-member (Free) Function Implementation =============== */
// Equality Operators
/**
* bool operator==(const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t)
* Returns !f
*/
template <typename ResultType, typename... ArgumentTypes>
bool operator==(const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t) {
return !f;
}
/**
* bool operator==(std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f)
* Returns !f
*/
template <typename ResultType, typename... ArgumentTypes>
bool operator==(std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f) {
return !f;
}
// Inequality Operators
/**
* bool operator!=(const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t)
* Returns bool(f)
*/
template <typename ResultType, typename... ArgumentTypes>
bool operator!=(const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t) {
return bool(f);
}
/**
* bool operator!=(std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f)
* Returns bool(f)
*/
template <typename ResultType, typename... ArgumentTypes>
bool operator!=(std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f) {
return bool(f);
}
} /* namespace cs540 */
#endif /* #ifndef FUNCTION_HPP */
<file_sep>/assignment3/RvalueRef/Array.hpp
#ifndef ARRAY_HPP
#define ARRAY_HPP
#include "MyInt.hpp"
#include <iostream>
#include <utility>
#include <chrono>
#include <random>
#include <algorithm>
#include <assert.h>
namespace cs540 {
// TODO: Make a helper class to assign using the index operator
/* ============================= Array Class ============================== */
/**
* An array class modelled after standard array.
*/
class Array {
private:
/* ----------------------- Private Variables ---------------------- */
MyInt* array_data;
size_t length;
size_t max_length;
/* -------------------------- Modifiers --------------------------- */
void insert(const MyInt &val);
public:
/* ------ Constructors, Assignment Operators, and Destructor ------ */
/* Default Constructor */
Array();
/* Value Constructor */
Array(std::initializer_list<MyInt> init_list);
/* Copy Constructor */
Array(const Array &other);
/* Move Constructor */
Array(Array &&other);
/* Copy Assignment Operator */
Array& operator=(const Array &other);
/* Move Assignment Operator */
Array& operator=(Array &&other);
/* Destructor */
~Array();
/* ------------------------ Element Access ------------------------ */
MyInt& at(const size_t &i) const;
MyInt& operator[](const size_t &i) const;
/* --------------------------- Capacity --------------------------- */
bool empty() const;
size_t size() const;
size_t max_size() const;
/* --------------------- Performance Testing ---------------------- */
// Use a static function so it can be used independently of an object
static void move_performance_test();
/* ----------------------- Ostream Operator ---------------------- */
friend std::ostream& operator<<(std::ostream &os, const Array &arr);
}; /* class Array */
/* ====================== Array Function Implementation =================== */
/* ---------- Constructors, Assignment Operators, and Destructor ---------- */
// Default Constructor
/**
* Array()
* Constructs an Array with 0 elements.
*/
Array::Array(){
array_data = nullptr;
length = 0;
max_length = 0;
}
// Value Constructor
/**
* Array(std::initializer_list<MyInt> init_list)
* Constructs an Array from the initializer list
*/
Array::Array(std::initializer_list<MyInt> init_list){
array_data = new MyInt[init_list.size()];
max_length = init_list.size();
length = 0;
for (MyInt value : init_list){
insert(value);
}
}
// Copy Constructor
Array::Array(const Array &other){
array_data = new MyInt[other.max_length];
max_length = other.max_length;
length = 0;
for (size_t i = 0; i < other.max_length; i++){
insert(other.at(i));
}
// assert(length == other.length);
}
/* Move Constructor */
Array::Array(Array &&other){
array_data = std::move(other.array_data);
length = std::move(other.length);
max_length = std::move(other.max_length);
other.array_data = nullptr;
other.length = 0;
other.max_length = 0;
}
/* Copy Assignment Operator */
Array& Array::operator=(const Array &other){
// Check self assignment
if (&other == this) return *this;
// Check if the current array is not empty
if (!empty()){
delete[] array_data;
array_data = nullptr;
length = 0;
}
// Copy the contents of the other Array
array_data = new MyInt[other.max_length];
max_length = other.max_length;
length = 0;
for (size_t i = 0; i < other.max_length; i++){
insert(other.at(i));
}
// assert(length == other.length);
return *this;
}
/* Move Assignment Operator */
Array& Array::operator=(Array &&other){
// Check self assignment
if (&other == this) return *this;
// Check if the current array is not empty
if (!empty()){
delete[] array_data;
array_data = nullptr;
length = 0;
}
// Move the contents of the other Array into the current Array
array_data = std::move(other.array_data);
length = std::move(other.length);
max_length = std::move(other.max_length);
other.array_data = nullptr;
other.length = 0;
other.max_length = 0;
return *this;
}
// Destructor
/**
* ~Array()
* Frees all allocated memory
*/
Array::~Array(){
delete[] array_data;
array_data = nullptr;
}
/* ------------------------------- Modifiers ------------------------------ */
/**
* void insert(const MyInt &val)
* Inserts an element into the array.
*/
void Array::insert(const MyInt &val){
if (length >= max_size()) return;
array_data[length] = val;
length++;
}
/* ----------------------------- Element Access --------------------------- */
/**
* MyInt& at(const size_t &i) const
* Index into the Array with bounds checking.
* Throws an std::out_of_range error if index is out of bounds of the array.
*/
MyInt& Array::at(const size_t &i) const {
if (i > size() - 1){
throw std::out_of_range("Error in Array::at(size_t i) = Index out of range.");
}
return array_data[i];
}
/**
* MyInt& operator[](const size_t &i) const
* Overload the index operator so it indexes into the Array with .at() instead
* for bounds checking.
*/
MyInt& Array::operator[](const size_t &i) const {
return at(i);
}
/* ------------------------------- Capacity ------------------------------- */
/**
* bool empty() const
* Returns whether or not the Array is empty
*/
bool Array::empty() const {
if (length == 0){
return true;
}
return false;
}
/**
* size_t size() const
* Returns the length of the Array, i.e., how many elements are in it.
*/
size_t Array::size() const {
return length;
}
/**
* size_t max_size() const
* Returns the maximum length of the Array, i.e., how many total
* elements may be in it.
*/
size_t Array::max_size() const {
return max_length;
}
/* -------------------------- Performance Testing ------------------------- */
/**
* void move_performance_test()
* Verifies that the move constructor and move assignment operator have better
* performance compared to the copy constructor and copy assignment operator.
*/
void Array::move_performance_test(){
// Setup for timing the performance tests
using Milli = std::chrono::duration<double, std::ratio<1,1000>>;
using TimePoint = std::chrono::time_point<std::chrono::system_clock>;
using namespace std::chrono;
TimePoint start, end;
// Initial insertion of all Array elements
long num_elements = 1000000;
Array test_array1{};
Array test_array2{};
test_array1.array_data = new MyInt[1000000];
test_array2.array_data = new MyInt[1000000];
for (int i = 0; i < num_elements; i++){
test_array1.insert(i);
test_array2.insert(i);
}
/* ==================================================================== */
std::cout << "\n=============== COPY VS MOVE CONSTRUCTOR " <<
"PERFORMANCE TEST ===============" << std::endl;
/* -------------------------- Copy Contruction ------------------------ */
start = system_clock::now();
Array copy_ctor_array{test_array1};
end = system_clock::now();
Milli copy_elapsed = end - start;
std::cout << "Copy construction of an Array of " << num_elements << " elements "
<< " took " << copy_elapsed.count() << " milliseconds" << std::endl;
/* -------------------------- Move Contruction ------------------------ */
start = system_clock::now();
Array move_ctor_array{std::move(test_array1)};
end = system_clock::now();
Milli move_elapsed = end - start;
std::cout << "Move construction of an Array of " << num_elements << " elements "
<< " took " << move_elapsed.count() << " milliseconds" << std::endl;
// assert(move_elapsed < copy_elapsed);
/* ==================================================================== */
std::cout << "\n=============== COPY VS MOVE ASSIGNMENT OPERATOR " <<
"PERFORMANCE TEST ===============" << std::endl;
/* -------------------------- Copy Assignment ------------------------- */
start = system_clock::now();
Array copy_assignment_array = test_array2;
end = system_clock::now();
copy_elapsed = end - start;
std::cout << "Copy assignment of an Array of " << num_elements << " elements "
<< " took " << copy_elapsed.count() << " milliseconds" << std::endl;
/* -------------------------- Move Assignment ------------------------- */
start = system_clock::now();
Array move_assignment_array = std::move(test_array2);
end = system_clock::now();
move_elapsed = end - start;
std::cout << "Move assignment of an Array of " << num_elements << " elements "
<< " took " << move_elapsed.count() << " milliseconds" << std::endl;
// assert(move_elapsed < copy_elapsed);
}
/* --------------------------- Ostream Operator -------------------------- */
/**
* std::ostream& operator<<(std::ostream &os, const Array &arr)
* Outputs all array elements horizontally in a list format.
*/
std::ostream& operator<<(std::ostream &os, const Array &arr){
for (size_t i = 0; i < arr.size(); i++){
if (i != arr.size() - 1){
os << arr.at(i) << ", " << std::flush;
} else {
os << arr.at(i) << std::flush;
}
}
return os;
}
} /* namespace cs540 */
#endif /* ifndef ARRAY_HPP */
<file_sep>/assignment4/ostream/README.md
Part2: Interpolated ostream Output (50 pts)
<file_sep>/final/Makefile
CC=g++
CFLAG = -g -Wall -Wextra -pedantic -std=c++17
# CFLAG_TEMP = -Wno-unused-parameter -Wno-return-type
all: chimeraExe extractorExe
# Executables
chimeraExe: chimeraExe.o
$(CC) $(CFLAG) $(CFLAG_TEMP) chimeraExe.o -o chimeraExe
extractorExe: extractorExe.o
$(CC) $(CFLAG) $(CFLAG_TEMP) extractorExe.o -o extractorExe
# Objects
chimeraExe.o: chimera/main.cpp
$(CC) $(CFLAG) $(CFLAG_TEMP) -c chimera/main.cpp -o chimeraExe.o
extractorExe.o: extractor/main.cpp
$(CC) $(CFLAG) $(CFLAG_TEMP) -c extractor/main.cpp -o extractorExe.o
clean:
rm -f chimeraExe extractorExe *.o
rm -rf *.dSYM
<file_sep>/assignment4/README.md
# Assignment 4: Metaprogramming
<NAME>
CS 440
Due: 05/16/18
## Assignment Instructions
http://www.cs.binghamton.edu/~kchiu/cs540/prog/4/
All classes should be in the `cs540` namespace. Your code must work with test
classes that are not in the `cs540` namespace, however. Your code should not
have any memory errors or leaks as reported by `valgrind`. Your code should
compile and run on the `remote.cs.binghamton.edu` cluster. Your code must not
have any hard-coded, arbitrary limits or assumptions about maximum sizes, etc.
Your code should compile without warning with `-Wall -Wextra -pedantic`.
Special exemptions to this may be requested in advance.
These may (or may not) be useful:
* `std::tuple`
* `std::remove_const`
* `std::remove_reference`
* `std::enable_if`
More [here](http://en.cppreference.com/w/cpp/header/type_traits).
Reading about [SFINAE](http://en.cppreference.com/w/cpp/language/sfinae)
may also be helpful, though I don't believe that it is necessary.
## Part 1: Arbitrary Dimension Array Class Template (50 pts)
Implement a array class template named `cs540::Array` that can be instantiated
with any number of dimensions. The size of each dimension is given as a
sequence of `size_t` constant template arguments. You must not allocate any
memory from the heap in your implementation.
First-dimension-major corresponds to row-major order in 2-D.
Likewise, last-dimension-major corresponds to column-major order in 2-D.
The `LastDimensionMajorIterator` is for 25 points extra credit.
Here is an example of how it might be used. The full API is further below.
```c++
#include "Array.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
int
main() {
// Define a 2X3X4 array of integers. Elements are uninitialized.
cs540::Array<int, 2, 3, 4> a, b;
cs540::Array<short, 2, 3, 4> c;
// cs540::Array<int, 0> e1; // This line must cause a compile-time error.
// Initialize.
int counter = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
a[i][j][k] = b[i][j][k] = counter;
c[i][j][k] = counter;
counter++;
}
}
}
// Range-checked indexing.
a[0][0][0] = 1234;
a[1][1][1] = a[0][0][0];
a[0][2][3] = 5678; // Set the element in the first plane, 3rd row, and 4th column.
try {
a[0][3][0] = 1; // Out of range, throws.
assert(false);
} catch (cs540::OutOfRange) {
}
a = a; // Self-assignment must be a no-op.
b = a; // Okay, as long as dimensions and type match exactly.
a = c; // Member template constructor.
const cs540::Array<int, 2, 3, 4> &const_ref(a);
int i = const_ref[0][0][0]; // Okay.
// const_ref[0][0][0] = 1; // Syntax error.
// Iterate through in plane major order. (Note: Normally, you would use
// auto to simplify.)
std::cout << "First dimension major (row-major in 2-D): " << std::endl;
for (cs540::Array<int, 2, 3, 4>::FirstDimensionMajorIterator it = a.fmbegin(); it != a.fmend(); ++it) {
std::cout << *it << std::endl;
}
// Iterate through in column major order.
std::cout << "Last dimension major (column-major in 2-D): " << std::endl;
for (cs540::Array<int, 2, 3, 4>::LastDimensionMajorIterator it = a.lmbegin(); it != a.lmend(); ++it) {
std::cout << *it << std::endl;
}
}
#pragma GCC diagnostic pop
```
You should throw an object of class type `cs540::OutOfRange` as an exception
if there is indexing operation that is out of range. You should provide the
definition of this class in your header file.
Your code must not have any fixed limits. You must be able to construct arrays
with any number of elements and dimensions, etc.
Your array implementation must be completely contained in `Array.hpp` and
`Array.cpp`. Note that `Array.cpp` will likely be empty. Test code for your
array is [here](https://github.com/SamKustin/cs440/blob/master/assignment4/docs/array/test_Array.cpp).
The correct output is [here](https://github.com/SamKustin/cs440/blob/master/assignment4/docs/array/correct_output.txt).
Your code must work with the test code without change. We reserve the right
to add addtional tests to this as we see fit, but we will conform to the API
used in the provided test code.
### Template
| Declaration | Description |
| :---------- | :---------- |
| `template <typename T, size_t... Dims> class Array;` | This declares a multidimensional array containing elements of type `T` with the given dimensions. If any dimension is zero it should fail to compile. Use `static_assert` to force this behavior. Note: Clang++ version 3.7.0 will emit an error if a negative number is supplied for an unsigned template parameter. G++ 5.2.0 does not, however. |
### Type Members
| Member | Description |
| :---------- | :---------- |
| `ValueType` | The type of the elements: `T`. |
| `FirstDimensionMajorIterator` | The type of the named iterator. |
| `LastDimensionMajorIterator` | The type of the named iterator. |
### Public Member Functions
**Constructors and Assignment Operators:**
| Prototype | Description |
| :---------- | :---------- |
| `Array();` | The default constructor must be defined, either explicitly or implicitly. |
| `Array(const Array &);` | The copy constructor must work. The dimensionality of the source array must be the same. Note that a non-template copy constructor must be provided, in addtion to the member template copy constructor. |
| `template <typename U> Array(const Array<U, Dims...> &);` | The copy constructor must work. The dimensionality of the source array must be the same. |
| `Array &operator=(const Array &);` | The assignment operator must work. The dimensionality of the source array must be the same. Self-assignment must be a no-op. Note that this non-template assignment operator must be provided, in addtion to the member template assignment operator. |
| `template <typename U> Array &operator=(const Array<U, Dims...> &);` | The assignment operator must work. The dimensionality of the source array must be the same. Self-assignment must be a no-op. |
| `T &operator[size_t i_1][size_t i_2]...[size_t i_D]; const T &operator[size_t i_1][size_t i_2]...[size_t i_D] const` | This is used to index into the array with range-checking. If any given indices are out-of-range, then an `OutOfRange` exception must be thrown. Note that this is a “conceptual” operator only. Such an operator does not really exist. Instead, you must figure out how to provide this functionality. (Helper classes may be useful.) |
**Iterators:**
| Prototype | Description |
| :---------- | :---------- |
| `FirstDimensionMajorIterator fmbegin();` | Returns a `FirstDimensionMajorIterator` (nested classes) object pointing to the first element. |
| `FirstDimensionMajorIterator fmend();` | Returns a `FirstDimensionMajorIterator` (nested classes) object pointing one past the last element. |
| `LastDimensionMajorIterator lmbegin();` | Returns a `LastDimensionMajorIterator` pointing to the first element. |
| `LastDimensionMajorIterator lmend();` | Returns a `LastDimensionMajorIterator` pointing one past the last element. |
### Public Member Functions for Nested Class FirstDimensionMajorIterator
This iterator is used to iterate through the array in row-major order.
This iterator can be be used to read or write from the array.
| Prototype | Description |
| :---------- | :---------- |
| `FirstDimensionMajorIterator();` | Must have correct default ctor. |
| `FirstDimensionMajorIterator(const FirstDimensionMajorIterator &);` | Must have correct copy constructor. (The implicit one will probably be correct.) |
| `FirstDimensionMajorIterator &operator=(const FirstDimensionMajorIterator &);` | Must have correct assignment operator. (The implicit one will probably be correct.) |
| `bool operator==(const FirstDimensionMajorIterator &, const FirstDimensionMajorIterator &);` | Compares the two iterators for equality. |
| `bool operator!=(const FirstDimensionMajorIterator &, const FirstDimensionMajorIterator &);` | Compares the two iterators for inequality. |
| `FirstDimensionMajorIterator &operator++();` | Increments the iterator one element in row-major order, and returns the incremented iterator (preincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `FirstDimensionMajorIterator operator++(int);` | Increments the iterator one element in row-major, and returns an iterator pointing to the element prior to incrementing the iterator (postincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `T &operator*() const;` | Returns a reference to the `T` at this position in the array. If the iterator is pointing to the end of the list, the behavior is undefined. |
### Public Member Functions for Nested Class LastDimensionMajorIterator
This iterator is used to iterate through the array in column-major order.
This iterator can be only be used to read or write from the array.
| Prototype | Description |
| :---------- | :---------- |
| `LastDimensionMajorIterator();` | Must have correct default constructor. |
| `LastDimensionMajorIterator(const LastDimensionMajorIterator &);` | Must have correct copy constructor. (The implicit one will probably be correct.) |
| `LastDimensionMajorIterator &operator=(const LastDimensionMajorIterator &);` | Must have correct assignment operator. (The implicit one will probably be correct.) |
| `bool operator==(const LastDimensionMajorIterator &, const LastDimensionMajorIterator &);` | Compares the two iterators for equality. |
| `bool operator!=(const LastDimensionMajorIterator &, const LastDimensionMajorIterator &);` | Compares the two iterators for inequality. |
| `LastDimensionMajorIterator &operator++();` | Increments the iterator one element in column-major order, and returns the incremented iterator (preincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `LastDimensionMajorIterator operator++(int);` | Increments the iterator one element in column-major order, and returns an iterator pointing to the element prior to incrementing the iterator (postincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `T &operator*() const;` | Returns a reference to the `T` at this position in the array. If the iterator is pointing to the end of the list, the behavior is undefined. |
## Part 2: Interpolated Ostream Output (50 pts)
The C++ `<iostream>` facility is arguably more idiomatic for C++ and has a
number of advantages, but is harder to read and type (at least for me) than
C's `printf()`. This is an attempt to get the best of both worlds.
Write a function template named `Interpolate` that will make the below work.
Each value argument will be output when its corresponding `%` is encountered
in the format string. All output should be ultimately done with the
appropriate overloaded `<<` operator as applied to the given stream object.
A `\%` sequence should output a percent sign.
```c++
SomeArbitraryClass obj;
int i = 1234;
double x = 3.14;
std::string str("foo");
std::cout << Interpolate(R"(i=%, x1=%, x2=%\%, str1=%, str2=%, obj=%)", i, x, 1.001, str, "hello", obj) << std::endl;
```
If there is a mismatch between the number of percent signs and the number of
arguments to output, throw an exception of type `cs540::WrongNumberOfArgs`.
Support the I/O manipulators listed [here](http://en.cppreference.com/w/cpp/io/manip).
Some I/O manipulators have an immediate effect on the output stream, such as
`std::endl` and `std::ends`. Such manipulators consume a percent sign, and
should be applied at the corresponding point. Others only have an effect on
the next item, such as `std::setprecision`. These manipulators do *not*
consume a percent sign.
Note that manipulators should never affect the characters in the format string.
In particular,
```c++
std::cout << cs540::Interpolate("%B%", "A", std::setw(2), std::setfill('-'), "C") << std::endl;
```
should print `AB-C`, rather than `A-BC`.
You should not use `std::stringstream`. All manipulators should be applied
directly to the actual stream object.
You should be able to support these without creating a partial specialization
or overloaded function template for every single manipulator.
Some manipulators are function templates. This poses a problem, which is
resolved by the `ffr()` function. As far as I know, there is no better
solution, but please let me know if you find one.
A test program is [here](https://github.com/SamKustin/cs440/blob/master/assignment4/docs/ostream/test_Interpolate.cpp).
<file_sep>/midterm/primes/Makefile
CC=g++
CFLAG = -g -Wall -Wextra -pedantic -std=c++14
all: primes
primes: primes.o
$(CC) $(CFLAG) primes.o -o primes
primes.o: main.cpp
$(CC) $(CFLAG) -c main.cpp -o primes.o
clean:
rm -f *.o primes
rm -rf *.dSYM
<file_sep>/midterm/primes/main.cpp
#include <assert.h>
#include <iostream>
#include <cstdlib>
#include <vector>
// Write a class and it's iterator that will generate primes, and then iterate
// through them.
namespace cs540 {
class Primes {
public:
// forward dec
class Iterator;
// variables
unsigned long n;
std::vector<bool> primes;
// Value Constructor
Primes(unsigned long l) : n{l} {
// init
primes.push_back(false); // 0
primes.push_back(false); // 1
for (unsigned long i = 2; i <= n; i++){
primes.push_back(true);
}
// sieve
for (unsigned long i = 2; i*i <= n; i++){
if (primes.at(i)){
for (unsigned long j = i*2; j <= n; j+=i){
primes.at(j) = false;
}
}
}
#if 0
// print
for (unsigned long i = 2; i <= n; i++){
if (primes.at(i)){
std::cout << i << std::endl;
}
}
#endif
}
// Returns an iterator to the first prime number
Iterator begin(){
return {this, 2};
}
// Returns an interator to the last prime number
Iterator end(){
// get last prime
unsigned long last;
for (unsigned long i = n-1; i >= 2; i--){
if (primes.at(i)){
last = i;
}
}
return {this, last};
}
// Gets the next prime number after the index
unsigned long next(unsigned long index){
if ((index+1) > primes.size()) return 0;
// search for next prime
for (unsigned long i = index+1; i < primes.size(); i++){
if (primes.at(i)){
// std::cout << "return next: " << i << std::endl;
return i;
}
}
return 2;
}
// Gets the previous prime number before the index
unsigned long prev(unsigned long index){
if ((index-1) < 2 || (index-1) > primes.size()) return 0;
// search for prev prime
for (unsigned long i = index-1; i >= 2; i--){
if (primes.at(i)){
return i;
}
}
return 2;
}
public:
class Iterator {
friend class Primes;
public:
unsigned long num; // current prime number
// int index;
Primes *p;
Iterator() = default;
Iterator(Primes *p, unsigned long num) : num(num), p(p) {}
friend bool operator==(const Iterator &it1, const Iterator &it2){
return it1.num == it2.num;
}
friend bool operator!=(const Iterator &it1, const Iterator &it2){
return !(it1.num == it2.num);
}
Iterator& operator++(){
num = p->next(num);
// std::cout << "++() num: " << num << std::endl;
return *this;
}
Iterator operator++(int){
Iterator temp(*this);
num = p->next(num);
// std::cout << "++(int) num: " << num << std::endl;
return temp;
}
Iterator& operator--(){
num = p->prev(num);
return *this;
}
Iterator operator--(int){
Iterator temp(*this);
num = p->prev(num);
return temp;
}
const unsigned long& operator*() const {
// std::cout << "* num: " << num << std::endl;
return num;
}
}; // Iterator
}; // Primes
} // namespace cs540
int
main() {
// Primes in the range of 2 to 1000. Define the constructor as:
// Primes(unsigned long);
cs540::Primes primes(1000);
for (auto it = primes.begin(); it != primes.end(); ++it) {
// Type of prime should be unsigned long.
std::cout << *it << std::endl;
assert(typeid(*it) == typeid(unsigned long));
// Should be compile-time error.
// *it = 1234;
}
auto it = primes.begin();
// Comparison should work as expected.
assert(*it == 2);
auto it2 = it;
++it2;
assert(*it2 == 3);
assert(it2 != it);
assert(--it2 == it);
cs540::Primes primes1(100);
auto it1 = primes.begin();
assert(*it1++ == 2 );
assert(*it1++ == 3 );
assert(*it1++ == 5 );
assert(*it1++ == 7 );
assert(*it1++ == 11 );
assert(*it1++ == 13 );
assert(*it1++ == 17 );
assert(*it1++ == 19 );
assert(*it1++ == 23 );
assert(*it1++ == 29 );
assert(*it1++ == 31 );
assert(*it1++ == 37 );
assert(*it1++ == 41 );
assert(*it1++ == 43 );
assert(*it1++ == 47 );
assert(*it1++ == 53 );
assert(*it1++ == 59 );
assert(*it1++ == 61 );
assert(*it1++ == 67 );
assert(*it1++ == 71 );
assert(*it1++ == 73 );
assert(*it1++ == 79 );
assert(*it1++ == 83 );
assert(*it1++ == 89 );
assert(*it1-- == 97 );
assert(*it1-- == 89 );
assert(*it1-- == 83 );
assert(*it1-- == 79 );
assert(*it1-- == 73 );
assert(*it1-- == 71 );
assert(*it1-- == 67 );
assert(*it1-- == 61 );
assert(*it1-- == 59 );
assert(*it1-- == 53 );
assert(*it1-- == 47 );
assert(*it1-- == 43 );
assert(*it1-- == 41 );
assert(*it1-- == 37 );
assert(*it1-- == 31 );
assert(*it1-- == 29 );
assert(*it1-- == 23 );
assert(*it1-- == 19 );
assert(*it1-- == 17 );
assert(*it1-- == 13 );
assert(*it1-- == 11 );
assert(*it1-- == 7 );
assert(*it1-- == 5 );
assert(*it1-- == 3 );
assert(*it1-- == 2 );
}
<file_sep>/assignment2/README.md
# Assignment 2: Container
<NAME>
CS 440
Due: 03/15/18
## Assignment Instructions
http://www.cs.binghamton.edu/~kchiu/cs540/prog/2/
Implement a container class template named `Map` similar to the `std::map`
class from the C++ Standard Library. Such containers implement key-value pairs,
where key and value may be any types, including class types. (In the following,
the value will be referred to as the mapped type or mapped object, and the
term value will used to designate the entire pair. This is so as to be
consistent with the terminology in the standard library.) Note that C++
terminology uses object even for fundamental types such as `int`s. Your `Map`
class template will have two type parameters, `Key_T` and `Mapped_T`, denoting
the key type and the mapped type, respectively. As in `std::map`, the mapped
type values themselves must be in your map, not pointers to the values.
The specification given below is intended to be a proper subset of the
functionality of `std::map`. This means that if you don't fully understand
something, you can check the documentation for `std::map`, or even write a
small test using `std::map`. If you find any discrepancies between what is
described below and `std::map`, please let me know.
You may assume that the `Key_T` and `Mapped_T` are copy constructible and
destructible. You may assume that `Key_T` has a less-than operator (`<`),
and an equality operator (`==`), as free-standing functions (not member
functions). You may also assume that `Mapped_T` has an equality comparison
(`==`). If `operator<` is invoked on `Map` objects, you may also assume that
`Mapped_T` has `operator<`. You may *not* assume that either class has a
default constructor or an assignment operator. You may only assume that a
`Mapped_T` that is used with `operator[]` may be default initialized.
You may *not* make any other assumptions. (Check with us if there is any doubt.)
Your `Map` class must expose three nested classes: `Iterator`, `ConstIterator`,
and `ReverseIterator`. None of these classes should permit default construction.
An iterator is an object that points to an element in a sequence. The iterators
must traverse the `Map` by walking through the keys in sorted order.
Iterators must remain valid as long as the element they are pointing to has not
been erased. Any function that results in the removal of an element from a map,
such as `erase`, will invalidate any iterator that points to that element, but
not any other iterator.
Your map implementation must be completely contained in your `Map.hpp` file.
I do not believe that you will need a `Map.cpp` file, but you may have one
if you wish.
Additionally, your class must meet the following time complexity requirements:
`O(lg(N))` for key lookup, insertion, and deletion; and `O(1)` for all iterator
increments and decrements. These time complexities are the worst-case,
expected time complexities. In other words, for the worst-case possible input,
your submission must, when averaged over many runs, have the given time complexity.
If you use amortization to achieve the above bounds, that is fine, but contact me.
To achieve the performance requirements, two data structures that will work are
balanced binary trees or skip lists. Note that the latter is easier to implement.
Hash tables will *not* work.
All classes should be in the `cs540` namespace. Your code must work with test
classes that are not in the `cs540` namespace, however. Your code should not
have any memory errors or leaks as reported by `valgrind`. Your code should
compile and run on the `remote.cs.binghamton.edu` cluster. Your code should not
have any hard-coded, arbitrary limits or assumptions about maximum number of
elements, maximum sizes, etc.
You may find that you need a linked list in your implementation. There are
many variations on how to implement linked lists. In my experience, I have
found doubly-linked, circular lists with a sentinel node to be convenient in
most cases, and usually the cost of the extra pointer to maintain a
doubly-linked list is not an issue. Some example code is
[here](https://github.com/SamKustin/cs440/blob/master/assignment2/docs/doubly_linked_circular_list.cpp).
Preliminary test code is here. Be sure to skim through the code below to
understand any options, and to understand what is being tested.
* [Test 1](https://github.com/SamKustin/cs440/blob/master/assignment2/docs/test-kec.cpp)
* [Test 2](https://github.com/SamKustin/cs440/blob/master/assignment2/docs/test.cpp)
* [Minimal](https://github.com/SamKustin/cs440/blob/master/assignment2/docs/minimal.cpp)
* [Morse Code Example](https://github.com/SamKustin/cs440/blob/master/assignment2/docs/morseex.cpp)
* [Performance Test](https://github.com/SamKustin/cs440/blob/master/assignment2/docs/test-scaling.cpp) (Compile with `-O`)
### Extra Credit
For the extra credit, you must also include test code that convinces us that
it works. Note that this may require some thought.
Also, you can only get the extra credit if you meet the other requirements.
For example, you cannot get extra credit if you cannot successfully erase elements.
The number of points is somewhat variable, depending on exactly what you do,
so check with me first with your specific idea to find out how much extra credit.
#### Indexable (15 pts)
Make your `Map` indexable. Performance must be better than `O(N)`.
## API
### Template
| Declaration | Description |
| :---------- | :---------- |
| `template <typename Key_T, typename Mapped_T> class Map;` | This declares a Map class that maps from `Key_T` objects to `Mapped_T` objects. |
### Type Member
| Member | Description |
| :---------- | :---------- |
| `ValueType` | The type of the elements: `std::pair<const Key_T, Mapped_T>`. |
### Public Member Functions and Comparison Operators of Map
**Constructors and Assignment Operator:**
| Prototype | Description |
| :---------- | :---------- |
| `Map();` | This constructor creates an empty map. |
| `Map(const Map &);` | Copy constructor. |
| `Map &operator=(const Map &);` | Copy assignment operator. [Value semantics](https://isocpp.org/wiki/faq/value-vs-ref-semantics) must be used. You must be able to handle self-assignment. |
| `Map(std::initializer_list<std::pair<const Key_T, Mapped_T>>);` | Initializer list constructor. Support for creation of Map with initial values, such as `Map<string,int> m{{"key1", 1}, {"key2", 2}};`. |
| `~Map();` | Destructor, release any acquired resources. |
**Size:**
| Prototype | Description |
| :---------- | :---------- |
| `size_t size() const;` | Returns the number of elements in the map. |
| `bool empty() const;` | Returns `true` if the Map has no entries in it, `false` otherwise. |
**Iterators:**
| Prototype | Description |
| :---------- | :---------- |
| `Iterator begin();` | Returns an `Iterator` pointing to the first element, in order. |
| `Iterator end();` | Returns an `Iterator` pointing one past the last element, in order. |
| `ConstIterator begin() const;` | Returns a `ConstIterator` pointing to the first element, in order. |
| `ConstIterator end() const;` | Returns a `ConstIterator` pointing one past the last element, in order. |
| `ReverseIterator rbegin()` | Returns an `ReverseIterator` to the first element in reverse order, which is the last element in normal order. |
| `ReverseIterator rend()` | Returns an `ReverseIterator` pointing to one past the last element in reverse order, which is one before the first element in normal order. |
**Element Access:**
| Prototype | Description |
| :---------- | :---------- |
| `Iterator find(const Key_T &);` <br> `ConstIterator find(const Key_T &) const;` | Returns an iterator to the given key. If the key is not found, these functions return the `end()` iterator. |
| `Mapped_T &at(const Key_T &);` | Returns a reference to the mapped object at the specified key. If the key is not in the Map, throws `std::out_of_range`. |
| `const Mapped_T &at(const Key_T &) const;` | Returns a const reference to the mapped object at the specified key. If the key is not in the map, throws `std::out_of_range`. |
| `Mapped_T &operator[](const Key_T &);` | If key is in the map, return a reference to the corresponding mapped object. If it is not, [value initialize](http://en.cppreference.com/w/cpp/language/value_initialization) a mapped object for that key and returns a reference to it (after insert). This operator may not be used for a `Mapped_T` class type that does not support default construction. |
**Modifiers**
| Prototype | Description |
| :---------- | :---------- |
| `std::pair<Iterator, bool> insert(const ValueType &);` <br> <br> `template <typename IT_T> void insert(IT_T range_beg, IT_T range_end);` | The first version inserts the given pair into the map. If the key does not already exist in the map, it returns an iterator pointing to the new element, and `true`. If the key already exists, no insertion is performed nor is the mapped object changed, and it returns an iterator pointing to the element with the same key, and `false`. <br> <br> The second version inserts the given object or range of objects into the map. In the second version, the range of objects inserted includes the object *range_beg* points to, but not the object that *range_end* points to. In other words, the range is *half-open*. The iterator returned in the first version points to the newly inserted element. There must be only one constructor invocation per object inserted. Note that the range may be in a different container type, as long as the iterator is compatible. A compatible iterator would be one from which a `ValueType` can be constructed. For example, it might be from a `std::vector<std::pair<Key_T, Mapped_T>>`. There might be any number of compatible iterator types, therefore, the range insert is a member template. |
| `void erase(Iterator pos);` <br> `void erase(const Key_T &);` | Removes the given object from the map. The object may be indicated by iterator, or by key. If given by key, throws std::out_of_range if the key is not in the Map |
| `void clear();` | Removes all elements from the map. |
**Comparison:**
| Prototype | Description |
| :---------- | :---------- |
| `bool operator==(const Map &, const Map &);` <br> `bool operator!=(const Map &, const Map &);` <br> `bool operator<(const Map &, const Map &);` | These operators may be implemented as member functions or free functions, though implementing as free functions is recommended. The first operator compares the given maps for equality. Two maps compare equal if they have the same number of elements, and if all elements compare equal. The second operator compares the given maps for inequality. You may implement this simply as the logical complement of the equality operator. For the third operator, you must use lexicographic sorting. Corresponding elements from each maps must be compared one-by-one. A map M<sub>1</sub> is less than a map M<sub>2</sub> if there is an element in M<sub>1</sub> that is less than the corresponding element in the same position in map M<sub>2</sub>, or if all corresponding elements in both maps are equal and M<sub>1</sub> is shorter than M<sub>2</sub>. <br> Map elements are of type `ValueType`, so this actually compares the pairs. |
### Public Member Functions of Iterator
**Map<Key_T, Mapped_T>::Iterator**
| Prototype | Description |
| :---------- | :---------- |
| `Iterator(const Iterator &);` | Your class must have a copy constructor, but you do not need to define this if the implicit one works for your implementation. (Which is what I expect in most cases.) |
| `~Iterator();` | Destructor (implicit definition is likely good enough). |
| `Iterator& operator=(const Iterator &);` | Your class must have an assignment operator, but you do not need to define this if the implicit one works for your implementation. (Which is what I expect in most cases.) |
| `Iterator &operator++();` | Increments the iterator one element, and returns a reference to the incremented iterator (preincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `Iterator operator++(int);` | Increments the iterator one element, and returns an iterator pointing to the element prior to incrementing the iterator (postincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `Iterator &operator--();` | Decrements the iterator one element, and returns a reference to the decremented iterator (predecrement). If the iterator is pointing to the beginning of the list, the behavior is undefined. If the iterator has the special value returned by the `end()` function, then the iterator must point to the last element after this function. |
| `Iterator operator--(int);` | Decrements the iterator one element, and returns an iterator pointing to the element prior to decrementing (postdecrement). If the iterator is pointing to the beginning of the list, the behavior is undefined. If the iterator has the special value returned by the `end()` function, then the iterator must point to the last element after this function. |
| `ValueType &operator*() const;` | Returns a reference to the `ValueType` object contained in this element of the list. If the iterator is pointing to the end of the list, the behavior is undefined. This can be used to change the `Mapped_T` member of the element. |
| `ValueType *operator->() const;` | Special member access operator for the element. If the iterator is pointing to the end of the list, the behavior is undefined. This can be used to change the `Mapped_T` member of the element. |
### Public Member Functions of ConstIterator
This class has all the same functions and operators as the `Iterator` class,
except that the dereference operator (`*`) and the class member access
operator (`->`), better known as the arrow operator, return const references.
You should try to move as many of the operations below as possible into a base
class that is common to the other iterator types.
**Map<Key_T, Mapped_T>::ConstIterator**
| Prototype | Description |
| :---------- | :---------- |
| `ConstIterator(const ConstIterator &);` | Your class must have a copy constructor, but you do not need to define this if the implicit one works for your implementation. (Which is what I expect in most cases.) |
| `ConstIterator(const Iterator &);` | This is a conversion operator. |
| `~ConstIterator();` | Destructor (implicit definition is likely good enough). |
| `ConstIterator& operator=(const ConstIterator &);` | Your class must have an assignment operator, but you do not need to define this if the implicit one works for your implementation. (Which is what I expect in most cases.) |
| `ConstIterator &operator++();` | Increments the iterator one element, and returns a reference to the incremented iterator (preincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `ConstIterator operator++(int);` | Increments the iterator one element, and returns an iterator pointing to the element prior to incrementing the iterator (postincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `ConstIterator &operator--();` | Decrements the iterator one element, and returns a reference to the decremented iterator (predecrement). If the iterator is pointing to the beginning of the list, the behavior is undefined. If the iterator has the special value returned by the `end()` function, then the iterator must point to the last element after this function. |
| `ConstIterator operator--(int);` | Decrements the iterator one element, and returns an iterator pointing to the element prior to decrementing (postdecrement). If the iterator is pointing to the beginning of the list, the behavior is undefined. If the iterator has the special value returned by the `end()` function, then the iterator must point to the last element after this function. |
| `const ValueType &operator*() const;` | Returns a reference to the current element of the iterator. If the iterator is pointing to the end of the list, the behavior is undefined. |
| `const ValueType *operator->() const;` | Special member access operator for the element. If the iterator is pointing to the end of the list, the behavior is undefined. |
### Public Member Functions of ReverseIterator
This class has all the same functions and operators as the `Iterator` class,
except that the direction of increment and decrement are reversed. In other
words, incrementing this iterator actually goes backwards through the map.
You should try to move as many of the operations below as possible into a base
class that is common to the other iterator types.
Note that a real container would probably also have a const reverse iterator,
which would result in even more duplication.
**Map<Key_T, Mapped_T>::ReverseIterator**
| Prototype | Description |
| :---------- | :---------- |
| `ReverseIterator(const ReverseIterator &);` | Your class must have a copy constructor, but you do not need to define this if the implicit one works for your implementation. (Which is what I expect in most cases.) |
| `~ReverseIterator();` | Destructor (implicit definition is likely good enough). |
| `ReverseIterator& operator=(const ReverseIterator &);` | Your class must have an assignment operator, but you do not need to define this if the implicit one works for your implementation. (Which is what I expect in most cases.) |
| `ReverseIterator &operator++();` | Increments the iterator one element, and returns a reference to the incremented iterator (preincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `ReverseIterator operator++(int);` | Increments the iterator one element, and returns an iterator pointing to the element prior to incrementing the iterator (postincrement). If the iterator is pointing to the end of the list, the behavior is undefined. |
| `ReverseIterator &operator--()` | Decrements the iterator one element, and returns a reference to the decremented iterator (predecrement). If the iterator is pointing to the beginning of the list, the behavior is undefined. If the iterator has the special value returned by the `end()` function, then the iterator must point to the last element after this function. |
| `ReverseIterator operator--(int)` | Decrements the iterator one element, and returns an iterator pointing to the element prior to decrementing (postdecrement). If the iterator is pointing to the beginning of the list, the behavior is undefined. If the iterator has the special value returned by the `end()` function, then the iterator must point to the last element after this function. |
| `ValueType &operator*() const;` | Returns a reference to the `ValueType` object contained in this element of the list. If the iterator is pointing to the end of the list, the behavior is undefined. This can be used to change the `Mapped_T` member of the element. |
| `ValueType *operator->() const;` | Special member access operator for the element. If the iterator is pointing to the end of the list, the behavior is undefined. This can be used to change the `Mapped_T` member of the element. |
### Comparison Operators for Iterators
These operators implemented as member functions or free functions. I suggest
that you use free functions, however.
| Member | Description |
| :---------- | :---------- |
| `bool operator==(const Iterator &, const Iterator &)` <br> `bool operator==(const ConstIterator &, const ConstIterator &)` <br> `bool operator==(const Iterator &, const ConstIterator &)` <br> `bool operator==(const ConstIterator &, const Iterator &)` <br> `bool operator!=(const Iterator &, const Iterator &)` <br> `bool operator!=(const ConstIterator &, const ConstIterator &)` <br> `bool operator!=const Iterator &, const ConstIterator &)` <br> `bool operator!=const ConstIterator &, const Iterator &)` | You must be able to compare any combination of `Iterator` and `ConstIterator`. Two iterators compare equal if they point to the same element in the list. Two iterators may compare unequal even if the `T` objects that they contain compare equal. It's not strictly necessary that you implement the above exactly as written, only that you must be able to compare the above. For example, if your `Iterator` inherits from `ConstIterator`, then you may be able to get some of the above comparisons autumatically via implicit upcasts. |
| `bool operator==(const ReverseIterator &, const ReverseIterator &)` <br> `bool operator!=(const ReverseIterator &, const ReverseIterator &)` | It's not strictly necessary that you implement the above exactly as written, only that you must be able to compare the above. For example, if your `ReverseIterator` inherits from `Iterator`, then you may be able to get some of the above comparisons autumatically via implicit upcasts. |
## My Submission
* Assignment 2 Submission: https://github.com/bu-cs540/s18a2-SamKustin/commit/746759231d6c499c357eff0ee5efbc9addac39d2
* I believe that my copy constructor performs a deep copy in O(n) time.
* My copy constructor keeps the heights of nodes and their respective links the same, rather than just calling the insert function and getting different heights and links.
* I also believe that I implemented the extra credit, making the map integer indexable, with O(log(n)) performance.
* My index function obtains an iterator to the mapped element by calculating the width of the skiplist links.
* I tested my index function in three ways, with ascending insertion, descending insertion, and shuffled insertion. Then, I index randomly into the map and verify whether the value is correct for all three insertion types.
<file_sep>/final/README.md
# Final
<NAME>
CS 440
Due: 05/14/18
## Instructions
### Chimera (35 pts)
Create some classes to pass all the test cases within `main()`.
### Extractor (65 pts)
An Extractor extracts the corresponding elements from a native array, a
`std::vector`, or a `std::array`, and returns a `std::array` with the
corresponding elements in it.
This extractor will extract the elements with the corresponding indices
from the given sequence container, and return a `std::array` of the
appropriate type with the specified elements.
The extractor should work for any size !!!
including any size of template arguments and any size of the argument array.
Otherwise, you will lose some points.
<file_sep>/assignment4/array/Array.hpp
#ifndef ARRAY_HPP
#define ARRAY_HPP
#include <iostream>
#include <exception>
#include <vector>
#include <utility>
namespace cs540 {
/* ============================ OutOfRange class ========================== */
class OutOfRange : public std::exception {
public:
/**
* const char* what() const throw()
* Returns the explanatory string about the error.
*/
virtual const char* what() const throw() {
return "Error: Out Of Range";
}
}; /* class OutOfRange */
/* ============================== Array class ============================= */
/**
* This declares a multidimensional array containing elements of type T with
* the given dimensions. If any dimension is zero it should fail to compile.
* Use static_assert to force this behavior.
*/
// Most general case. Needed to use partial specialization.
template <typename T, size_t... Dims>
class Array;
// Partial specialization:
// Recursive case w/ multidimensional arrays
template <typename T, size_t D, size_t... Ds>
class Array<T, D, Ds...> {
private:
template <typename U, size_t... D2s> friend class Array;
Array<T, Ds...> inner_arrays[D]; // An array, of size D, of nested Arrays
size_t max_dimensions;
public:
using ValueType = T; // The type of the elements: T
/* =============== FirstDimensionMajorIterator class ============== */
/**
* This iterator is used to iterate through the array in
* row-major order. This iterator can be be used to
* read or write from the array.
*/
class FirstDimensionMajorIterator {
public:
// The array the iterator iterates through
Array<T, D, Ds...>* array_ptr;
// The inner Array that the current Array holds
typename Array<T, Ds...>::FirstDimensionMajorIterator inner_iter;
// Maximum number of dimensions in the current Array
size_t max_dimensions;
// Index of the element the iterators points to
size_t index;
// Whether the iterator has reached the end of the Array
bool end;
public:
/**
* Increment the index
* Row ("First Dimension") major order increments the last
* (innermost/rightmost) dimension first.
* When that one reaches the end, it increments its outer
* array (immediately to the left) and then repeats
* incrementing from the last dimension again.
* This function increments the "outer" array.
*/
bool increment(){
/**
* If the inner iterator increment returns true,
* that means it has reached the end and must "carry",
* we must increment the "outer" (current) array instead,
* and reset the inner array iterator index to 0.
*/
if (inner_iter.increment()){
if (++index == max_dimensions){
index = 0;
end = true;
return true;
}
reset();
}
return false;
}
void reset(){
inner_iter.array_ptr = &((*array_ptr)[index]);
inner_iter.end = false;
inner_iter.reset();
}
public:
// Constructor
/**
* FirstDimensionMajorIterator();
* Must have correct default ctor.
*/
FirstDimensionMajorIterator() :
array_ptr{nullptr},
max_dimensions{D},
index{0},
end{false} {}
/**
* FirstDimensionMajorIterator(Array<T, D, Ds...> &outer)
* Value Constructor
*/
FirstDimensionMajorIterator(Array<T, D, Ds...> *arr_ptr,
size_t i, Array<T, Ds...> *inner_ptr, bool is_end) :
array_ptr{arr_ptr},
inner_iter{inner_ptr->fmbegin()},
max_dimensions{D},
index{i},
end{is_end} {}
// Copy Constructor
/**
* FirstDimensionMajorIterator(const FirstDimensionMajorIterator &);
* Must have correct copy constructor.
* (The implicit one will probably be correct.)
*/
FirstDimensionMajorIterator(const FirstDimensionMajorIterator &other){
array_ptr = other.array_ptr;
inner_iter = other.inner_iter;
max_dimensions = other.max_dimensions;
index = other.index;
end = other.end;
}
// Assignment Operator
/**
* FirstDimensionMajorIterator &operator=(const FirstDimensionMajorIterator &);
* Must have correct assignment operator.
* (The implicit one will probably be correct.)
*/
FirstDimensionMajorIterator &operator=(const FirstDimensionMajorIterator &other){
if (this == &other) return *this;
array_ptr = other.array_ptr;
inner_iter = other.inner_iter;
max_dimensions = other.max_dimensions;
index = other.index;
end = other.end;
return *this;
}
// Equality Operator
/**
* Compares the two iterators for equality.
*/
friend bool operator==(const FirstDimensionMajorIterator &it1,
const FirstDimensionMajorIterator &it2){
if (it1.end && it2.end){
return true; // end of the array
}
return it1.index == it2.index &&
it1.array_ptr == it2.array_ptr &&
it1.inner_iter == it2.inner_iter;
}
// Inequality Operator
/**
* Compares the two iterators for inequality.
*/
friend bool operator!=(const FirstDimensionMajorIterator &it1,
const FirstDimensionMajorIterator &it2){
return !(it1 == it2);
}
// Increment Operators
/**
* FirstDimensionMajorIterator &operator++();
* Increments the iterator one element in row-major order,
* and returns the incremented iterator (preincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
FirstDimensionMajorIterator &operator++(){
increment();
return *this;
}
/**
* FirstDimensionMajorIterator operator++(int);
* Increments the iterator one element in row-major,
* and returns an iterator pointing to the element prior to
* incrementing the iterator (postincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
FirstDimensionMajorIterator operator++(int){
FirstDimensionMajorIterator temp(*this);
increment();
return temp;
}
// Dereference Operator
/**
* T &operator*() const;
* Returns a reference to the T at this position in the array.
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
T &operator*() const {
return *inner_iter;
}
}; /* class FirstDimensionMajorIterator */
/* =============== class LastDimensionMajorIterator =============== */
/**
* This iterator is used to iterate through the array in
* column-major order. This iterator can be only be used to
* read or write from the array.
*/
class LastDimensionMajorIterator {
public:
// The array the iterator iterates through
Array<T, D, Ds...>* array_ptr;
// The inner Array that the current Array holds
typename Array<T, Ds...>::LastDimensionMajorIterator inner_iter;
// Maximum number of dimensions in the current Array
size_t max_dimensions;
// index of the element the iterators points to
size_t index;
// Whether the iterator has reached the end of the Array
bool end;
public:
/**
* Increment the index
* Column ("Last Dimension") major order increments the first
* (outermost/leftmost) dimension first.
* When that one reaches the end, it increments its inner
* array (immediately to the right) and then repeats
* incrementing from the first dimension again.
* This function increments the "outermost" array.
*/
void increment(){
if (++index == max_dimensions){
index = 0; // reset the outermost (current) index to 0
inner_iter.array_ptr = &((*array_ptr)[index]);
inner_iter.increment();
if (inner_iter.end){
end = true;
}
}
reset();
}
void reset(){
inner_iter.array_ptr = &((*array_ptr)[index]);
inner_iter.reset();
if (inner_iter.end){
end = true;
}
}
public:
// Constructor
/**
* LastDimensionMajorIterator();
* Must have correct default constructor.
*/
LastDimensionMajorIterator() :
array_ptr{nullptr},
max_dimensions{D},
index{0},
end{false} {}
/**
* LastDimensionMajorIterator(Array<T, D, Ds..> *arr_ptr,
* size_t i, Array<T, Ds...> *inner_ptr, bool is_end)
* Value Constructor
*/
LastDimensionMajorIterator(Array<T, D, Ds...> *arr_ptr,
size_t i, Array<T, Ds...> *inner_ptr, bool is_end) :
array_ptr{arr_ptr},
inner_iter{inner_ptr->lmbegin()},
max_dimensions{D},
index{i},
end{is_end} {}
// Copy Constructor
/**
* LastDimensionMajorIterator(const LastDimensionMajorIterator &);
* Must have correct copy constructor.
* (The implicit one will probably be correct.)
*/
LastDimensionMajorIterator(const LastDimensionMajorIterator &other){
array_ptr = other.array_ptr;
inner_iter = other.inner_iter;
max_dimensions = other.max_dimensions;
index = other.index;
end = other.end;
}
// Assignment Operator
/**
* LastDimensionMajorIterator &operator=(const LastDimensionMajorIterator &);
* Must have correct assignment operator.
* (The implicit one will probably be correct.)
*/
LastDimensionMajorIterator &operator=(const LastDimensionMajorIterator &other){
if (this == &other) return *this;
array_ptr = other.array_ptr;
inner_iter = other.inner_iter;
max_dimensions = other.max_dimensions;
index = other.index;
end = other.end;
return *this;
}
// Equality Operator
/**
* Compares the two iterators for equality.
*/
friend bool operator==(const LastDimensionMajorIterator &it1,
const LastDimensionMajorIterator &it2){
if (it1.end && it2.end){
return true; // end of the array
}
return it1.index == it2.index &&
it1.array_ptr == it2.array_ptr &&
it1.inner_iter == it2.inner_iter;
}
// Inequality Operator
/**
* Compares the two iterators for inequality.
*/
friend bool operator!=(const LastDimensionMajorIterator &it1,
const LastDimensionMajorIterator &it2){
return !(it1 == it2);
}
// Increment Operators
/**
* LastDimensionMajorIterator &operator++();
* Increments the iterator one element in column-major order,
* and returns the incremented iterator (preincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
LastDimensionMajorIterator &operator++(){
increment();
return *this;
}
/**
* LastDimensionMajorIterator operator++(int);
* Increments the iterator one element in column-major order,
* and returns an iterator pointing to the element prior to
* incrementing the iterator (postincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
LastDimensionMajorIterator operator++(int){
LastDimensionMajorIterator temp(*this);
increment();
return temp;
}
// Dereference Operator
/**
* T &operator*() const;
* Returns a reference to the T at this position in the array.
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
T &operator*() const {
return *inner_iter;
}
}; /* class LastDimensionMajorIterator */
public:
/* ------------ Constructors, Destructors, Operators -------------- */
// Constructor
Array();
// Copy Constructors
Array(const Array<T, D, Ds...> &);
template <typename U> Array(const Array<U, D, Ds...> &);
// Assignment Operators
Array<T, D, Ds...> &operator=(const Array<T, D, Ds...> &);
template <typename U> Array<T, D, Ds...> &operator=(const Array<U, D, Ds...> &);
// Index Operators
Array<T, Ds...> &operator[](size_t);
const Array<T, Ds...> &operator[](size_t) const;
/* --------------------------- Iterators -------------------------- */
FirstDimensionMajorIterator fmbegin();
FirstDimensionMajorIterator fmend();
LastDimensionMajorIterator lmbegin();
LastDimensionMajorIterator lmend();
}; /* template <typename T, size_t D, size_t... Ds> class Array<T, D, Ds...> */
// Partial specialization:
// Base case w/ 1 dimensional array
template <typename T, size_t D>
class Array<T, D> {
private:
template <typename U, size_t... D2s> friend class Array;
T data[D]; // an array with D elements of type T
size_t max_elements; // Maximum length of the array
public:
using ValueType = T; // The type of the elements: T
/* =============== FirstDimensionMajorIterator class ============== */
/**
* This iterator is used to iterate through the array in
* row-major order. This iterator can be be used to
* read or write from the array.
*/
class FirstDimensionMajorIterator {
public:
// The array the iterator iterates through
Array<T, D>* array_ptr;
// Pointer to the element the iterator points to
T* element;
// Maximum number of elements in the array
size_t max_elements;
// Index of the element the iterators points to
size_t index;
// Whether the iterator has reached the end of the Array
bool end;
public:
/**
* Increment the index
* Row ("First Dimension") major order increments the last
* (innermost/rightmost) dimension first.
* When that one reaches the end, it increments its outer
* array (immediately to the left) and then repeats
* incrementing from the last dimension again.
* This function increments the "innermost" array.
*/
bool increment(){
if (++index == max_elements){
end = true;
element = &((*array_ptr)[index - 1]) + 1;
return true;
}
element = &((*array_ptr)[index]);
return false;
}
void reset(){
index = 0;
element = &((*array_ptr)[index]);
end = false;
}
public:
// Constructor
/**
* FirstDimensionMajorIterator();
* Must have correct default ctor.
*/
FirstDimensionMajorIterator() :
array_ptr{nullptr},
element{nullptr},
max_elements{D},
index{0},
end{false} {}
/**
* FirstDimensionMajorIterator(Array<T, D> *arr_ptr, size_t i)
* Value Constructor
*/
FirstDimensionMajorIterator(Array<T, D> *arr_ptr, size_t i, bool is_end) :
array_ptr{arr_ptr},
element{&((*array_ptr)[0])},
max_elements{D},
index{i},
end{is_end} {
if (index < max_elements){
element = &((*array_ptr)[index]);
}
}
// Copy Constructor
/**
* FirstDimensionMajorIterator(const FirstDimensionMajorIterator &);
* Must have correct copy constructor.
* (The implicit one will probably be correct.)
*/
FirstDimensionMajorIterator(const FirstDimensionMajorIterator &other){
array_ptr = other.array_ptr;
element = other.element;
max_elements = other.max_elements;
index = other.index;
end = other.end;
}
// Assignment Operator
/**
* FirstDimensionMajorIterator &operator=(const FirstDimensionMajorIterator &);
* Must have correct assignment operator.
* (The implicit one will probably be correct.)
*/
FirstDimensionMajorIterator &operator=(const FirstDimensionMajorIterator &other){
if (this == &other) return *this;
array_ptr = other.array_ptr;
element = other.element;
max_elements = other.max_elements;
index = other.index;
end = other.end;
return *this;
}
// Equality Operator
/**
* Compares the two iterators for equality.
*/
friend bool operator==(const FirstDimensionMajorIterator &it1,
const FirstDimensionMajorIterator &it2){
if (it1.end && it2.end){
return true; // end of array
}
return it1.index == it2.index &&
it1.array_ptr == it2.array_ptr &&
it1.element == it2.element;
}
// Inequality Operator
/**
* Compares the two iterators for inequality.
*/
friend bool operator!=(const FirstDimensionMajorIterator &it1,
const FirstDimensionMajorIterator &it2){
return !(it1 == it2);
}
// Increment Operators
/**
* FirstDimensionMajorIterator &operator++();
* Increments the iterator one element in row-major order,
* and returns the incremented iterator (preincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
FirstDimensionMajorIterator &operator++(){
increment();
return *this;
}
/**
* FirstDimensionMajorIterator operator++(int);
* Increments the iterator one element in row-major,
* and returns an iterator pointing to the element prior to
* incrementing the iterator (postincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
FirstDimensionMajorIterator operator++(int){
FirstDimensionMajorIterator temp(*this);
increment();
return temp;
}
// Dereference Operator
/**
* T &operator*() const;
* Returns a reference to the T at this position in the array.
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
T &operator*() const {
return *element;
}
}; /* class FirstDimensionMajorIterator */
/* =============== class LastDimensionMajorIterator =============== */
/**
* This iterator is used to iterate through the array in
* column-major order. This iterator can be only be used to
* read or write from the array.
*/
class LastDimensionMajorIterator {
public:
// The array the iterator iterates through
Array<T, D>* array_ptr;
// Pointer to the element the iterator points to
T* element;
// Maximum number of elements in the array
size_t max_elements;
// Index of the element the iterators points to
size_t index;
// Whether the iterator has reached the end of the Array
bool end;
public:
/**
* Increment the index
* Column ("Last Dimension") major order increments the first
* (outermost/leftmost) dimension first.
* When that one reaches the end, it increments its inner
* array (immediately to the right) and then repeats
* incrementing from the first dimension again.
* This function increments the "inner" array.
*/
bool increment(){
if (++index == max_elements){
end = true;
element = &((*array_ptr)[index - 1]) + 1;
return true;
}
element = &((*array_ptr)[index]);
return false;
}
void reset(){
if (!end) {
element = &((*array_ptr)[index]);
}
}
public:
// Constructor
/**
* LastDimensionMajorIterator();
* Must have correct default constructor.
*/
LastDimensionMajorIterator() :
array_ptr{nullptr},
element{nullptr},
max_elements{D},
index{0},
end{false} {}
/**
* LastDimensionMajorIterator(Array<T, D> *arr_ptr, size_t i)
* Value Constructor
*/
LastDimensionMajorIterator(Array<T, D> *arr_ptr, size_t i, bool is_end) :
array_ptr{arr_ptr},
element{&((*array_ptr)[0])},
max_elements{D},
index{i},
end{is_end} {
if (index < max_elements){
element = &((*array_ptr)[index]);
}
}
// Copy Constructor
/**
* LastDimensionMajorIterator(const LastDimensionMajorIterator &);
* Must have correct copy constructor.
* (The implicit one will probably be correct.)
*/
LastDimensionMajorIterator(const LastDimensionMajorIterator &other){
array_ptr = other.array_ptr;
element = other.element;
max_elements = other.max_elements;
index = other.index;
end = other.end;
}
// Assignment Operator
/**
* LastDimensionMajorIterator &operator=(const LastDimensionMajorIterator &);
* Must have correct assignment operator.
* (The implicit one will probably be correct.)
*/
LastDimensionMajorIterator &operator=(const LastDimensionMajorIterator &other){
if (this == &other) return *this;
array_ptr = other.array_ptr;
element = other.element;
max_elements = other.max_elements;
index = other.index;
end = other.end;
return *this;
}
// Equality Operator
/**
* Compares the two iterators for equality.
*/
friend bool operator==(const LastDimensionMajorIterator &it1,
const LastDimensionMajorIterator &it2){
if (it1.end && it2.end) {
return true; // end of the array
}
return it1.index == it2.index &&
it1.array_ptr == it2.array_ptr &&
it1.element == it2.element;
}
// Inequality Operator
/**
* Compares the two iterators for inequality.
*/
friend bool operator!=(const LastDimensionMajorIterator &it1,
const LastDimensionMajorIterator &it2){
return !(it1 == it2);
}
// Increment Operators
/**
* LastDimensionMajorIterator &operator++();
* Increments the iterator one element in column-major order,
* and returns the incremented iterator (preincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
LastDimensionMajorIterator &operator++(){
increment();
return *this;
}
/**
* LastDimensionMajorIterator operator++(int);
* Increments the iterator one element in column-major order,
* and returns an iterator pointing to the element prior to
* incrementing the iterator (postincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
LastDimensionMajorIterator operator++(int){
LastDimensionMajorIterator temp(*this);
increment();
return temp;
}
// Dereference Operator
/**
* T &operator*() const;
* Returns a reference to the T at this position in the array.
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
T &operator*() const {
return *element;
}
}; /* class LastDimensionMajorIterator */
public:
/* ------------ Constructors, Destructors, Operators -------------- */
// Constructor
Array();
// Copy Constructors
Array(const Array<T, D> &);
template <typename U> Array(const Array<U, D> &);
// Assignment Operators
Array<T, D> &operator=(const Array<T, D> &);
template <typename U> Array<T, D> &operator=(const Array<U, D> &);
// Index Operators
T &operator[](size_t);
const T &operator[](size_t) const;
// Other Functions
size_t size() const;
/* --------------------------- Iterators -------------------------- */
FirstDimensionMajorIterator fmbegin();
FirstDimensionMajorIterator fmend();
LastDimensionMajorIterator lmbegin();
LastDimensionMajorIterator lmend();
}; /* template <typename T, size_t D> class Array<T, D> */
/* ===================== Array<T, D, Ds...> Implementation ================ */
/* ------------------- Constructors, Destructors, Operators --------------- */
// Constructor
/**
* Array()
* The default constructor must be defined, either explicitly or implicitly.
*/
template <typename T, size_t D, size_t... Ds>
Array<T, D, Ds...>::Array() : max_dimensions{D} {
static_assert(D > 0, "Array must have dimenstions greater than 0.");
// NOTE: I set length to D because I don't want to make a specific class
// to deal with value assignment to the array e.g. a1[i] = a[i];
}
// Copy Constructors
/**
* Array(const Array &other)
* The copy constructor must work.
* The dimensionality of the source array must be the same.
* Note that a non-template copy constructor must be provided,
* in addtion to the member template copy constructor.
*/
template <typename T, size_t D, size_t... Ds>
Array<T, D, Ds...>::Array(const Array<T, D, Ds...> &other) :
max_dimensions{D} {
for (size_t i = 0; i < max_dimensions; i++){
inner_arrays[i] = other.inner_arrays[i];
}
}
/**
* Array(const Array<U, Dims...> &other)
* The copy constructor must work.
* The dimensionality of the source array must be the same.
*/
template <typename T, size_t D, size_t... Ds>
template <typename U>
Array<T, D, Ds...>::Array(const Array<U, D, Ds...> &other) :
max_dimensions{D} {
for (size_t i = 0; i < max_dimensions; i++){
inner_arrays[i] = other.inner_arrays[i];
}
}
// Assignment Operators
/**
* Array& operator=(const Array &other)
* The assignment operator must work.
* The dimensionality of the source array must be the same.
* Self-assignment must be a no-op.
* Note that this non-template assignment operator must be provided,
* in addtion to the member template assignment operator.
*/
template <typename T, size_t D, size_t... Ds>
Array<T, D, Ds...>& Array<T, D, Ds...>::operator=(const Array<T, D, Ds...> &other) {
if (this == &other) return *this;
max_dimensions = other.max_dimensions;
for (size_t i = 0; i < max_dimensions; i++){
inner_arrays[i] = other.inner_arrays[i];
}
return *this;
}
/**
* Array& operator=(const Array<U, Dims...> &other)
* The assignment operator must work.
* The dimensionality of the source array must be the same.
* Self-assignment must be a no-op.
*/
template <typename T, size_t D, size_t... Ds>
template <typename U>
Array<T, D, Ds...>& Array<T, D, Ds...>::operator=(const Array<U, D, Ds...> &other){
// Don't need to check self assignment because they are
// different types if this method is called to begin with
max_dimensions = other.max_dimensions;
for (size_t i = 0; i < max_dimensions; i++){
inner_arrays[i] = other.inner_arrays[i];
}
return *this;
}
// Index Operators
/**
* T &operator[size_t i_1][size_t i_2]...[size_t i_D];
* const T &operator[size_t i_1][size_t i_2]...[size_t i_D] const;
*
* This is used to index into the array with range-checking.
* If any given indices are out-of-range, then an OutOfRange exception must
* be thrown. Note that this is a “conceptual” operator only.
* Such an operator does not really exist. Instead, you must figure out how
* to provide this functionality. (Helper classes may be useful.)
*/
template <typename T, size_t D, size_t... Ds>
Array<T, Ds...>& Array<T, D, Ds...>::operator[](size_t i){
if (i >= D) throw OutOfRange();
return inner_arrays[i];
}
template <typename T, size_t D, size_t... Ds>
const Array<T, Ds...>& Array<T, D, Ds...>::operator[](size_t i) const {
if (i >= D) throw OutOfRange();
return inner_arrays[i];
}
/* ------------------------------- Iterators ------------------------------ */
/**
* FirstDimensionMajorIterator fmbegin()
* Returns a FirstDimensionMajorIterator (nested classes) object
* pointing to the first element.
*/
template <typename T, size_t D, size_t... Ds>
typename Array<T, D, Ds...>::FirstDimensionMajorIterator
Array<T, D, Ds...>::fmbegin(){
return {this, 0, &(inner_arrays[0]), false};
}
/**
* FirstDimensionMajorIterator fmend()
* Returns a FirstDimensionMajorIterator (nested classes) object
* pointing one past the last element.
*/
template <typename T, size_t D, size_t... Ds>
typename Array<T, D, Ds...>::FirstDimensionMajorIterator
Array<T, D, Ds...>::fmend(){
return {this, max_dimensions, &(inner_arrays[max_dimensions - 1]) + 1, true};
}
/**
* LastDimensionMajorIterator lmbegin()
* Returns a LastDimensionMajorIterator pointing to the first element.
*/
template <typename T, size_t D, size_t... Ds>
typename Array<T, D, Ds...>::LastDimensionMajorIterator
Array<T, D, Ds...>::lmbegin(){
return {this, 0, &(inner_arrays[0]), false};
}
/**
* LastDimensionMajorIterator lmend()
* Returns a LastDimensionMajorIterator pointing one past the last element.
*/
template <typename T, size_t D, size_t... Ds>
typename Array<T, D, Ds...>::LastDimensionMajorIterator
Array<T, D, Ds...>::lmend(){
return {this, max_dimensions, &(inner_arrays[max_dimensions - 1]) + 1, true};
}
/* ======================== Array<T, D> Implementation ==================== */
/* ------------------- Constructors, Destructors, Operators --------------- */
// Constructor
/**
* Array()
* The default constructor must be defined, either explicitly or implicitly.
*/
template <typename T, size_t D>
Array<T, D>::Array() : max_elements{D} {
static_assert(D > 0, "Array must have a dimenstion greater than 0.");
}
// Copy Constructors
/**
* Array(const Array &other)
* The copy constructor must work.
* The dimensionality of the source array must be the same.
* Note that a non-template copy constructor must be provided,
* in addtion to the member template copy constructor.
*/
template <typename T, size_t D>
Array<T, D>::Array(const Array<T, D> &other) : max_elements{D} {
for (size_t i = 0; i < max_elements; i++){
data[i] = other.data[i];
}
}
/**
* Array(const Array<U, Dims...> &other)
* The copy constructor must work.
* The dimensionality of the source array must be the same.
*/
template <typename T, size_t D>
template <typename U>
Array<T, D>::Array(const Array<U, D> &other): max_elements{D} {
for (size_t i = 0; i < max_elements; i++){
data[i] = other.data[i];
}
}
// Assignment Operators
/**
* Array& operator=(const Array &other)
* The assignment operator must work.
* The dimensionality of the source array must be the same.
* Self-assignment must be a no-op.
* Note that this non-template assignment operator must be provided,
* in addtion to the member template assignment operator.
*/
template <typename T, size_t D>
Array<T, D>& Array<T, D>::operator=(const Array<T, D> &other){
if (this == &other) return *this;
max_elements = other.max_elements;
for (size_t i = 0; i < max_elements; i++){
data[i] = other.data[i];
}
return *this;
}
/**
* Array& operator=(const Array<U, Dims...> &other)
* The assignment operator must work.
* The dimensionality of the source array must be the same.
* Self-assignment must be a no-op.
*/
template <typename T, size_t D>
template <typename U>
Array<T, D>& Array<T, D>::operator=(const Array<U, D> &other){
// Don't need to check self assignment because they are
// different types if this method is called to begin with
max_elements = other.max_elements;
for (size_t i = 0; i < max_elements; i++){
data[i] = other.data[i];
}
return *this;
}
// Index Operators
/**
* T &operator[size_t i_1][size_t i_2]...[size_t i_D];
* const T &operator[size_t i_1][size_t i_2]...[size_t i_D] const;
*
* This is used to index into the array with range-checking.
* If any given indices are out-of-range, then an OutOfRange exception must
* be thrown. Note that this is a “conceptual” operator only.
* Such an operator does not really exist. Instead, you must figure out how
* to provide this functionality. (Helper classes may be useful.)
*/
template <typename T, size_t D>
T& Array<T, D>::operator[](size_t i){
if (i >= D) throw OutOfRange();
return data[i];
}
template <typename T, size_t D>
const T& Array<T, D>::operator[](size_t i) const {
if (i >= D) throw OutOfRange();
return data[i];
}
// Other Functions
/**
* size_t size() const;
* Returns the length of the array
*/
template <typename T, size_t D>
size_t Array<T, D>::size() const {
return max_elements;
}
/* ------------------------------- Iterators ------------------------------ */
/**
* FirstDimensionMajorIterator fmbegin()
* Returns a FirstDimensionMajorIterator (nested classes) object
* pointing to the first element.
*/
template <typename T, size_t D>
typename Array<T, D>::FirstDimensionMajorIterator
Array<T, D>::fmbegin(){
return {this, 0, false};
}
/**
* FirstDimensionMajorIterator fmend()
* Returns a FirstDimensionMajorIterator (nested classes) object
* pointing one past the last element.
*/
template <typename T, size_t D>
typename Array<T, D>::FirstDimensionMajorIterator
Array<T, D>::fmend(){
return {this, max_elements, true};
}
/**
* LastDimensionMajorIterator lmbegin()
* Returns a LastDimensionMajorIterator pointing to the first element.
*/
template <typename T, size_t D>
typename Array<T, D>::LastDimensionMajorIterator
Array<T, D>::lmbegin(){
return {this, 0, false};
}
/**
* LastDimensionMajorIterator lmend()
* Returns a LastDimensionMajorIterator pointing one past the last element.
*/
template <typename T, size_t D>
typename Array<T, D>::LastDimensionMajorIterator
Array<T, D>::lmend(){
return {this, max_elements, true};
}
} /* namespace cs540 */
#endif /* ifndef ARRAY_HPP */
<file_sep>/assignment1/makefile
all:
g++ -o test -Wall -Wextra -pedantic -g -ldl src/test.cpp
clean:
rm -f test
<file_sep>/assignment3/SmartPtr/SharedPtr.hpp
#ifndef SHAREDPTR_HPP
#define SHAREDPTR_HPP
#include <iostream> // cout, endl
#include <utility> // nullptr
#include <mutex> // mutex, unique_lock
namespace cs540 {
/* ======================== ReferenceCountBase Class ====================== */
/**
* ReferenceCountBase describes the interface for the ReferenceCount.
* It is the base control block for the shared pointer.
* It also manages the reference count for the object.
*/
class ReferenceCountBase {
private:
int count;
std::mutex rc_mutex;
public:
ReferenceCountBase() : count{1} {}
virtual ~ReferenceCountBase() {} // prevent slicing w/ type erasure
/**
* void increment_count()
* Increment the reference count for the reference object
*/
void increment_count(){
// std::cout << "ReferenceCountBase::increment_count called" << std::endl;
std::unique_lock<std::mutex> lock(rc_mutex);
count++;
}
/**
* void decrement_count()
* Decrement the reference count for the reference object
*/
void decrement_count(){
std::unique_lock<std::mutex> lock(rc_mutex);
--count;
if (count == 0){
lock.unlock();
delete this;
}
}
/**
* int get_count()
* return the reference count for the reference object
*/
int get_count(){
return count;
}
}; /* class ReferenceCountBase */
/* ========================== ReferenceCountClass ========================= */
/**
* ReferenceCount contains the implementation for the ReferenceCountBase.
*/
template <typename U>
class ReferenceCount : public ReferenceCountBase {
private:
U* rc_pointer;
public:
ReferenceCount() : ReferenceCountBase{}, rc_pointer{nullptr} {}
ReferenceCount(U* p) : ReferenceCountBase{}, rc_pointer{p} {}
virtual ~ReferenceCount() {
delete rc_pointer;
}
}; /* class ReferenceCount */
/* =========================== SharedPtr Class ============================ */
template <typename T>
class SharedPtr {
private:
T* sp_pointer;
cs540::ReferenceCountBase* rc_object;
/**
* void increment_count()
* Increment the reference count for the SharedPtr's reference object
*/
void increment_count(){
if (sp_pointer != nullptr && rc_object != nullptr){
rc_object->increment_count();
}
}
/**
* void decrement_count()
* Decrement the reference count for the SharedPtr's reference object.
* If the count becomes 0, delete the reference object.
*/
void decrement_count(){
if (sp_pointer != nullptr && rc_object != nullptr){
if (rc_object->get_count() == 1){
rc_object->decrement_count();
sp_pointer = nullptr;
rc_object = nullptr;
} else {
rc_object->decrement_count();
}
}
}
public:
/* ------ Constructors, Assignment Operators, and Destructor ------ */
/* Default Constructor */
SharedPtr();
/* Value Constructor */
template <typename U> explicit SharedPtr(U *);
/* Copy Constructor */
SharedPtr(const SharedPtr &p);
template <typename U> SharedPtr(const SharedPtr<U> &p);
/* Move Constructor */
SharedPtr(SharedPtr &&p);
template <typename U> SharedPtr(SharedPtr<U> &&p);
/* Extra constructor - needed for casting */
template <typename U> SharedPtr(const SharedPtr<U> &p, T* ptr);
/* Copy assignment operator */
SharedPtr<T>& operator=(const SharedPtr &);
template <typename U> SharedPtr<T>& operator=(const SharedPtr<U> &);
/* Move Assignment Operator */
SharedPtr<T>& operator=(SharedPtr &&p);
template <typename U> SharedPtr<T>& operator=(SharedPtr<U> &&p);
/* Destructor */
~SharedPtr();
/* --------------------------- Modifiers -------------------------- */
void reset();
template <typename U> void reset(U *p);
/* --------------------------- Observers -------------------------- */
T* get() const;
T& operator*() const;
T* operator->() const;
/**
* operator bool() const
* Returns true if the SharedPtr is not null.
*/
explicit operator bool() const {
return sp_pointer != nullptr;
}
/* -------------------------- Friend Classes ---------------------- */
template <typename U> friend class SharedPtr;
}; /* class SharedPtr */
/* ================== SharedPtr Function Implementation =================== */
/* ------ Constructors, Assignment Operators, and Destructor ------ */
// Default Constructor
/**
* SharedPtr()
* Constructs a smart pointer that points to null.
*/
template <typename T>
SharedPtr<T>::SharedPtr() : sp_pointer{nullptr}, rc_object{nullptr} {}
// Value Constructor
/**
* SharedPtr(U *)
* Constructs a smart pointer that points to the given object.
* The reference count is initialized to one.
*/
template <typename T>
template <typename U>
SharedPtr<T>::SharedPtr(U *p) :
sp_pointer{p},
rc_object{new cs540::ReferenceCount<U>{p}} {}
// Copy Constructor
/**
* SharedPtr(const SharedPtr &p)
* If p is not null, then reference count of the managed object is
* incremented.
*/
template <typename T>
SharedPtr<T>::SharedPtr(const SharedPtr &p) :
sp_pointer{p.sp_pointer}, rc_object{p.rc_object} {
if (p != nullptr){
increment_count();
}
}
/**
* SharedPtr(const SharedPtr<U> &p)
* If p is not null, then reference count of the managed object is
* incremented. If U * is not implicitly convertible to T *, use of the
* templated constructor will result in a compile-time error when the
* compiler attempts to instantiate the member template.
*/
template <typename T>
template <typename U>
SharedPtr<T>::SharedPtr(const SharedPtr<U> &p) :
sp_pointer{p.sp_pointer}, rc_object{p.rc_object} {
if (p != nullptr){
increment_count();
}
}
// Move Constructor
/**
* SharedPtr(SharedPtr &&p)
* Move the managed object from the given smart pointer. The reference
* count must remain unchanged. After this function, p must be null.
*/
template <typename T>
SharedPtr<T>::SharedPtr(SharedPtr &&p) :
sp_pointer{std::move(p.sp_pointer)}, rc_object{std::move(p.rc_object)} {
p.sp_pointer = nullptr;
p.rc_object = nullptr;
}
/**
* SharedPtr(SharedPtr<U> &&p)
* Move the managed object from the given smart pointer. The reference
* count must remain unchanged. After this function, p must be null.
* This must work if U * is implicitly convertible to T *.
*/
template <typename T>
template <typename U>
SharedPtr<T>::SharedPtr(SharedPtr<U> &&p) :
sp_pointer{std::move(p.sp_pointer)}, rc_object{std::move(p.rc_object)} {
p.sp_pointer = nullptr;
p.rc_object = nullptr;
}
// Extra constructor - needed for casting
template <typename T>
template <typename U>
SharedPtr<T>::SharedPtr(const SharedPtr<U> &p, T* ptr){
sp_pointer = ptr;
rc_object = p.rc_object;
increment_count();
}
// Copy Assignment Operator
/**
* SharedPtr<T>& operator=(const SharedPtr &p)
* Copy assignment. Must handle self assignment. Decrement reference count
* of current object, if any, and increment reference count of the given
* object.
*/
template <typename T>
SharedPtr<T>& SharedPtr<T>::operator=(const SharedPtr &p){
if (&p == this) return *this;
decrement_count();
sp_pointer = p.sp_pointer;
rc_object = p.rc_object;
increment_count();
return *this;
}
/**
* SharedPtr<T>& operator=(const SharedPtr<U> &p)
* Copy assignment. Must handle self assignment. Decrement reference count
* of current object, if any, and increment reference count of the given
* object. If U * is not implicitly convertible to T *, this will result in a
* syntax error. Note that both the normal assignment operator and a member
* template assignment operator must be provided for proper operation.
*/
template <typename T>
template <typename U>
SharedPtr<T>& SharedPtr<T>::operator=(const SharedPtr<U> &p){
decrement_count();
sp_pointer = p.sp_pointer;
rc_object = p.rc_object;
increment_count();
return *this;
}
// Move Assignment Operator
/**
* SharedPtr<T>& operator=(SharedPtr &&p)
* Move assignment. After this operation, p must be null.
* The reference count associated with the object (if p is not null before
* the operation) will remain the same after this operation.
*/
template <typename T>
SharedPtr<T>& SharedPtr<T>::operator=(SharedPtr &&p){
if (&p == this) return *this;
decrement_count();
sp_pointer = std::move(p.sp_pointer);
rc_object = std::move(p.rc_object);
p.sp_pointer = nullptr;
p.rc_object = nullptr;
return *this;
}
/**
* SharedPtr<T>& operator=(SharedPtr<U> &&p)
* Move assignment. After this operation, p must be null.
* The reference count associated with the object (if p is not null before
* the operation) will remain the same after this operation.
* This must compile and run correctly if U * is implicitly
* convertible to T *, otherwise, it must be a syntax error.
*/
template <typename T>
template <typename U>
SharedPtr<T>& SharedPtr<T>::operator=(SharedPtr<U> &&p){
decrement_count();
sp_pointer = std::move(p.sp_pointer);
rc_object = std::move(p.rc_object);
p.sp_pointer = nullptr;
p.rc_object = nullptr;
return *this;
}
// Destructor
/**
* ~SharedPtr()
* Decrement reference count of managed object.
* If the reference count is zero, delete the object.
*/
template <typename T>
SharedPtr<T>::~SharedPtr(){
decrement_count();
}
/* --------------------------- Modifiers -------------------------- */
/**
* void reset()
* The smart pointer is set to point to the null pointer.
* The reference count for the currently pointed to object, if any,
* is decremented.
*/
template <typename T>
void SharedPtr<T>::reset(){
decrement_count();
sp_pointer = nullptr;
rc_object = nullptr;
}
/**
* void reset(U *p)
* Replace owned resource with another pointer. If the owned resource has no
* other references, it is deleted. If p has been associated with some other
* smart pointer, the behavior is undefined.
*/
template <typename T>
template <typename U>
void SharedPtr<T>::reset(U *p){
decrement_count();
sp_pointer = p;
rc_object = new cs540::ReferenceCount<U>{p};
}
/* --------------------------- Observers -------------------------- */
/**
* T* get() const
* Returns a pointer to the owned object.
* Note that this will be a pointer-to-const if T is a const-qualified type.
*/
template <typename T>
T* SharedPtr<T>::get() const {
return sp_pointer;
}
/**
* T& operator*() const
* A reference to the pointed-to object is returned.
* Note that this will be a const-reference if T is a const-qualified type.
*/
template <typename T>
T& SharedPtr<T>::operator*() const {
return *sp_pointer;
}
/**
* T* operator->() const
* The pointer is returned.
* Note that this will be a pointer-to-const if T is a const-qualified type.
*/
template <typename T>
T* SharedPtr<T>::operator->() const {
return sp_pointer;
}
/* ============== Non-member (Free) Function Implementation =============== */
// Equality operators
/**
* operator==(const SharedPtr<T1> &, const SharedPtr<T2> &)
* Returns true if the two smart pointers point to the same object or if
* they are both null. Note that implicit conversions may be applied.
*/
template <typename T1, typename T2>
bool operator==(const SharedPtr<T1> &p1, const SharedPtr<T2> &p2){
return p1.get() == p2.get();
}
/**
* operator==(const SharedPtr<T> &, std::nullptr_t)
* Compare the SharedPtr against nullptr.
*/
template <typename T>
bool operator==(const SharedPtr<T> &p, std::nullptr_t){
return p.get() == nullptr;
}
/**
* operator==(std::nullptr_t, const SharedPtr<T> &)
* Compare the SharedPtr against nullptr.
*/
template <typename T>
bool operator==(std::nullptr_t, const SharedPtr<T> &p){
return nullptr == p.get();
}
// Inequality operators
/**
* operator!=(const SharedPtr<T1> &, const SharedPtr<T2> &)
* True if the SharedPtrs point to different objects, or one points to
* null while the other does not.
*/
template <typename T1, typename T2>
bool operator!=(const SharedPtr<T1> &p1, const SharedPtr<T2> &p2){
return !(p1 == p2);
}
/**
* operator!=(const SharedPtr<T> &, std::nullptr_t)
* Compare the SharedPtr against nullptr.
*/
template <typename T>
bool operator!=(const SharedPtr<T> &p, std::nullptr_t n_ptr){
return !(p == n_ptr);
}
/**
* operator!=(std::nullptr_t, const SharedPtr<T> &)
* Compare the SharedPtr against nullptr.
*/
template <typename T>
bool operator!=(std::nullptr_t n_ptr, const SharedPtr<T> &p){
return !(n_ptr == p);
}
// Casting
/**
* static_pointer_cast(const SharedPtr<U> &sp)
* Convert sp by using static_cast to cast the contained pointer.
* It will result in a syntax error if static_cast cannot be applied to
* the relevant types.
*/
template <typename T, typename U>
SharedPtr<T> static_pointer_cast(const SharedPtr<U> &sp){
// see: http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
return SharedPtr<T>(sp, static_cast<T*>(sp.get()));
}
/**
* dynamic_pointer_cast(const SharedPtr<U> &sp)
* Convert sp by using dynamic_cast to cast the contained pointer.
* It will result in a syntax error if dynamic_cast cannot be applied to the
* relevant types, and will result in a smart pointer to null if the dynamic
* type of the pointer in sp is not T *.
*/
template <typename T, typename U>
SharedPtr<T> dynamic_pointer_cast(const SharedPtr<U> &sp){
// see: http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
if (auto p = dynamic_cast<T*>(sp.get())){
return SharedPtr<T>(sp, p);
}
return SharedPtr<T>();
}
} /* namespace cs540 */
#endif /* ifndef SHAREDPTR_HPP */
<file_sep>/assignment2/docs/doubly_linked_circular_list.cpp
#include <iostream>
using namespace std;
struct Node {
Node() : pred(0), suc(0) {}
Node(Node *p, Node *s) : pred(p), suc(s) {}
Node *pred; // Predecessor
Node *suc; // Successor
};
struct DataNode : public Node {
DataNode(int i) : some_data(i) {}
const int some_data;
};
// Insert before pos.
void
insert(Node *pos, Node *n) {
n->pred = pos->pred;
n->suc = pos;
pos->pred->suc = n;
pos->pred = n;
}
// Remove.
void
remove(Node *n) {
n->pred->suc = n->suc;
n->suc->pred = n->pred;
n->pred = n->suc = 0;
}
template <Node *Node::*ptr> struct Traits {
static const char *const order_type;
};
// Template specializations.
template <> const char *const Traits<&Node::pred>::order_type = "reverse";
template <> const char *const Traits<&Node::suc>::order_type = "forward";
void
print_forward(const Node &sent) {
for (Node *n = sent.suc; n != &sent; n = n->suc) {
cout << static_cast<DataNode *>(n)->some_data << endl;
}
}
template <Node *Node::*ptr>
void
print_list(const Node &sent) {
cout << "Printing list in " << Traits<ptr>::order_type << " order: " << endl;
for (Node *n = sent.*ptr; n != &sent; n = n->*ptr) {
cout << static_cast<DataNode *>(n)->some_data << endl;
}
}
int
main() {
Node sentinel;
sentinel.suc = sentinel.pred = &sentinel;
// Insert at end.
insert(&sentinel, new DataNode(1));
// Insert at end.
insert(&sentinel, new DataNode(2));
print_list<&Node::suc>(sentinel);
// Insert at beginning.
insert(sentinel.suc, new DataNode(-1));
insert(sentinel.suc, new DataNode(-2));
print_list<&Node::suc>(sentinel);
// Remove first.
remove(sentinel.suc);
// Remove last.
remove(sentinel.pred);
// Traverse in reverse order.
print_list<&Node::pred>(sentinel);
// Should delete memory at the end.
}
<file_sep>/assignment3/Makefile
CC=g++
CFLAG = -g -Wall -Wextra -pedantic -ldl -std=c++14
all: smartPtrExe rvalueRefExe functionExe
# Executables
smartPtrExe: smartPtr.o
# Execute smartPtr with -t secs, where secs is how long to run the thread test for.
# secs defaults to 15 seconds.
$(CC) $(CFLAG) smartPtr.o -lpthread -o smartPtrExe
rvalueRefExe: rvalueRef.o myInt.o
$(CC) $(CFLAG) rvalueRef.o myInt.o -o rvalueRefExe
functionExe: function.o
$(CC) $(CFLAG) function.o -o functionExe
# Objects
smartPtr.o: SmartPtr/SharedPtr_test.cpp SmartPtr/SharedPtr.hpp
# smartPtr.o compiled with -pthread
$(CC) $(CFLAG) -pthread -c SmartPtr/SharedPtr_test.cpp -lpthread -o smartPtr.o
rvalueRef.o: RvalueRef/Array_test.cpp RvalueRef/Array.hpp RvalueRef/MyInt.hpp
$(CC) $(CFLAG) -c RvalueRef/Array_test.cpp -o rvalueRef.o
myInt.o: RvalueRef/MyInt.cpp RvalueRef/MyInt.hpp
$(CC) $(CFLAG) -c RvalueRef/MyInt.cpp -o myInt.o
function.o: FuncWrapper/Function_test.cpp FuncWrapper/Function.hpp
$(CC) $(CFLAG) -c FuncWrapper/Function_test.cpp -o function.o
clean:
rm -f smartPtrExe rvalueRefExe functionExe *.o
rm -rf *.dSYM
<file_sep>/assignment4/ostream/Interpolate.hpp
#ifndef INTERPOLATE_HPP
#define INTERPOLATE_HPP
#include <iostream>
#include <iomanip>
#include <exception>
#include <string>
#include <tuple>
#include <vector>
#include <utility>
#include <type_traits>
namespace cs540 {
/* ============================= ffr() Function ========================== */
/**
* ffr() is used to force instantiation of a function template.
* It takes in the relevant function by reference and then returns it.
*/
constexpr auto ffr(std::ostream &(*function_ptr)(std::ostream &)) {
return function_ptr;
}
constexpr auto ffr(std::ios_base &(*function_ptr)(std::ios_base &)) {
return function_ptr;
}
/* ========================= WrongNumberOfArgs class ====================== */
class WrongNumberOfArgs : public std::exception {
public:
/**
* const char* what() const throw()
* Returns the explanatory string about the error.
*/
virtual const char* what() const throw() {
return "Error: Wrong number of arguments";
}
}; /* class WrongNumberOfArgs */
/* =========================== Interpolate_T class ======================== */
template <typename... Ts>
class Interpolate_Implementation {
private:
std::string format_string;
std::tuple<const Ts &...> arguments;
public:
/**
* Interpolate(const std::string &, const Ts &...)
* Value constructor
*/
Interpolate_Implementation(
const std::string & format_str, const Ts &... args) :
format_string{format_str}, arguments{args...} {}
/**
* Output operator
* Outputs the correctly formatted string
*/
friend std::ostream& operator<<(
std::ostream &os,
const Interpolate_Implementation<Ts...> &interpolate) {
return interpolate.print(os);
}
/**
* Initiates the recursion to format the string.
*/
std::ostream& print(std::ostream &os) const {
return format<0>(os, arguments, format_string.cbegin());
}
/**
* Formats the string with each argument, one by one.
*/
template <std::size_t index, typename T>
std::ostream& format(std::ostream &os, const T &arg,
std::string::const_iterator string_iter) const {
while (string_iter != format_string.cend()){
// If the % was escaped, print a literal percent sign.
if (*string_iter == '\\' && (string_iter + 1) != format_string.cend()){
if (*(string_iter + 1) == '%'){
os << '%';
// Skip processing the percent sign bc it's not an arg
string_iter = string_iter + 2;
continue;
}
}
// If the % is an argument, print it, if any args still exist.
if (*string_iter == '%'){
if constexpr (index < std::tuple_size_v<T>){
// Output the argument and check for io manipulator
if (output_and_check_io_manip(os, std::get<index>(arg))){
// If there was an io manip, don't inc string iter
// because it does not consume a % sign
return format<index + 1>(os, arg, string_iter);
}
return format<index + 1>(os, arg, ++string_iter);
} else {
// Too little arguments given
throw WrongNumberOfArgs();
}
}
// If not a % or an escaped %, print the string character.
os << *string_iter;
string_iter++;
}
if constexpr (index != std::tuple_size_v<T>){
// Check if remaining arguments are io manipulators
if (output_and_check_io_manip(os, std::get<index>(arg))){
// If there was an io manip, don't inc string iter
return format<index + 1>(os, arg, string_iter);
}
// If it wasn't an io manipulator, throw an error
// Too many arguments given
throw WrongNumberOfArgs();
}
// Clear any extra format flags
// os.unsetf(os.flags());
// std::cout.unsetf(std::cout.flags());
return os;
}
/**
* Outputs the argument and returns whether it was an IO manipulator.
* This overload is not an io manip, so it consumes a % sign.
*/
template <typename T>
bool output_and_check_io_manip(std::ostream &os, const T &arg) const {
/**
* This is horrible but idk how to check for the other io manips.
* These are checks for if arg are one of the following:
* resetiosflags, setiosflags, setbase --> returns fmtflags
* fill --> returns CharT, default fill character = ' '
* setprecision, setw --> returns streamsize
*/
std::ios_base::fmtflags before_flags = os.flags();
char before_fill = os.fill();
std::streamsize before_precision = os.precision();
std::streamsize before_width = os.width();
// Output the argument
os << arg;
// Check for differences in case of io manipulator
if ((before_flags != os.flags()) ||
(before_fill != os.fill()) ||
(before_precision != os.precision()) ||
(os.width() != 0 && before_width != os.width())){
return true; // Argument is an io manipulator
}
return false; // Argument was not an io manipulator.
}
/**
* If the argument is an io manipulator, we will overload the output
* function so the io manip gets converted to a function pointer.
* Then, we output the io manip function pointer to the stream.
*/
bool output_and_check_io_manip(std::ostream &os,
std::ios_base &(*io_manip)(std::ios_base &)) const {
// Output/set the io manipulator
os << io_manip;
return true; // Argument is an io manipulator
}
/**
* If the argument is an output stream operation, we will overload the
* output function so operation gets converted to a function pointer.
* Then, we output the operation function pointer to the stream.
*/
bool output_and_check_io_manip(std::ostream &os,
std::ostream &(*output_operation)(std::ostream &)) const {
// Output the operation
os << output_operation;
// std::flush should not consume a % sign, so treat it
// like an io manipulator and return true.
if (output_operation == ffr(std::flush)) return true;
// Otherwise, return false because the operation will
// consume a % sign so it is treated like a normal argument.
return false;
}
}; /* class Interpolate_T */
/* ========================== Interpolate Function ======================= */
template <typename... Ts>
Interpolate_Implementation<Ts...> Interpolate(
const std::string &format_string,
const Ts &... arguments) {
return Interpolate_Implementation<Ts...>(format_string, arguments...);
}
} /* namespace cs540 */
#endif /* ifndef INTERPOLATE_HPP */
<file_sep>/assignment2/src/Map.hpp
#ifndef MAP_HPP
#define MAP_HPP
#include <iostream>
#include <vector>
#include <utility>
#include <cstdlib>
#include <cassert>
#include <ctime>
namespace cs540 {
// Declares a Map class that maps from Key_T objects to Mapped_T objects.
template <typename Key_T, typename Mapped_T>
class Map {
public:
/* Forward declarations */
class Iterator;
class ConstIterator;
class ReverseIterator;
private:
class SkipList {
public:
using ValueType = std::pair<const Key_T, Mapped_T>;
/* ================ Nested Class Definitions ============== */
/* Forward declaration for Node class */
class Node;
// ------------------------ Link Class -------------------- //
/**
* Link represents the actual connections between the Nodes.
* The Link class is a wrapper for the vector of Node*
* We use a class as a wrapper so we can do things like overloading.
*/
class Link {
public:
/**
* Contains pointers to what the current Node points to
* at each level
*/
std::vector<Node*> links;
/* The distance to the next node at each level */
std::vector<int> width;
Link() = default;
/**
* Assign all elements of the links vector to point to the
* Node and initialize all width distances to the next node
* to 1.
*/
Link& operator=(Node* node){
for (auto &p : links){
p = node;
width.push_back(1);
}
return *this;
}
/* Index links, but use .at() for range-checking */
Node* operator[](int i){
return links.at(i);
}
/* Index links, but use .at() for range-checking */
const Node* operator[](int i) const {
return links.at(i);
}
/**
* Get the width distance to the next node at the
* i'th level
*/
int get_width(int level){
return width.at(level);
}
int get_width(int level) const {
return width.at(level);
}
/**
* Set the width distance to the next node the
* i'th level
*/
void set_width(int level, int d){
width.at(level) = d;
}
};
// ------------------------ Node Class -------------------- //
/**
* Base class for Node. It contains links but not the actual data.
* This allows us to have a sentinel that doesn't contain data.
*/
class Node {
public:
Link next, prev;
Node() = default;
/* Set all links to the same height */
void set_height(int h) {
next.links.resize(h);
prev.links.resize(h);
next.width.resize(h);
prev.width.resize(h);
}
/* Return the height of the node */
int get_height() const {
// Just double-checking this invariant
assert(next.links.size() == prev.links.size());
return next.links.size();
}
};
// ---------------------- NodeData Class ------------------ //
/**
* Derived class for Node. It contains the data for the base Node.
*/
class Node_data : public Node {
public:
explicit Node_data(ValueType d) : data(d) {}
ValueType data;
Key_T key() {
return data.first;
}
const Key_T key() const {
return data.first;
}
Mapped_T& value() {
return data.second;
}
const Mapped_T& value() const {
return data.second;
}
};
/* =================== Variable Declarations ============== */
const int MAX_HEIGHT = 32; // Max height of the skiplist
Node head; // Sentinel node
size_t length; // length of skiplist, not including sentinel
/* =================== Function Declarations ============== */
SkipList();
~SkipList();
SkipList(const SkipList &other);
SkipList& operator=(const SkipList &other);
size_t size() const;
bool empty() const;
Node* front();
const Node* front() const;
Node* back();
const Node* back() const;
Node* index(int i);
const Node* index(int i) const;
Node* find(const Key_T key);
const Node* find(const Key_T key) const;
int random_height();
std::pair<typename Map<Key_T, Mapped_T>::Iterator, bool>
insert(const ValueType &data);
void remove(Key_T key);
void clear();
}; /* class SkipList */
public:
using ValueType = std::pair<const Key_T, Mapped_T>;
/* ========================== Iterators =========================== */
// TODO: MAKE A BASE ITERATOR CLASS AND DERIVE OTHER ITERATORS FROM IT
// ------------------------ Iterator Class ------------------------ //
/**
* The Iterator class moves forward through the map.
*/
class Iterator {
public:
// The node that the Iterator points to
typename SkipList::Node* node;
// Default constructor is not permitted.
Iterator() = delete;
// Value constructor
explicit Iterator(typename SkipList::Node* n) : node(n) {}
// Copy constructor
Iterator(const Iterator &) = default;
// Destructor
~Iterator() = default;
// Assignment operator
Iterator& operator=(const Iterator &) = default;
/**
* operator++()
* Increments the iterator one element, and returns a
* reference to the incremented iterator (preincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
Iterator& operator++(){
this->node = this->node->next[0];
return *this;
}
/**
* operator++(int)
* Increments the iterator one element, and returns an
* iterator pointing to the element prior to incrementing
* the iterator (postincrement). If the iterator is pointing
* to the end of the list, the behavior is undefined.
*/
Iterator operator++(int){
Iterator temp(*this); // Explicit temporary
this->node = this->node->next[0];
return temp;
}
/**
* operator--()
* Decrements the iterator one element, and returns a
* reference to the decremented iterator (predecrement).
* If the iterator is pointing to the beginning of the list,
* the behavior is undefined. If the iterator has the special
* value returned by the end() function, then the iterator
* must point to the last element after this function.
*/
Iterator& operator--(){
this->node = this->node->prev[0];
return *this;
}
/**
* operator--(int)
* Decrements the iterator one element, and returns an
* iterator pointing to the element prior to decrementing
* (postdecrement). If the iterator is pointing to the
* beginning of the list, the behavior is undefined. If the
* iterator has the special value returned by the end()
* function, then the iterator must point to the last
* element after this function.
*/
Iterator operator--(int){
Iterator temp(*this); // Explicit temporary
this->node = this->node->prev[0];
return temp;
}
/**
* operator*() const
* Returns a reference to the ValueType object contained in
* this element of the list. If the iterator is pointing to
* the end of the list, the behavior is undefined. This can
* be used to change the Mapped_T member of the element.
*/
ValueType& operator*() const {
typename SkipList::Node_data* node_data =
static_cast<typename SkipList::Node_data*>(this->node);
return node_data->data;
}
/**
* operator->() const
* Special member access operator for the element.
* If the iterator is pointing to the end of the list,
* the behavior is undefined. This can be used to change
* the Mapped_T member of the element.
*/
ValueType* operator->() const {
typename SkipList::Node_data* node_data =
static_cast<typename SkipList::Node_data*>(this->node);
return &(node_data->data);
}
}; /* class Iterator */
// ---------------------- ConstIterator Class --------------------- //
/**
* The ConstIterator class has all the same functions and operators
* as the Iterator class, except that the dereference operator (*)
* and the class member access operator (->), better known as the
* arrow operator, return const references.
*/
class ConstIterator {
public:
// The node that the ConstIterator points to
const typename SkipList::Node* node;
// Default constructor is not permitted.
ConstIterator() = delete;
// Value constructor
explicit ConstIterator(const typename SkipList::Node* n) : node(n) {}
// Copy constructor
ConstIterator(const ConstIterator &) = default;
// Conversion operator
ConstIterator(const Iterator &other) : node(other.node) {}
// Destructor
~ConstIterator() = default;
// Assignment operator
ConstIterator& operator=(const ConstIterator &) = default;
/**
* operator++()
* Increments the iterator one element, and returns a
* reference to the incremented iterator (preincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
ConstIterator& operator++(){
this->node = this->node->next[0];
return *this;
}
/**
* operator++(int)
* Increments the iterator one element, and returns an
* iterator pointing to the element prior to incrementing
* the iterator (postincrement). If the iterator is pointing
* to the end of the list, the behavior is undefined.
*/
ConstIterator operator++(int){
ConstIterator temp(*this); // Explicit temporary
this->node = this->node->next[0];
return temp;
}
/**
* operator--()
* Decrements the iterator one element, and returns a
* reference to the decremented iterator (predecrement).
* If the iterator is pointing to the beginning of the list,
* the behavior is undefined. if the iterator has the special
* value returned by the end() function, then the iterator
* must point to the last element after this function.
*/
ConstIterator& operator--(){
this->node = this->node->prev[0];
return *this;
}
/**
* operator--(int)
* Decrements the iterator one element, and returns an
* iterator pointing to the element prior to decrementing
* (postdecrement). If the iterator is pointing to the
* beginning of the list, the behavior is undefined. if the
* iterator has the special value returned by the end()
* function, then the iterator must point to the last element
* after this function.
*/
ConstIterator operator--(int){
ConstIterator temp(*this); // Explicit temporary
this->node = this->node->prev[0];
return temp;
}
/**
* operator*() const
* Returns a const reference to the current element of the iterator.
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
const ValueType& operator*() const {
const typename SkipList::Node_data* node_data =
static_cast<const typename SkipList::Node_data*>(this->node);
return node_data->data;
}
/**
* operator->() const
* Special member access operator for the element.
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
const ValueType* operator->() const {
const typename SkipList::Node_data* node_data =
static_cast<const typename SkipList::Node_data*>(this->node);
return &(node_data->data);
}
}; /* class ConstIterator */
// --------------------- ReverseIterator Class -------------------- //
/**
* This class has all the same functions and operators as the
* Iterator class, except that the direction of increment and
* decrement are reversed. In other words, incrementing this
* iterator actually goes backwards through the map.
*/
class ReverseIterator {
public:
// The node that the ReverseIterator points to
typename SkipList::Node* node;
// Default constructor is not permitted.
ReverseIterator() = delete;
// Value constructor
explicit ReverseIterator(typename SkipList::Node* node){
this->node = node;
}
// Copy constructor
ReverseIterator(const ReverseIterator &) = default;
// Destructor
~ReverseIterator() = default;
// Assignment operator
ReverseIterator& operator=(const ReverseIterator &) = default;
/**
* operator++()
* Increments the iterator backwards one element, and returns
* a reference to the incremented iterator (preincrement).
* If the iterator is pointing to the end of the list,
* the behavior is undefined.
*/
ReverseIterator& operator++(){
this->node = this->node->prev[0];
return *this;
}
/**
* operator++(int)
* Increments the iterator backwards one element, and returns
* an iterator pointing to the element prior to incrementing
* the iterator (postincrement). If the iterator is pointing
* to the end of the list, the behavior is undefined.
*/
ReverseIterator operator++(int){
ReverseIterator temp(*this);
this->node = this->node->prev[0];
return temp;
}
/**
* operator--()
* Decrements the iterator forward one element, and returns a
* reference to the decremented iterator (predecrement).
* If the iterator is pointing to the beginning of the list,
* the behavior is undefined. If the iterator has the special
* value returned by the end() function, then the iterator
* must point to the last element after this function.
*/
ReverseIterator& operator--(){
this->node = this->node->next[0];
return *this;
}
/**
* operator--(int)
* Decrements the iterator forward one element, and returns an
* iterator pointing to the element prior to decrementing
* (postdecrement). If the iterator is pointing to the
* beginning of the list, the behavior is undefined. If the
* iterator has the special value returned by the end()
* function, then the iterator must point to the last element
* after this function.
*/
ReverseIterator operator--(int){
ReverseIterator temp(*this);
this->node = this->node->next[0];
return temp;
}
/**
* operator*() const
* Returns a reference to the ValueType object contained in
* this element of the list. If the iterator is pointing to
* the end of the list, the behavior is undefined. This can
* be used to change the Mapped_T member of the element.
*/
ValueType& operator*() const {
typename SkipList::Node_data* node_data =
static_cast<typename SkipList::Node_data*>(this->node);
return node_data->data;
}
/**
* operator->() const
* Special member access operator for the element.
* If the iterator is pointing to the end of the list,
* the behavior is undefined. This can be used to change
* the Mapped_T member of the element.
*/
ValueType* operator->() const {
typename SkipList::Node_data* node_data =
static_cast<typename SkipList::Node_data*>(this->node);
return &(node_data->data);
}
}; /* class ReverseIterator */
/* ===================== Variable Declarations ==================== */
SkipList skiplist;
/* ===================== Function Declarations ==================== */
/* Constructors and Assignment Operator */
Map(); // Constructor
Map(const Map &); // Copy constructor
Map &operator=(const Map &); // Copy assignment operator
// Initializer list constructor
Map(std::initializer_list<std::pair<const Key_T, Mapped_T>>);
~Map(); // Destructor
/* Size */
size_t size() const;
bool empty() const;
/* Iterators */
Iterator begin();
Iterator end();
ConstIterator begin() const;
ConstIterator end() const;
ReverseIterator rbegin();
ReverseIterator rend();
/* Element Access */
Iterator find(const Key_T &);
ConstIterator find(const Key_T &) const;
Mapped_T &at(const Key_T &);
const Mapped_T &at(const Key_T &) const;
Mapped_T &operator[](const Key_T &);
Iterator index(int i);
ConstIterator index(int i) const;
/* Modifiers */
std::pair<Iterator, bool> insert(const ValueType &);
template <typename IT_T>
void insert(IT_T range_beg, IT_T range_end);
void erase(Iterator pos);
void erase(const Key_T &);
void clear();
/* =================== Comparison Operators for Map =============== */
/**
* operator==(const Map &map1, const Map &map2)
* Compares the given maps for equality.
* Two maps compare equal if they have the same number of elements,
* and if all elements compare equal.
*/
friend bool operator==(const Map &map1, const Map &map2){
if (map1.size() != map2.size()) return false;
ConstIterator it1 = map1.begin();
ConstIterator it2 = map2.begin();
while (it1 != map1.end()){
if (*it1 != *it2) return false;
it1++;
it2++;
}
return true;
}
/**
* operator!=(const Map &map1, const Map &map2)
* Compares the given maps for inequality.
*/
friend bool operator!=(const Map &map1, const Map &map2){
return !(map1 == map2);
}
/**
* operator<(const Map &map1, const Map &map2)
* You must use lexicographic sorting.
* Corresponding elements from each maps must be compared one-by-one.
* A map M1 is less than a map M2 if there is an element in M1 that is less
* than the corresponding element in the same position in map M2, or if all
* corresponding elements in both maps are equal and M1 is shorter than M2.
*/
friend bool operator<(const Map &map1, const Map &map2){
ConstIterator it1 = map1.begin();
ConstIterator it2 = map2.begin();
while (it1 != map1.end() && it2 != map2.end()){
if (*it1 < *it2) return true;
it1++;
it2++;
}
if (map1.size() < map2.size()) return true;
return false;
}
/* =============== Comparison Operators for Iterators ============= */
/**
* Compares any combination of Iterator and ConstIterator.
* Also compares two ReverseIterator objects.
* Two iterators compare equal if they point to the same element in
* the list. Two iterators may compare unequal even if the T objects
* that they contain compare equal.
*/
/* Equality comparisons for Iterators */
friend bool operator==(const Iterator &it1, const Iterator &it2){
return it1.node == it2.node;
}
friend bool operator==(const ConstIterator &const_it1, const ConstIterator &const_it2){
return const_it1.node == const_it2.node;
}
friend bool operator==(const Iterator &it1, const ConstIterator &const_it2){
return it1.node == const_it2.node;
}
friend bool operator==(const ConstIterator &const_it1, const Iterator &it2){
return const_it1.node == it2.node;
}
/* Inequality comparisons for Iterators */
friend bool operator!=(const Iterator &it1, const Iterator &it2){
return it1.node != it2.node;
}
friend bool operator!=(const ConstIterator &const_it1, const ConstIterator &const_it2){
return const_it1.node != const_it2.node;
}
friend bool operator!=(const Iterator &it1, const ConstIterator &const_it2){
return it1.node != const_it2.node;
}
friend bool operator!=(const ConstIterator &const_it1, const Iterator &it2){
return const_it1.node != it2.node;
}
/* ReverseIterator comparisons */
friend bool operator==(const ReverseIterator &reverse_it1, const ReverseIterator &reverse_it2){
return reverse_it1.node == reverse_it2.node;
}
friend bool operator!=(const ReverseIterator &reverse_it1, const ReverseIterator &reverse_it2){
return reverse_it1.node != reverse_it2.node;
}
}; /* class Map */
/* ====================== SkipList Function Definitions =================== */
/* Default Constructor */
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>::SkipList::SkipList(){
// Set sentinel
head.set_height(MAX_HEIGHT);
head.prev = head.next = &head;
length = 0;
}
/* Destructor */
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>::SkipList::~SkipList(){
clear();
}
/* Copy constructor */
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>::SkipList::SkipList(const SkipList &other){
// std::cout << "copy constructor called" << std::endl;
head.set_height(other.MAX_HEIGHT);
head.prev = head.next = &head;
length = other.length;
// update contains the most recently copied node at each level
std::vector<Node*> update(MAX_HEIGHT, &head);
Node other_head = other.head;
Node* other_current = &(other_head);
/* Copy each node and update all pointers */
for (other_current = other_current->next[0]; other_current != &(other.head);
other_current = other_current->next[0]){
// Make a deep copy of the other node
Node_data* other_data = static_cast<Node_data*>(other_current);
Node* copied = new Node_data(other_data->data);
// Set the height of the copied node links
copied->set_height(other_current->get_height());
/**
* Insert the copied node onto each level it exists on
* and update all relevant pointers.
*/
for (int level = 0; level < copied->get_height(); level++){
// Update relevant next and prev pointers
Node* previously_copied = update[level];
previously_copied->next.links.at(level) = copied;
copied->prev.links.at(level) = previously_copied;
copied->next.links.at(level) = &head;
head.prev.links.at(level) = copied;
// The current copied node is now the most recent one at this level
update[level] = copied;
}
}
}
/* Copy assignment operator */
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::SkipList&
Map<Key_T, Mapped_T>::SkipList::operator=(const SkipList &other){
// std::cout << "copy assignment operator called" << std::endl;
/* Clear the contents of the skiplist, if any. */
if (!empty()){
clear();
}
/* Set the sentinel node */
head.set_height(other.MAX_HEIGHT);
head.prev = head.next = &head;
length = other.length;
// update contains the most recently copied node at each level
std::vector<Node*> update(MAX_HEIGHT, &head);
Node other_head = other.head;
Node* other_current = &(other_head);
/* Copy each node and update all pointers */
for (other_current = other_current->next[0]; other_current != &(other.head);
other_current = other_current->next[0]){
// Make a deep copy of the other node
Node_data* other_data = static_cast<Node_data*>(other_current);
Node* copied = new Node_data(other_data->data);
// Set the height of the copied node links
copied->set_height(other_current->get_height());
/**
* Insert the copied node onto each level it exists on
* and update all relevant pointers.
*/
for (int level = 0; level < copied->get_height(); level++){
// Update relevant next and prev pointers
Node* previously_copied = update[level];
previously_copied->next.links.at(level) = copied;
copied->prev.links.at(level) = previously_copied;
copied->next.links.at(level) = &head;
head.prev.links.at(level) = copied;
// The current copied node is now the most recent one at this level
update[level] = copied;
}
}
return *this;
}
/**
* length()
* Returns the length of the skiplist (not including the sentinel).
*/
template <typename Key_T, typename Mapped_T>
size_t Map<Key_T, Mapped_T>::SkipList::size() const {
return length;
}
/**
* empty()
* Returns true or false whether the skiplist is empty.
*/
template <typename Key_T, typename Mapped_T>
bool Map<Key_T, Mapped_T>::SkipList::empty() const {
if (length != 0) return false;
return true;
}
/**
* front()
* Returns a node pointer to the first element.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::front(){
return head.next[0];
}
/**
* front() const
* Returns a node pointer to the first element.
*/
template <typename Key_T, typename Mapped_T>
const typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::front() const {
return head.next[0];
}
/**
* back()
* Returns a node pointer to the last element.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::back(){
return head.prev[0];
}
/**
* back() const
* Returns a node pointer to the last element.
*/
template <typename Key_T, typename Mapped_T>
const typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::back() const {
return head.prev[0];
}
/**
* index(int i)
* Returns a node pointer to node at the index i
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::index(int i){
if (empty() || i < 0 || (size_t) i > size()) return &head;
Node* current = &head;
i = i + 1; // Don't count the head node
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Keep going right until we overshoot the index we are looking for
while (next(current) != &head && i >= current->next.get_width(level)){
i = i - current->next.get_width(level);
current = next(current);
}
}
return current;
}
/**
* index(int i) const
* Returns a node pointer to node at the index i
*/
template <typename Key_T, typename Mapped_T>
const typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::index(int i) const {
if (empty() || i < 0 || (size_t) i > size()) return &head;
const Node* current = &head;
i = i + 1; // Don't count the head node
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](const Node* node) -> const Node* {
return node->next[level];
};
// Keep going right until we overshoot the index we are looking for
while (next(current) != &head && i >= current->next.get_width(level)){
i = i - current->next.get_width(level);
current = next(current);
}
}
return current;
}
/**
* find(int key)
* Returns the Node* that contains the key we are searching for.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::find(const Key_T key){
if (empty()) return &head;
/**
* current points to the node whose next links we follow so we can
* compare the Node* key with the key of the node we are searching for.
*/
Node* current = &head;
/**
* Start the search at the top level of the head node and check if the
* key at current->next[level] is less than the key we are searching for.
* If so, update current to the node at current->next[level] and keep
* going right until we have gone past the key we are searching for.
* Then, move down to the next level and check again.
*/
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Convert base Node class to derived Node_data class
Node_data* next_node = static_cast<Node_data*>(next(current));
// Keep going right until we overshoot the key we are looking for
while (next(current) != &head && next_node->key() < key){
current = next(current);
next_node = static_cast<Node_data*>(next(current));
}
}
/**
* If we are at the base level and we have overshot the key we are
* searching for, then the next node is the one we we want.
*/
current = current->next[0];
Node_data* current_data = static_cast<Node_data*>(current);
if (current != &head && current_data->key() == key){
return current;
}
// If we cannot find the key, return the sentinel node.
return &head;
}
/**
* find(int key)
* Returns the Node* that contains the key we are searching for.
*/
template <typename Key_T, typename Mapped_T>
const typename Map<Key_T, Mapped_T>::SkipList::Node*
Map<Key_T, Mapped_T>::SkipList::find(const Key_T key) const {
if (empty()) return &head;
/**
* current points to the node whose next links we follow so we can
* compare the Node* key with the key of the node we are searching for.
*/
const Node* current = &head;
/**
* Start the search at the top level of the head node and check if the
* key at current->next[level] is less than the key we are searching for.
* If so, update current to the node at current->next[level] and keep
* going right until we have gone past the key we are searching for.
* Then, move down to the next level and check again.
*/
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](const Node* node) -> const Node* {
return node->next[level];
};
// Convert base Node class to derived Node_data class
const Node_data* next_node = static_cast<const Node_data*>(next(current));
// Keep going right until we overshoot the key we are looking for
while (next(current) != &head && next_node->key() < key){
current = next(current);
next_node = static_cast<const Node_data*>(next(current));
}
}
/**
* If we are at the base level and we have overshot the key we are
* searching for, then the next node is the one we we want.
*/
current = current->next[0];
const Node_data* current_data = static_cast<const Node_data*>(current);
if (current != &head && current_data->key() == key){
return current;
}
// If we cannot find the key, return the sentinel node.
return &head;
}
/**
* random_height()
* Picks the height of the node based on a coin toss mechanism.
* It flips a coin with a probability, p, of being heads.
* The number of heads in a row up to the first tails, plus one,
* is the total height of the node.
* Reference: http://cseweb.ucsd.edu/~kube/cls/100/Lectures/lec6/lec6.pdf
*/
template <typename Key_T, typename Mapped_T>
int Map<Key_T, Mapped_T>::SkipList::random_height(){
auto drand = []() -> double {
return std::rand() / (RAND_MAX + 1.0);
};
double p = 0.5; // probability of coin toss resulting in heads
int height;
for(height = 1; drand() < p && height < MAX_HEIGHT; height++){};
return height;
}
/**
* insert(int d)
* Inserts a node into it's correct spot in the skiplist.
*/
template <typename Key_T, typename Mapped_T>
std::pair<typename Map<Key_T, Mapped_T>::Iterator, bool>
Map<Key_T, Mapped_T>::SkipList::insert(const ValueType &data){
if (empty()){
// std:: cout << "Inserting " << key << " to empty skiplist: " << std::endl;
// Create the new node with a random height
int new_height = random_height();
Node* current = new Node_data(data);
current->set_height(new_height);
for (int level = 0; level < new_height; level++){
// update current's next and prev links
current->next.links.at(level) = &head;
current->prev.links.at(level) = &head;
// update current's surrounding nodes' (i.e., before and after) links
head.next.links.at(level) = current;
head.prev.links.at(level) = current;
// update width
current->next.set_width(level, 1);
current->prev.set_width(level, 1);
head.next.set_width(level, 1);
head.prev.set_width(level, 1);
}
length++;
return std::make_pair(Iterator(current), true);
}
// std::cout << "Inserting " << key << " to non-empty skiplist: " << std::endl;
/**
* current points to the node whose next links we follow so we can compare
* the Node* key with the key of the node we are currently inserting.
*/
Node* current = &head;
/**
* update is a vector of Node* whose next links may need be updated to
* point to the node we are currently inserting.
* The indices in update correspond to the level of the Node* that
* may need to be updated.
*/
std::vector<Node*> update(MAX_HEIGHT, &head);
std::vector<int> update_width(MAX_HEIGHT, 0);
/**
* Search for the correct insert position.
* Begin at the top level of the head node and check if the key at
* current->next[level] is less than the key we are inserting.
* If so, update current to the node at current->next[level] and keep
* going right until we have gone past the key we want to insert.
* Then, update the update vector with current and move down to the
* next level and check again.
*/
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Convert base Node class to derived Node_data class
Node_data* next_node= static_cast<Node_data*>(next(current));
// Keep going right until we overshoot the key we are inserting
while (next(current) != &head && next_node->key() < data.first){
update_width[level] += current->next.get_width(level);
current = next(current);
next_node = static_cast<Node_data*>(next(current));
}
update[level] = current;
}
/**
* Check if the key has already been inserted into the skiplist
* If the key is already in skiplist, don't insert a duplicate.
*/
current = current->next[0];
Node_data* current_data = static_cast<Node_data*>(current);
if (current != &head && current_data->key() == data.first){
return std::make_pair(Iterator(current), false);
}
// Create the new node with a random height
int new_height = random_height();
current = new Node_data(data);
current->set_height(new_height);
current->next.set_width(0, 0);
current->prev.set_width(0, 0);
/**
* Insert the node into the skiplist at the correct position
* and update all the relevant pointers
*/
int width_counter = 0;
for (int level = 0; level < new_height; level++){
// update current's next and prev links
current->next.links.at(level) = update[level]->next[level];
current->prev.links.at(level) = update[level];
// update current's surrounding nodes' (i.e., before and after) links
current->prev.links.at(level)->next.links.at(level) = current;
current->next.links.at(level)->prev.links.at(level) = current;
// update width
current->next.set_width(level,
current->prev[level]->next.get_width(level) - width_counter);
current->prev.set_width(level, width_counter + 1);
current->next.links.at(level)->prev.set_width(level,
current->prev[level]->next.get_width(level) - width_counter);
current->prev.links.at(level)->next.set_width(level, width_counter + 1);
width_counter += update_width[level];
}
/* increment the width of all higher, non-updated levels */
for (int level = new_height; level < MAX_HEIGHT; level++){
update[level]->next.set_width(level, update[level]->next.get_width(level) + 1);
update[level]->prev.set_width(level, update[level]->prev.get_width(level) + 1);
}
length++;
return std::make_pair(Iterator(current), true);
}
/**
* remove(int key)
* Removes the key from the skiplist.
*/
template <typename Key_T, typename Mapped_T>
void Map<Key_T, Mapped_T>::SkipList::remove(Key_T key){
if (empty()) return;
/**
* current points to the node whose next links we follow so we can
* compare the Node* key with the key of the node we are searching for.
*/
Node* current = &head;
/**
* update is a vector of Node* whose next links may need be updated to
* stop pointing to the node we are currently deleting.
* The indices in update correspond to the level of the Node* that
* may need to be updated.
*/
std::vector<Node*> update(MAX_HEIGHT, &head);
/**
* Start the search at the top level of the head node and check if the
* key at current->next[level] is less than the key we are searching for.
* If so, update current to the node at current->next[level] and keep
* going right until we have gone past the key we are searching for.
* Then, move down to the next level and check again.
*/
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Convert base Node class to derived Node_data class
Node_data* next_node = static_cast<Node_data*>(next(current));
// Keep going right until we overshoot the key we are looking for
while (next(current) != &head && next_node->key() < key){
current = next(current);
next_node = static_cast<Node_data*>(next(current));
}
update[level] = current;
}
/**
* If we are at the base level and we have overshot the key we are
* searching for, then the next node is the one we we want.
*/
current = current->next[0];
Node_data* current_data = static_cast<Node_data*>(current);
// Check that the next node is correct, then continue
if (current == &head || !(current_data->key() == key)) return;
/**
* Delete the node from the skiplist and update all the relevant
* pointers and link width distances.
*/
for (int level = 0; level < current->get_height(); level++){
Node* update_prev = current->prev[level];
Node* update_next = current->next[level];
// update width
update_prev->next.set_width(level, update_prev->next.get_width(level)
+ current->next.get_width(level) - 1);
update_next->prev.set_width(level, update_prev->next.get_width(level));
// Update links
update_prev->next.links.at(level) = update_next;
update_next->prev.links.at(level) = update_prev;
}
/* decrement the width of all higher, non-updated levels */
for (int level = current->get_height(); level < MAX_HEIGHT; level++){
update[level]->next.set_width(level, update[level]->next.get_width(level) - 1);
update[level]->prev.set_width(level, update[level]->prev.get_width(level) - 1);
}
delete current;
length--;
}
/**
* clear()
* Removes all elements from the skiplist.
*/
template <typename Key_T, typename Mapped_T>
void Map<Key_T, Mapped_T>::SkipList::clear(){
if (empty()) return;
// Returns the next node in the base layer of the linked list
auto next = [&](Node* node) -> Node* {
return node->next[0];
};
Node* node = next(&head);
while (node != &head){
Node* temp = next(node);
delete node;
node = temp;
}
// Reset sentinel
head.set_height(MAX_HEIGHT);
head.prev = head.next = &head;
length = 0;
}
/* ======================== Map Function Definitions ====================== */
/* ----- Constructors and Assignment Operator ----- */
/**
* Default Constructor
* Creates an empty map.
*/
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>::Map(){
}
/**
* Copy constructor
*/
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>::Map(const Map &other){
this->skiplist = other.skiplist;
}
/**
* Copy assignment operator
* Value semantics are used. Handles self-assignment.
*/
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>& Map<Key_T, Mapped_T>::operator=(const Map &other){
this->skiplist = other.skiplist;
return *this;
}
/**
* Initializer list constructor
* Supports the creation of a Map with initial values, such as:
* ``` Map<string,int> m{{"key1", 1}, {"key2", 2}}; ```
*/
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>::Map(std::initializer_list<std::pair<const Key_T, Mapped_T>> initial_values){
for (auto &value : initial_values){
insert(value);
}
}
/**
* Destructor
*/
template <typename Key_T, typename Mapped_T>
Map<Key_T, Mapped_T>::~Map(){
}
/* ----- Size ----- */
/**
* size() - Returns the number of elements in the Map.
*/
template <typename Key_T, typename Mapped_T>
size_t Map<Key_T, Mapped_T>::size() const {
return this->skiplist.size();
}
/**
* empty()
* Returns true if the Map has no entries in it, false otherwise.
*/
template <typename Key_T, typename Mapped_T>
bool Map<Key_T, Mapped_T>::empty() const {
return this->skiplist.empty();
}
/* ----- Iterators ----- */
/**
* begin()
* Returns an Iterator pointing to the first element, in order.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::Iterator Map<Key_T, Mapped_T>::begin(){
return Iterator(this->skiplist.front());
}
/**
* end()
* Returns an Iterator pointing one past the last element, in order.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::Iterator Map<Key_T, Mapped_T>::end(){
// Same as: return Iterator(&(this->skiplist.head));
return Iterator(this->skiplist.back()->next[0]);
}
/**
* begin() const
* Returns a ConstIterator pointing to the first element, in order.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::ConstIterator Map<Key_T, Mapped_T>::begin() const {
return ConstIterator(this->skiplist.front());
}
/**
* end() const
* Returns a ConstIterator pointing one past the last element, in order.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::ConstIterator Map<Key_T, Mapped_T>::end() const {
// Same as: return ConstIterator(&(this->skiplist.head));
return ConstIterator(this->skiplist.back()->next[0]);
}
/**
* rbegin()
* Returns an ReverseIterator to the first element in reverse order,
* which is the last element in normal order.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::ReverseIterator Map<Key_T, Mapped_T>::rbegin(){
return ReverseIterator(this->skiplist.back());
}
/**
* rend()
* Returns an ReverseIterator pointing to one past the last element in
* reverse order, which is one before the first element in normal order.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::ReverseIterator Map<Key_T, Mapped_T>::rend(){
return ReverseIterator(this->skiplist.front()->prev[0]);
}
/* ----- Element Access ----- */
/**
* find(const Key_T &key)
* Returns an iterator to the given key.
* If the key is not found, these functions return the end() iterator.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::Iterator
Map<Key_T, Mapped_T>::find(const Key_T &key){
typename SkipList::Node* found = this->skiplist.find(key);
if (found != &(this->skiplist.head)){
return Iterator(found);
}
return end();
}
/**
* find(const Key_T &key) const
* Returns an iterator to the given key.
* If the key is not found, these functions return the end() iterator.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::ConstIterator
Map<Key_T, Mapped_T>::find(const Key_T &key) const {
const typename SkipList::Node* found = this->skiplist.find(key);
if (found != &(this->skiplist.head)){
return ConstIterator(found);
}
return end();
}
/**
* at(const Key_T &key)
* Returns a reference to the mapped object at the specified key.
* If the key is not in the Map, throws std::out_of_range.
*/
template <typename Key_T, typename Mapped_T>
Mapped_T& Map<Key_T, Mapped_T>::at(const Key_T &key){
typename SkipList::Node* found = this->skiplist.find(key);
if (found == &(this->skiplist.head)){
throw std::out_of_range("Error: Key not found.");
}
typename SkipList::Node_data* found_data =
static_cast<typename SkipList::Node_data*>(found);
return found_data->value();
}
/**
* at(const Key_T &key) const
* Returns a const reference to the mapped object at the specified key.
* If the key is not in the map, throws std::out_of_range.
*/
template <typename Key_T, typename Mapped_T>
const Mapped_T& Map<Key_T, Mapped_T>::at(const Key_T &key) const {
const typename SkipList::Node* found = this->skiplist.find(key);
if (found == &(this->skiplist.head)){
throw std::out_of_range("Error: Key not found.");
}
const typename SkipList::Node_data* found_data =
static_cast<const typename SkipList::Node_data*>(found);
return found_data->value();
}
/**
* operator[](const Key_T &key)
* If key is in the map, return a reference to the corresponding mapped object.
* If it is not, value initialize a mapped object for that key and
* returns a reference to it (after insert). This operator may not be used
* for a Mapped_T class type that does not support default construction.
*/
template <typename Key_T, typename Mapped_T>
Mapped_T& Map<Key_T, Mapped_T>::operator[](const Key_T &key){
typename SkipList::Node* found = this->skiplist.find(key);
if (found == &(this->skiplist.head)){
auto new_node = std::make_pair(key, Mapped_T());
insert(new_node);
}
found = this->skiplist.find(key);
typename SkipList::Node_data* found_data =
static_cast<typename SkipList::Node_data*>(found);
return found_data->value();
}
/**
* index(int i)
* Returns an iterator to the node at the given index i
* If the index is not found, these functions return the end() iterator.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::Iterator
Map<Key_T, Mapped_T>::index(int i){
typename SkipList::Node* found = this->skiplist.index(i);
if (found != &(this->skiplist.head)){
return Iterator(found);
}
return end();
}
/**
* index(int i) const
* Returns a ConstIterator to the node at the given index i
* If the index is not found, these functions return the end() iterator.
*/
template <typename Key_T, typename Mapped_T>
typename Map<Key_T, Mapped_T>::ConstIterator
Map<Key_T, Mapped_T>::index(int i) const {
const typename SkipList::Node* found = this->skiplist.index(i);
if (found != &(this->skiplist.head)){
return ConstIterator(found);
}
return end();
}
/* ----- Modifiers ----- */
/**
* insert(const ValueType &pair)
* Inserts the given pair into the map. If the key does not already exist
* in the map, it returns an iterator pointing to the new element, and true.
* If the key already exists, no insertion is performed nor is the mapped
* object changed, and it returns an iterator pointing to the element with
* the same key, and false.
*/
template <typename Key_T, typename Mapped_T>
std::pair<typename Map<Key_T, Mapped_T>::Iterator, bool>
Map<Key_T, Mapped_T>::insert(const ValueType &data){
return this->skiplist.insert(data);
}
/**
* insert(IT_T range_beg, IT_T, range_end)
* Inserts the given object or range of objects into the map.
* The range of objects inserted includes the object range_beg points to,
* but not the object that range_end points to. In other words, the range is
* half-open. The iterator returned in the first version points to the newly
* inserted element. There must be only one constructor invocation per object
* inserted. Note that the range may be in a different container type, as long
* as the iterator is compatible. A compatible iterator would be one from
* which a ValueType can be constructed. For example, it might be from a
* std::vector<std::pair<Key_T, Mapped_T>>. There might be any number of
* compatible iterator types, therefore, the range insert is a member template.
*/
template <typename Key_T, typename Mapped_T>
template <typename IT_T>
void Map<Key_T, Mapped_T>::insert(IT_T range_beg, IT_T range_end){
for (auto it = range_beg; it != range_end; it++){
this->skiplist.insert(*it);
}
}
/**
* erase(Iterator pos)
* Removes the given object, indicated by iterator, from the map.
*/
template <typename Key_T, typename Mapped_T>
void Map<Key_T, Mapped_T>::erase(Iterator pos){
typename SkipList::Node_data* node_data =
static_cast<typename SkipList::Node_data*>(pos.node);
this->skiplist.remove(node_data->key());
}
/**
* erase(const Key_T key)
* Removes the given object, indicated by key, from the map.
* Throws std::out_of_range if the key is not in the Map.
*/
template <typename Key_T, typename Mapped_T>
void Map<Key_T, Mapped_T>::erase(const Key_T &key){
typename SkipList::Node* found = this->skiplist.find(key);
if (found == &(this->skiplist.head)){
throw std::out_of_range("Error: Key not found.");
}
this->skiplist.remove(key);
}
/**
* clear()
* Removes all elements from the map.
*/
template <typename Key_T, typename Mapped_T>
void Map<Key_T, Mapped_T>::clear(){
this->skiplist.clear();
}
} /* namespace cs540 */
#endif /* ifndef MAP_HPP */
<file_sep>/assignment1/README.MD
# Assignment 1: Container in C
<NAME>
CS 440
Due: 02/15/18
## Assignment Instructions
http://www.cs.binghamton.edu/~kchiu/cs540/prog/1/
The topic of the assignment is how to do containers in C. This will give you
some understanding of what goes in behind-the-scenes in C++, and also serve as
a good review of C.
A secondary goal of this assignment is to give you experience in a form of
test-driven development. I do not tell you exactly what to write, but rather
I give you a piece of code (the test) that you must conform to.
The assignment is not to be completed in strict C, but rather more like C++
without classes. You may not use any C++ classes, inheritance, templates,
member functions, virtual member functions, `dynamic_cast`, etc. Also do not
use any of the standard C++ containers such as `std::vector` or `std::list`.
You will need to use C++ references. You must compile with `g++`, not `gcc`.
You do not need to handle any error conditions not explicitly specified.
For example, you may assume that the iterator returned by end() is never
incremented. If the user does increment this, then this will cause
undefined behavior.
You may find these [two](https://news.ycombinator.com/item?id=13175832)
[posts](https://news.ycombinator.com/item?id=13186232) at Hacker News, and of
course the accompanying referenced posts, useful.
### A Container in C
You will use a macro to implement a “template” for a double-ended queue
container, known as a *deque*, in C. As a “template”, it will be able to contain
any type without using `void *` (which violates type safety). The requirements
are given via the `test.cpp` program, linked below. You are to write the macro
so that this program will compile and run properly. You must implement the
deque as a circular, dynamic array. In other words, you are not allowed to
use a linked list.
You should use two `struct` types: one to represent the container itself and a
another for the iterator. The `struct` type for the container itself would
contain any bookkeeping information that you need. The iterator `struct` type
would contain any bookkeeping information that you need to maintain the iterator.
Since the container must have slightly different source code for each type,
you cannot code it directly. Instead, you need to write a long macro, named
`Deque_DEFINE()`. The macro takes one argument, which is the contained type,
provided as a typedef if it is not already single word. This macro will
contain all the definitions needed for the container. By making the name of
the contained type part of the generated classes and functions, a separate
instance of the source code is generated for each contained type.
For example, the `struct` for a container containing `MyClass` objects would
be named `Deque_MyClass`, while the `struct` for a container of `int`
variables would be named `Deque_int`. A container for pointers to `MyClass`
objects would be created by first defining a typedef:
```c++
typedef MyClass *MyClassPtr;
```
and then instantiating the container code by `Deque_DEFINE(MyClassPtr)`.
I strongly suggest that you first do this part as regular code.
When you are sure it is working, then convert it to a macro as the last step.
Also, after converting it to a macro, save the original. If you find a bug,
fix it in the original, then convert to a macro again.
An example of how to use a macro as a template mechanism is
[here](https://github.com/SamKustin/cs440/blob/master/assignment1/docs/example.cpp).
### Evaluation
Your code should compile with no warnings. Your code must not have any fixed
limits. You must be able to put any number elements into your deque, etc.
Your program must not have any memory leaks, nor any other types of memory
errors, such as using data before it is initialized, writing to beyond a
valid memory region, etc. Your program must not output any debugging messages.
Use the `valgrind` command to test your submission.
Your code should be in one file, `Deque.hpp`. Your header files must have
[include guards](https://en.wikipedia.org/wiki/Include_guard).
The test program for the assignment is
[here](https://github.com/SamKustin/cs440/blob/master/assignment1/docs/test.cpp).
Correct output is given
[here](https://github.com/SamKustin/cs440/blob/master/assignment1/docs/correct_output.txt).
Your performance will of course not give exactly the same numbers.
Your code must work with the unaltered `test.cpp`.
(You are of course allowed to modify it on your own, as long as your
submission still works with the unaltered version.) We may also test your
code with other test files, but we will conform to the API used in the
provided `test.cpp` file.
Your grade will be based on correctness. Correctness will include whether or
not your output is correct, and whether or not you can scale, or have any
memory (or other resource) leaks. Correctness will also depend on whether or
not you have followed instructions, such as not using inheritance or member
functions. If your code does not work correctly with the provided `test.cpp`,
you must provide your own test code, which we will use to assign partial
credit, along with an explanation in your `README.txt` as to what works.
To receive credit for a functionality, your test code must test it. In other
words, if you don't work with our `test.cpp`, and your supplied test code
only tests `push_back()`, then you will not receive credit for being able
to `push_front()`, even if you claim to be able to do it.
Performance will only be a factor for this assignment if you are unusually slow.
The test program is provided as a means for you to check whether or not your
program is as expected. In other words, it tests conformance.
It is NOT intended to be especially helpful in debugging, however. You may
find it hard to understand, etc. So you will almost certainly need to write
additional test code to help you find your bugs. Also, we may update the test
program periodically.
You may of course develop your program on any machine, but it will be tested
on the Linux classroom machines, and your grade will be determined by how it
works on those.
---
## My Submission:
* My assignment 1 submission: https://github.com/bu-cs540/assignment1-SamKustin/commit/c1e7c54a18f6982f6c1c2ad9e5c9ba89c3724d8a
* My Assignment 1 submission uses a modified version of the provided src/test.cpp.
Beginning at line 516 in test.cpp, the only modification was changing the
sort performance test for-loop to iterate for just 10 loops rather than
1,000,000. This change is intended to allow the program to complete faster
and in a reasonable amount of time. When my program was tested with the
original 1,000,000 loops, it had extremely poor sort performance.
* However, since the only modification began at line 516 of the test code,
as far as I am aware, my program does correctly implement all other functions.
My change was only intended to bypass the slow sort performance but still
demonstrate the code's functionality.
<file_sep>/assignment2/src/SkipList.hpp
#ifndef SKIPLIST_HPP
#define SKIPLIST_HPP
#include <iostream>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <ctime>
namespace cs540{
class SkipList {
public:
/* ==================== Nested Class Definitions ================== */
/* Forward declaration for Node class */
class Node;
// ---------------------------- Link Class ------------------------ //
/**
* Link represents the actual connections between the Nodes.
* The Link class is a wrapper for the vector of Node*
* We use a class as a wrapper so we can do things like overloading.
*/
class Link {
public:
/**
* Contains pointers to what the current Node points to
* at each level
*/
std::vector<Node*> links;
/* The distance to the next node at each level */
std::vector<int> width;
Link() = default;
/**
* Assign all elements of the links vector to point to the
* Node and initialize all width distances to the next node
* to 1.
*/
Link& operator=(Node* node){
for (auto &p : links){
p = node;
width.push_back(1);
}
return *this;
}
/* Index the links, but use .at() for range-checking */
Node* operator[](int level){
return links.at(level);
}
/* Get the width distance to the next node at the i'th level */
int get_width(int level){
return width.at(level);
}
void set_width(int level, int d){
width.at(level) = d;
}
};
// ---------------------------- Node Class ------------------------ //
/**
* Base class for Node. It contains links but not the actual data.
* This allows us to have a sentinel that doesn't contain data.
*/
class Node {
public:
Link next, prev;
Node() = default;
/* Set all links to the same height */
void set_height(int h) {
next.links.resize(h);
prev.links.resize(h);
next.width.resize(h);
prev.width.resize(h);
}
/* Return the height of the node */
int get_height() const {
// Just double-checking this invariant
assert(next.links.size() == prev.links.size());
return next.links.size();
}
};
// --------------------------- NodeData Class ---------------------- //
/**
* Derived class for Node. It contains the data for the base Node.
*/
class Node_data : public Node {
public:
explicit Node_data(int d) : data(d) {}
int data;
int get_data(){
return this->data;
}
};
/* ======================= Variable Declarations ================== */
/* const */ int MAX_HEIGHT = 4; // Max height of the skiplist
Node head; // Sentinel node
size_t length; // length of skiplist, not including sentinel
/* ======================= Function Declarations ================== */
SkipList();
~SkipList();
SkipList(const SkipList &other);
SkipList& operator=(const SkipList &other);
size_t size() const;
bool empty() const;
Node* front();
Node* back();
Node* index(int i);
Node* find(int key);
int random_height();
void insert(int key);
void remove(int key);
void clear();
void print_levels();
void print_levels_reverse();
void print_widths();
};
/* Default Constructor */
SkipList::SkipList(){
// Set sentinel
head.set_height(MAX_HEIGHT);
head.prev = head.next = &head;
length = 0;
}
/* Destructor */
SkipList::~SkipList(){
clear();
}
/* Copy constructor */
SkipList::SkipList(const SkipList &other){
// std::cout << "copy constructor called" << std::endl;
head.set_height(other.MAX_HEIGHT);
head.prev = head.next = &head;
length = other.length;
// update contains the most recently copied node at each level
std::vector<Node*> update(MAX_HEIGHT, &head);
Node other_head = other.head;
Node* other_current = &(other_head);
/* Copy each node and update all pointers */
for (other_current = other_current->next[0]; other_current != &(other.head);
other_current = other_current->next[0]){
// Make a deep copy of the other node
Node_data* other_data = static_cast<Node_data*>(other_current);
Node* copied = new Node_data(other_data->data);
// Set the height of the copied node links
copied->set_height(other_current->get_height());
/**
* Insert the copied node onto each level it exists on
* and update all relevant pointers.
*/
for (int level = 0; level < copied->get_height(); level++){
// Update relevant next and prev pointers
Node* previously_copied = update[level];
previously_copied->next.links.at(level) = copied;
copied->prev.links.at(level) = previously_copied;
copied->next.links.at(level) = &head;
head.prev.links.at(level) = copied;
// The current copied node is now the most recent one at this level
update[level] = copied;
}
}
}
/* Copy assignment operator */
SkipList& SkipList::operator=(const SkipList &other){
// std::cout << "copy assignment operator called" << std::endl;
/* Clear the contents of the skiplist, if any. */
if (!empty()){
clear();
}
/* Set the sentinel node */
head.set_height(other.MAX_HEIGHT);
head.prev = head.next = &head;
length = other.length;
// update contains the most recently copied node at each level
std::vector<Node*> update(MAX_HEIGHT, &head);
Node other_head = other.head;
Node* other_current = &(other_head);
/* Copy each node and update all pointers */
for (other_current = other_current->next[0]; other_current != &(other.head);
other_current = other_current->next[0]){
// Make a deep copy of the other node
Node_data* other_data = static_cast<Node_data*>(other_current);
Node* copied = new Node_data(other_data->data);
// Set the height of the copied node links
copied->set_height(other_current->get_height());
/**
* Insert the copied node onto each level it exists on
* and update all relevant pointers.
*/
for (int level = 0; level < copied->get_height(); level++){
// Update relevant next and prev pointers
Node* previously_copied = update[level];
previously_copied->next.links.at(level) = copied;
copied->prev.links.at(level) = previously_copied;
copied->next.links.at(level) = &head;
head.prev.links.at(level) = copied;
// The current copied node is now the most recent one at this level
update[level] = copied;
}
}
return *this;
}
/**
* length()
* Returns the length of the skiplist (not including the sentinel).
*/
size_t SkipList::size() const {
return length;
}
/**
* empty()
* Returns true or false whether the skiplist is empty.
*/
bool SkipList::empty() const {
if (length != 0) return false;
return true;
}
/**
* front()
* Returns a node pointer to the first element.
*/
SkipList::Node* SkipList::front(){
return head.next[0];
}
/**
* back()
* Returns a node pointer to the last element.
*/
SkipList::Node* SkipList::back(){
return head.prev[0];
}
/**
* index(int i)
* Returns a node pointer to node at the index i
*/
SkipList::Node* SkipList::index(int i){
if (empty() || i < 0 || (size_t) i > size()) return &head;
Node* current = &head;
i = i + 1; // Don't count the head node
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Keep going right until we overshoot the index we are looking for
while (next(current) != &head && i >= current->next.get_width(level)){
i = i - current->next.get_width(level);
current = next(current);
}
}
return current;
}
/**
* find(int key)
* Returns the Node* that contains the key we are searching for.
*/
SkipList::Node* SkipList::find(int key){
if (empty()) return &head;
/**
* current points to the node whose next links we follow so we can
* compare the Node* key with the key of the node we are searching for.
*/
Node* current = &head;
/**
* Start the search at the top level of the head node and check if the
* key at current->next[level] is less than the key we are searching for.
* If so, update current to the node at current->next[level] and keep
* going right until we have gone past the key we are searching for.
* Then, move down to the next level and check again.
*/
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Convert base Node class to derived Node_data class
Node_data* next_node = static_cast<Node_data*>(next(current));
// Keep going right until we overshoot the key we are looking for
while (next(current) != &head && next_node->data < key){
current = next(current);
next_node = static_cast<Node_data*>(next(current));
}
}
/**
* If we are at the base level and we have overshot the key we are
* searching for, then the next node is the one we we want.
*/
current = current->next[0];
Node_data* current_data = static_cast<Node_data*>(current);
if (current != &head && current_data->data == key){
return current;
}
// If we cannot find the key, return the sentinel node.
return &head;
}
/**
* random_height()
* Picks the height of the node based on a coin toss mechanism.
* It flips a coin with a probability, p, of being heads.
* The number of heads in a row up to the first tails, plus one,
* is the total height of the node.
* Reference: http://cseweb.ucsd.edu/~kube/cls/100/Lectures/lec6/lec6.pdf
*/
int SkipList::random_height(){
auto drand = []() -> double {
return std::rand() / (RAND_MAX + 1.0);
};
double p = 0.5; // probability of coin toss resulting in heads
int height;
for(height = 1; drand() < p && height < MAX_HEIGHT; height++){};
return height;
}
/**
* insert(int d)
* Inserts a node into it's correct spot in the skiplist.
*/
void SkipList::insert(int key){
if (empty()){
std:: cout << "Inserting " << key << " to empty skiplist: " << std::endl;
// Create the new node with a random height
int new_height = random_height();
Node* current = new Node_data(key);
current->set_height(new_height);
for (int level = 0; level < new_height; level++){
std::cout << "level: " << level << std::endl;
// update current's next and prev links
current->next.links.at(level) = &head;
current->prev.links.at(level) = &head;
// update current's surrounding nodes' (i.e., before and after) links
head.next.links.at(level) = current;
head.prev.links.at(level) = current;
// update width
current->next.set_width(level, 1);
current->prev.set_width(level, 1);
head.next.set_width(level, 1);
head.prev.set_width(level, 1);
// std::cout << "\tupdate[level]: " << static_cast<Node_data*>(current)->data << std::endl;
// std::cout << "\t\twidth: " << 1 << std::endl;
}
length++;
return;
}
std::cout << "Inserting " << key << " to non-empty skiplist: " << std::endl;
/**
* current points to the node whose next links we follow so we can compare
* the Node* key with the key of the node we are currently inserting.
*/
Node* current = &head;
/**
* update is a vector of Node* whose next links may need be updated to
* point to the node we are currently inserting.
* The indices in update correspond to the level of the Node* that
* may need to be updated.
*/
std::vector<Node*> update(MAX_HEIGHT, &head);
std::vector<int> update_width(MAX_HEIGHT, 0);
/**
* Search for the correct insert position.
* Begin at the top level of the head node and check if the key at
* current->next[level] is less than the key we are inserting.
* If so, update current to the node at current->next[level] and keep
* going right until we have gone past the key we want to insert.
* Then, update the update vector with current and move down to the
* next level and check again.
*/
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// std::cout << "level " << level << ": " << std::endl;
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Convert base Node class to derived Node_data class
Node_data* next_node = static_cast<Node_data*>(next(current));
// Keep going right until we overshoot the key we are inserting
while (next(current) != &head && next_node->data < key){
update_width[level] += current->next.get_width(level);
current = next(current);
next_node = static_cast<Node_data*>(next(current));
}
update[level] = current;
}
/**
* Check if the next node is already in the skiplist.
* If the key is already in skiplist, don't insert a duplicate.
*/
current = current->next[0];
Node_data* current_data = static_cast<Node_data*>(current);
if (current != &head && current_data->data == key) return;
// Create the new node with a random height
int new_height = random_height();
#if 0
if (new_height > MAX_HEIGHT){
for (int level = MAX_HEIGHT; level < new_height; level++){
update_width[level] = 0;
update[level] = &head;
update[level]->next.set_width(level, MAX_HEIGHT);
}
MAX_HEIGHT = new_height;
}
#endif
// std::cout << "new height: " << new_height << std::endl;
current = new Node_data(key);
current->set_height(new_height);
current->next.set_width(0, 0);
current->prev.set_width(0, 0);
/**
* Insert the node into the skiplist at the correct position
* and update all the relevant pointers
*/
int width_counter = 0;
for (int level = 0; level < new_height; level++){
std::cout << "level: " << level << std::endl;
// update current's next and prev links
current->next.links.at(level) = update[level]->next[level];
current->prev.links.at(level) = update[level];
// update current's surrounding nodes' (i.e., before and after) links
current->prev.links.at(level)->next.links.at(level) = current;
current->next.links.at(level)->prev.links.at(level) = current;
// update width
current->next.set_width(level,
current->prev[level]->next.get_width(level) - width_counter);
current->prev.set_width(level, width_counter + 1);
current->next.links.at(level)->prev.set_width(level,
current->prev[level]->next.get_width(level) - width_counter);
current->prev.links.at(level)->next.set_width(level, width_counter + 1);
std::cout << "\tupdate[level]: " << static_cast<Node_data*>(update[level])->data << std::endl;
std::cout << "\t\twidth: " << update[level]->next.get_width(level) << std::endl;
width_counter += update_width[level];
}
/* increment the width of all higher, non-updated levels */
for (int level = new_height; level < MAX_HEIGHT; level++){
update[level]->next.set_width(level, update[level]->next.get_width(level) + 1);
update[level]->prev.set_width(level, update[level]->prev.get_width(level) + 1);
}
length++;
}
/**
* remove(int key)
* Removes the key from the skiplist.
*/
void SkipList::remove(int key){
if (empty()) return;
/**
* current points to the node whose next links we follow so we can
* compare the Node* key with the key of the node we are searching for.
*/
Node* current = &head;
/**
* update is a vector of Node* whose next links may need be updated to
* stop pointing to the node we are currently deleting.
* The indices in update correspond to the level of the Node* that
* may need to be updated.
*/
std::vector<Node*> update(MAX_HEIGHT, &head);
/**
* Start the search at the top level of the head node and check if the
* key at current->next[level] is less than the key we are searching for.
* If so, update current to the node at current->next[level] and keep
* going right until we have gone past the key we are searching for.
* Then, move down to the next level and check again.
*/
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
// Lambda function to return the Node* that current points to at this level
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
// Convert base Node class to derived Node_data class
Node_data* next_node = static_cast<Node_data*>(next(current));
// Keep going right until we overshoot the key we are looking for
while (next(current) != &head && next_node->data < key){
current = next(current);
next_node = static_cast<Node_data*>(next(current));
}
update[level] = current;
}
/**
* If we are at the base level and we have overshot the key we are
* searching for, then the next node is the one we we want.
*/
current = current->next[0];
Node_data* current_data = static_cast<Node_data*>(current);
// Check that the next node is correct, then continue
if (current == &head || current_data->data != key) return;
/**
* Delete the node from the skiplist and update all the relevant
* pointers and link width distances.
*/
for (int level = 0; level < current->get_height(); level++){
Node* update_prev = current->prev[level];
Node* update_next = current->next[level];
// update width
update_prev->next.set_width(level, update_prev->next.get_width(level)
+ current->next.get_width(level) - 1);
update_next->prev.set_width(level, update_prev->next.get_width(level));
// Update links
update_prev->next.links.at(level) = update_next;
update_next->prev.links.at(level) = update_prev;
}
/* decrement the width of all higher, non-updated levels */
for (int level = current->get_height(); level < MAX_HEIGHT; level++){
update[level]->next.set_width(level, update[level]->next.get_width(level) - 1);
update[level]->prev.set_width(level, update[level]->prev.get_width(level) - 1);
}
delete current;
length--;
}
/**
* clear()
* Removes all elements from the skiplist.
*/
void SkipList::clear(){
if (empty()) return;
// Returns the next node in the base layer of the linked list
auto next = [&](Node* node) -> Node* {
return node->next[0];
};
Node* node = next(&head);
while (node != &head){
Node* temp = next(node);
delete node;
node = temp;
}
// Reset sentinel
head.set_height(MAX_HEIGHT);
head.prev = head.next = &head;
length = 0;
}
/**
* print_levels()
* Prints all the keys in each level in the skiplist.
*/
void SkipList::print_levels(){
if (empty()){
std::cout << "SkipList is empty. Nothing to print." << std::endl;
return;
}
std::cout << "============= print_levels() =============== " << std::endl;
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
/**
* next is a lamda function
* Returns the next pointer of the Node at the level
*/
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
/**
* Print the node data for the entire level. Start after the sentinel
* and end when we hit the sentinel again (bc circular linked list).
*/
std::cout << "level " << level << ": ";
for (Node* node = next(&head); node != &head; node = next(node)){
// Convert base Node class to derived Node_data class
Node_data* n = static_cast<Node_data*>(node);
if (next(node) != &head){
std::cout << "[" << n->data << "] -> ";
} else {
std::cout << "[" << n->data << "]";
}
}
std::cout << std::endl;
}
std::cout << "============================================ " << std::endl;
}
/**
* print_levels_reverse()
* Prints all the keys in each level in the skip list in reverse.
*/
void SkipList::print_levels_reverse(){
if (empty()){
std::cout << "SkipList is empty. Nothing to print." << std::endl;
return;
}
std::cout << "========= print_levels_reverse() =========== " << std::endl;
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
/**
* next is a lamda function
* Returns the next pointer of the Node at the level
*/
auto prev = [&](Node* node) -> Node* {
return node->prev[level];
};
/**
* Print the node data for the entire level. Start after the sentinel
* and end when we hit the sentinel again (bc circular linked list).
*/
std::cout << "level " << level << ": ";
for (Node* node = prev(&head); node != &head; node = prev(node)){
// Convert base Node class to derived Node_data class
Node_data* n = static_cast<Node_data*>(node);
if (prev(node) != &head){
std::cout << "[" << n->data << "] -> ";
} else {
std::cout << "[" << n->data << "]";
}
}
std::cout << std::endl;
}
std::cout << "============================================ " << std::endl;
}
/**
* print_widths()
* Prints all the keys in each level in the skiplist.
*/
void SkipList::print_widths(){
if (empty()){
std::cout << "SkipList is empty. Nothing to print." << std::endl;
return;
}
std::cout << "============= print_widths() =============== " << std::endl;
for (int level = MAX_HEIGHT - 1; level >= 0; level--){
/**
* next is a lamda function
* Returns the next pointer of the Node at the level
*/
auto next = [&](Node* node) -> Node* {
return node->next[level];
};
/**
* Print the node data for the entire level. Start after the sentinel
* and end when we hit the sentinel again (bc circular linked list).
*/
std::cout << "level " << level << ": ";
for (Node* node = next(&head); node != &head; node = next(node)){
if (next(node) != &head){
std::cout << "[" << node->next.get_width(level) << "] -> ";
} else {
std::cout << "[" << node->next.get_width(level) << "]";
}
}
std::cout << std::endl;
}
std::cout << "============================================ " << std::endl;
}
} /* namespace cs540 */
#endif /* ifndef SKIPLIST_HPP */
<file_sep>/README.md
# CS 440
CS 440: Advanced Topics in Object-Oriented Programming Languages
Term: Spring 2018
Professor: <NAME>
## Course Description:
Object-oriented programming and its concomitant design patterns provide rich
abstractions for program development. These programs will eventually execute
on real hardware, however. This course will investigate advanced
object-oriented techniques and how they interact with hardware and operating
system issues. We will ground our topics in C++, but the goal of the course
will be to develop understanding that can be applied across languages.
We will examine different design techniques for things such as memory
management, and explore how and why they differ in performance and robustness.
We will also cover idioms such as "Resource Acquisition Is Initialization"
(RAII) and how they can be used to provide robust resource management for
exceptions (exception safety). We will also devote time to covering generic
programming and related topics such as expression templates. This is a growing
area that seeks to decouple algorithms and data structures through the use of
templates and other meta-programming techniques. These techniques exploit the
fact that the C++ template mechanism is a language-within-a-language that is
executed at compile-time rather than run-time. Additional topics include
dynamic linking for techniques such as "plug-ins", template instantiation
mechanisms, template specialization, idioms for memory management,
thread-safety issues, thread-safety, C++ reflection.
<file_sep>/midterm/README.md
# Midterm
<NAME>
CS 440
Due: 03/28/18
## Instructions
Please make sure the code is compilable, otherwise, no credit will be given.
You can comment some lines if you cannot pass all of them.
### Primes
Write a class and its iterator that will generate primes, and then iterate
through them.
### Fixed Point
Write a fixed-point number class that always maintains 2 digits to the right
of the decimal point.
The suggested internal representation is simply as an long integer. Then:
1234 means 12.34
12 means .12
20 means .20
122 means 1.22
etc.
You can output integers with leading 0's with:
```c++
#include <iostream>
#include <iomanip>
std::cout << std::setw(4) << std::setfill('0') << 30 << std::endl;
```
Note that width (set by `std::setw()`) will be reset with every output
operation, so you will need to reset it.
<file_sep>/assignment2/src/SkipList.cpp
#include "SkipList.hpp"
#include <iostream>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <ctime>
int main(){
cs540::SkipList sl;
// Test empty function
assert(sl.empty());
// Test insert function
sl.insert(0);
sl.insert(1);
sl.insert(2);
sl.insert(-1);
sl.insert(-2);
// Test to ensure no duplicates are inserted
sl.insert(2);
assert(sl.size() == 5);
// Test print function
sl.print_levels();
sl.print_widths();
// Test find function
cs540::SkipList::Node_data* found = static_cast<cs540::SkipList::Node_data*>(sl.find(0));
std::cout << "sl.find(0) -- found: " << found->data << std::endl;
assert(found->data == 0);
// Test remove function
sl.remove(0);
std::cout << "sl.remove(0)" << std::endl;
assert(sl.size() == 4);
// Test remove function on node that does not exist
sl.remove(1234);
assert(sl.size() == 4);
sl.print_levels();
sl.print_widths();
// Test clear() function
sl.clear();
assert(sl.empty());
sl.print_levels();
std::cout << "original sl: " << std::endl;
sl.insert(0);
sl.insert(1);
sl.insert(2);
sl.insert(-1);
sl.insert(-2);
sl.print_levels();
#if 0
std::cout << "sl1:" << std::endl;
cs540::SkipList sl1;
sl1.insert(5);
sl1.insert(26);
sl1.insert(25);
sl1.insert(6);
sl1.insert(21);
sl1.insert(3);
sl1.insert(22);
sl1.print_levels();
#endif
#if 1
// Testing copy constructor
std::cout << "Testing copy constructor:" << std::endl;
cs540::SkipList sl2(sl);
std::cout << "sl2(sl): " << std::endl;
sl2.print_levels();
std::cout << "proof of deep copy by removing 1 in sl2 and finding 1 in sl" << std::endl;
std::cout << "sl2: after removing 1" << std::endl;
sl2.remove(1);
assert(sl2.size() == 4);
sl2.print_levels();
std::cout << "sl: after finding 1" << std::endl;
sl.find(1);
assert(sl.size() == 5);
sl.print_levels();
#endif
#if 1
// Testing index function
std::cout << "Testing index function" << std::endl;
found = static_cast<cs540::SkipList::Node_data*>(sl.index(0));
std::cout << "sl.index(0) -- found: " << found->data << std::endl;
assert(found->data == -2);
found = static_cast<cs540::SkipList::Node_data*>(sl.index(1));
std::cout << "sl.index(1) -- found: " << found->data << std::endl;
assert(found->data == -1);
#endif
return 0;
}
<file_sep>/assignment4/array/README.md
Part 1: Arbitrary Dimension Array Class Template (50 pts)
<file_sep>/midterm/fixed-point/main.cpp
/*
* Write a fixed-point number class that always maintains 2 digits to the right
* of the decimal point.
* The suggested internal representation is simply as an long integer. Then:
* 1234 means 12.34
* 12 means .12
* 20 means .20
* 122 means 1.22
* etc.
*
* You can output integers with leading 0's with:
*
* #include <iostream>
* #include <iomanip>
* std::cout << std::setw(4) << std::setfill('0') << 30 << std::endl;
*
* Note that width (set by std::setw()) will be reset with every output
* operation, so you will need to reset it.
*/
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <assert.h>
// You can modifiy the class internally as needed
class Fixed {
private:
long digits;
// Tag dispatching used to help specify the use of the below ctor
static struct PrivTag {} privtag;
// Private value constructor used to set digits after math operations
Fixed(long d, PrivTag) : digits(d) {}
public:
// Value Constructor
template <typename T>
Fixed(const T &v) : digits(std::round(100*v)) {
std::cerr << digits << ", " << v << std::endl;
}
// Output operator
friend std::ostream &operator<<(std::ostream &os, const Fixed &f) {
return os << f.digits / 100 << "." << std::setw(2) <<
std::setfill('0') << f.digits % 100;
}
// Type casting operator - e.g. int(), double(), etc
// Make it explicit to forbid implicit conversion from Fixed to T
template <typename T>
explicit operator T() const { return T(digits) / 100; }
// Addition
friend Fixed operator+(const Fixed &f1, const Fixed &f2) {
return Fixed{f1.digits + f2.digits, privtag};
}
// Multiplication
friend Fixed operator*(const Fixed &f1, const Fixed &f2) {
return Fixed{(f1.digits * f2.digits) / 100, privtag};
}
// Division
friend Fixed operator/(const Fixed &f1, const Fixed &f2) {
return Fixed{(100 * f1.digits) / f2.digits, privtag};
}
};
#define CHECK(f, out) check(f, out, __LINE__)
void
check(const Fixed &f, const std::string &out, const int ln) {
std::stringstream ss;
ss << f;
if (ss.str() != out) {
std::cerr << "At line " << ln << ": ";
std::cerr << "Should output " << out << ", but instead output " << ss.str() << "." << std::endl;
}
}
int
main() {
Fixed f1(2); // Becomes 2.00.
f1 = 1.27;
// Prints out 1.27.
std::cout << f1 << std::endl;
CHECK(f1, "1.27");
// Prints out 3.27.
std::cout << f1 + 2 << std::endl;
CHECK(f1 + 2, "3.27");
// Prints out 3.28.
std::cout << f1 + 2.01 << std::endl;
CHECK(f1 + 2.01, "3.28");
// Prints out 3.28.
std::cout << f1 + 2.011 << std::endl;
CHECK(f1 + 2.011, "3.28");
// Prints out 3.28.
std::cout << 2.011 + f1 << std::endl;
CHECK(2.011 + f1, "3.28");
auto f2 = f1;
// Prints out 2.54.
std::cout << f1 + f2 << std::endl;
CHECK(f1 + f2, "2.54");
// Prints out 1.61.
std::cout << f1*f2 << std::endl;
CHECK(f1 * f2, "1.61");
// Convert from int.
f1 = 3;
// Prints out 3.00.
std::cout << f1 << std::endl;
CHECK(f1, "3.00");
f1 = 2.45;
// Convert to int, just truncate.
// Prints 2.
std::cout << int(f1) << std::endl;
assert(int(f1) == 2);
// Convert to double.
double x = double(f1);
// Prints 2.45.
std::cout << x << std::endl;
assert(fabs(x - 2.45) < .00001);
Fixed f3{1.223};
// Prints out 1.22.
std::cout << f3 << std::endl;
CHECK(f3, "1.22");
// Division.
Fixed f4(2);
f4 = 2.01;
// Prints out 1.00.
std::cout << f4/2 << std::endl;
CHECK(f4/2, "1.00");
}
<file_sep>/assignment1/tests/all_fns_2.cpp
#include <dlfcn.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <random>
#include <unistd.h>
#include "Deque.hpp"
struct MyClass {
int id;
char name[10];
};
bool
MyClass_less_by_id(const MyClass &o1, const MyClass &o2) {
return o1.id < o2.id;
}
void
MyClass_print(const MyClass *o) {
printf("%d\n", o->id);
printf("%s\n", o->name);
}
Deque_DEFINE(MyClass)
/*
* Test for int.
*/
bool
int_less(const int &o1, const int &o2) {
return o1 < o2;
}
Deque_DEFINE(int)
int
main() {
FILE *devnull = fopen("/dev/null", "w");
assert(devnull != 0);
// Test equality. It is undefined behavior if the two deques were constructed with different
// comparison functions.
{
Deque_int deq1, deq2;
Deque_int_ctor(&deq1, int_less);
Deque_int_ctor(&deq2, int_less);
deq1.push_back(&deq1, 1);
deq1.push_back(&deq1, 2);
deq1.push_back(&deq1, 3);
deq2.push_front(&deq2, 3);
deq2.push_front(&deq2, 2);
deq2.push_front(&deq2, 1);
assert(Deque_int_equal(deq1, deq2));
deq1.pop_back(&deq1);
assert(!Deque_int_equal(deq1, deq2));
deq1.push_back(&deq1, 4);
assert(!Deque_int_equal(deq1, deq2));
deq1.dtor(&deq1);
deq2.dtor(&deq2);
}
fclose(devnull);
}
<file_sep>/assignment0/README.md
# Assignment 0 : Test Assignment
You need to complete myapi.h function.
This is a test assignment.
<file_sep>/assignment0/Makefile
all: test.o
g++ test.cpp -o a.out
clean:
rm -rf a.out
<file_sep>/assignment2/Makefile
CC=g++
CFLAG = -g -Wall -Wextra -pedantic -ldl -std=c++14
all: map skiplist
map: minimal morseex test-kec test-scaling test
minimal: src/Map.hpp
$(CC) -o minimal $(CFLAG) src/minimal.cpp
morseex: src/Map.hpp
$(CC) -o morseex $(CFLAG) src/morseex.cpp
test-kec: src/Map.hpp
# run with "-i iterations" to do a stress test for the given number of iterations.
# run with -p to print correct output
$(CC) -o test-kec $(CFLAG) src/test-kec.cpp
test-scaling: src/Map.hpp
# compiling with -O
$(CC) -o test-scaling $(CFLAG) src/test-scaling.cpp -O
test: src/Map.hpp
$(CC) -o test $(CFLAG) src/test.cpp
skiplist: src/SkipList.hpp
$(CC) -o skiplist $(CFLAG) src/SkipList.cpp
index_test: src/Map.hpp
# compiling with -O
$(CC) -o index_test $(CFLAG) src/index_test.cpp -O
clean:
rm -f skiplist minimal morseex test-kec test-scaling test *.o
rm -rf *.dSYM
rm -f index_test
<file_sep>/assignment0/test.cpp
#include "myapi.h"
#include <iostream>
int main(){
std::cout << "Testing My API" << std::endl;
myApiFunc();
return 0;
}
<file_sep>/assignment2/src/index_test.cpp
#include "Map.hpp"
#include <chrono>
#include <random>
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
#include <assert.h>
#include <map>
#include <initializer_list>
#include <set>
#include <algorithm>
using Milli = std::chrono::duration<double, std::ratio<1,1000>>;
using TimePoint = std::chrono::time_point<std::chrono::system_clock>;
void dispTestName(const char *testName, const char *typeName) {
std::cout << std::endl << std::endl << "************************************" << std::endl;
std::cout << "\t" << testName << " for " << typeName << "\t" << std::endl;
std::cout << "************************************" << std::endl << std::endl;
}
template <typename T>
T ascendingInsert(int count, bool print = true) {
using namespace std::chrono;
TimePoint start, end;
start = system_clock::now();
T map;
for(int i = 0; i < count; i++) {
map.insert(std::pair<int, int>(i,i));
}
end = system_clock::now();
Milli elapsed = end - start;
if(print)
std::cout << "Inserting " << count << " elements in aescending order took " << elapsed.count() << " milliseconds" << std::endl;
return map;
}
template <typename T>
T descendingInsert(int count, bool print = true) {
using namespace std::chrono;
TimePoint start, end;
start = system_clock::now();
T map;
for(int i = count; i > 0; i--) {
map.insert(std::pair<int, int>(i,i));
}
end = system_clock::now();
Milli elapsed = end - start;
if(print)
std::cout << "Inserting " << count << " elements in descending order took " << elapsed.count() << " milliseconds" << std::endl;
return map;
}
template <typename T>
T shuffledInsert(int count, bool print = true) {
using namespace std::chrono;
TimePoint start, end;
start = system_clock::now();
T map;
std::vector<int> toShuffle;
for (int i = 0; i < count; i++){
toShuffle.push_back(i);
}
std::random_shuffle(toShuffle.begin(), toShuffle.end());
for(int i = 0; i < count; i++) {
// std::cout << "toShuffle.at(i) = " << toShuffle.at(i) << std::endl;
map.insert(std::pair<int, int>(toShuffle.at(i),toShuffle.at(i)));
}
end = system_clock::now();
Milli elapsed = end - start;
if(print)
std::cout << "Inserting " << count << " elements in shuffled order took " << elapsed.count() << " milliseconds" << std::endl;
return map;
}
#if 1
template <typename T>
void indexTestAscending() {
using namespace std::chrono;
TimePoint start, end;
T m1 = ascendingInsert<T>(10000, false);
T m2 = ascendingInsert<T>(100000, false);
T m3 = ascendingInsert<T>(1000000, false);
T m4 = ascendingInsert<T>(10000000, false);
std::vector<int> toIndex;
for(int i = 0; i < 10000; i++) {
toIndex.push_back(i);
}
/* Shuffle the toIndex vector so we index at random locations */
std::random_shuffle(toIndex.begin(), toIndex.end());
start = system_clock::now();
for(const int e : toIndex) {
auto it = m1.index(e);
// std::cout << "(*it).first = " << (*it).first << "\te = " << e << std::endl;
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed1 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m1.size() << " took " << elapsed1.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,99999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m2.index(e);
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed2 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m2.size() << " took " << elapsed2.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,999999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m3.index(e);
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed3 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m3.size() << " took " << elapsed3.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,9999999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m4.index(e);
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed4 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m4.size() << " took " << elapsed4.count() << " milliseconds" << std::endl;
}
template <typename T>
void indexTestDescending() {
using namespace std::chrono;
TimePoint start, end;
T m1 = descendingInsert<T>(10000, false);
T m2 = descendingInsert<T>(100000, false);
T m3 = descendingInsert<T>(1000000, false);
T m4 = descendingInsert<T>(10000000, false);
std::vector<int> toIndex;
for(int i = 0; i < 10000; i++) {
toIndex.push_back(i);
}
/* Shuffle the toIndex vector so we index at random locations */
std::random_shuffle(toIndex.begin(), toIndex.end());
/**
* Note: Since the map is ordered, even though the insertion order
* is descending, it should still be indexed in ascending order.
*/
/**
* Note: I need to add 1 to e in the assertion because the
* descendingInsert function inserts elements in the interval: [count, 0)
* i.e, 0 is NOT an element of the map.
* For example, when I index 0, the first element of the map would be 1.
*/
start = system_clock::now();
for(const int e : toIndex) {
auto it = m1.index(e);
// std::cout << "(*it).first = " << (*it).first << "\te = " << e+1 << std::endl;
assert((*it).first == e+1);
}
end = system_clock::now();
Milli elapsed1 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m1.size() << " took " << elapsed1.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,99999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m2.index(e);
assert((*it).first == e+1);
}
end = system_clock::now();
Milli elapsed2 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m2.size() << " took " << elapsed2.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,999999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m3.index(e);
assert((*it).first == e+1);
}
end = system_clock::now();
Milli elapsed3 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m3.size() << " took " << elapsed3.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,9999999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m4.index(e);
assert((*it).first == e+1);
}
end = system_clock::now();
Milli elapsed4 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m4.size() << " took " << elapsed4.count() << " milliseconds" << std::endl;
}
template <typename T>
void indexTestShuffled() {
using namespace std::chrono;
TimePoint start, end;
T m1 = shuffledInsert<T>(10000, false);
T m2 = shuffledInsert<T>(100000, false);
T m3 = shuffledInsert<T>(1000000, false);
T m4 = shuffledInsert<T>(10000000, false);
std::vector<int> toIndex;
for(int i = 0; i < 10000; i++) {
toIndex.push_back(i);
}
/* Shuffle the toIndex vector so we index at random locations */
std::random_shuffle(toIndex.begin(), toIndex.end());
/**
* Note: Since the map is ordered, even though the insertion order
* is shuffled, it should still be indexed in ascending order.
*/
start = system_clock::now();
for(const int e : toIndex) {
auto it = m1.index(e);
// std::cout << "(*it).first = " << (*it).first << "\te = " << e << std::endl;
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed1 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m1.size() << " took " << elapsed1.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,99999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m2.index(e);
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed2 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m2.size() << " took " << elapsed2.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,999999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m3.index(e);
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed3 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m3.size() << " took " << elapsed3.count() << " milliseconds" << std::endl;
{
toIndex.clear();
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,9999999);
while(toIndex.size() < 10000) {
toIndex.push_back(distribution(generator));
}
}
start = system_clock::now();
for(const int e : toIndex) {
auto it = m4.index(e);
assert((*it).first == e);
}
end = system_clock::now();
Milli elapsed4 = end - start;
std::cout << "Indexing 10000 elements from a map of size " << m4.size() << " took " << elapsed4.count() << " milliseconds" << std::endl;
}
#endif
class comma_numpunct : public std::numpunct<char> {
protected:
virtual char do_thousands_sep() const { return ','; }
virtual std::string do_grouping() const { return "\03"; }
};
int main(){
//separate all printed numbers with commas
std::locale comma_locale(std::locale(), new comma_numpunct());
std::cout.imbue(comma_locale);
auto demangle = [](const std::type_info &ti) {
int ec;
return abi::__cxa_demangle(ti.name(), 0, 0, &ec);
assert(ec == 0);
};
const char *m = demangle(typeid(cs540::Map<int,int>));
//Add your own indexibility scaling test here
{
dispTestName("Index test [ASCENDING INSERT]", m);
indexTestAscending<cs540::Map<int,int>>();
dispTestName("Index test [DESCENDING INSERT]", m);
indexTestDescending<cs540::Map<int,int>>();
dispTestName("Index test [SHUFFLED INSERT]", m);
indexTestShuffled<cs540::Map<int,int>>();
}
// Cast, due to const-ness.
free((void *) m);
}
<file_sep>/midterm/fixed-point/Makefile
CC=g++
CFLAG = -g -Wall -Wextra -pedantic -std=c++14
all: fixed
fixed: fixed.o
$(CC) $(CFLAG) fixed.o -o fixed
fixed.o: main.cpp
$(CC) $(CFLAG) -c main.cpp -o fixed.o
clean:
rm -f *.o fixed
rm -rf *.dSYM
<file_sep>/assignment0/myapi.h
#ifndef __MYAPI__H__
#define __MYAPI__H__
#include <iostream>
// Write a function named "myApiFunc"
// The function should take no argument
// Return void and should print "MyAPI Function called".
void myApiFunc(){
std::cout << "MyAPI Function called" << std::endl;
}
#endif
<file_sep>/assignment4/Makefile
CC=g++
CFLAG = -g -Wall -Wextra -pedantic -std=c++17
all: ArrayExe InterpolateExe
# Executables
ArrayExe: array.o
$(CC) $(CFLAG) array.o -o ArrayExe
InterpolateExe: interpolate.o
$(CC) $(CFLAG) interpolate.o -o InterpolateExe
# Objects
array.o: array/test_Array.cpp array/Array.hpp
$(CC) $(CFLAG) -c array/test_Array.cpp -o array.o
interpolate.o: ostream/test_Interpolate.cpp ostream/Interpolate.hpp
$(CC) $(CFLAG) -c ostream/test_Interpolate.cpp -o interpolate.o
clean:
rm -f ArrayExe InterpolateExe *.o
rm -rf *.dSYM
<file_sep>/assignment3/README.md
# Assignment 3: Smart Pointer and Rvalue References
<NAME>
CS 440
Due: 04/20/18
## Assignment Instructions
http://www.cs.binghamton.edu/~kchiu/cs540/prog/3/
All classes should be in the `cs540` namespace. Your code must work with test
classes that are not in the `cs540` namespace, however. Your code should not
have any memory errors or leaks as reported by `valgrind`. Your code should
compile and run on the `remote.cs.binghamton.edu` cluster. Your code must not
have any hard-coded, arbitrary limits or assumptions about maximum sizes, etc.
Your code should compile without warning with `-Wall -Wextra -pedantic`.
Special exemptions to this may be requested in advance.
## Part 1: Smart Pointer (57 pts)
Implement a non-intrusive, thread-safe, exception-safe, reference-counting
smart pointer named `cs540::SharedPtr`. Our model for this will be
`std::shared_ptr`, so you can read up on that to understand how it should behave.
`SharedPtr` must allow different smart pointers in different threads to be
safely assigned and unassigned to the same shared objects. You may use either
locks or atomic increment operations to ensure thread-safety. You do not need
to (and in fact should not) ensure that the same `SharedPtr` can be used
concurrently.
Note that when the smart pointer determines that the object should be deleted,
it must delete the object via a pointer to the original type, even if the
template argument of the final smart pointer is of a base type. This is to
avoid object slicing for non-virtual destructors.
You may (and should) create any helper classes you feel necessary.
NOTE: We are using the term “object” as in the standard, where it refers to
any region of storage except functions. Thus, these smart pointers should be
able to work with fundamental types as well as objects of class type.
* [Shared Pointer Test](https://github.com/SamKustin/cs440/blob/master/assignment3/docs/SharedPtr/SharedPtr_test.cpp): Check the comment at the beginning of the file.
The API is given below.
### Template
| Declaration | Description |
| :---------- | :---------- |
| `template <typename T> class SharedPtr;` | The smart pointer points to an object of type `T`. `T` may refer to a `const`-qualified type. |
### Public member Functions
**Constructors, Assignment Operators, and Destructor:**
| Prototype | Description |
| :---------- | :---------- |
| `SharedPtr();` | Constructs a smart pointer that points to null. |
| `template <typename U> explicit SharedPtr(U *);` | Constructs a smart pointer that points to the given object. The reference count is initialized to one. |
| `SharedPtr(const SharedPtr &p);` <br> `template <typename U> SharedPtr(const SharedPtr<U> &p);` | If `p` is not null, then reference count of the managed object is incremented. If `U *` is not implicitly convertible to `T *`, use of the second constructor will result in a compile-time error when the compiler attempts to instantiate the member template. |
| `SharedPtr(SharedPtr &&p);` <br> `template <typename U> SharedPtr(SharedPtr<U> &&p);` | Move the managed object from the given smart pointer. The reference count must remain unchanged. After this function, `p` must be null. This must work if `U *` is implicitly convertible to `T *`. |
| `SharedPtr &operator=(const SharedPtr &);` <br> `template <typename U> SharedPtr<T> &operator=(const SharedPtr<U> &);`| Copy assignment. Must handle self assignment. Decrement reference count of current object, if any, and increment reference count of the given object. If `U *` is not implicitly convertible to `T *`, this will result in a syntax error. Note that both the normal assignment operator and a member template assignment operator must be provided for proper operation. |
| `SharedPtr &operator=(SharedPtr &&p);` <br> `template <typename U> SharedPtr &operator=(SharedPtr<U> &&p);` | Move assignment. After this operation, `p` must be null. The reference count associated with the object (if `p` is not null before the operation) will remain the same after this operation. This must compile and run correctly if `U *` is implicitly convertible to `T *`, otherwise, it must be a syntax error. |
| `~SharedPtr();` | Decrement reference count of managed object. If the reference count is zero, delete the object. |
**Modifiers:**
| Prototype | Description |
| :---------- | :---------- |
| `void reset();` | The smart pointer is set to point to the null pointer. The reference count for the currently pointed to object, if any, is decremented. |
| `template <typename U> void reset(U *p);` | Replace owned resource with another pointer. If the owned resource has no other references, it is deleted. If `p` has been associated with some other smart pointer, the behavior is undefined. |
**Observers:**
| Prototype | Description |
| :---------- | :---------- |
| `T *get() const;` | Returns a pointer to the owned object. Note that this will be a pointer-to-`const` if `T` is a `const`-qualified type. |
| `T &operator*() const;` | A reference to the pointed-to object is returned. Note that this will be a `const`-reference if `T` is a `const`-qualified type. |
| `T *operator->() const;` | The pointer is returned. Note that this will be a pointer-to-`const` if `T` is a `const`-qualified type. |
| `explicit operator bool() const;` | Returns true if the `SharedPtr` is not null. |
### Non-member (Free) Functions
| Prototype | Description |
| :---------- | :---------- |
| `template <typename T1, typename T2> bool operator==(const SharedPtr<T1> &, const SharedPtr<T2> &);` | Returns true if the two smart pointers point to the same object or if they are both null. Note that implicit conversions may be applied. |
| `template <typename T> bool operator==(const SharedPtr<T> &, std::nullptr_t);` <br> `template <typename T> bool operator==(std::nullptr_t, const SharedPtr<T> &);` | Compare the SharedPtr against nullptr. |
| `template <typename T1, typename T2> bool operator!=(const SharedPtr<T1>&, const SharedPtr<T2> &);` | True if the `SharedPtr`s point to different objects, or one points to null while the other does not. |
| `template <typename T> bool operator!=(const SharedPtr<T> &, std::nullptr_t);` <br> `template <typename T> bool operator!=(std::nullptr_t, const SharedPtr<T> &);` | Compare the `SharedPtr` against `nullptr`. |
| `template <typename T, typename U> SharedPtr<T> static_pointer_cast(const SharedPtr<U> &sp);` | Convert `sp` by using `static_cast` to cast the contained pointer. It will result in a syntax error if `static_cast` cannot be applied to the relevant types. |
| `template <typename T, typename U> SharedPtr<T> dynamic_pointer_cast(const SharedPtr<U> &sp);` | Convert `sp` by using `dynamic_cast` to cast the contained pointer. It will result in a syntax error if `dynamic_cast` cannot be applied to the relevant types, and will result in a smart pointer to null if the dynamic type of the pointer in `sp` is not `T *`. |
## Part 2: Rvalue References (15 pts)
For this part, you are to implement an array class including the move
constructor and move assignment. The array class contains elements of
type `MyInt`. The files for this are [MyInt.hpp](https://github.com/SamKustin/cs440/blob/master/assignment3/docs/RvalueRef/MyInt.hpp),
and [MyInt.cpp](https://github.com/SamKustin/cs440/blob/master/assignment3/docs/RvalueRef/MyInt.cpp).
The test code is [Array_test.cpp](https://github.com/SamKustin/cs440/blob/master/assignment3/docs/RvalueRef/Array_test.cpp).
Correct output is [here](https://github.com/SamKustin/cs440/blob/master/assignment3/docs/RvalueRef/correct_output.txt).
Note that you also need a add a performance test to verify that your move
constructor and move assignment have better performance compared to copy
constructor and copy assignment.
## Part 3: Function Wrapper (28 pts)
Implement an exception-safe subset of `std::function` as a template named `cs540::Function`.
Your wrapper must be able to work with targets of the following types:
* free functions
* lambda functions
* functor objects
You may (and should) create any helper classes you feel necessary.
A test program is [here](https://github.com/SamKustin/cs440/blob/master/assignment3/docs/FuncWrapper/Function_test.cpp).
The API is given below.
### Template
| Declaration | Description |
| :---------- | :---------- |
| `template <typename> class Function;` | Undefined, allows partial specialization. |
| `template <typename ResultType, typename ... ArgumentTypes> class Function<ResultType(ArgumentTypes...)>;` | A specialization used to parse function signature types. |
### Public Member Functions
**Constructors, Assignment Operators, and Destructor:**
| Prototype | Description |
| :---------- | :---------- |
| `Function();` | Constructs a function wrapper that does not yet reference a target function. |
| `template <typename FunctionType> Function(FunctionType);` | Constructs a function wrapper with a function of `FunctionType` as its target. |
| `Function(const Function &);` | Copy construct from an existing `cs540::Function`. |
| `Function &operator=(const Function &);` | Copy assignment. Must handle self assignment. Must be able to freely assign between `cs540::Function` objects that contain a free function, lambda, or functor given that they have the same function signature. |
| `~Function();` | Properly destroy the object and clear any memory as necessary. |
**Functionality:**
| Prototype | Description |
| :---------- | :---------- |
| `ResultType operator()(ArgumentTypes...);` | Call the wrapped function target with the given arguments and return its result. <br> Throw `cs540::BadFunctionCall` if a callable function is not stored. |
**Observers:**
| Prototype | Description |
| :---------- | :---------- |
| `explicit operator bool() const;` | Return true if the `cs540::Function` references a callable function and false otherwise. |
### Non-member (Free) Functions
| Prototype | Description |
| :---------- | :---------- |
| `template <typename ResultType, typename... ArgumentTypes> bool operator==(const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t);` <br> `template <typename ResultType, typename... ArgumentTypes> bool operator==(std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f);` | Returns `!f`. |
| `template <typename ResultType, typename... ArgumentTypes> bool operator!=(const Function<ResultType(ArgumentTypes...)> &f, std::nullptr_t);` <br> `template <typename ResultType, typename... ArgumentTypes> bool operator!=(std::nullptr_t, const Function<ResultType(ArgumentTypes...)> &f);` | Returns `bool(f)`. |
<file_sep>/final/extractor/main.cpp
#include <cstddef>
#include <vector>
#include <iostream>
#include <array>
#include <type_traits>
template <std::size_t... Indices>
class Extractor {
public:
template <typename T>
auto operator()(const T &container) {
return std::array{container[Indices]...};
}
};
int
main() {
// An Extractor extracts the corresponding elements from a native array, a
// std::vector, or a std::array, and returns a std::array with the
// corresponding elements in it.
// This extractor will extract the elements with the corresponding indices
// from the given sequence container, and return a std::array of the
// appropriate type with the specified elements.
// The extractor should work for any size !!!
// including any size of template arguments and any size of the argument array
// Otherwise, you will lose some points
Extractor<1, 2, 2, 0> ex;
int a1[] = {11, 22, 33};
std::array<int, 3> aa1{11, 22, 33};
std::vector<int> v1{11, 22, 33};
double a2[] = {1.1, 2.2, 3.3, 4.4};
std::array<double, 4> aa2{1.1, 2.2, 3.3, 4.4};
std::vector<double> v2{1.1, 2.2, 3.3, 4.4};
const char *a3[] = {"1", "22", "333", "4444", "55555"};
std::array<const char *, 5> aa3{"1", "22", "333", "4444", "55555"};
std::vector<const char *> v3{"1", "22", "333", "4444", "55555"};
std::cout << "Below should be 22, 33, 33, 11." << std::endl;
for (auto e : ex(a1)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 22, 33, 33, 11." << std::endl;
for (auto e : ex(aa1)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 22, 33, 33, 11." << std::endl;
for (auto e : ex(v1)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 2.2, 3.3, 3.3, 1.1." << std::endl;
for (auto e : ex(a2)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 2.2, 3.3, 3.3, 1.1." << std::endl;
for (auto e : ex(aa2)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 2.2, 3.3, 3.3, 1.1." << std::endl;
for (auto e : ex(v2)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 22, 333, 333, 1." << std::endl;
for (auto e : ex(a3)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 22, 333, 333, 1." << std::endl;
for (auto e : ex(aa3)) {
std::cout << e << std::endl;
}
std::cout << "Below should be 22, 333, 333, 1." << std::endl;
for (auto e : ex(v3)) {
std::cout << e << std::endl;
}
}
<file_sep>/assignment1/tests/attempt.cpp
// Just to check if Deque.hpp is submitted in system or not
#include "Deque.hpp"
int main(){
return 0;
}
<file_sep>/assignment1/src/Deque.hpp
#ifndef DEQUE_HPP
#define DEQUE_HPP
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Deque_DEFINE(_type_) \
\
/* ======================== Struct Definitions ========================= */ \
\
/* Forward Declarations */ \
struct Deque_##_type_; \
struct Deque_##_type_##_Iterator; \
\
typedef struct Deque_##_type_ { \
/* Public Fields */ \
/* Uses stringificaiton (#) to combine two adjacent string literals */ \
const char type_name[sizeof "Deque_"#_type_] = "Deque_"#_type_; \
\
unsigned int current_size; \
unsigned int total_capacity; \
\
_type_* array; \
unsigned int front_index; \
unsigned int back_index; \
\
Deque_##_type_##_Iterator* begin_iterator; \
Deque_##_type_##_Iterator* end_iterator; \
\
bool (*less)(const _type_ &object1, const _type_ &object2); \
\
/* Function Pointer Declarations */ \
size_t (*size)(const Deque_##_type_ * deque); \
bool (*empty)(const Deque_##_type_ * deque); \
bool (*full)(const Deque_##_type_ * deque); \
void (*clear)(Deque_##_type_ * deque); \
\
void (*push_back)(Deque_##_type_ * deque, const _type_ value); \
void (*push_front)(Deque_##_type_ * deque, const _type_ value); \
\
void (*pop_back)(Deque_##_type_ * deque); \
void (*pop_front)(Deque_##_type_ * deque); \
\
Deque_##_type_##_Iterator (*begin)(Deque_##_type_ * deque); \
Deque_##_type_##_Iterator (*end)(Deque_##_type_ * deque); \
\
void (*sort)(Deque_##_type_ * deque, Deque_##_type_##_Iterator begin, Deque_##_type_##_Iterator end); \
\
_type_& (*front)(const Deque_##_type_ * deque); \
_type_& (*back)(const Deque_##_type_ * deque); \
_type_& (*at)(Deque_##_type_ * deque, unsigned int i); \
\
void (*dtor)(Deque_##_type_ * deque); \
\
} Deque_##_type_; \
\
typedef struct Deque_##_type_##_Iterator { \
/* Public Fields */ \
Deque_##_type_ * deque; \
unsigned int index; \
\
/* Function Pointers */ \
void (*inc)(Deque_##_type_##_Iterator * it); \
void (*dec)(Deque_##_type_##_Iterator * it); \
_type_& (*deref)(Deque_##_type_##_Iterator * it); \
} Deque_##_type_##_Iterator; \
\
/* ======================== Function Implementations ====================*/ \
\
size_t Deque_##_type_##_size(const Deque_##_type_ * deque){ \
return deque->current_size; \
} \
\
bool Deque_##_type_##_empty(const Deque_##_type_ * deque){ \
if (deque->current_size == 0) return true; \
return false; \
} \
\
bool Deque_##_type_##_full(const Deque_##_type_ * deque){ \
if (deque->current_size == deque->total_capacity) return true; \
return false; \
} \
\
void Deque_##_type_##_clear(Deque_##_type_ * deque){ \
/* The clear function deletes all the elements in the deque */ \
\
/* Free and reallocate the array to easily remove all elements */ \
free(deque->array); \
deque->array = nullptr; \
deque->array = (_type_*) malloc(deque->total_capacity * sizeof(_type_));\
\
/* Reset the size of the deque and the front and back pointers. */ \
deque->current_size = 0; \
deque->front_index = deque->total_capacity / 2; \
deque->back_index = deque->total_capacity / 2; \
} \
\
void Deque_##_type_##_unwrap(Deque_##_type_ * deque){ \
/* Adjust array if back pointer is before front pointer */ \
if (deque->back_index < deque->front_index){ \
for (unsigned int i = 0; i <= deque->back_index; i++){ \
deque->array[(deque->total_capacity / 2) + i] = deque->array[i];\
} \
/* Adjust the back pointer */ \
deque->back_index = deque->back_index + (deque->total_capacity / 2);\
} \
} \
\
void Deque_##_type_##_push_back(Deque_##_type_ * deque, const _type_ value){ \
/* Check if the array is full */ \
if (deque->full(deque)){ \
/* Expand the array using geometric expansion */ \
deque->total_capacity *= 2; \
deque->array = (_type_*) realloc(deque->array, deque->total_capacity * sizeof(_type_)); \
/* Adjust array if back pointer is before front pointer */ \
Deque_##_type_##_unwrap(deque); \
} \
\
/** \
* If array is not empty, increment the back pointer
* (using modular arithmetic in case the array wraps around)
* and then set the value of the array.
*/ \
if (!deque->empty(deque)){ \
deque->back_index = (deque->back_index + 1) % deque->total_capacity;\
} \
\
deque->array[deque->back_index] = value; \
deque->current_size++; \
} \
\
void Deque_##_type_##_push_front(Deque_##_type_ * deque, const _type_ value){ \
/* Check if the array is full */ \
if (deque->full(deque)){ \
/* Expand the array using geometric expansion */ \
deque->total_capacity *= 2; \
deque->array = (_type_*) realloc(deque->array, deque->total_capacity * sizeof(_type_)); \
/* Adjust array if back pointer is before front pointer */ \
Deque_##_type_##_unwrap(deque); \
} \
\
/** \
* If array is not empty, decrement the front pointer
* (using modular arithmetic in case the array wraps around)
* and then set the value of the array.
*/ \
if (!deque->empty(deque)){ \
deque->front_index = (deque->front_index + deque->total_capacity - 1) % deque->total_capacity; \
} \
\
deque->array[deque->front_index] = value; \
deque->current_size++; \
} \
\
void Deque_##_type_##_pop_back(Deque_##_type_ * deque){ \
/* Check if the array is empty */ \
if (deque->empty(deque)) return; \
\
/** \
* Decrement the back pointer (using modular arithmetic in case
* the array wraps around).
*/ \
deque->back_index = (deque->back_index + deque->total_capacity - 1) % deque->total_capacity; \
deque->current_size--; \
} \
\
void Deque_##_type_##_pop_front(Deque_##_type_ * deque){ \
/* Check if the array is empty */ \
if (deque->empty(deque)) return; \
\
/** \
* Increment the front pointer (using modular arithmetic in case
* the array wraps around).
*/ \
deque->front_index = (deque->front_index + 1) % deque->total_capacity; \
deque->current_size--; \
} \
\
\
_type_& Deque_##_type_##_front(const Deque_##_type_ * deque){ \
return deque->array[deque->front_index]; \
} \
\
_type_& Deque_##_type_##_back(const Deque_##_type_ * deque){ \
return deque->array[deque->back_index]; \
} \
\
_type_& Deque_##_type_##_at(Deque_##_type_ * deque, unsigned int i){ \
/** \
* Must add the index to the front pointer and do modular arithmetic
* because the front pointer (i.e. the front of the deque) may not
* be at the 0th index so we cannot index the array normally.
*/ \
return deque->array[(deque->front_index + i) % deque->total_capacity]; \
} \
\
void Deque_##_type_##_Iterator_inc(Deque_##_type_##_Iterator * it){ \
it->index = (it->index + 1) % it->deque->total_capacity; \
} \
\
void Deque_##_type_##_Iterator_dec(Deque_##_type_##_Iterator * it){ \
it->index = (it->index + it->deque->total_capacity - 1) % it->deque->total_capacity; \
} \
\
_type_& Deque_##_type_##_Iterator_deref(Deque_##_type_##_Iterator * it){ \
/** \
* Return the reference that the iterator points to.
*/ \
return it->deque->array[it->index]; \
} \
\
Deque_##_type_##_Iterator Deque_##_type_##_begin(Deque_##_type_ * deque){ \
/** \
* The begin iterator points to the first element in a container.
*/ \
(deque->begin_iterator)->index = deque->front_index; \
return *(deque->begin_iterator); \
} \
\
Deque_##_type_##_Iterator Deque_##_type_##_end(Deque_##_type_ * deque){ \
/** \
* The end iterator points to one past the last element
* in the container.
*/ \
(deque->end_iterator)->index = (deque->back_index + 1) % deque->total_capacity; \
return *(deque->end_iterator); \
} \
\
bool Deque_##_type_##_Iterator_equal(const Deque_##_type_##_Iterator &it1, \
const Deque_##_type_##_Iterator &it2) { \
if ((it1.deque == it2.deque) && (it1.index == it2.index)) return true; \
return false; \
} \
\
bool Deque_##_type_##_equal(Deque_##_type_ &deque1, Deque_##_type_ &deque2) { \
if (deque1.size(&deque1) != deque2.size(&deque2)) { \
return false; \
} \
\
Deque_##_type_##_Iterator it1 = deque1.begin(&deque1); \
Deque_##_type_##_Iterator it2 = deque2.begin(&deque2); \
Deque_##_type_##_Iterator deque1_end_it = deque1.end(&deque1); \
\
for (; !Deque_##_type_##_Iterator_equal(it1, deque1_end_it); \
it1.inc(&it1), it2.inc(&it2)) { \
\
if (deque1.less(it1.deref(&it1), it2.deref(&it2))) { \
return false; \
} \
if (deque2.less(it2.deref(&it2), it1.deref(&it1))) { \
return false; \
} \
} \
return true; \
} \
\
void Deque_##_type_##_swap(_type_* i, _type_* j){ \
_type_ temp = *i; \
*i = *j; \
*j = temp; \
} \
\
/** \
* Gets the median value of deque->at(low), deque->at(middle), and
* deque->at(high). This is to solve the problem of sorting a container
* that is already sorted or sorted in reverse order.
*/ \
_type_& Deque_##_type_##_median_of_three(Deque_##_type_ * deque, int low, int high){ \
int middle = (low + high) / 2; \
\
if (deque->less(deque->at(deque, middle), deque->at(deque, low))){ \
Deque_##_type_##_swap(&(deque->at(deque, low)), &(deque->at(deque, middle))); \
} \
if (deque->less(deque->at(deque, high), deque->at(deque, low))){ \
Deque_##_type_##_swap(&(deque->at(deque, low)), &(deque->at(deque, high))); \
} \
if (deque->less(deque->at(deque, high), deque->at(deque, middle))){ \
Deque_##_type_##_swap(&(deque->at(deque, middle)), &(deque->at(deque, high))); \
} \
\
/** \
* Currently, the pivot element is deque->at(middle)
* Swap again so the pivot element is deque->at(high)
* Then return deque->at(high)
*/ \
Deque_##_type_##_swap(&(deque->at(deque, middle)), &(deque->at(deque, high))); \
return deque->at(deque, high); \
} \
\
int Deque_##_type_##_partition(Deque_##_type_ * deque, int low, int high){ \
_type_ pivot = Deque_##_type_##_median_of_three(deque, low, high); \
int i = low - 1; \
\
for (int j = low; j <= high - 1; j++){ \
if (deque->less(deque->at(deque, j), pivot)){ \
i++; \
Deque_##_type_##_swap(&(deque->at(deque, i)), &(deque->at(deque, j))); \
} \
} \
Deque_##_type_##_swap(&(deque->at(deque, i + 1)), &(deque->at(deque, high))); \
return (i + 1); \
} \
\
void Deque_##_type_##_quicksort(Deque_##_type_* deque, int low, int high){ \
\
if (low < high){ \
int partition_index = Deque_##_type_##_partition(deque, low, high); \
Deque_##_type_##_quicksort(deque, low, partition_index - 1); \
Deque_##_type_##_quicksort(deque, partition_index + 1, high); \
} \
} \
\
void Deque_##_type_##_sort(Deque_##_type_ * deque, \
Deque_##_type_##_Iterator begin, Deque_##_type_##_Iterator end){ \
/* Quicksort */ \
Deque_##_type_##_quicksort(deque, 0, deque->current_size - 1); \
\
/* To get rid of unused parameter warning */ \
begin = deque->begin(deque); \
end = deque->end(deque); \
} \
\
/* Destructor */ \
void Deque_##_type_##_dtor(Deque_##_type_ * deque){ \
free(deque->array); \
free(deque->begin_iterator); \
free(deque->end_iterator); \
deque->array = nullptr; \
deque->begin_iterator = nullptr; \
deque->end_iterator = nullptr; \
} \
\
/* Constructor */ \
void Deque_##_type_##_ctor(Deque_##_type_ * deque, \
bool (*less)(const _type_ &object1, const _type_ &object2)){ \
/* Default Deque_##_type_ private field initializations */ \
deque->current_size = 0; \
deque->total_capacity = 10; \
\
deque->array = (_type_*) malloc(deque->total_capacity * sizeof(_type_));\
\
/* Start with front and back pointers in the middle of the array */ \
deque->front_index = deque->total_capacity / 2; \
deque->back_index = deque->total_capacity / 2; \
\
/* Initialize the Deque_##_type_ "less" comparison function pointer */ \
deque->less = less; \
\
/* Initialize the begin and end iterators */ \
deque->begin_iterator = (Deque_##_type_##_Iterator*) malloc(sizeof(Deque_##_type_##_Iterator)); \
(deque->begin_iterator)->deque = deque; \
(deque->begin_iterator)->index = deque->front_index; \
(deque->begin_iterator)->inc = &Deque_##_type_##_Iterator_inc; \
(deque->begin_iterator)->dec = &Deque_##_type_##_Iterator_dec; \
(deque->begin_iterator)->deref = &Deque_##_type_##_Iterator_deref; \
\
deque->end_iterator = (Deque_##_type_##_Iterator*) malloc(sizeof(Deque_##_type_##_Iterator)); \
(deque->end_iterator)->deque = deque; \
(deque->end_iterator)->index = (deque->back_index + 1) % deque->total_capacity; \
(deque->end_iterator)->inc = &Deque_##_type_##_Iterator_inc; \
(deque->end_iterator)->dec = &Deque_##_type_##_Iterator_dec; \
(deque->end_iterator)->deref = &Deque_##_type_##_Iterator_deref; \
\
/* Deque_##_type_ Function pointer initializations */ \
deque->size = &Deque_##_type_##_size; \
deque->empty = &Deque_##_type_##_empty; \
deque->full = &Deque_##_type_##_full; \
deque->clear = &Deque_##_type_##_clear; \
deque->push_back = &Deque_##_type_##_push_back; \
deque->push_front = &Deque_##_type_##_push_front; \
deque->pop_back = &Deque_##_type_##_pop_back; \
deque->pop_front = &Deque_##_type_##_pop_front; \
deque->begin = &Deque_##_type_##_begin; \
deque->end = &Deque_##_type_##_end; \
deque->sort = &Deque_##_type_##_sort; \
deque->front = &Deque_##_type_##_front; \
deque->back = &Deque_##_type_##_back; \
deque->at = &Deque_##_type_##_at; \
deque->dtor = &Deque_##_type_##_dtor; \
}
#endif
<file_sep>/assignment1/tests/performance.cpp
/*
* Compile with -ldl.
*/
#include <dlfcn.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <random>
#include <unistd.h>
#include "Deque.hpp"
#include <chrono>
bool int_less(const int &o1, const int &o2) {
return o1 < o2;
}
Deque_DEFINE(int)
int main() {
FILE *devnull = fopen("/dev/null", "w");
assert(devnull != 0);
using TimePoint = std::chrono::time_point<std::chrono::system_clock>;
using Milli = std::chrono::duration<double, std::ratio<1,1000>>;
using namespace std::chrono;
TimePoint start, end;
start = system_clock::now();
// Test random access performance
{
size_t sum = 0;
int lo = 0, hi = 10000000;
Deque_int deq;
Deque_int_ctor(&deq, int_less);
for(int i = lo; i < hi; i++) {
deq.push_back(&deq, i);
}
for(int i = lo; i < hi; i++) {
sum += deq.at(&deq, i);
}
deq.dtor(&deq);
assert(sum == 49999995000000);
}
end = system_clock::now();
Milli elapsed = end - start;
assert(elapsed.count() < 2000);
int rv = fclose(devnull);
assert(rv == 0);
}
<file_sep>/assignment4/ostream/test_Interpolate2.cpp
#include "Interpolate.hpp"
#include <iostream>
#include <string>
int main(){
std::cout << "------ Easy tests without io manipulators: ------" << std::endl;
std::cout << "Testing with correct amount of arguments:" << std::endl;
std::cout << '\t' << cs540::Interpolate("1 = %, 3.14 = %, Foo = % ", 1, 3.14, "Foo") << std::endl;
std::cout << "Testing with too many arguments: " << std::endl;
try {
std::cout << '\t' << cs540::Interpolate("1 = % ", 1, 2, 3) << std::endl;
} catch (cs540::WrongNumberOfArgs) {
std::cout << '\t' << "Exception caught. Passed." << std::endl;
}
std::cout << "Testing with too little arguments: " << std::endl;
try {
std::cout << '\t' << cs540::Interpolate("1 = %, 2 = %, 3 = % ", 1) << std::endl;
} catch (cs540::WrongNumberOfArgs) {
std::cout << '\t' << "Exception caught. Passed." << std::endl;
}
std::cout << "Testing the escaped % sign works: " << std::endl;
std::cout << '\t' << cs540::Interpolate(R"("i=%, x1=%\%, str1=%, done. ")", 1, 100, "wow") << std::endl;
return 0;
}
| b8c95b50ce15468445e39c4ccdb34f101a670088 | [
"Markdown",
"Makefile",
"C++"
] | 38 | C++ | SamKustin/cs440 | 12fe3f953cbe1a6c2e031d9c7c03497d66b62c96 | a66990699f3258765ed4fbe68ec6d11cb714206d |
refs/heads/master | <file_sep>//
const TopClient = require('../lib');
const assert = require('assert');
const client = new TopClient({
appkey: '1',
appsecret: '2',
redirect_uri: '3',
});
describe('订单相关', () => {
it('getAuthorizeUrl', async () => {
const res = client.getAuthorizeUrl();
});
})
| 820fb36385dccb456dc71b6193c5b59af7a5a8ad | [
"JavaScript"
] | 1 | JavaScript | dcboy/yp-taobao-topclient | 216c9febb35c043ca1858619a04b1491e0cc94dc | 5445d54564aaf163124857dd22c224a6374078bf |
refs/heads/master | <repo_name>jeremimucha/hello-travis<file_sep>/src/hello.cpp
#include <cstdio>
#include "hello.h"
int say_hello(const char* const name) noexcept
{
std::printf("Hello, %s!\n", name);
return 1;
}
int say_hi(const char* const name) noexcept
{
std::printf("Hi, %s!\n", name);
return 1;
}
<file_sep>/src/main.cpp
#include <cstdio>
#include "hello.h"
int main()
{
// char a[14] = "Hello, world!";
// char invalid = a[15];
// std::printf("%s\n", a);
// std::printf("%c\n", invalid);
say_hello("Travis");
say_hi("Appveyor");
}
<file_sep>/test/test_hi.cpp
#include "gtest/gtest.h"
#include "hello.h"
TEST(TestHi, Hi)
{
ASSERT_EQ(say_hi("Travis"), 1);
}
<file_sep>/test/test_hello.cpp
#include "gtest/gtest.h"
#include "hello.h"
TEST(HelloTest, Hello)
{
ASSERT_EQ(say_hello("Test"), 1);
}
<file_sep>/include/hello.h
#pragma once
int say_hello(const char* const) noexcept;
int say_hi(const char*) noexcept;
| f604fb145cd442b63daaa676dec0f8232d489879 | [
"C",
"C++"
] | 5 | C++ | jeremimucha/hello-travis | f223703f78d033328963ea06a22e58c8ca299d90 | 1ed314f224b4da386b4c31916075857fae4fe7b7 |
refs/heads/master | <file_sep># Swarm_Robotics
Swarm robotics is the study of how to coordinate rhead large groups of relatively simple robots through the use of local rules. It takes its inspiration from societies of insects that can perform tasks that are beyond the capibilities of the individuals.
### GUI
We have an overhead camera mounted to capture the view of the whole aren acontinously and detect the location and orientation of the robots through unique aruco marker placed on top of each robot. The user then inputs any shape into the GUI, which we map to the arena as the final coordinates that the robots must move to.


---
### Hardware used for the robot:
- Motor Driver
- 3 wheels(2 normal wheels and 1 castor wheel)
- NodeMCU
- 3-5volt Battery
- 2 IR sensors
A overhead logitech camera was used as a central network.

---
# Aruco Marker generation and Detection
We used OpenCV in python to generate and detect the ArUco Marker. The axes in ArUco markers are in pre-defined orientation and can be found by finding angle between one of the side of arena and x-axis of marker. Then apply cropping, and perspective transform to get final image of arena.
# Getting the Goal Location
The GUI gets input of the shape drawn by the user(certain pixels in image of arena make one cell on GUI). Then the shape is selected depending on the number of robots.
# Planning the Path
We used CBS(Conflict-Based Search) path planning algorithm. CBS is a two level algorithm that does not convert the problem into the single 'joint agent' model. At the high level, a search is performed on a Conflict Tree(CT) which is a tree based on conflicts between individual agents.
# Communication between Robots
We used NodeMCU to share the data robot and the central server. They shared the information like the current position of the robot and it's and final goal, it's orientation. Then NodeMCU drives motors through motor driver to ultimately reach final location.
<file_sep>/*
UDPSendReceive.pde:
This sketch receives UDP message strings, prints them to the serial port
and sends an "acknowledge" string back to the sender
A Processing sketch is included at the end of file that can be used to send
and received messages for testing with a computer.
created 21 Aug 2010
by <NAME>
This code is in the public domain.
adapted from Ethernet library examples
*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#ifndef STASSID
#define STASSID "Electronics Club"
#define STAPSK "RandomShit"
#endif
const int EnA = 4; //D2
const int EnB = 14; //D5
const int In1 = 16; //D0
const int In2 = 5; //D1
const int In3 = 0; //D3
const int In4 = 2; //D4
unsigned int localPort = 5007; // local port to listen on
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; //buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged\r\n"; // a string to send back
WiFiUDP Udp;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(500);
}
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
Serial.printf("UDP server on port %d\n", localPort);
Udp.begin(localPort);
pinMode(EnA, OUTPUT);
pinMode(EnB, OUTPUT);
pinMode(In1, OUTPUT);
pinMode(In2, OUTPUT);
pinMode(In3, OUTPUT);
pinMode(In4, OUTPUT);
analogWrite(EnB, 500);
analogWrite(EnA, 500);
}
void forward(){
digitalWrite(In2, LOW);
digitalWrite(In1,HIGH);
digitalWrite(In4, LOW);
digitalWrite(In3, HIGH);
}
void back(){
digitalWrite(In2, HIGH);
digitalWrite(In1,LOW);
digitalWrite(In4, HIGH);
digitalWrite(In3, LOW);
}
void right(){
analogWrite(EnB, 500);
analogWrite(EnA, 255);
digitalWrite(In2, HIGH);
digitalWrite(In1,LOW);
digitalWrite(In4, HIGH);
digitalWrite(In3, LOW);
}
void left(){
analogWrite(EnB, 255);
analogWrite(EnA, 500);
digitalWrite(In2, HIGH);
digitalWrite(In1,LOW);
digitalWrite(In4, HIGH);
digitalWrite(In3, LOW);
}
void stop_motion(){
digitalWrite(In2, LOW);
digitalWrite(In1,LOW);
digitalWrite(In4, LOW);
digitalWrite(In3, LOW);
}
void loop() {
int x = 0;
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.printf("Received packet of size %d from %s:%d\n (to %s:%d, free heap = %d B)\n",
packetSize,
Udp.remoteIP().toString().c_str(), Udp.remotePort(),
Udp.destinationIP().toString().c_str(), Udp.localPort(),
ESP.getFreeHeap());
// read the packet into packetBufffer
//String x = client.readStringUntil('\r');
int n = Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
packetBuffer[n] = 0;
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
x = (int)packetBuffer;
Udp.endPacket();
}
if(x == 0){
back();
}
else if(x == 1){
forward();
}
else if(x == 2){
right();
}
else if(x == 3){
left();
}
else if(x == 4){
stop_motion();
}
Serial.println(x);
}
/*
test (shell/netcat):
--------------------
nc -u 192.168.esp.address 8888
*/
<file_sep>import numpy as numpy
import cv2
import cv2.aruco as aruco
import math
import datetime
import time
import glob
from socket import *
i = 0
x = (0, 0)
y = (0, 0)
theta = 0
j=0
g=0
phi = 0
def distance(pt1, pt2):
x = pt1[0] - pt2[0]
y = pt1[1] - pt2[1]
distance = math.sqrt(x*x + y*y)
#print("distance: ",distance)
return distance
def angle_calculate(pt1, pt2):
a = pt2[0]-pt1[0]
b = pt2[1]-pt1[1]
angle = math.degrees(math.atan2(b, a))
if(angle<0):
angle =angle+360
return int(angle)
def allignment(theta, phi):
global g
clientSocket1 = socket(AF_INET, SOCK_DGRAM)
clientSocket1.settimeout(1)
print("angle difference: ",(theta - phi))
addr1 = ("192.168.0.120", 5007)
if -10<=theta-phi<=10:
if(g<=3):
clientSocket1.sendto('4'.encode(), addr1)
g=g+1
print(4)
else:
clientSocket1.sendto('0'.encode(), addr1)
print(0)
else:
clientSocket1.sendto('2'.encode(), addr1)
print(2)
def aruco_detect(frame, robot):
global i,j
i = 0
global x
x = (0, 0)
global y
y = (0, 0)
global theta
theta = 0
global phi
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)
parameters = aruco.DetectorParameters_create()
corners, ids, _ = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
aruco_frame = aruco.drawDetectedMarkers(gray, corners)
#print("corners")
#print(len(corners))
if len(corners)>0:
for marker in range(len(ids)):
#print(len(corners))
#print(ids)
x_center= int((corners[marker][0][0][0] + corners[marker][0][1][0] + corners[marker][0][2][0] + corners[marker][0][3][0])/4)
y_center= int((corners[marker][0][0][1] + corners[marker][0][1][1] + corners[marker][0][2][1] + corners[marker][0][3][1])/4)
#print(x_center, y_center)
cv2.circle(frame, (x_center, y_center),2,(0,0,255),2)
x1 = int(corners[marker][0][0][0])
x3 = int(corners[marker][0][3][0])
y1 = int(corners[marker][0][0][1])
y3 = int(corners[marker][0][3][1])
pt1 = (x3,y3)
pt2 = (x1,y1)
cv2.circle(frame, pt1, 2, (0,0,255), 2)
cv2.circle(frame,pt2, 2, (0,0,255), 2)
cv2.imshow('aruco_frame', frame)
if ids[marker] == 8:
theta = angle_calculate(pt1, pt2)
print('theta', theta)
x = (x_center, y_center)
else if ids[marker] == 1:
y = (x_center, y_center)
cv2.imshow('aruco_frame', frame)
robot[int(ids[marker])]=(int(x_center), int(y_center), int(theta))
if not (j == 2) :
# print("YES")
j+=1
phi = angle_calculate(y, x)
print("phi: ",phi)
dist = distance(x,y)
if len(ids)>1:
if(dist>150):
allignment(theta, phi)
j=2
else:
clientSocket1 = socket(AF_INET, SOCK_DGRAM)
clientSocket1.settimeout(1)
addr1 = ("192.168.0.120", 5007)
clientSocket1.sendto('4'.encode(), addr1)
#return direction
start = 0
start_time_update = time.time()
cv2.imshow("aruco_frame", frame)
return robot
robot={}
cap = cv2.VideoCapture(2)
while(1):
_,img_rgb = cap.read()
robot = aruco_detect(img_rgb,robot)
k = cv2.waitKey(1) & 0xFF
if k == 27:
cap.release()
cv2.destroyAllWindow()
break
<file_sep>import time
from socket import *
pings = 1
#Send ping 10 times
while pings < 11:
#Create a UDP socket
clientSocket1 = socket(AF_INET, SOCK_DGRAM)
clientSocket2 = socket(AF_INET, SOCK_DGRAM)
#Set a timeout value of 1 second
clientSocket1.settimeout(1)
clientSocket2.settimeout(1)
#Ping to server
message1 = input('> ').encode()
message2 = input('> ').encode()
addr1 = ("192.168.0.120", 5007)
addr2 = ("192.168.0.103", 5007)
#Send ping
start = time.time()
clientSocket1.sendto(message1, addr1)
clientSocket2.sendto(message2, addr2)
#If data is received back from server, print
try:
data, server = clientSocket1.recvfrom(1024)
end = time.time()
elapsed = end - start
print(data)
#If data is not received back from server, print it has timed out
except timeout:
print('REQUEST TIMED OUT1')
try:
data, server = clientSocket2.recvfrom(1024)
end = time.time()
elapsed = end - start
print(data)
except timeout:
print('REQUEST TIMED OUT2')
pings = pings - 1
<file_sep>/* Connects to the home WiFi network
* Asks some network parameters
* Starts WiFi server with fix IP and listens
* Receives and sends messages to the client
* Communicates: wifi_client_01.ino
*/
#include <SPI.h>
#include <ESP8266WiFi.h>
//byte ledPin = 2;
char ssid[] = "Electronics Club"; // SSID of your home WiFi
char pass[] = "<PASSWORD>"; // password of your home WiFi
WiFiServer server(80);
IPAddress ip(192, 168, 0, 112); // IP address of the server
IPAddress gateway(192,168,0, 8); // gateway of your network
IPAddress subnet(255,255,255,0); // subnet mask of your network
void setup() {
Serial.begin(115200); // only for debug
WiFi.config(ip, gateway, subnet); // forces to use the fix IP
WiFi.begin(ssid, pass); // connects to the WiFi router
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
server.begin(); // starts the server
/* Serial.println("Connected to wifi");
Serial.print("Status: "); Serial.println(WiFi.status()); // some parameters from the network
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());
Serial.print("Networks: "); Serial.println(WiFi.scanNetworks());*/
//pinMode(ledPin, OUTPUT);
}
void loop () {
//Serial.println("HII");
WiFiClient client = server.available();
if (client) {
if (client.connected()) {
//digitalWrite(ledPin, LOW); // to show the communication only (inverted logic)
Serial.println(".");
char ch = Serial.read();
client.println(ch);
String request = client.readStringUntil('\r'); // receives the message from the client
//Serial.print("From client: ");
Serial.println(request);
client.flush();
//client.println("Hi client! No, I am listening.\r"); // sends the answer to the client
//digitalWrite(ledPin, HIGH);
}
client.stop(); // tarminates the connection with the client
}
}
<file_sep>import numpy as numpy
import cv2
import cv2.aruco as aruco
import math
import datetime
import time
import glob
from socket import *
i = 0
cen1 = (0, 0)
cen2 = (0, 0)
cen0 = (0, 0)
theta1 = 0
theta2 = 0
j=0
g=0
phi = 0
def distance(pt1, pt2):
x = pt1[0] - pt2[0]
y = pt1[1] - pt2[1]
distance = math.sqrt(x*x + y*y)
#print("distance: ",distance)
return distance
def angle_calculate(pt1, pt2):
a = pt2[0]-pt1[0]
b = pt2[1]-pt1[1]
angle = math.degrees(math.atan2(b, a))
if(angle<0):
angle =angle+360
return int(angle)
def allignment(theta, phi, id):
global g
clientSocket1 = socket(AF_INET, SOCK_DGRAM)
clientSocket1.settimeout(1)
clientSocket2 = socket(AF_INET, SOCK_DGRAM)
clientSocket2.settimeout(1)
print("angle difference: ",(theta - phi))
addr1 = ("192.168.0.120", 5007)
addr2 = ("192.168.0. ", 5007)
if id == 8:
addr = addr1
else:
addr = addr2
if -10<=theta-phi<=10:
if(g<=3):
clientSocket1.sendto('4'.encode(), addr)
g=g+1
print(4)
else:
clientSocket1.sendto('0'.encode(), addr)
print(0)
else:
clientSocket1.sendto('2'.encode(), addr)
print(2)
def aruco_detect(frame, robot):
global i,j
i = 0
global cen2
cen2 = (0, 0) #for aruco9
global cen1
cen1 = (0, 0) #for aruco8
global theta1
theta1 = 0
global theta2
theta2 = 0
global phi
global cen0
cen0 = (0, 0) #for goal
goal = 0
follower = 0
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)
parameters = aruco.DetectorParameters_create()
corners, ids, _ = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
aruco_frame = aruco.drawDetectedMarkers(gray, corners)
#print("corners")
#print(len(corners))
# if len(corners)>0:
# for marker in range(len(ids)):
# if ids[marker] == 1: #goal id
# x_center = int((corners[marker][0][0][0] + corners[marker][0][1][0] + corners[marker][0][2][0] + corners[marker][0][3][0])/4)
# y_center = int((corners[marker][0][0][1] + corners[marker][0][1][1] + corners[markers][0][2][1] + corners[marker][0][3][1])/4)
if len(corners)>0:
for marker in range(len(ids)):
#print(len(corners))
#print(ids)
x_center= int((corners[marker][0][0][0] + corners[marker][0][1][0] + corners[marker][0][2][0] + corners[marker][0][3][0])/4)
y_center= int((corners[marker][0][0][1] + corners[marker][0][1][1] + corners[marker][0][2][1] + corners[marker][0][3][1])/4)
#print(x_center, y_center)
cv2.circle(frame, (x_center, y_center),2,(0,0,255),2)
x1 = int(corners[marker][0][0][0])
x3 = int(corners[marker][0][3][0])
y1 = int(corners[marker][0][0][1])
y3 = int(corners[marker][0][3][1])
pt1 = (x3, y3)
pt2 = (x1, y1)
if ids[marker] == 1:
cen0 = (x_center, y_center)
elif ids[marker] == 8:
cen1 = (x_center, y_center)
theta1 = 360 - angle_calculate(pt1, pt2)
print("theta1 ",theta1)
elif ids[marker] == 9:
cen2 = (x_center, y_center)
theta2 = 360 - angle_calculate(pt1, pt2)
print("theta2 ",theta2)
cv2.circle(frame, pt1, 2, (0,0,255), 2)
cv2.circle(frame,pt2, 2, (0,0,255), 2)
#cv2.imshow('aruco_frame', frame)
cv2.imshow('aruco_frame', frame)
robot[int(ids[marker])]=(int(x_center), int(y_center), int(theta))
dist1 = distance(cen0, cen1)
dist2 = distance(cen0, cen2)
if dist1 < dist2:
phi = angle_calculate(cen0, cen1)
allignment(theta1, phi, 8)
goal = 8
follower = 9
else:
phi = angle_calculate(cen0, cen2)
allignment(theta2, phi, 9)
goal = 9
follower = 8
if len(ids)>1:
if(dist>150):
allignment(theta, phi)
j=2
else:
clientSocket1 = socket(AF_INET, SOCK_DGRAM)
clientSocket1.settimeout(1)
addr1 = ("192.168.0.120", 5007)
clientSocket1.sendto('4'.encode(), addr1)
#return direction
start = 0
start_time_update = time.time()
cv2.imshow("aruco_frame", frame)
return robot
robot={}
cap = cv2.VideoCapture(2)
while(1):
_,img_rgb = cap.read()
robot = aruco_detect(img_rgb,robot)
k = cv2.waitKey(1) & 0xFF
if k == 27:
cap.release()
cv2.destroyAllWindow()
break
<file_sep>import cv2
import numpy as np
import cv2.aruco as aruco
'''
File Name:perspective
Funtions:mainarea
Global Variable:
'''
'''
Function Name:mainarea
Input:img_rgb(image from camera)
Output:back box enclosed area in image or returns the same image
Logic:contours of specific area in selected to fet the largest black box in area
Example Call:
'''
calibration = np.load("calibrated.npz", allow_pickle=False)
mtx=calibration["mtx"]
dist=calibration["dist"]
def mainarea(img_rgb):
img_gray=cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY) #converts image int gray image
img_gray = cv2.bitwise_not(img_gray)
ret,thresh = cv2.threshold(img_gray,210,255,cv2.THRESH_BINARY) #converts image into binary
cv2.imshow('thresh',thresh)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)#find contours in the image
x=0 #initial x corner of black box rectagle
y=0 #nitial y corner of block box rectangle
w=0 #initial width of black box rectangle
h=0 #initial height of black box rectangle
if contours:
# for contour in contours:
#approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
#area = cv2.contourArea(contour) #calculate the area of contour detected
contour= max(contours, key = cv2.contourArea)
#if (area >100000)and area<250000 : # true if area is between range may vary with the height of camera set each time when camera height is changed
x,y,w,h = cv2.boundingRect(contour) #gives x,y,w,h of rectangle around contour
cv2.rectangle(img_rgb,(x,y),(x+w,y+h),(0,0,255),2) #draw bounding rectangle around rectangle
#print x,y,w,h
if w>0 and h>0:
crop_img = img_rgb[y:y+h, x:x+w] #crop black rectangel from the img_rgb
pts1 = np.float32([[x,y],[x+w,y],[x,y+h],[x+w,y+h]]) # rectangle for perspective transform
pts2 = np.float32([[0,0],[w,0],[0,h],[w,h]]) #canvas size for perspective transform
M = cv2.getPerspectiveTransform(pts1,pts2) #perspective transform of the img_rgb
arena = cv2.warpPerspective(crop_img,M,(w,h)) #wrap perspectie
#cv2.imshow('Arena',arena)
h, w = arena.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
# undistort
dst = cv2.undistort(arena, mtx, dist, None, newcameramtx)
#crop the image
x, y, w, h = roi
arena = dst[y:y+h, x:x+w]
cv2.imshow('cropped',arena)
return arena #returns image of black box arena
else:
return img_rgb #returns image of img_rgb as it is
'''
to make the script stand alone and check persperctive transform of black box arena
decomment the below code change the comport if required
'''
cap=cv2.VideoCapture(0)
while(1):
ret,img_rgb=cap.read()
#img_gray=cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY)
if ret:
mainarea(img_rgb)
gray=cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY)
#cv2.imshow('Gray',img_gray)
rows,cols,ch = img_rgb.shape
cv2.imshow('image',img_rgb)
# set dictionary size depending on the aruco marker selected
aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)
# detector parameters can be set here (List of detection parameters[3])
parameters = aruco.DetectorParameters_create()
parameters.adaptiveThreshConstant = 10
# lists of ids and the corners belonging to each id
corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
# font for displaying text (below)
font = cv2.FONT_HERSHEY_SIMPLEX
# check if the ids list is not empty
# if no check is added the code will crash
if np.all(ids != None):
# estimate pose of each marker and return the values
# rvet and tvec-different from camera coefficients
rvec, tvec ,_ = aruco.estimatePoseSingleMarkers(corners, 0.05, mtx, dist)
#(rvec-tvec).any() # get rid of that nasty numpy value array error
for i in range(0, ids.size):
# draw axis for the aruco markers
aruco.drawAxis (img_rgb, mtx, dist, rvec[i], tvec[i], 0.1)
# draw a square around the markers
aruco.drawDetectedMarkers(img_rgb, corners)
# code to show ids of the marker found
strg = ''
for i in range(0, ids.size):
strg += str(ids[i][0])+', '
cv2.putText(img_rgb, "Id: " + strg, (0,64), font, 1, (0,255,0),2,cv2.LINE_AA)
else:
# code to show 'No Ids' when no markers are found
cv2.putText(img_rgb, "No Ids", (0,64), font, 1, (0,255,0),2,cv2.LINE_AA)
k = cv2.waitKey(20) & 0xFF
if k == 27:
cv2.destroyAllWindows()
break
<file_sep>#include <SPI.h>
#include <ESP8266WiFi.h>
//byte ledPin = 2;
//char ssid[] = "Electronics Club"; // SSID of your home WiFi
//char pass[] = "<PASSWORD>"; // password of your home WiFi
//
//unsigned long askTimer = 0;
//
//IPAddress server(192,168,0,112); // the fix IP address of the server
//WiFiClient client;
const int EnA = 4; //D2
const int EnB = 14; //D5
const int In1 = 16; //D0
const int In2 = 5; //D1
const int In3 = 0; //D3
const int In4 = 2; //D4
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
// WiFi.begin(ssid, pass); // connects to the WiFi router
// while (WiFi.status() != WL_CONNECTED) {
// Serial.print(".");
// delay(500);
pinMode(EnA, OUTPUT);
pinMode(EnB, OUTPUT);
pinMode(In1, OUTPUT);
pinMode(In2, OUTPUT);
pinMode(In3, OUTPUT);
pinMode(In4, OUTPUT);
analogWrite(EnB, 300);
analogWrite(EnA, 300);
}
void forward(){
digitalWrite(In2, LOW);
digitalWrite(In1,HIGH);
digitalWrite(In4, LOW);
digitalWrite(In3, HIGH);
}
void back(){
digitalWrite(In2, HIGH);
digitalWrite(In1,LOW);
digitalWrite(In4, HIGH);
digitalWrite(In3, LOW);
}
void right(){
analogWrite(EnB, 200);
analogWrite(EnA, 200);
digitalWrite(In2, LOW);
digitalWrite(In1,HIGH);
digitalWrite(In4, HIGH);
digitalWrite(In3, LOW);
}
void left(){
analogWrite(EnB, 255);
analogWrite(EnA, 500);
digitalWrite(In2, HIGH);
digitalWrite(In1,LOW);
digitalWrite(In4, HIGH);
digitalWrite(In3, LOW);
}
void stop_motion(){
digitalWrite(In2, LOW);
digitalWrite(In1,LOW);
digitalWrite(In4, LOW);
digitalWrite(In3, LOW);
}
void loop() {
// put your main code here, to run repeatedly:
//client.connect(server, 80); // Connection to the server
//digitalWrite(ledPin, LOW); // to show the communication only (inverted logic)
//Serial.println(".");
//client.println("Hello server! Are you sleeping?\r"); // sends the message to the server
//String x = client.readStringUntil('\r');
//client.println("Hii\r");
char x = Serial.read();
if(x == '0'){
back();
}
else if(x == '1'){
forward();
}
else if(x == '2'){
right();
}
else if(x == '3'){
left();
}
else if(x == '4'){
stop_motion();
}
//client.flush();
delay(500);
}
| b6845e153ad3e2338f310639a5a854fca97fb54c | [
"Markdown",
"Python",
"C++"
] | 8 | Markdown | vyush/Swarm-Robotics | 77befcadddcc03951ff6226d48c585715d617097 | 13c8beaffcd97ff975259c9b51618c3ab89422f1 |
refs/heads/master | <file_sep>import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.fftpack import ifft
import math
def main():
#Enter code here (see README.TXT for examples)
return 0
"""Define a data segment class. Each instance corresponds to a given segment of data (which could be ECG or otherwise)
The methods of this class are useful as they allow us to set offsets, find maxima/minima, compute means and more
By default, this class is used for data extracted directly from some file (for this, we use data = [])
To use the methods of this class on other lists (for example, when computing R-R intervals), we can
change the default value for the entry data by passing the array we would like to work with."""
class DataSegment:
def __init__(self, filename, offset, events, data = []):
if data == []:
self.filename = filename
self.offset = offset
self.events = events
self.data = read_data(self.filename, self.offset, self.events)
else:
self.data = data
"""This method computes the maximum element of self.data"""
def mymax(self):
current_max = self.data[0]
for element in self.data:
if element > current_max:
current_max = element
return current_max
"""This method computes the minimum element of self.data"""
def mymin(self):
current_min = self.data[0]
for element in self.data:
if element < current_min:
current_min = element
return current_min
"""This method computes the mean of self.data"""
def mean(self):
mysum = 0
for element in self.data:
mysum += element
mean = float(mysum)/len(self.data)
return mean
"""This method computes the standard deviation of self.data"""
def stddev(self):
mean = self.mean()
sum_squares = 0
for element in self.data:
sum_squares += (mean - element) ** 2
stddev = (sum_squares/len(self.data)) ** 0.5
return stddev
"""Define a subclass of DataSegment that has additional methods used specifically for ECG data"""
class ECG(DataSegment):
def __init__(self, filename, offset, events):
self.filename = filename
self.offset = offset
self.events = events
self.data = read_data(self.filename, self.offset, self.events)
if len(self.data) == 0:
raise Exception("Offset should not exceed file length and events should be greater than 0.")
"""This is method for finding peaks in linear time. We set a threshold (defined by the variable tolerance) for the start of a peak depending on the
mean and standard deviation of the data. The function returns an array where each element is the index of a peak (note that the incides have
been shifted by the offset, which depends on how the class is initialised).
UPDATE: We have since added some code to account for potential false T wave peak detections that occur in a02.dat. The code we have added includes
the edge case at the start of the for loop, the final conditional in the for loop, and the use of found_end_peak."""
def find_peaks(self, tolerance = 2):
found_peak = False
found_end_peak = False
mean = self.mean()
stddev = self.stddev()
peaks = []
for i in range(0, len(self.data)):
#Edge case. This will delete a false T wave peak detection at the end of the data segment. It may also delete
#a true peak if the following trough occurs after the end of the data segment. However, this is not as an issue
#as this true peak will be picked up when using a data buffer to analyse larger segments of data.
if (i == len(self.data) - 1) and (found_end_peak):
del peaks[-1]
#If we have found a peak, we continue until the data falls back below peak threshold
if found_peak and self.data[i] <= mean + (tolerance * stddev):
#Reached end of peak
found_peak = False
found_end_peak = True
end_peak = i
peaks.append(start_peak + index_of_max(self.data[start_peak:end_peak+1]) + self.offset)
#If we have not yet found a peak (or we are between peaks), we keep searching until we find the next peak
elif (not found_peak) and self.data[i] > mean + (tolerance * stddev):
found_peak = True
#Here, we delete the previously detected peak if found_end_peak is True (which means the previously detected peak is not followed by a significant
#trough and so we expect it to be a falsely detected T wave peak)
if found_end_peak:
del peaks[-1]
start_peak = i
#If the below statement is true, the previous peak we found was an R wave peak (and not a T wave peak)
#and so we do not need to remove any false peaks from the array peaks
if found_end_peak and self.data[i] <= mean - stddev:
found_end_peak = False
return peaks
def RR_intervals(self):
RR_data = []
peaks = self.find_peaks()
for i in range(0, len(peaks) - 1):
RR_data.append(peaks[i + 1] - peaks[i])
return RR_data
"""This method finds the peaks of the result of the find_peaks method. This allows us to compute respiratory rate from
amplitude modulation of the ECG peaks. The function returns a list containing the locations of the found peaks
as an integer representing its index in the ECG data. The location corresponds to the end of the found peak.
Recommended range of tolerances is discussed in the final report. Higher tolerance works better for apnoea data and
lower tolerance works better for non-apnoea data."""
def resp_peaks_amplitude(self, tolerance = 2):
peaks = self.find_peaks()
amplitude_data = []
location_data = []
for peak in peaks:
amplitude_data.append(self.data[peak - self.offset])
#Obtain the mean and standard deviation of amplitude data
amplitude = DataSegment("", 0, 0, amplitude_data)
amplitude_data_stddev = amplitude.stddev()
i = 0
while i < (len(amplitude_data) - 3):
#If data at index i+1 greater than data at index i, and either data at index i+2 greater than data at index i+1 or index i+3 greater than data
#at index i+1, we assume we have reached the start of a peak
if (amplitude_data[i + 1] > amplitude_data[i]) and ((amplitude_data[i + 2] > amplitude_data[i + 1]) or (amplitude_data[i + 3] > amplitude_data[i + 1])):
#Search for end of peak. We assume that we are still at a peak if the data continues to increase (i.e. data[i+1]>data[i] or data[i+2]>data[i])
count = 0
while (i < (len(amplitude_data) - 4)) and ((amplitude_data[i + 3] > amplitude_data[i + 2]) or (amplitude_data[i + 4] > amplitude_data[i + 2])):
count += 1
i += 1
#Check if peak is sufficiently large
if abs(amplitude_data[i + 2] - amplitude_data[i - count]) > (tolerance * amplitude_data_stddev):
location_data.append(peaks[i + 2])
i += 2
i += 1
return location_data
"""This method finds the troughs of the R-R intervals. This allows us to compute respiratory rate from
frequency modulation of the ECG peaks. The function returns a list containing the locations of the found troughs
as an integer representing its index in the ECG data. The location corresponds to the end of the found trough. Recommended
values for tolerance are discussed in the final report."""
def resp_troughs_frequency(self, tolerance = 1):
RR_data = self.RR_intervals()
peaks = self.find_peaks()
location_data = []
RR = DataSegment("", 0, 0, RR_data)
RR_data_stddev = RR.stddev()
i = 0
while i < (len(RR_data) - 1):
#If data at index i+1 smaller than data at index i, we assume we have reached the start of a trough
if RR_data[i + 1] < RR_data[i]:
#Search for end of trough. We assume that we are still at a trough if the data continues to decrease (i.e. data[i+1]<data[i] or data[i+2]<data[i])
count = 0
while (i < len(RR_data) - 3) and ((RR_data[i + 2] < RR_data[i + 1]) or (RR_data[i + 3] < RR_data[i + 1])):
count += 1
i += 1
#Check if trough is sufficiently large
if abs(-RR_data[i + 1] + RR_data[i - count]) > (tolerance * RR_data_stddev):
location_data.append(peaks[i + 1])
i += 2
i += 1
return location_data
"""Define a subclass of DataSegment that has additional methods used specifically for Respiratory data"""
class Respiratory(DataSegment):
def __init__(self, filename, offset, events):
self.filename = filename
self.offset = 4 * offset
self.events = 4 * events
self.respdata = read_data(self.filename, self.offset, self.events)
self.data = []
for i in range(0, len(self.respdata)):
if (i + 2) % 4 == 0:
self.data.append(self.respdata[i])
if len(self.data) == 0:
raise Exception("Offset should not exceed file length and events should be greater than 0." + str(self.offset) + " " +str(self.events))
"""This function is used to find troughs in the oronasal airflow data. These troughs should correspond to inhalation.
We use this function to compute the respiratory rate using the oronasal airflow data as a benchmark for our
algorithm that computes the respiratory rate from the ECG signal. Note that the algorithm used here is essentially
the same as the algorithm used for the find_peaks function except that we look for data that falls below a certain
threshold rather than above it.
The variable tolerance refers to how many standard deviations we would like the data to reach below the mean
before counting as a trough. Recommended tolerance = 2 for apnoea and tolerance = 1 for no apnoea in a01.dat. We set
the tolerance to be 1.5 so that it works well for both apnoea and no apnoea data."""
def find_airflow_troughs(self, tolerance = 1.5):
found_trough = False
mean = self.mean()
stddev = self.stddev()
troughs = []
for i in range(0, len(self.data)):
#If we have found a trough, we continue until the data increases back above trough threshold
if found_trough and self.data[i] >= mean - (tolerance * stddev):
#Reached end of trough
found_trough = False
end_trough = i
troughs.append(start_trough + index_of_min(self.data[start_trough:end_trough+1]) + self.offset)
#If we have not yet found a trough (or we are between troughs), we keep searching until we find the next trough
elif (not found_trough) and self.data[i] < mean - (tolerance * stddev):
found_trough = True
start_trough = i
return troughs
"""This function filters data using a Gaussian kernel (low pass). It is useful for removing noise from signals.
The variable scale is a constant factor that scales the attenuated data.
The variable attenuation determines how much the high frequencies are attenuated.
Higher attenuation corresponds to attentuating the high frequencies more."""
def low_pass_filter(data, scale, attenuation):
#Take the discrete Fourier transform of the data
transformed_data = fft(data)
attenuated_data = []
#Attenuate unwanted frequencies
for i in range(0, len(data)):
attenuated_data.append(transformed_data[i] * scale * math.exp(-((attenuation * i) ** 2)))
#Take the inverse Fourier transform of the data
filtered_data = ifft(attenuated_data)
return filtered_data
"""This function can be used to plot ECG data and the associated peaks. The variable ecg represents
an instance of the class ECG where the corresponding data has a sample rate of 100Hz. If the sample rate
changes, the only variable that would need to change is xlabel, which can be done manually. The boolean peaks
and amplitude_peaks are set to True by default. They correspond to adding a subplot of the R-peaks and the
breaths computed from amplitude modulation respectively. To remove either of these subplots, one can set the
corresponding variable to False."""
def plot_ECG_amplitude_data(ecg, outfilename, peaks = True, amplitude_peaks = True, xlabel = "Time (10ms)", ylabel = "Voltage (A/D)"):
plt.clf()
plt.plot(ecg.data, color = "black")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.tight_layout()
plt.subplot(1, 1, 1)
if peaks:
for element in ecg.find_peaks():
plt.plot(element - ecg.offset, ecg.data[element - ecg.offset], color = "red", ls = "", marker = "o", label = "points")
if amplitude_peaks:
for element in ecg.resp_peaks_amplitude():
plt.plot(element - ecg.offset, ecg.data[element - ecg.offset], color = "blue", ls = "", marker = "o", label = "points")
plt.savefig(outfilename)
return 0
"""This function can be used to plot frequency domain data such as R-R intervals. Plotting R-R intervals
will be the primary purpose of this function. The variable ecg represents an instance of the class ECG. The boolean
peaks is set to True by default and corresponds to adding a subplot containing the breaths computed from frequency
modulation. To remove this subplot, set the variable troughs to False. The R-R interval plotted at some time t corresponds
to the time interval between the R-peak at time t and the next R-peak."""
def plot_ECG_frequency_data(ecg, outfilename, troughs = True, xlabel = "Time (10ms)", ylabel = "R-R interval (10ms)"):
plt.clf()
RR_data = {}
peaks = ecg.find_peaks()
for i in range(0, len(peaks) - 1):
RR_data[peaks[i]] = peaks[i + 1] - peaks[i]
RR_intervals = RR_data.values()
frequency_troughs = ecg.resp_troughs_frequency()
plt.plot([element - ecg.offset for element in peaks[0:-1]], RR_intervals, color = "black")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.tight_layout()
plt.subplot(1, 1, 1)
if troughs:
for element in frequency_troughs:
plt.plot(element - ecg.offset, RR_data[element], color = "blue", ls = "", marker = "o", label = "points")
plt.savefig(outfilename)
return 0
"""This function can be used to plot oronasal airflow data and the associated troughs. To plot data without troughs,
set the variable troughs to False. We have the option to overlay ECG data onto this plot by setting overlay to
True. To overlay the ECG data, call the corresponding ECG plot function before calling this function and leave
overlay as its default value False."""
def plot_airflow_data(ecg, outfilename, troughs = True, overlay = False, xlabel = "Time (10ms)", ylabel = "Pressure"):
if not overlay:
plt.clf()
plt.plot(ecg.data, color = "black")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.tight_layout()
plt.subplot(1, 1, 1)
if troughs:
for element in ecg.find_airflow_troughs():
plt.plot(element - ecg.offset, ecg.data[element - ecg.offset], color = "red", ls = "", marker = "o", label = "points")
plt.savefig(outfilename)
return 0
"""This function returns the index of the maximum value in an array of data"""
def index_of_max(array):
current_max = array[0]
max_index = 0
for i in range(0, len(array)):
if array[i] > current_max:
current_max = array[i]
max_index = i
return max_index
"""This function returns the index of the minimum value in an array of data"""
def index_of_min(array):
current_min = array[0]
min_index = 0
for i in range(0, len(array)):
if array[i] < current_min:
current_min = array[i]
min_index = i
return min_index
"""This function reads data (ECG or otherwise). (Function obtained from Roger with slight modification)"""
def read_data(filename, offset, events): # extract data
file = open(filename, 'rb') # returns data in A/D units
file.seek(offset * 2)
data = []
for i in range(0, events):
D = file.read(2)
#If we have reached end of file, then break
if not D:
break
N = int.from_bytes(D, byteorder = 'little', signed = True)
data.append(N)
file.close()
return data
"""This function is used to extract data from an ECG file including heatbeats and amplitude as a function of time.
Here, we use a data buffer to read the data in segments. The variables filename and respfilename are the file names of the
ECG data and oronasal airflow data respectively. The variables outfilename1, outfilename2, and outfilename3
correspond to files containing R-peaks data, AM respiratory data + benchmark, and FM respiratory data + benchmark respectively.
This function also prints data. Descriptions of the data printed and output files are given in readme.txt."""
def extract_ecg_data(filename, respfilename, outfilename1, outfilename2, outfilename3, offset, events, resp_rate_interval = 120):
"""resp_rate_interval is the time interval (in seconds) for which we compute the respiratory rate
segment_size is the number of events per segment of data (which is defined by the resp_rate_interval)
overlap is the number of overlapping events between two adjacent segments. This has been chosen sufficiently large so
that we don't miss detecting peaks that occur between segments."""
amp_count = 0
freq_count = 0
airflow_count = 0
segment_size = resp_rate_interval * 100
overlap = segment_size // 5
number_of_segments = ((events - segment_size) // (segment_size - overlap)) + 2
current_event = offset
current_segment = ECG(filename, current_event, segment_size)
current_segment_airflow = Respiratory(respfilename, current_event, segment_size)
file1 = open(outfilename1, "w+")
file1.write("R-PEAK INDEX, TIME, AMPLITUDE\n")
file2 = open(outfilename2, "w+")
file2.write("R-PEAK AMPLITUDE PEAK INDEX, TIME, AMPLITUDE, COMPUTED RESPIRATORY RATE (BREATHS PER MINUTE), BENCHMARK RESPIRATORY RATE (BREATHS PER MINUTE)\n")
file3 = open(outfilename3, "w+")
file3.write("R-R INTERVAL TROUGHS INDEX, TIME, AMPLITUDE, COMPUTED RESPIRATORY RATE (BREATHS PER MINUTE), BENCHMARK RESPIRATORY RATE (BREATHS PER MINUTE)\n")
rms_difference_amplitude = 0
rms_difference_frequency = 0
rms_airflow = 0
for i in range(0, number_of_segments - 1):
prev_segment = current_segment
prev_segment_airflow = current_segment_airflow
current_event += (segment_size - overlap)
current_segment = ECG(filename, current_event, segment_size)
current_segment_airflow = Respiratory(respfilename, current_event, segment_size)
#Compare first peak in current_segment to last peak in previous segment to ensure that we aren't double counting peaks due to the events in the overlap.
prev_segment_peaks = prev_segment.find_peaks()
prev_segment_amplitude_peaks = prev_segment.resp_peaks_amplitude()
prev_segment_frequency_troughs = prev_segment.resp_troughs_frequency()
prev_segment_airflow_troughs = prev_segment_airflow.find_airflow_troughs()
current_segment_peaks = current_segment.find_peaks()
current_segment_amplitude_peaks = current_segment.resp_peaks_amplitude()
current_segment_frequency_troughs = current_segment.resp_troughs_frequency()
current_segment_airflow_troughs = current_segment_airflow.find_airflow_troughs()
#Look at the first peak in current_segment and check if it is in prev_segment. If it is, truncate the prev_segment data so that there are no repeating peaks
j = 1
k = 1
l = 1
m = 1
#Truncate prev_segment data
while ((current_segment_peaks != []) and (len(prev_segment_peaks) >= j)) and (current_segment_peaks[0] <= prev_segment_peaks[-j]):
j += 1
prev_segment_peaks = prev_segment_peaks[0:len(prev_segment_peaks) - (j - 1)]
while ((current_segment_amplitude_peaks != []) and (len(prev_segment_amplitude_peaks) >= k)) and (current_segment_amplitude_peaks[0] <= prev_segment_amplitude_peaks[-k]):
k += 1
prev_segment_amplitude_peaks = prev_segment_amplitude_peaks[0:len(prev_segment_amplitude_peaks) - (k - 1)]
while ((current_segment_frequency_troughs != []) and (len(prev_segment_frequency_troughs) >= l)) and (current_segment_frequency_troughs[0] <= prev_segment_frequency_troughs[-l]):
l += 1
prev_segment_frequency_troughs = prev_segment_frequency_troughs[0:len(prev_segment_frequency_troughs) - (l - 1)]
while ((current_segment_airflow_troughs != []) and (len(prev_segment_airflow_troughs) >= m)) and (current_segment_airflow_troughs[0] <= prev_segment_airflow_troughs[-m]):
m += 1
prev_segment_airflow_troughs = prev_segment_airflow_troughs[0:len(prev_segment_airflow_troughs) - (m - 1)]
#Write prev_segment data to file
for element in prev_segment_peaks:
#Time in seconds
time = float(element) / 100
#Amplitude in A/D units
amplitude = prev_segment.data[element - (current_event - (segment_size - overlap))]
file1.write(str(element) + "," + str(time) + "," + str(amplitude) + "\n")
for element in prev_segment_amplitude_peaks:
time = float(element) / 100
amplitude = prev_segment.data[element - (current_event - (segment_size - overlap))]
file2.write(str(element) + "," + str(time) + "," + str(amplitude) + ", , " + "\n")
for element in prev_segment_frequency_troughs:
time = float(element) / 100
amplitude = prev_segment.data[element - (current_event - (segment_size - overlap))]
file3.write(str(element) + "," + str(time) + "," + str(amplitude) + ", , " + "\n")
#Write respiratory rate data to files
resp_rate_amplitude = (100 * 60 * float(len(prev_segment_amplitude_peaks))) / (segment_size - overlap)
resp_rate_frequency = (100 * 60 * float(len(prev_segment_frequency_troughs))) / (segment_size - overlap)
resp_rate_airflow = (100 * 60 * float(len(prev_segment_airflow_troughs))) / (segment_size - overlap)
file2.write(" , , , " + str(resp_rate_amplitude) + ", " + str(resp_rate_airflow) + "\n")
file3.write(" , , , " + str(resp_rate_frequency) + ", " + str(resp_rate_airflow) + "\n")
#Compute root mean squared difference between algorithm and its benchmark for testing
rms_difference_amplitude += (resp_rate_amplitude - resp_rate_airflow) ** 2
rms_difference_frequency += (resp_rate_frequency - resp_rate_airflow) ** 2
rms_airflow += resp_rate_airflow ** 2
amp_count += len(prev_segment_amplitude_peaks)
freq_count += len(prev_segment_frequency_troughs)
airflow_count += len(prev_segment_airflow_troughs)
#Write current_segment data to file. This is an edge case.
for element in current_segment_peaks:
time = float(element) / 100
amplitude = current_segment.data[element - current_event]
file1.write(str(element) + "," + str(time) + "," + str(amplitude) + "\n")
for element in current_segment_amplitude_peaks:
time = float(element) / 100
amplitude = current_segment.data[element - current_event]
file2.write(str(element) + "," + str(time) + "," + str(amplitude) + "\n")
for element in current_segment_frequency_troughs:
time = float(element) / 100
amplitude = current_segment.data[element - current_event]
file3.write(str(element) + "," + str(time) + "," + str(amplitude) + "\n")
resp_rate_amplitude = (100 * 60 * float(len(current_segment_amplitude_peaks))) / (segment_size)
resp_rate_frequency = (100 * 60 * float(len(current_segment_frequency_troughs))) / (segment_size)
resp_rate_airflow = (100 * 60 * float(len(current_segment_airflow_troughs))) / (segment_size)
file2.write(" , , , " + str(resp_rate_amplitude) + ", " + str(resp_rate_airflow) + "\n")
file3.write(" , , , " + str(resp_rate_frequency) + ", " + str(resp_rate_airflow) + "\n")
rms_difference_amplitude += (resp_rate_amplitude - resp_rate_airflow) ** 2
rms_difference_frequency += (resp_rate_frequency - resp_rate_airflow) ** 2
rms_airflow += resp_rate_airflow ** 2
rms_difference_amplitude = math.sqrt(rms_difference_amplitude / number_of_segments)
rms_difference_frequency = math.sqrt(rms_difference_frequency / number_of_segments)
rms_airflow = math.sqrt(rms_airflow / number_of_segments)
amp_count += len(current_segment_amplitude_peaks)
freq_count += len(current_segment_frequency_troughs)
airflow_count += len(current_segment_airflow_troughs)
print("RMS difference (AM): " + str(rms_difference_amplitude))
print("RMS difference (FM): " + str(rms_difference_frequency))
print("RMS of airflow: " + str(rms_airflow))
print("Total number of breaths (AM): " + str(amp_count))
print("Total number of breaths (FM): " + str(freq_count))
print("Total number of breaths (airflow): " + str(airflow_count))
file1.close()
file2.close()
file3.close()
return 0
"""This function is used to test the function find_peaks by searching for R-R intervals that differ significantly from the mean
in a given segment of data.
It returns array of tuples (peak number, R-R interval) where peak number identifies a peak corresponding to an R-R interval that differs
significantly from the mean R-R interval in the data segment"""
def test_find_peaks(peaks, number_of_peaks):
anomalies = []
intervals = []
for i in range(0, len(peaks) - 1):
intervals.append(peaks[i + 1] - peaks[i])
sums = 0
for interval in intervals:
sums += interval
interval_mean = float(sums) / len(intervals)
sum_squares = 0
for interval in intervals:
sum_squares += (interval_mean - interval) ** 2
interval_stddev = (float(sum_squares) / len(intervals)) ** 0.5
for i in range(0, len(intervals)):
#check if R-R interval is an anomaly
if (intervals[i] >= interval_mean + 3 * interval_stddev) or (intervals[i] <= interval_mean - 3 * interval_stddev):
anomalies.append((number_of_peaks - (len(intervals) - i) + 1, intervals[i]))
return anomalies
"""This function computes the running variance of some data.
The running variance at each point is the variance of the
n data samples ahead of that point. Here, n = segment_size."""
def compute_running_variance(data, segment_size = 1000):
variance_data = []
for i in range(0, len(data) - segment_size):
sums = 0
sum_squares = 0
for j in range(0, segment_size):
sums += data[i + j]
mean = float(sums) / segment_size
for j in range(0, segment_size):
sum_squares += (mean - data[i + j]) ** 2
variance = float(sum_squares) / segment_size
variance_data.append(variance)
return variance_data
"""Call main() function on execution."""
if __name__ == "__main__":
main()
<file_sep>##############################################################################################################
INTRODUCTION
##############################################################################################################
This code was submitted for assessment as part of the subject COMP90072 at The University of Melbourne. The goal was to efficiently and accurately compute the respiratory rate of an individual using electrocardiography. The data files were obtained from https://physionet.org/physiobank/database/apnea-ecg/.
##############################################################################################################
PROGRAM STRUCTURE
##############################################################################################################
This program requires Python3, Pyplot, and SciPy (for FFTs).
This program is used for the analysis of ECG data. The program is structured as follows. We have one superclass DataSegment that is used for simple manipulation of time series data. The data can be obtained in two ways: by reading .dat files or by passing an array. For example, if we have an array of data called my_array, we can create an instance of the class DataSegment by defining my_segment = DataSegment("", 0, 0, my_array). The first three arguments are not important and can be set to anything since we already have an array of data. If we wish to use data obtained from a .dat file, we create an instance of the class my defining my_segment = DataSegment(filename, offset, events). Here, filename is the name of the .dat file, offset is the starting point in the .dat file (in terms of number of events), and events is the number of events to be read.
Given an instance of DataSegment called my_segment, we can obtain the offset by using self.offset, and we can obtain the data by using self.data. The class DataSegment has four methods: mymax, mymin, mean, and stddev. The methods mymax and mymin return the maximum and minimum values in self.data respectively. The methods mean and stddev return the mean and standard deviation of self.data respectively.
The class DataSegment has two subclasses: ECG and Respiratory. The subclass ECG is used for studying data obtained from an ECG signal. This subclass has a method find_peaks, which locates the R-peaks of ECG data. The algorithm used in find_peaks is discussed in the final report. The method find_peaks takes an argument called tolerance, which defines the threshold for a peak in terms of the standard deviation of the data. For example, if we choose tolerance = 2 (which is the default value), the algorithm requires the start of a peak to be at least 2 standard deviations above the mean of the ECG data. The method find_peaks returns an array of indices giving the location of the peaks found with the algorithm. Note that the indices returned are not adjusted by the offset of the data. For example, let us assume that we define an instance of the class ECG with offset 1000 and that the algorithm locates a peak at index 100 relative to this offset. Then the index returned will be 1100. Note also that the index returned is the location of the maximum amplitude value of the R-peak.
The method RR_intervals returns an array consisting of the R-R intervals in self.data (where the interval is defined in terms of number of events, not time in seconds). The R-R interval at index i is the difference between the indices of the (i+1)th and ith peaks.
The method resp_peaks_amplitude is used to estimate the respiratory rate from the ECG signal by studying the amplitude modulation of the ECG R-peaks. The algorithm used is described in the final report. It has an argument tolerance, which is used to set a statistical threshold for the definition of a breath. A tolerance of 2 means that we require the height of a "peak" (not an R-peak but a peak in the R-peak data) to be greater than 2 times the standard deviation of the amplitude data in the given data segment. This method outputs an array of indices corresponding to the location of the breath. This location corresponds to the end of the peak found.
The method resp_troughs_frequency is used to estimate the respiratory rate from the ECG signal by studying the frequency modulation of the ECG R-peaks. The algorithm used is described in the final report. Similar to resp_peaks_amplitude, the argument tolerance is used to set the threshold for a breath. A tolerance of 2 means that we require the height of a "trough" (a trough in the R-R interval data) to be greater than 2 times the standard deviation of the R-R interval data in the given data segment. This method outputs an array of indices corresponding to the location of the breath. This location corresponds to the end of the trough found.
The subclass Respiratory of DataSegment is used to study oronasal airflow data. Similar to the class ECG, it requires a filename, offset, and number of events. The offset and number of events here is the number of oronasal airflow events (not the number of events that includes all 4 respiratory channels). When we initialise self.offset and self.events, we multiply by a factor of 4 to account for the 4 channels. Then, self.data is initialised to the data in only the oronasal airflow channel of the respiratory data. The class Respiratory contains the method find_airflow_troughs, which is used to locate breaths in the oronasal airflow data. The algorithm used for this is described in the final report. The variable tolerance is used to check if we have reached the start of a trough in the airflow data (corresponding to a breath). We assume that we have reached the start of a trough if the airflow data falls below mean - (tolerance * stddev) where mean is the mean of the airflow data in the given data segment and stddev is the standard deviation of the airflow data in a given segment.
Outside of the class DataSegments, we have some additional functions. The function low_pass_filter(data, scale, attenuation) filters the array data using a Gaussian kernel and returns the filtered data. The scale and attenuation are the contents appearing in the kernel.
The function extract_ecg_data(filename, respfilename, outfilename1, outfilename2, outfilename3, offset, events, resp_rate_interval = 120) is used to test our AM and FM algorithms on large samples of data and extract relevant data including our computed respiratory rate. The function creates 3 output files with the following data:
Output file 1 format = CSV:
R-PEAK INDEX, CORRESPONDING TIME, CORRESPONDING AMPLITUDE
Output file 2 format = CSV:
R-PEAK AMPLITUDE PEAK INDEX, CORRESPONDING TIME, CORRESPONDING AMPLITUDE, COMPUTED RESPIRATORY RATE (BREATHS PER MINUTE), BENCHMARK RESPIRATORY RATE (BREATHS PER MINUTE)
Output file 3 format = CSV:
R-R INTERVAL TROUGHS INDEX, CORRESPONDING TIME, CORRESPONDING AMPLITUDE, COMPUTED RESPIRATORY RATE (BREATHS PER MINUTE), BENCHMARK RESPIRATORY RATE (BREATHS PER MINUTE)
In other words, the first CSV file contains index, time and amplitude information of the ECG R-peaks. The next file contains index, time, and amplitude information of the peaks of the ECG R-peaks data (for amplitude modulation method). It also contains the computed respiratory rate (in breaths per minute) for each interval (given in seconds by resp_rate_interval) along with the benchmark respiratory rate. The final file contains index, time, and amplitude information of the troughs of the ECG R-R intervals (for frequency modulation method). It also contains the computed and benchmark respiratory rates. The respiratory rate is computed every resp_rate_interval seconds. This has been set to 120 by default but can be changed.
The function extract_ecg_data also prints data for testing. This includes the root mean squared (RMS) of the computed airflow respiratory rate, the RMS of the difference between the airflow respiratory rate and the AM respiratory rate, and the RMS of the difference between the airflow respiratory rate and the FM respiratory rate. The function also prints the number of breaths computed using our AM and FM algorithms and the number of breaths computed using our benchmark (airflow) algorithm.
There are additional simple functions with brief descriptions that are commented in the code.
##############################################################################################################
INPUT/OUTPUT EXAMPLES
##############################################################################################################
To use this program, modify the main() function. The below examples show the main function used to produce the output files in the relevant directories. We begin with some plotting examples.
______________________________________________________________________________________________________________
Example1
This example produces three plots. The first two are the amplitude and frequency data for the first 4000 events in a01.dat with no peaks or troughs shown. The third plot is the airflow data for the first 4000 events in a01.dat with troughs (i.e. breaths) shown. The ECG data has not been overlaid onto the respiratory data in this example.
______________________________________________________________________________________________________________
def main():
myecg = ECG("Data_Files/a01.dat", 0, 4000)
myresp = Respiratory("Data_Files/a01r.dat", 0, 4000)
plot_ECG_amplitude_data(myecg, "Output_Examples/Plots/Example1/Amplitude_No_Peaks.png", False, False)
plot_ECG_frequency_data(myecg, "Output_Examples/Plots/Example1/Frequency_No_Troughs.png", False)
plot_airflow_data(myresp, "Output_Examples/Plots/Example1/Airflow_Troughs_No_Overlay.png")
return 0
______________________________________________________________________________________________________________
______________________________________________________________________________________________________________
Example2
This example produces three plots. Two of these plots are the amplitude and frequency data from events 300000 to 300000+4000 in a02.dat. The R-peaks are shown in red. The breaths computed using our amplitude/frequency modulation algorithms are in blue. The third plot is the oronasal airflow data corresponding to events 300000 to 300000+4000 in a02.dat. The read dots are the breaths found using our benchmark algorithm. We have overlaid the plot of the amplitude data to compare the amplitude modulation algorithm to the benchmark algorithm. Notice the order the functions have been called in. The function plot_ECG_amplitude_data comes directly before plot_airflow_data since we are overlaying the amplitude data plot onto the airflow data plot.
______________________________________________________________________________________________________________
def main():
myecg = ECG("Data_Files/a02.dat", 300000, 4000)
myresp = Respiratory("Data_Files/a02r.dat", 300000, 4000)
plot_ECG_amplitude_data(myecg, "Output_Examples/Plots/Example2/Amplitude_Peaks.png")
plot_airflow_data(myresp, "Output_Examples/Plots/Example2/Airflow_Troughs_Overlay.png", True, True)
plot_ECG_frequency_data(myecg, "Output_Examples/Plots/Example2/Frequency_Troughs.png")
return 0
______________________________________________________________________________________________________________
______________________________________________________________________________________________________________
Example3
This example is the same as Example2 except that we have instead overlaid the frequency plot onto the airflow plot (rather than the amplitude plot onto the airflow plot). Notice the order in which the functions are called.
______________________________________________________________________________________________________________
def main():
myecg = ECG("Data_Files/a02.dat", 300000, 4000)
myresp = Respiratory("Data_Files/a02r.dat", 300000, 4000)
plot_ECG_frequency_data(myecg, "Output_Examples/Plots/Example3/Frequency_Troughs.png")
plot_airflow_data(myresp, "Output_Examples/Plots/Example3/Airflow_Troughs_Overlay.png", True, True)
plot_ECG_amplitude_data(myecg, "Output_Examples/Plots/Example3/Amplitude_Peaks.png")
return 0
______________________________________________________________________________________________________________
We will now show some examples of using the function extract_ecg_data.
______________________________________________________________________________________________________________
Example1
This example produces three CSV files (see extract_ecg_data function description for more details) corresponding to the R-peaks data, AM respiratory data, and FM respiratory data. The data used was from a01.dat and a01r.dat, and we have read events 0 to 2957000 (i.e the entire file).
______________________________________________________________________________________________________________
def main():
outfile1 = "Output_Examples/CSV_Files/Example1/R-Peaks_Data.csv"
outfile2 = "Output_Examples/CSV_Files/Example1/AM_Resp_Data.csv"
outfile3 = "Output_Examples/CSV_Files/Example1/FM_Resp_Data.csv"
extract_ecg_data("Data_Files/a01.dat", "Data_Files/a01r.dat", outfile1, outfile2, outfile3, 0, 2957000)
return 0
______________________________________________________________________________________________________________
Console output:
RMS difference (AM): 2.3370602579631212
RMS difference (FM): 2.192491984910345
RMS of airflow: 4.390169665463789
Total number of breaths (AM): 2731
Total number of breaths (FM): 1597
Total number of breaths (airflow): 2059
______________________________________________________________________________________________________________
______________________________________________________________________________________________________________
Example2
The CSV files produced here use the data a02.dat and a02r.dat. We read events 100,000 to 100,000 + 1,000,000.
______________________________________________________________________________________________________________
def main():
outfile1 = "Output_Examples/CSV_Files/Example2/R-Peaks_Data.csv"
outfile2 = "Output_Examples/CSV_Files/Example2/AM_Resp_Data.csv"
outfile3 = "Output_Examples/CSV_Files/Example2/FM_Resp_Data.csv"
extract_ecg_data("Data_Files/a02.dat", "Data_Files/a02r.dat", outfile1, outfile2, outfile3, 100000, 1100000)
return 0
______________________________________________________________________________________________________________
Console output:
RMS difference (AM): 6.399834406825118
RMS difference (FM): 6.96018373383172
RMS of airflow: 12.056287823661002
Total number of breaths (AM): 1216
Total number of breaths (FM): 1291
Total number of breaths (airflow): 2039
______________________________________________________________________________________________________________
Finally, we provide a couple of miscellaneous examples. In practice, when studying small segments of data it is easier to not use the function extract_ecg_data. In this case, it is easier to use the peak/trough finding methods directly. For example, to compute the number of R-peaks between events 0 and 10000 in a02.dat, we can define:
def main():
myecg = ECG("Data_Files/a02.dat", 0, 10000)
print(len(myecg.find_peaks()))
return 0
This prints 149 and so we have found 149 R-peaks here.
If we wish to print the number of breaths in this data (using AM, FM, and benchmark), we simply define:
def main():
myecg = ECG("Data_Files/a02.dat", 0, 10000)
myresp = Respiratory("Data_Files/a02r.dat", 0, 10000)
print(len(myecg.resp_peaks_amplitude()))
print(len(myecg.resp_troughs_frequency()))
print(len(myresp.find_airflow_troughs()))
return 0
This prints the following:
17
15
17
Hence, we have found 17 breaths using our AM algorithm, 15 peaks using our FM algorithm, and 17 peaks using our benchmark (oronasal airflow) algorithm. We can easily modify the tolerance of the corresponding algorithms. For example, to use a tolerance of 2.5 standard deviations for the AM algorithm (the default is 2), we can use the line print(len(myecg.resp_peaks_amplitude(2.5))). A tolerance of 2.5 for AM turns out to work better in the data with apnoea.
The easiest way to get familiar with the full functionality of the program is to experiment by calling various functions in main(). Have fun!
| 590d3b449e2ade4e1421f55da926eec97a157d58 | [
"Python",
"Text"
] | 2 | Python | tysonfield/ECG-Analysis | 12001412c7a0dfe16b4548706da922576f99b104 | 800aaf243330ec075370e29049a80342d79e5777 |
refs/heads/master | <repo_name>JGordy/JGordy.github.io<file_sep>/js/main.js
let main = document.querySelector('#main'),
mainHeader = document.querySelector('#main_header'),
menu = document.querySelectorAll('.menu_button'),
nav = document.querySelector('#nav'),
screen_width = document.documentElement.clientWidth,
floatersAmount,
newHeader = "",
date = new Date();
// console.log(date.getMonth() + 1, date.getDate());
// adding event listeners for mobile menu toggle open and close
for (var i = 0; i < menu.length; i++) {
menu[i].addEventListener('click', function() {
nav.classList.toggle('openMenu');
});
};
// adding divs around each letter in the header to animate them
for (var i = 0; i < mainHeader.innerHTML.length; i++) {
newHeader += `<div onmouseover="letterBounce(${i})" class="letter" id="letter${i}" >${mainHeader.innerHTML[i]}</div>`;
};
mainHeader.innerHTML = newHeader;
// adding letter animation on mouseover
letterBounce = (i) => {
let letter = document.querySelector(`#letter${i}`);
letter.setAttribute('class', 'letter hover');
// letter.style.color = `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 1)`;
// rgba(100,0,200,)
setTimeout(function() {
letter.setAttribute('class', 'letter');
}, 600);
};
// changing the color of the navigation when moved from "main"
changeNavColor = () => {
let navLinks = document.querySelectorAll('.navLinks');
if ((document.body.scrollTop > 500 || document.documentElement.scrollTop > 500) && (screen_width > 500)) {
//adding class to navlinks when scrolled 500px from top
for (var i = 0; i < navLinks.length; i++) {
if (navLinks[i].className === "navLinks menu_button") {
navLinks[i].className = "navLinks menu_button light"
} else if (navLinks[i].className === "navLinks") {
navLinks[i].className = "navLinks light";
}
}
} else {
// removing class from navlinks when scroll is less than 500px from the top
for (var i = 0; i < navLinks.length; i++) {
if (navLinks[i].className === "navLinks menu_button light" || navLinks[i].className === "navLinks menu_button") {
navLinks[i].className = "navLinks menu_button"
} else if (navLinks[i].className === "navLinks menu_button light") {
navLinks[i].className = "navLinks menu_button";
}
}
};
if ((document.body.scrollTop > 650 || document.documentElement.scrollTop > 650) && (screen_width <= 500)) {
//adding a class to the navbar if the screen is below 500px
menu[0].style.color = "rgba(255 ,255, 255, 1)";
nav.style.backgroundColor = 'rgba(255 ,255, 255, 0.9)';
for (var i = 0; i < navLinks.length; i++) {
navLinks[i].style.backgroundColor = 'rgba(255 ,255, 255, 0.0)';
navLinks[i].style.color = "#102027";
navLinks[i].style.borderTop = "1px solid #102027";
};
} else if ((document.body.scrollTop < 650 || document.documentElement.scrollTop < 650) && (screen_width <= 500)) {
// removing a class from the navbar if the screen is below 500px
menu[0].style.color = "#102027";
nav.style.backgroundColor = '#102027';
for (var i = 0; i < navLinks.length; i++) {
navLinks[i].style.backgroundColor = 'inherit';
navLinks[i].style.color = "rgba(255, 255, 255, 1)";
navLinks[i].style.borderTop = "1px solid rgba(255, 255, 255, 0.2)";
};
};
};
window.onscroll = function() {changeNavColor()};
// smooth scrolling jquery function for navigation
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 750);
return false;
});
// Adding projects from data.js
createProjectHTML = (project) => {
return `<div class="image-container ${project.mobile ? " mobile" : ''}">
<a href=${project.href} target="_blank">
<img src=${project.imageURL} alt="" class="image ${project.mobile ? 'mobile' : ''}">
<div class="overlay">
<div class="text">
<div class="views">
<h3>${project.name}</h3>
<div class="view_icons">
${project.icons.map(icon => {
return `<i class="material-icons">${icon}</i>`;
})}
</div>
</div>
<div class="project_skills">
<div class="skills_list">
${project.skills.map(skill => {
return `<span>${skill}</span>`;
})}
</div>
</div>
</div>
</div>
</a>
</div>`;
}
addProjects = (projects) => {
const desktop = document.getElementById('desktop_projects');
const mobile = document.getElementById('mobile_projects');
projects.forEach(project => {
if (project.mobile) {
mobile.innerHTML += createProjectHTML(project);
} else {
desktop.innerHTML += createProjectHTML(project);
}
})
}
addProjects(projects);
// Github api repository request
fetch(repoURL)
.then(results => results.json())
.then(data => {
for (var i = 0; i < data.length; i++) {
if (data[i].homepage) {
createRepo(data, i);
} else if (i <= 10 && !data[i].homepage) {
createRepo(data, i);
};
};
});
// Github api user info request
fetch(userURL)
.then(results => results.json())
.then(data => vCardFunction(data));
// adding github user data to the DOM
vCardFunction = (data) => {
let company,
list = document.querySelector(".list"),
contacts = document.querySelector('.contact-list');
if (data.company === null) {
company = `<a class="company hire" href="mailTo:<EMAIL>" ></a>`;
} else {
company = data.company;
};
list.innerHTML = `<li>
<span><i class="material-icons">person_pin</i></i></span> ${data.location}
</li>
<li>
<span><i class="material-icons">school</i></span><a href="https://www.theironyard.com/" target="_blank">The Iron Yard</a>
</li>
<li>
<span><i class="material-icons">business</i></span> ${company}
</li>
<li>
<span><i class="fab fa-github" aria-hidden="true"></i></span><a href=${data.html_url} target="_blank">github.com/Jgordy</a>
</li>
<li>
<span><i class="fa fa-globe" aria-hidden="true"></i></span><a href=https://${data.blog}>${data.blog}</a>
</li>`;
contacts.innerHTML = `<li>
<span><i class="material-icons">email</i></span>
<h4>Email me at</h4>
<a href="mailTo:<EMAIL>"><EMAIL></a>
</li>
<li>
<span><i class="fab fa-linkedin" aria-hidden="true"></i></span>
<h4>Message me on LinkedIn</h4>
<a href="https://www.linkedin.com/in/joseph-gordy" target="_blank">LinkedIn.com/joseph-gordy</a>
</li>
<li>
<span><i class="material-icons">phone_android</i></span>
<h4>Call me at</h4>
<a href="tel:13347186808">(334) 718 - 6808</a>
</li>`;
let image = document.createElement("img");
image.setAttribute("src", data.avatar_url);
// let icon = document.getElementById("icon");
icon.appendChild( image );
};
// Adding project company logos below
createCompanyHTML = logo => {
return `<div class="logo">
<a href=${logo.href} />
<img src="./images/Logo/${logo.imageURL}" />
</a>
</div>`;
}
addCompanyLogos = logos => {
const companies = document.querySelector('#company-wrapper');
logos.forEach(logo => {
companies.innerHTML += createCompanyHTML(logo);
})
};
addCompanyLogos(logos);
// creating list item elements for each repo, from the api data
createRepo = (data, i) => {
let repositories = document.querySelector('.repositories'),
eachRepo = document.createElement('div');
eachRepo.setAttribute('class', 'eachRepo');
repositories.appendChild(eachRepo);
let repo_container = document.createElement('div');
repo_container.setAttribute('class', 'repo_container');
eachRepo.appendChild(repo_container);
let link_container = document.createElement('div');
link_container.setAttribute('class', 'link_container');
eachRepo.appendChild(link_container);
if (data[i].homepage != null) {
let site = document.createElement('a');
site.setAttribute('href', `${data[i].homepage}`);
site.setAttribute('class', 'github');
site.setAttribute('target', "_blank");
link_container.appendChild(site);
let ghIcon = document.createElement('div');
ghIcon.setAttribute('class', 'ghIcon');
ghIcon.innerHTML = `<i class="fa fa-globe" aria-hidden="true"></i>`;
site.appendChild(ghIcon);
}
let link = document.createElement('a');
link.setAttribute('href', `${data[i].html_url}`);
link_container.appendChild(link);
let title = document.createElement('h4');
title.textContent = `${data[i].name}`;
repo_container.appendChild(title);
let language = document.createElement('h5');
language.setAttribute('class', 'language');
language.textContent = `${data[i].language}`;
repo_container.appendChild(language);
let codeIcon = document.createElement('div');
codeIcon.setAttribute('class', 'codeIcon');
codeIcon.innerHTML = `<i class="material-icons">code</i>`;
link.appendChild(codeIcon);
};
//function to create the standard background floater
createFloater = (index) => {
let dot = document.createElement('div');
let line = document.createElement('div');
let cross = document.createElement('div');
dot.setAttribute('class', 'dot');
main.appendChild(dot);
if (dot.className === 'dot') {
// dot.style.top === Math.random().toFixed(2) * 100 + "vh";
// dot.style.left === Math.random().toFixed(2) * 100 + "vw";
// dot.style.transition = `top ${Math.random().toFixed(2) * 15}s, left ${Math.random().toFixed(2) * 15}s`;
dot.style.transform = `rotate(${Math.random().toFixed(2) * 180}deg)`;
};
setTimeout(function() {
dot.setAttribute('class', 'move');
if (dot.className === 'move') {
let randomSpeed = Math.random().toFixed(2) * 15;
dot.style.top = Math.random().toFixed(2) * 100 + "vh";
dot.style.left = Math.random().toFixed(2) * 95 + "vw";
dot.style.transition = `top ${randomSpeed}s, left ${randomSpeed}s`;
}
}, 1500);
let rotateSpeed = Math.random().toFixed(2) * 150;
line.setAttribute('class', 'line');
line.style.transform = "rotate(" + Math.random().toFixed(2) * 180 + "deg)";
line.style.animation = `${rotateSpeed}s ease-out 0s infinite rotateCW`;
dot.appendChild(line);
cross.setAttribute('class', 'cross');
cross.style.transform = "rotate(" + Math.random().toFixed(2) * 180 + "deg)";
cross.style.animation = `${rotateSpeed}s ease-out 0s infinite rotateCCW`;
dot.appendChild(cross);
if (index % 5 === 0) {
line.style.backgroundColor = `rgba(0,0,0,0.9)`;
cross.style.backgroundColor = `rgba(0,0,0,0.9)`;
} else if (index % 9 === 0) {
line.style.backgroundColor = `rgba(0,0,0,0.1)`;
cross.style.backgroundColor = `rgba(0,0,0,0.1)`;
}
};
// function to create snow themed background
snowTheme = () => {
let snowflake = document.createElement('div');
snowflake.innerHTML = `<i class="fa fa-snowflake-o" aria-hidden="true"></i>`;
snowflake.style.position = 'absolute';
snowflake.style.top = '0';
snowflake.style.left = `${Math.floor(Math.random().toFixed(2) * 100)}vw`;
snowflake.style.transform = `scale(${Math.random().toFixed(2) * 1.5})`;
snowflake.style.color = 'lightblue';
main.appendChild(snowflake);
};
// adding floating elements in the background of main section
if (screen_width <= 500 ) {
floatersAmount = 25;
} else if (screen_width <= 800 ) {
floatersAmount = 40;
} else if (screen_width <= 1000 ) {
floatersAmount = 75;
} else {
floatersAmount = 80;
};
for (var i = 0; i < floatersAmount; i++) {
// if (date.getMonth() + 1 === 12) {
// snowTheme()
// } else {
// createFloater();
// };
createFloater(i);
};
<file_sep>/README.md
# Welcome to JosephGordy.com
### Tech Used
- Javascript (Basic)
- CSS3 animations and transitions
- HTML5
- Api fetch for Github user info and projects/repositories
## Dependencies
- none on this project
| 4b7564cf19f9d94ab6e0dcda1516f79c6c7074de | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | JGordy/JGordy.github.io | 8e318fff49fd22a86a67b6f58b17bbcc63c6103b | abd2ce3df375c31beefe7a58c6e99a0c97b7ac59 |
refs/heads/master | <repo_name>santhos995/MusicPlayer<file_sep>/README.md
# MusicPlayer
A simple music player application
Requirements -
1) List songs
2) Playlist
3) Shuffle play
4) Buttons to play - Play, Pause/Resume, Next, Prev
Song DB - For now, use ISongSorage interface
UI - Need to figure it out with team
<file_sep>/DataStructures/PlayList.cs
using System;
using System.Collections.Generic;
namespace DataStructures
{
public class PlayList
{
private List<Song> Songs;
public PlayList()
{
Songs = new List<Song>();
}
public void Play()
{
throw new NotImplementedException();
}
}
}<file_sep>/DataStructures/Song.cs
using System;
namespace DataStructures
{
public class Song
{
public string Name;
public string Author;
public TimeSpan SongDuration;
public string Album;
public string Format;
public double Size;
}
}<file_sep>/MusicPlayer/MusicPlayerClass.cs
namespace MusicPlayer
{
public class MusicPlayerClass
{
}
}<file_sep>/Interfaces/IPlayer.cs
namespace SongStorageInterfaces
{
public interface IPlayer
{
void ShufflePlay();
}
}<file_sep>/Interfaces/ISongStorage.cs
using DataStructures;
namespace SongStorageInterfaces
{
interface ISongStorage
{
string[] GetSongs();
Song GetSong(string name);
bool AddSong(Song song);
bool UpdateSong(string name, Song song);
}
} | 1d7d347c5281e459f0d758ae2d3ec5de6446e9de | [
"Markdown",
"C#"
] | 6 | Markdown | santhos995/MusicPlayer | a06b51df6434529e9d176be254a4d92dfbfb4f74 | 08c679e64a7e3388c39f7c382dbc7f99fe52bede |
refs/heads/master | <file_sep>/*REFERENCE APPLICATION FOR MY LEARNING AND FUTURE REVISION
In this application I will be using ES6 syntax, so you will see the use of
ES6 arrow functions for example*/
//MODULE DECLARATIONS
/*Whenever you import a new module, you have to import it with the require function and
declare it as a constant*/
const express = require('express');
//Bring in express handlebars; this is used to render HTML templates on the server
const exphbs = require('express-handlebars');
//Bring in mongoose
const mongoose = require('mongoose');
//Bring in body-parser. This will allow use to fetch input from forms and pass them using a post request
const bodyParser = require('body-parser');
//Bring in the method override module
const methodOverride = require('method-override');
//Bring in express connect-flash - this will allow me to display flash messages to inform the user when tasks are complete
const flash = require('connect-flash');
const session = require('express-session');
//Bring in passport module
const passport = require('passport');
//You then assign that to a new object with a call to the variable you just declared
const app = express();
//HOW MIDDLEWARE WORKS
/*Whenever we use modules we're always going to do it in three steps, we bring in the module using the require function
and then we decalre the middleware, and then use the module code*/
/*An express application is basically a set of middleware function calls;
these are functions that have access to the request and response objects, and
the next middleware function in the request-response cycle*/
//EXAMPLE:
/*app.use(function(request, reponse, next){
//If we included the line below, every time the page loads, the current datetime will be printed to console
console.log(Date.now());
//If we add a value to the request object here, we can acccess it later on
request.name = 'Rossco';
//And the commented code in the get calls show how we could access the value declared above
Call the next bit of middleware to run
next();
});*/
//DATABASE CONFIG
//Check if using local dev or remote production database
const db = require('./config/database');
//CONNECT TO MONGOOSE
//We pass into the connect function the path for our database as so
//Also, always pass an object with the property useMongoClient: true
/*Connect responses with a promise, you can revise promises here: https://www.youtube.com/watch?v=swdWUWtGxR4
when we use a promise we have to catch it with a .then, we also put a .catch in to catch any errors,
this process is the same as using callbacks, except its much cleaner and generally better practice*/
//Map global promise - gets rid of depreciation error
mongoose.Promise = global.Promise;
mongoose.connect(db.mongoURL, {
useMongoClient: true
})
.then(() => console.log('MongoDB connected...'))
.catch(err => console.log(err));
//CONNECT TO MODELS
//the dot means we are looking in the current directory that we are in
require('./models/Idea')
const Idea = mongoose.model('ideas');
//HANDLEBARS MIDDLEWARE
//This is just telling the system that we want to use the handlebars template engine
app.engine('handlebars', exphbs({
//We create a directory in our project folder called views, this will contain all our handlebar templates
//Within this directory we have another directory called layouts.Layouts wrap around all our other views.
//The default layout will be set to main
defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
//BODY PARSER MIDDLEWARE
app.use(bodyParser.urlencoded({encoded: false}));
app.use(bodyParser.json());
//METHOD OVERRIDE MIDDLEWARE
app.use(methodOverride('_method'));
//SESSION and FLASH MIDDLEWARE
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));
app.use(flash());
//PASSPORT MIDDLEWARE
//This MUST be declared after the express session middleware
app.use(passport.initialize());
app.use(passport.session());
//GLOBAL VARS
//Here I just define some global variables that will be used by the flash messages
//There is a partial for messages and errors in the partial directory
app.use(function(request, response, next){
response.locals.success_msg = request.flash('success_msg');
response.locals.error_msg = request.flash('error_msg');
response.locals.error = request.flash('error');
response.locals.user = request.user || null;
next();
});
//SETTING ROUTES
/*We make a get request (HTTP reminder, get retrieves data, post is submitting data to a server,delete to delete data,
and put is updating existing data)
Get takes in two parameters in the callback function, a request object and a response object*/
//The send method for the response object is going to send something to the browser
//Index route
app.get('/', (request, response) => {
//The call below would send 'INDEX' to browser
//response.send("INDEX");
//This will call the index handlebars template in views
//We also pass in a dynamic variable called title, which will be passed into the template when rendered
const title = "Welcome"
response.render('index', {
title: title
});
//NOTE
//We can access parameters of the object we defined in the middleware above
//When index loads, the console will print not just the datetime, but also the name 'Rossco'
//console.log(request.name);
})
//About route
app.get('/about', (request, response) => {
response.render("about");
});
//All other routes are contained in the route folder, and accessed through the express.Router method
const ideas = require('./routes/ideas');
app.use('/ideas', ideas);
const users = require('./routes/users');
app.use('/users', users);
//PASSPORT CONFIG
//We are taking passport, and passing it into the config function that is exported from the passport config file
require('./config/passport')(passport);
//SET PORT
//You set a port for your listen method
const port = process.env.PORT || 5000;
//LISTEN METHOD
//Pass in the port value, and then pass in a callback function
app.listen(port, () => {
/*Back ticks allows you to declare a template string, which can
include variables implicitly within the dolar sign and curly brackets*/
console.log(`Server started on port ${port}`)
});<file_sep>//This is where we define our passport strategy
const LocalStrategy = require('passport-local')
.Strategy;
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
//LOAD USER MODEL
const User = mongoose.model('users');
//Now we export a function, with an instance of passport, that has our strategy in it
module.exports = function(passport){
passport.use(new LocalStrategy({usernameField: 'email',}, (email, password, done) => {
//Find user
User.findOne({email:email})
.then(user => {
//Check to see if the user exists
if(!user){
return done(null, false, {message: `No user ${email} found`});
};
//Match password using bcrypt
bcrypt.compare(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Incorrect password'});
}
})
})
}));
/*When a user logs in, that users information is only transmitted once, and if the login is successful
a session is established. The user information will be serialised and stored within a cookie in the users browser
that identifies that particular session.
So we need to define a serialise and deserialise function*/
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
};<file_sep># The Idea Book
Hello there! This is my Node/Express web application I made as part of the Udemy course I completed, which can be found here: https://www.udemy.com/nodejs-express-mongodb-dev-to-deployment
This crud application is powered by Node.js and a MongoDB database. The purpose of the application is to create an online depository for noting down ideas whilst on the go.
Hope you enjoy!<file_sep>if(process.env.NODE_ENV === 'production'){
module.exports = {mongoURL: 'mongodb://admin:<EMAIL>:11588/ideabook-prod'}
}else{
module.exports = {mongoURL: 'mongodb://localhost/ideabook-dev'}
}<file_sep>//THIS FILE CONTAINS ALL ROUTES RELATED TO THE CREATION AND MANAGEMENT OF USERS
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const passport = require('passport');
//LOAD USER MODEL
require('../models/Users');
const User = mongoose.model('users')
//USER LOGIN ROUTE
router.get('/login', (request, response) => {
response.render("users/login")
});
//USER REGISTER ROUTE
router.get('/register', (request, response) => {
response.render("users/register")
});
//LOGIN FORM POST
router.post('/login', (request, response, next) => {
//Here, we use the authenticate method of passport, and pass in the strategy. So here we will be using a local strategy,
//aposed to something like logging in with Google or Facebook etc
passport.authenticate('local', {
//Pass in an object as the second parameter
//Where to redirect too if successful
successRedirect: '/ideas',
failureRedirect: '/users/login',
failureFlash: true
})(request, response, next);
})
//REGISTER FORM POST
router.post('/register', (request, response) => {
let errors = [];
//Client side password validation
if(request.body.password != request.body.passwordConf){
errors.push({text: 'Passwords do not match'})
}
if(request.body.password.length < 8){
errors.push({text: "Password must be at least 8 characters in length"})
}
//If any errors, re-render the form with entered information, but also display any errors
if(errors.length > 0){
response.render('users/register', {
errors: errors,
name: request.body.name,
email: request.body.email
})
} else {
//Check if user already exists
User.findOne({email: request.body.email})
.then(user => {
if(user){
request.flash('error_msg', "Email already registered");
response.redirect('/users/register');
} else {
//If validation passed, create new object containing new user info
const newUser = new User({
name: request.body.name,
email: request.body.email,
password: <PASSWORD>
});
//Then using bcrypt, we use the genSalt function to generate a hash for our password
//We then make the newUser object password parameter equal to the hash
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = <PASSWORD>;
newUser.save()
.then(user => {
request.flash('success_msg', "You're now registered, and can login");
response.redirect('/users/login');
})
.catch(err => {
console.log(err);
return;
})
})
});
}
})
}
});
//LOGOUT USER
router.get('/logout', (request, response) => {
request.logout();
request.flash('success_msg', "You have been logged out");
response.redirect('/users/login');
});
module.exports = router; | 9aeba66e162c1cd70c5d2d0b96cafd2ec4b09fee | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | burtonrj/ideabook | 33a31e9dd25c128cd00c466c286e12835bd9c991 | fdea2e177d1bfd735cf3c5b9f12565e855bdf8ea |
refs/heads/master | <repo_name>maxkalik/Memorize<file_sep>/Memorize/Array+Identifiable.swift
import Foundation
extension Array where Element: Identifiable {
func firstIndex(matching: Element) -> Int? {
for index in 0..<self.count {
if self[index].id == matching.id {
return index
}
}
// return 0 it's because if the func won't find the mathced id it will return 0
/// and 0 means the first thing in the array
/// but the problem that the array can be an empty so we need to return an Optional Int
// return 0
return nil // Int? -> return nil because an array can be empty
}
}
<file_sep>/Memorize/ContentView.swift
import SwiftUI
// totaly dependant - view
struct EmojiMemoryGameView: View {
// Call ViewModel
var viewModel: EmojiMemoryGame
// Create variables (computed) here for using in ViewBuilder
var body: some View {
HStack {
// Vars cannot be created inside a ViewBuilder
ForEach(viewModel.cards) { card in
CardView(card: card).onTapGesture {
self.viewModel.choose(card: card)
}
}
}
.padding()
.foregroundColor(Color.orange)
// This func font modifies the view
/// The difference between declarative and imperative programming
/// In declarative we just declare this fanc to draw the this View
/// In imperative we are calling this function to set the font at a certain moment in time
/// In our case there is no moment in time with this declarative
/// So any time this should draw the View that reflects the Model
.font(
viewModel.cards.count < 5 ? Font.largeTitle : Font.body
)
}
}
struct CardView: View {
var card: MemoryGame<String>.Card
var body: some View {
ZStack {
if card.isFaceUp {
RoundedRectangle(cornerRadius: 10.0).fill(Color.white)
RoundedRectangle(cornerRadius: 10.0).stroke(lineWidth: 3)
Text(card.content)
} else {
RoundedRectangle(cornerRadius: 10.0).fill()
}
}.aspectRatio(3/4, contentMode: .fit)
}
}
// MARK: - Preview Provider
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
EmojiMemoryGameView(viewModel: EmojiMemoryGame())
}
}
<file_sep>/Memorize/Cardify.swift
import SwiftUI
// struct Cardify: ViewModifier {
struct Cardify: AnimatableModifier {
// struct Cardify: ViewModifier, Animatable {
var rotation: Double
var isFaceUp: Bool { rotation < 90 }
var animatableData: Double {
// trick - ranaming from rotation to animatableData
get { return rotation }
set { rotation = newValue}
}
init(isFaceUp: Bool) {
rotation = isFaceUp ? 0 : 180
}
func body(content: Content) -> some View {
ZStack {
// Vars cannot be created inside a ViewBuilder
/*
if isFaceUp {
RoundedRectangle(cornerRadius: cornerRadius).fill(Color.white)
RoundedRectangle(cornerRadius: cornerRadius).stroke(lineWidth: edgeLineWidth)
content
} else {
RoundedRectangle(cornerRadius: cornerRadius).fill()
// .aspectRatio(3/4, contentMode: .fit)
}
*/
Group {
RoundedRectangle(cornerRadius: cornerRadius).fill(Color.white)
RoundedRectangle(cornerRadius: cornerRadius).stroke(lineWidth: edgeLineWidth)
content
}
.opacity(isFaceUp ? 1 : 0)
RoundedRectangle(cornerRadius: cornerRadius).fill()
.opacity(isFaceUp ? 0 : 1)
}
// .rotation3DEffect(Angle.degrees(isFaceUp ? 0 : 180), axis: (0,1,0))
.rotation3DEffect(.degrees(rotation), axis: (0,1,0))
}
// MARK: - Drawing Constants
private let cornerRadius: CGFloat = 10.0
private let edgeLineWidth: CGFloat = 3
}
// MARK: - View Extenstion
extension View {
func cardify(isFaceUp: Bool) -> some View {
self.modifier(Cardify(isFaceUp: isFaceUp))
}
}
<file_sep>/Memorize/EmojiMemoryGame.swift
import SwiftUI
// ViewModel
// it's a portal between Views and Model
class EmojiMemoryGame: ObservableObject { // To make View be Reactive we have to apply this protocol
// Why class
/// It's easy to share
/// one of the most cool thing about class lives in the heap and it has pointers to it
/// All our views could have pointers to it
/// So since you will have many of view - they will look through this "portal" (class) into the model
// But it could be a problem
/// Lots of people are pointing to the same ViewModel. They can mess it up. It ruins the party for everybody.
/// for example we can have here a global var Model which will give an access to change something in the Whole Model
/// it will cause messing up because we can change something we have not to change
/// so in other words the model could be like opened door
/// just dont forget private in some vars :)
// private var model: MemoryGame<String> = MemoryGame<String>(numberOfPairsOfCards: 2) { _ in "😀" }
/// @Published is not a swift keyword, it's a property wrapper (property var model: ..)
/// @Published (property wrapper) adds a little functionality around a property
/// In our case - every time this property (model) chages it calls objectWillChage.send()
/// So in the future just add this wrapper to all properties which will chage
///
@Published private var model: MemoryGame<String> = EmojiMemoryGame.createMemoryGame()
// static func will make function on the type (not the instance)
private static func createMemoryGame() -> MemoryGame<String> {
let emojis = ["👻", "🎃", "🕷", "👺"]
let numberOfPairs = emojis.count
return MemoryGame<String>(numberOfPairsOfCards: numberOfPairs) { pairIndex in
return emojis[pairIndex]
}
}
// observable function (which will get from ObservableObject protocol)
// var objectWillChange: ObservableObjectPublisher // <- we don't need it here because you can use alreay without
// MARK: - Access to the Model
// Safe way to do not mess up the model
var cards: Array<MemoryGame<String>.Card> {
return model.cards
}
// MARK: - Intent(s)
func choose(card: MemoryGame<String>.Card) {
// objectWillChange.send() // it will publish to the world
/// but we don't need this also here because we can add @Published wrapper to property that will change
model.choose(card: card)
}
func resetGame() {
// it will redraw all the cards
model = EmojiMemoryGame.createMemoryGame()
}
}
<file_sep>/Memorize/MemoryGame.swift
import Foundation
// totaly independent - Model
// Equtable protocol uses required static func == (Self, Self) -> Bool
struct MemoryGame<CardContent> where CardContent: Equatable { // <- this struct uses generic type
private(set) var cards: Array<Card>
// Int? Optional it's because it might be the start of a game and there's no face-up Card, or thre's two face-up Cards
/// Btw itelegent doesn't show an error because the var get initialized to nil automatically
private var indexOfTheOneAndOnlyFaceUpCard: Int? {
/// A little concer that we have this state (indexOfTheOneAndOnlyFaceUpCard) that I'm having to keep in sync with another state (chages to the Cards) during the game
/// chages to the cards means isFaceUp = false for all of the cards
/// It's kinda error-prone way to programm when we have state in two places
/// and it's also determinable from the cards array
/// so let's use computed this var - so if someone set this var we turn all the other cards face-down
get {
/*
// here we need to look at all cards and see which one isFaceUp and see if there's only one
var faceUpCardIndices = [Int]()
for index in cards.indices {
if cards[index].isFaceUp {
faceUpCardIndices.append(index)
}
}
if faceUpCardIndices.count == 1 {
return faceUpCardIndices.first // .first (element in array) is also Optional - Swift communication
} else {
// return here nil it's because if there's no exactly one card in the face-up card list
// we can do this because this computed var is Int?
return nil
}
*/
// all code above we can write in one line of code
cards.indices.filter { cards[$0].isFaceUp }.only
}
set {
for index in cards.indices {
// newValue - specific var which appears inside this set only in set computed property
/// btw newValue in this case could be nil so Index is an Int, and Int is never equal to Optional that's not set
/// sow newValue == with Optional with assosiated integer matched - will be true
cards[index].isFaceUp = index == newValue
}
}
}
struct Card: Identifiable {
var isFaceUp: Bool = false {
didSet {
if isFaceUp {
startUsingBonusTime()
} else {
stopUsingBonusTime()
}
}
}
var isMatched: Bool = false {
didSet {
stopUsingBonusTime()
}
}
var content: CardContent // don't care type - type parameter
var id: Int // for identifiable
// MARK: - Bonus Time
// this could give matching bonus points
// if the user matches the card
// before a certain amount of time passes during which the card is face up
// can be zero which means "no bonus available" for this card
var bonusTimeLimit: TimeInterval = 6
// hom long this card has ever been face up
private var faceUpTime: TimeInterval {
if let lastFaceUpDate = self.lastFaceUpDate {
return pastFaceUpTime + Date().timeIntervalSince(lastFaceUpDate)
} else {
return pastFaceUpTime
}
}
// the last time this card was turned face up (and is still face up)
var lastFaceUpDate: Date?
// the accumulated time this card has been face up in the past
// (i.e. not including the current time it's been face up if it is currently so)
var pastFaceUpTime: TimeInterval = 0
// home much time left before the bonus opportunity runs out
var bonusTimeRemaining: TimeInterval {
max(0, bonusTimeLimit - faceUpTime)
}
// rercentage of the bonus tiem remaining
var bonusRemaining: Double {
(bonusTimeLimit > 0 && bonusTimeRemaining > 0) ? bonusTimeRemaining / bonusTimeLimit : 0
}
// whether the card was matched during the bonus time period
var hasEarnedBonus: Bool {
isMatched && bonusTimeRemaining > 0
}
// whether we are currently face up, unmatched and have not yet used up the bonus window
var isConsumingBonusTime: Bool {
isFaceUp && !isMatched && bonusTimeRemaining > 0
}
// called when the card transitions to face up state
private mutating func startUsingBonusTime() {
if isConsumingBonusTime, lastFaceUpDate == nil {
lastFaceUpDate = Date()
}
}
// called when the card goes back face down (or gets matched)
private mutating func stopUsingBonusTime() {
pastFaceUpTime = faceUpTime
self.lastFaceUpDate = nil
}
}
// Initializer is implicitly changing ourself. Of course this is mutating.
// We don't need to put it here because all inits are mutating
init(numberOfPairsOfCards: Int, cardContentFactory: (Int) -> CardContent) {
cards = Array<Card>() // creating empty array of cards
for pairIndex in 0..<numberOfPairsOfCards {
let content = cardContentFactory(pairIndex)
cards.append(Card(content: content, id: pairIndex * 2))
cards.append(Card(content: content, id: pairIndex * 2 + 1))
}
cards.shuffle()
}
// here we do not changing we just get an index, so we do not need to have mutating mark
/*
func index(of card: Card) -> Int {
for index in 0..<self.cards.count {
if self.cards[index].id == card.id {
return index
}
}
return 0 // TODO: bogus!
}
*/
// all functions which modifies self have to be mutable
// e.g. classes are always live in the heap and can be changed
mutating func choose(card: Card) {
// Here we will allow the View to be Reactive
/// It means when chages happen in the Model (here) they automatically are going to show up in the View
/// First what we can write is like
// card.isFaceUp = !card.isFaceUp
/// But we will get an error that card is let and we cannot change it
/// But the problem besides above is worse
/// First Card is a struct - value type - it is copied every time, so here in the parameter of the func the card is already copied..
/// So we will try to find out which card in the array cards will be updated
// let chosenIndex: Int = self.index(of: card)
if let chosenIndex: Int = cards.firstIndex(matching: card), !self.cards[chosenIndex].isFaceUp, !cards[chosenIndex].isMatched {
// , comma means like && but first will be resolved chosenIndex and after it you can use it for the next condition
if let potentialMatchIndex = indexOfTheOneAndOnlyFaceUpCard {
if cards[chosenIndex].content == cards[potentialMatchIndex].content {
// but we will get and exception: Binary operator '==' cannot be applied to two 'CardContent' operands
/// == in Swift is not built in to the language - it's operator which assosiated with a function - so it assosiates it with the type function ==
/// this func takes two arguments and returns a bool, but not every type can be in those arguments
/// but luckily that == func is in a protocol called Equatable, so we can use Constrains & Gains here to dsay where our CardContent implements Equatable
cards[chosenIndex].isMatched = true
cards[potentialMatchIndex].isMatched = true
}
self.cards[chosenIndex].isFaceUp = true
// indexOfTheOneAndOnlyFaceUpCard = nil // it's already calculated in this computed var
} else {
/*
// so we do not need it because we already set all the rest of face down in the computed variable
for index in cards.indices {
cards[index].isFaceUp = false
}
*/
indexOfTheOneAndOnlyFaceUpCard = chosenIndex
}
// self.cards[chosenIndex].isFaceUp = true // it moved above
// let chosenCard: Card = self.cards[chosenIndex] /// another problem is we try to assign to copy Card out of the Array
// chosenCard.isFaceUp = !chosenCard.isFaceUp
/// So we have to change directly (because we could get the copy)
// self.cards[chosenIndex].isFaceUp = !self.cards[chosenIndex].isFaceUp
print("card chosen: \(card)")
}
}
}
<file_sep>/Memorize/EmojiMemoryGameView.swift
import SwiftUI
// totaly dependant - view
struct EmojiMemoryGameView: View {
// Call ViewModel
/// @ObservedObject will redraw the View every time when objectWillChange.send() be called from the ViewModel
/// It will redraw particular element (in our case card) because SwiftUI have this ForEach method for it
@ObservedObject var viewModel: EmojiMemoryGame
// Create variables (computed) here for using in ViewBuilder
var body: some View {
VStack {
HStack {
Spacer()
Button(action: {
withAnimation(.easeInOut) {
self.viewModel.resetGame()
}
}) { Text("New Game") }
}.padding(.trailing, 20)
Divider()
// escaping closure here will be like called in the future
/// so Swift making function type into the reference type (like classes)
/// so it will stored in the memory where we can point in the particular time (some one tap in the future e.g.)
/// so Functions can live in the heap and we can point to them
/// and everything inside of this func will also will live in the heap
/// but in our case we have a problem with self., because function itself points to self inside here
/// so they are both can be in the heap - so we've got a situation where two thing in the heap are pointing to each other
/// and the way that Swift cleans up memory is when nobody points to something anymore
/// So we have got a Memory Cycle - two thing in the heap pointing to each other - it causes memory leak because memory cannot be cleaned up
///
Grid(viewModel.cards) { card in
CardView(card: card).onTapGesture {
/// but this self. does not live in the heap because this self is this struct - structs are value type - they don't live in the heap
/// and that is the fix that has been publicly approved
/// so mostly in SwiftUI self. in closure it's a value types - structs, enums
withAnimation(.default) {
self.viewModel.choose(card: card)
}
}
.padding(5)
}
.padding()
.foregroundColor(Color.orange)
// This func font modifies the view
/// The difference between declarative and imperative programming
/// In declarative we just declare this fanc to draw this View
/// In imperative we are calling this function to set the font at a certain moment in time
/// In our case there is no moment in time with this declarative
/// So any time this should draw the View that reflects the Model
// .font(viewModel.cards.count < 5 ? Font.largeTitle : Font.body)
}
}
}
// MARK: - Card View
struct CardView: View {
var card: MemoryGame<String>.Card
var body: some View {
GeometryReader { geometry in
self.body(for: geometry.size)
}
}
@State private var animatedBonusRemaing: Double = 0
private func startBonusTimeAnimation() {
animatedBonusRemaing = card.bonusRemaining
withAnimation(.linear(duration: card.bonusTimeRemaining)) {
animatedBonusRemaing = 0
}
}
// To avoid self in all constants, let's make a func
@ViewBuilder // list of views
private func body(for size: CGSize) -> some View {
if card.isFaceUp || !card.isMatched {
ZStack {
Group {
if card.isConsumingBonusTime {
// Circle().padding(10).opacity(0.2)
Pie(startAngle: .degrees(0-90), endAngle: .degrees(-animatedBonusRemaing * 360 - 90), clockWise: true)
.onAppear() {
// this closure tell when this view appear on the screen (all the time)
self.startBonusTimeAnimation()
}
} else {
Pie(startAngle: .degrees(0-90), endAngle: .degrees(-card.bonusRemaining * 360 - 90), clockWise: true)
}
}.padding(10).opacity(0.2) // padding and opacity will apply to both of views
Text(card.content)
.font(Font.system(size: fontSize(for: size)))
.scaleEffect(CGFloat(card.isMatched ? 1.4: 1))
}
.cardify(isFaceUp: card.isFaceUp)
//.modifier(Cardify(isFaceUp: card.isFaceUp))
.transition(AnyTransition.scale)
} // else will draw nothing - empty view. Don't need else here (works with @ViewBuilder)
}
private func fontSize(for size: CGSize) -> CGFloat {
min(size.width, size.height) * 0.5
}
}
// MARK: - Preview Provider
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let game = EmojiMemoryGame()
game.choose(card: game.cards[0])
return EmojiMemoryGameView(viewModel: game)
}
}
<file_sep>/Memorize/Grid.swift
import SwiftUI
struct Grid<Item, ItemView>: View where Item: Identifiable, ItemView: View {
typealias ViewForItem = (Item) -> ItemView
private var items: [Item]
private var viewForItem: ViewForItem
// escaping happened a lot more in object-oriented programming
init(_ items: [Item], viewForItem: @escaping ViewForItem) {
self.items = items
// escaping means this var is going to escape this initializer without getting called
// escaping here because it might be called later from the variable above
self.viewForItem = viewForItem
}
var body: some View {
GeometryReader { geometry in
self.body(for: GridLayout(itemCount: self.items.count, in: geometry.size))
}
}
private func body(for layout: GridLayout) -> some View {
// items - should be an array with identifiable things
/// but the problem items: [Item] they are don't care type (generic)
/// so here is where we get constrains and gains into the act - View where Item: Identifiable
ForEach(items) { item in
// self.viewForItem(item)
self.body(for: item, in: layout)
}
}
private func body(for item: Item, in layout: GridLayout) -> some View {
let index = items.firstIndex(matching: item)!
/*
// This case if we want return some View conditionaly
// Group is like a ZStack and his argument { a View Builder }
return Group {
if index != nil {
viewForItem(item)
.frame(width: layout.itemSize.width, height: layout.itemSize.height)
.position(layout.location(ofItemAt: index!))
}
// else - will return empty content
}
*/
// but we will use just index! because we are sure that array deffinetly will have items
// if not - then something really wrong in our code above
return viewForItem(item)
.frame(width: layout.itemSize.width, height: layout.itemSize.height)
.position(layout.location(ofItemAt: index))
}
}
| e7abfbaf11cc8a56f92eb71d2a50baeb2cb9c54c | [
"Swift"
] | 7 | Swift | maxkalik/Memorize | 1f6a9e533dc89e0e50469f1708f2e72afd2c0f25 | 2c57d4fbc472930a6ae1dd8f95ced639d475bdd8 |
refs/heads/main | <repo_name>gonxhunter/ingredients<file_sep>/Phucct/Catalog/Model/Product/Attribute/Source/Ingredients.php
<?php
/**
* Created by PhpStorm.
* User: chutienphuc
* Date: 06/08/2021
* Time: 17:31
*/
namespace Phucct\Catalog\Model\Product\Attribute\Source;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
use Magento\Catalog\Model\Config;
class Ingredients extends AbstractSource
{
const INGREDIENTS = 'ingredients';
/** @var Config */
protected $catalogConfig;
/**
* Ingredients constructor.
* @param Config $catalogConfig
*/
public function __construct(Config $catalogConfig)
{
$this->catalogConfig = $catalogConfig;
}
/**
* {@inheritdoc}
*/
public function getAllOptions()
{
$attribute = $this->catalogConfig->getAttribute(4, self::INGREDIENTS);
return $attribute->getSource()->getAllOptions();
}
}
<file_sep>/README.md
# ingredients
Copy source code to app/code/
Please run:
php bin/magento setup:upgrade
php bin/magento setup:di:compile<file_sep>/Phucct/Catalog/registration.php
<?php
/**
* Created by PhpStorm.
* User: chutienphuc
* Date: 08/08/2021
* Time: 16:42
*/
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Phucct_Catalog', __DIR__);
<file_sep>/Phucct/Catalog/Plugin/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Ingredients.php
<?php
/**
* Created by PhpStorm.
* User: chutienphuc
* Date: 08/08/2021
* Time: 17:57
*/
namespace Phucct\Catalog\Plugin\Magento\Catalog\Ui\DataProvider\Product\Form\Modifier;
class Ingredients
{
/**
* @param $subject
* @param $result
* @return mixed
*/
public function afterModifyMeta($subject, $result)
{
if (isset($result['product-details']['children']['container_ingredients'])) {
$result['product-details']['children']['container_ingredients']['children']['ingredients']['arguments']['data']['config']['visible'] = false;
}
return $result;
}
}
| 199c311b8be25167664a5dc3910528d2c53fc8d2 | [
"Markdown",
"PHP"
] | 4 | PHP | gonxhunter/ingredients | bb6baf42e40ca854d834524dd5e34af043fd965c | 169813c5e8c436d058523c09394ead872ce9952f |
refs/heads/master | <repo_name>TheStDrone/Project_5<file_sep>/Include/threads.h
#ifndef THREADS_H
#define THREADS_H
#include <cmsis_os2.h>
#include "LCD_driver.h"
#include <MKL25Z4.H>
#define THREAD_READ_TS_PERIOD_MS (50) // 1 tick/ms
#define THREAD_READ_ACCELEROMETER_PERIOD_MS (100) // 1 tick/ms
#define THREAD_SOUND_PERIOD_MS (100) // 1 tick/ms
#define THREAD_UPDATE_SCREEN_PERIOD_MS (50)
#define THREADS_ARE_SAME_PRIORITY (1)
#define MEASURE_REFILL_LATENCY (1)
#define USE_LCD_MUTEX (1)
// Defines and instructions for demonstration
/*
1. Baseline: System crashes in display of roll or pitch
2. Increase default stack size in RTX_Config.h to 512, then 768
3. Now display is OK, but no audio. Why don't audio threads run? Set breakpoint in
one - is never hit. Then look at thread information in debugger.
4. Work back to start - Check return value when creating threads
5. Reduce default stack sizes, but use larger custom stack size for Read Accelerometer
6. Should work now.
*/
#define DEMO_DEFAULT_READ_ACCEL_STK_SZ (1)
// Custom stack sizes for larger threads
#define READ_ACCEL_STK_SZ 768
void Init_Debug_Signals(void);
// Events for sound generation and control
#define EV_PLAYSOUND (1)
#define EV_SOUND_ON (2)
#define EV_SOUND_OFF (4)
#define EV_REFILL_SOUND_BUFFER (1)
void Create_OS_Objects(void);
extern osThreadId_t t_Read_TS, t_Read_Accelerometer, t_Sound_Manager, t_US, t_Refill_Sound_Buffer;
extern osMutexId_t LCD_mutex;
// Game Constants
#define PADDLE_WIDTH (40)
#define PADDLE_HEIGHT (15)
#define PADDLE_Y_POS (LCD_HEIGHT-4-PADDLE_HEIGHT)
#endif // THREADS_H
| 5d98b5fa9308d422507590b5961b517dff1cf7b6 | [
"C"
] | 1 | C | TheStDrone/Project_5 | 4df7e40a541fd0e6c518978fbc8a2ceff76e997d | 8221c676f7bfa587a9b93d2cff7939312001f081 |
refs/heads/master | <file_sep>library(data.table)
library(mousetrap)
library(mousetrack)
files <- list.files(path = "~/Praktikum ETH/data/", pattern = "mod_mod", full.names = TRUE)
dt <- rbindlist(lapply(files, fread, fill = TRUE))
# Delete duplicated columns
data[, pageX := NULL]
data[, pageY := NULL]
data[, screenX := NULL]
data[, screenY := NULL]
data
| a3c1edb9055b7acf0dcee25cad2dc8ad4fb87503 | [
"R"
] | 1 | R | FlorianSeitz/MouseTracking | 5959fe407746b44190e06f0953be135b85c9f7c8 | 2a86ad59ef9cc9eea9d49ca6f55c6b9445ba3236 |
refs/heads/master | <file_sep>from .facebook_bot import (get_page_ids,
get_events,
get_events_by_location,
get_page_info,
get_event_info)
<file_sep>from unittest import TestCase
import facebook_bot
SAMPLE_LAT = 40.763871
SAMPLE_LONG = -73.979904
DISTANCE = 200
SAMPLE_PAGE_ID = 164606950371187
class TestBot(TestCase):
def test_get_pages_id(self):
s = facebook_bot.get_page_ids(SAMPLE_LAT, SAMPLE_LONG, distance=100)
self.assertIsInstance(s, list)
self.assertTrue(s)
def test_get_events(self):
s = facebook_bot.get_events(SAMPLE_PAGE_ID, base_time='2017-05-07')
self.assertIsInstance(s, dict)
self.assertTrue(s)
def test_get_page_info(self):
s = facebook_bot.get_page_info(SAMPLE_PAGE_ID)
self.assertIsInstance(s, dict)
self.assertTrue(s)
def test_get_events_by_location(self):
s = facebook_bot.get_events_by_location(SAMPLE_LAT,
SAMPLE_LONG,
distance=70,
scan_radius=70)
self.assertIsInstance(s, list)
self.assertTrue(s)
<file_sep>[](http://forthebadge.com) [](http://forthebadge.com)
# Python Facebook Bot
*Make your life easier*
### What is this?
----------------
This is a Facebook Bot/Assistant, writen in Python 3 and using Facebook API for some
specific tasks.
At the moment, I only implement it some functions to crawl/get Facebook's events by
location, since Facebook shutdown that APIs.
### What do I need? (requirements.txt)
------------------
Right now, I'm only using [requests](https://github.com/kennethreitz/requests) for requesting APIs.
### Installation
---------------
To install **python-facebook-bot**, simply:
```
$ pip install python-facebook-bot
```
### How to use?
---------------
First, you need to create a Facebook App for Developer.
Then, run `export` command for CLIENT_ID and CLIENT_SECRET.
Example:
```
$ export CLIENT_ID="Your facebook app's ID"
$ export CLIENT_SECRET="Your facebook app's secret key"
```
Then you can `import facebook_bot` and use it's methods.
Example with IPython:
```python
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.0.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import facebook_bot
In [2]: facebook_bot.get_events(1572248819704068)
Out[2]:
{'1572248819704068': {'events': {'data': [{'attending_count': 35,
'category': 'FAMILY_EVENT',
'cover': {'id': '1667937513468531',
'source': 'https://scontent.xx.fbcdn.net/v/t31.0-0/p180x540/12898397_1667937513468531_267697016695005514_o.jpg?oh=1ea3755b790a6837febf9621a3b23f6f&oe=597E6E0D'},
'declined_count': 0,
'description': "2020 is just a few years away. Will you join the World for this epic New Years' celebration? I know that you will. I look forward to celebrating with you. \n\nThis is a virtual event and the whole planet is invited.",
'id': '447828138744610',
'maybe_count': 119,
'name': 'Happy New Year 2020',
'noreply_count': 43,
...........
In [3]:
```
### Where are the tests?
-----------------------
Just run `$ python setup.py test`
It's may take a while, because we need to scan all available pages.
*And here is your Cat*

| 768d6f9f2b74f793b51f22939ab3d0af7548c30b | [
"Markdown",
"Python"
] | 3 | Python | ChaitanyaCixLive/python-facebook-bot | c30c21c4e2e9f4a003f616793cc0a4761b5c3cbb | 58d3b5e6661646da7a9527256bf96db9d4d133ce |
refs/heads/master | <repo_name>MasonWindus/RateMyProfessor<file_sep>/app/src/main/java/com/thisismyapp/ratemyprofessor/SubmitListener.java
package com.thisismyapp.ratemyprofessor;
import android.view.View;
import android.widget.TextView;
public class SubmitListener implements View.OnClickListener {
private ProfessorPage profPage;
private Professor prof;
public SubmitListener(ProfessorPage pp, Professor p){
profPage = pp;
prof = p;
}
@Override
public void onClick(View v) {
TextView userBox = (TextView) profPage.findViewById(R.id.user_name_input);
TextView ratingBox = (TextView) profPage.findViewById(R.id.user_rating_input);
TextView commentBox = (TextView) profPage.findViewById(R.id.commentBar);
String user = userBox.getText().toString();
String rating = ratingBox.getText().toString();
String comment = commentBox.getText().toString();
userBox.setText("");
ratingBox.setText("");
commentBox.setText("");
prof.addComment(user, rating, prof.getProfClass(), comment);
profPage.addComment();
}
}
<file_sep>/app/src/main/java/com/thisismyapp/ratemyprofessor/Database.java
package com.thisismyapp.ratemyprofessor;
import android.text.Layout;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
public class Database {
public static ArrayList<Professor> database;
public Database(View v){
database = new ArrayList<Professor>();
String[] profClassArray = v.getResources().getStringArray(R.array. array_professor_class);
String[] profRatingArray = v.getResources().getStringArray(R.array. array_professor_rating);
String[] profNameArray = v.getResources().getStringArray(R.array. array_professor);
for (int i = 0; i < profClassArray.length; i++){
database.add(new Professor(profNameArray[i], profRatingArray[i], profClassArray[i]));
}
}
// public static ArrayList<Professor> getDatabase(){
// return database;
// }
}
| d4fa65dabe1f36adcd87365b3b85a44f31a502d6 | [
"Java"
] | 2 | Java | MasonWindus/RateMyProfessor | ae48829edfb7b5787f5a2601706b846a9680dfe7 | 41661f8d58c5da484b34ed83b54b629752e29f23 |
refs/heads/master | <repo_name>alekh-github/myTest<file_sep>/odd.h
#ifndef ODD_H_INCLUDED
#define ODD_H_INCLUDED
int odd(int n)
{
int x;
if(n%2==0)
{
x=0;
}
else
x=1;
return x;
}
#endif
<file_sep>/change.c
#include<stdio.h>
void main()
{
printf("change added");
}
<file_sep>/README.md
hello my first local edit
<file_sep>/mainmod.c
#include <stdio.h>
#include "odd.h"
#include "prime.h"
int main()
{
int n,a,b;
printf("enter the no.");
scanf("%d",&n);
a=odd(n);
if(a==1)
{
b=prime(n);
}
printf("the output is %d %d",a,b);
return 0;
}
<file_sep>/prime.h
#ifndef PRIME_H_INCLUDED
#define PRIME_H_INCLUDED
int prime(int n)
{
int i,x;
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
x=0;
}
else
x=1;
}
return x;
}
#endif
| 75a62e0e07a536601f9e4504c3039095f431ff57 | [
"Markdown",
"C"
] | 5 | C | alekh-github/myTest | 54fd81efd9c39e213ce3da8c86a40d6e48399760 | dddb6171cb16dad4241210025803765474f66185 |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Jul 25 18:13:58 2021
@author: lenovo
"""
import pandas as pd
df = pd.read_csv('balanced_reviews.csv')
df.isnull().any(axis = 0)
df.dropna(inplace = True)
df = df [df['overall'] != 3]
import numpy as np
df['Positivity'] = np.where(df['overall'] > 3 , 1 , 0)
from sklearn.model_selection import train_test_split
features_train, features_test, labels_train, labels_test = train_test_split(df['reviewText'], df['Positivity'], random_state = 42 )
from sklearn.feature_extraction.text import TfidfVectorizer
vect = TfidfVectorizer(min_df = 5).fit(features_train)
features_train_vectorized = vect.transform(features_train)
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(features_train_vectorized, labels_train)
predictions = model.predict(vect.transform(features_test))
from sklearn.metrics import confusion_matrix
confusion_matrix(labels_test, predictions)
from sklearn.metrics import roc_auc_score
roc_auc_score(labels_test, predictions)
import pickle
file = open("pickle_model.pkl","wb")
pickle.dump(model, file)
pickle.dump(vect.vocabulary_, open('features.pkl', 'wb')) | c0289181cdfde6b46d2c711b78cb4bc5fc311440 | [
"Python"
] | 1 | Python | kavyaparnami/Forsk-Coding-School | 368f19dab5ea5790d5560a95206ca05aa2890d60 | 3ed6ff0d31ec70636f94f42e2f2487278aa39a51 |
refs/heads/master | <repo_name>d7my11/lokalise<file_sep>/src/request.js
import request from 'request'
export const bundle = (apiToken, projectId) => new Promise((resolve, reject) => (
request
.post({
url: 'https://lokalise.co/api/project/export',
form: {
api_token: apiToken,
id: projectId,
type: 'json',
bundle_filename: '%PROJECT_NAME%-intl.zip',
bundle_structure: '%LANG_ISO%.%FORMAT%'
}
},
async (err, httpResponse, body) => {
if (err) {
return reject(err)
}
if (httpResponse.statusCode >= 400) {
return reject(Error(`HTTP Error ${httpResponse.statusCode}`))
}
const parsed = await JSON.parse(body)
if (parsed.response.status === 'error') {
return reject(Error(body))
}
resolve(parsed.bundle.file)
})
))
| 2c1b469b95572427d81b45848c8fb9ee6e488796 | [
"JavaScript"
] | 1 | JavaScript | d7my11/lokalise | 87b48f035b25cfc7178b018e20c0f6e66dce1e0d | 9cb4821e992b2ed34699bf1d3018c6c73781d964 |
refs/heads/master | <file_sep><!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en">
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>lalal</title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/modernizr-2.5.3-respond-1.1.0.min.js"></script>
</head>
<body>
<!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]-->
<div id="header-container">
<header class="wrapper clearfix">
<h1 id="title">h1#title</h1>
<nav>
<ul>
<!--TODO
- i18n
- Crear links
-->
<li>
<a href="#">Princiapl</a>
</li>
<li>
<a href="#">Tutorial</a>
</li>
<li>
<a href="#">Contacto</a>
</li>
</ul>
</nav>
</header>
</div>
<div id="main-container">
<div id="main" class="wrapper clearfix">
<article>
<!-- TODO i18n http://html5boilerplate.com/docs/internationalization/-->
<form method="post" action="">
<input type="date" name="dateQuery" id="dateQuery">
Provincia:
<select name="provincia">
<option value='0'></option>
<option value='1'>Barcelona</option>
<option value='2'>Madrid</option>
<option value='3'>Valencia</option>
</select>
<input type="submit" value="Buscar">
</form>
<?php
require_once 'resources/searchData.php';
?>
</article>
<article>
<h3>Cargar video</h3>
<form method="post" action="">
<label for="url">URL: <span class="required">*</span></label>
<input type="url" name="url" id="url" required="required">
<!-- TODO ciutat ha de ser un desplegable -->
<!-- TODO Responsive css width -->
Provincia:
<select name="provincia">
<option value='0'></option>
<option value='1'>Barcelona</option>
<option value='2'>Madrid</option>
<option value='3'>Valencia</option>
</select>
Fecha:
<input type="date" name="date" id="date" required="required">
E-mail:
<input type="email" name="email" id="email">
<input type="submit" value="Enviar" id="submit-button">
<p id="req-field-desc">
<span class="required">*</span> campo requerido
</p>
<?php
require_once 'resources/loadData.php';
?>
</form>
</div>
<!-- #main -->
</div>
<!-- #main-container -->
<div id="footer-container">
<footer class="wrapper">
<h3>footer</h3>
</footer>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js"><\/script>')
</script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="fancybox/source/jquery.fancybox.css?v=2.0.6" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/jquery.fancybox.pack.js?v=2.0.6"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.fancybox-media').fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false
});
});
</script>
<script src="js/script.js"></script>
<script>
var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']]; ( function(d, t) {
var g = d.createElement(t), s = d.getElementsByTagName(t)[0];
g.src = ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js';
s.parentNode.insertBefore(g, s)
}(document, 'script'));
</script>
</body>
</html>
<file_sep><?php
$uri = 'localhost';
$database = 'DATABASE_NAME';
$user = 'DATABASE_USER';
$password = '<PASSWORD>';
$videosTable = 'videos';
$videoUrl = 'url';
$videoDate = 'videoDate';
$videoCity = 'province';
$videoEmail = 'email';
$videosSelectQuery = "select * from ".$videosTable." " ;
$videosInsertQuery = "insert into ".$videosTable." (".$videoUrl.", ".$videoDate.", ".$videoCity.", ".$videoEmail.") values ";
$maxCols = 5;
$maxRows = 5;
?><file_sep><?php
require_once 'config.php';
if (isset($_POST) && isset($_POST['dateQuery']))
{
$con = mysql_connect($uri,$user,$password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
$date = $_POST['dateQuery'];
// $province = $_POST['province'];
$sql = ($date == '') ? $videosSelectQuery : $videosSelectQuery. "where " . $videoDate . " = '".$date."'";
//TODO cambiar nombre de var de city!
// $sql = ($province == '') ? $sql . " and ".$videoCity" = " . $province;
$resultSet = mysql_query($sql);
if (!$resultSet)
{
die('Consulta no válida: ' . mysql_error());
}
// $num = mysql_num_rows ( $resultSet );
// echo "<table class='alerts'><td>";
//
// while($row = mysql_fetch_assoc($resultSet))
// {
// $youtubeUrl = "http://www.youtube.com/v/".$row['url']."?fs=1&autoplay=1";
// $youtubeThumbnail = "http://img.youtube.com/vi/".$row['url']."/1.jpg";
// echo "<tr>";
// echo "<a title='Título' href=".$youtubeUrl."><img src=".$youtubeThumbnail."></a>";
// echo "</tr>";
// }
// echo "</td></table>";
$num = mysql_num_rows ( $resultSet );
echo "<ul class='polaroids'>";
while($row = mysql_fetch_assoc($resultSet))
{
$youtubeUrl = "http://www.youtube.com/v/".$row['url']."?fs=1&autoplay=1";
$youtubeThumbnail = "http://img.youtube.com/vi/".$row['url']."/1.jpg";
echo "<li>";
echo "<a class='video' title='Título' href=".$youtubeUrl."><img class='fancybox-media' src=".$youtubeThumbnail."></a>";
echo "</li>";
}
echo "</ul>";
// Es necessari aixo?
mysql_free_result($resultSet);
mysql_close($con);
}
?><file_sep><?php
require_once 'config.php';
//TODO Obrir i tancar la connexio cada cop?
//TODO es necessari la primera condicio?
$con = mysql_connect($uri,$user,$password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
$resultSet = mysql_query($lastVideosSelectQuery);
if (!$resultSet)
{
die('Consulta no válida: ' . mysql_error());
}
$num = mysql_num_rows ( $resultSet );
echo "<table border='1'><tr>";
echo "<tr>";
while($row = mysql_fetch_assoc($resultSet))
{
echo "<iframe type='text/html' width='120' height='100' src='http://www.youtube.com/embed/cI-vg2QAtQM' frameborder='1'></iframe>";
}
echo "</tr>\n";
echo "</table>";
// Es necessari aixo?
mysql_free_result($resultSet);
mysql_close($con);
?><file_sep><?php
if (isset($_POST) && isset($_POST['url']))
{
require_once 'config.php';
/*
* Obtenim el ID de youtube
*/
preg_match(
'/[\\?\\&]v=([^\\?\\&]+)/',
$_POST['url'],
$matches
);
$url = $matches[1];
$date = $_POST['date'];
$city = $_POST['provincia'];
$email = $_POST['email'];
$con = mysql_connect($uri,$user,$password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
$sql = $videosInsertQuery . '("'.$url.'", "'.$date.'", "'.$city.'", "'.$email.'")';
if (!mysql_query($sql,$con))
{
$duplicate = (mysql_errno() == 1062) ? 'Duplicate!' : mysql_error();
echo $duplicate;
}
mysql_close($con);
}
?> | 7e7a2127acb342632fea95b5ca7ceaa4bff79da1 | [
"PHP"
] | 5 | PHP | ilopezluna/MyYoutube | e912c0316f1945de122a02f6d1f7ac0958021eab | 7f4fc1601ef5165ecb3e4dd97a4172e2287183b6 |
refs/heads/master | <file_sep><?php
//These are all functions used on the settings page.
/*
A function which validates the data from the personal information form. The parameters are the new first name, last name, email, comapany and the current user object.
1. Create an empty array of errors.
2. Perform a presence check on the email.
3. Check that the email is valid.
4. Check that the email isn't already in use.
5. Check the length of the first name.
6. Check the length of the last name.
7. Check the length of the company.
8. If there is no errors then update the personal information.
9. Return the errors.
*/
function validate_personal($first_name, $last_name, $email, $company, $User){
$errors = []; //1
if($email == ""){ //2
$errors[] = "Email is required.";
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){ //3
$errors[] = "Email is not valid.";
}
if(!User::check_email($email) && $User->get_email() != $email){ //4
$errors[] = "That email is already being used.";
}
if(strlen($first_name) > 29){ //5
$errors[] = "First name must be less than 30 characters.";
}
if(strlen($last_name) > 29){ //6
$errors[] = "Last name must be less than 30 characters.";
}
if(strlen($company) > 29){ //7
$errors[] = "Company must be less than 30 characters.";
}
if(count($errors) == 0){ //8
$User->update_personal($first_name, $last_name, $email, $company);
}
return $errors; //9
}
/*
A function which validates the data sent from the update password form. The parameters are the current password, new password, the retyped new password and the current user.
1. Create an empty errors array.
2. Check that the password is greater than 6 characters.
3. Check that the password is less than 30 characters.
4. Check that the new password and the retype password match.
5. Check the current password is correct.
6. Make sure the new password is not the same as the current.
7. If there is no errors encrypt the new password and update the password.
8. Return the errors.
*/
function validate_password($current, $new, $retype, $user){
$errors = []; //1
if(strlen($new) < 6){ //2
$errors[] = "New password must be more than 6 characters.";
}
if(strlen($new) > 29){ //3
$errors[] = "New password must be less than 30 characters.";
}
if($new != $retype){ //4
$errors[] = "New password does not match the retyped password.";
}
if(!hash_equals($user->get_password(), crypt($current, $user->get_password()))){ //5
$errors[] = "Current password is incorrect.";
}
else if($current == $new){ //6
$errors[] = "New password must not be the current password.";
}
if(count($errors) == 0){ //7
$hash_pass = crypt($new, <PASSWORD>");
$user->update_password($hash_pass);
}
return $errors; //8
}
/*
A function that validates the data sent from the extra information form when adding a new record. The parameters are the name, value, a private flag and the current user.
1. Create an empty errors array.
2. Check that the name has been entered.
3. Check that the value has been entered.
4. Check that the name isn't already being used.
5. If there is no errors add the new record.
6. Return the errors.
*/
function validate_extra_information($name, $value, $private, $user){
$errors = []; //1
if($name == ""){ //2
$errors[] = "Name is required.";
}
if($value == ""){ //3
$errors[] = "Value is required.";
}
if(!$user->extra_info_key_free($name)){ //4
$errors[] = "That name is already in use.";
}
if(count($errors) == 0){ //5
$private = ($private)?"Y":"N";
$user->add_extra_info($name, $value, $private);
}
return $errors; //6
}
/*
A function that validates the data sent from the extra information form when editing a record. The parameters are the name, value, a private flag and the current user.
1. Create an empty errors array.
2. Check that the name has been entered.
3. Check that the value has been entered.
4. If there is no errors edit the record.
5. Return the errors.
*/
function validate_edit_extra_information($name, $value, $private, $user){
$errors = []; //1
if($name == ""){ //2
$errors[] = "Name is required.";
}
if($value == ""){ //3
$errors[] = "Value is required.";
}
if(count($errors) == 0){ //4
$private = ($private)?"Y":"N";
$user->edit_extra_info($name, $value, $private);
}
return $errors; //5
}
/*
A function which returns a table of the extra information. The parameter is the current user.
1. Get all the fields from the user.
2. If there is no data then print a warning.
3. If there is data.
4. Loop over each record and create the html.
*/
function load_extra_information($user){
$extra_information = $user->get_user_defined_fields(); //1
if(count($extra_information) == 0){ //2
echo '<tr class="warning no-data-warning"><td colspan="3"><span class="glyphicon glyphicon-warning-sign"></span> No data to display</td></tr>';
}
else{ //3
foreach ($extra_information as $row) { //4
echo "<tr>";
if($row["Private"] == 'Y'){
printf('<td>%s <span class="label label-default">Private</span></td>', $row["FieldName"]);
}
else{
printf('<td>%s</td>', $row["FieldName"]);
}
printf('<td>%s</td>', $row["FieldValue"]);
echo '<td class="options"><a href="#" class="EditExtra" data-name="'.$row['FieldName'].'" data-value="'.$row["FieldValue"].'">Edit</a> <a href="php/settings_delete_extra_info.php?Name='.$row['FieldName'].'" class="DeleteExtra">Delete</a></td>';
echo "</tr>";
}
}
}
/*
A function which validates the data from the shift preset form when adding a new record. The parameters are the key, name, start time, end time and the current user.
1. Create an empty errors array.
2. Check the key has been entered.
3. Check the length of the key is less than 6 characters.
4. Check the name has been entered.
5. Check that the start time is valid.
6. Check that the end time is valid.
7. If there is no errors then create the shift preset.
8. Return the errors.
*/
function validate_shift_presets($key, $name, $start, $end, $user){
$errors = []; //1
if($key == ""){ //2
$errors[] = "Key is required.";
}
if(strlen($key) > 5){ //3
$errors[] = "Key must be less than 6 characters.";
}
if($name == ""){ //4
$errors[] = "Name is required.";
}
if(!strtotime($start)){ //5
$errors[] = "Start time is not valid.";
}
if(!strtotime($end)){ //6
$errors[] = "End time is not valid.";
}
if(count($errors) == 0){ //7
ShiftPreset::create_shift_preset($key, $name, $start, $end, $user);
}
return $errors; //8
}
/*
A function which validates the data from the shift preset form when editing a record. The parameters are the key, name, start time, end time and the current user.
1. Create an empty errors array.
2. Check the key has been entered.
3. Check the length of the key is less than 6 characters.
4. Check the name has been entered.
5. Check that the start time is valid.
6. Check that the end time is valid.
7. If there is no errors then edit the shift preset.
8. Return the errors.
*/
function validate_edit_shift_presets($shift_preset, $key, $name, $start, $end, $user){
$errors = []; //1
if($key == ""){ //2
$errors[] = "Key is required.";
}
if(strlen($key) > 5){ //3
$errors[] = "Key must be less than 6 characters.";
}
if($name == ""){ //4
$errors[] = "Name is required.";
}
if(!strtotime($start)){ //5
$errors[] = "Start time is not valid.";
}
if(!strtotime($end)){ //6
$errors[] = "End time is not valid.";
}
if(count($errors) == 0){ //7
$shift_preset->edit($key, $name, $start, $end);
}
return $errors; //8
}
/*
A function which loads the html table for the shift presets. The parameter is the current user.
1. Load all the shift presets for the user.
2. If there is no data then display a warning.
3. If there is data.
4. Loop over each record and print the html.
*/
function load_shift_presets($user){
$job_presets = ShiftPreset::load_all($user); //1
if(count($job_presets) == 0){ //2
echo '<tr class="warning no-data-warning"><td colspan="5"><span class="glyphicon glyphicon-warning-sign"></span> No data to display</td></tr>';
}
else{ //3
foreach ($job_presets as $row) { //4
echo "<tr>";
printf('<td>%s</td>', $row->get_key());
printf('<td>%s</td>', $row->get_name());
printf('<td>%s</td>', $row->get_start());
printf('<td>%s</td>', $row->get_end());
echo '<td class="options"><a href="#" class="EditShiftPresets" data-id="'.$row->get_preset_id().'" data-key="'.$row->get_key().'" data-name="'.$row->get_name().'" data-start="'.$row->get_start().'" data-end="'.$row->get_end().'">Edit</a> <a href="php/settings_delete_shift_preset.php?ID='.$row->get_preset_id().'" class="DeleteShiftPresets">Delete</a></td>';
echo "</tr>";
}
}
}
/*
A function which validates the the data sent from the job preset form when adding a preset. The parameters are the name, description and user ID.
1. Create an empty errors array.
2. Check to see if the name has been entered.
3. Check to see if the description has been entered.
4. If there is no errors then create the job preset.
5. Return the errors.
*/
function validate_job_preset($name, $desc, $user_id){
$errors = []; //1
if($name == ""){ //2
$errors[] = "Name is required.";
}
if($desc == ""){ //3
$errors[] = "Description is required.";
}
if(count($errors) == 0){ //4
JobPreset::create_job_preset($name, $desc, $user_id);
}
return $errors; //5
}
/*
A function which validates the the data sent from the job preset form when editing a preset. The parameters are the job preset, name, description and user ID.
1. Create an empty errors array.
2. Check to see if the name has been entered.
3. Check to see if the description has been entered.
4. If there is no errors then edit the job preset.
5. Return the errors.
*/
function validate_edit_job_preset($job_preset, $name, $desc, $user_id){
$errors = []; //1
if($name == ""){ //2
$errors[] = "Name is required.";
}
if($desc == ""){ //3
$errors[] = "Description is required.";
}
if(count($errors) == 0){ //4
$job_preset->edit($name, $desc, $user_id);
}
return $errors; //5
}
/*
A function that loads the html table for the job presets. The parameter is the current user.
1. Load all the job preset.
2. If there is no presets display a warning.
3. If there is data.
4. Loop over each record and print the table.
*/
function load_job_presets($user){
$job_presets = JobPreset::load_all($user); //1
if(count($job_presets) == 0){ //2
echo '<tr class="warning no-data-warning"><td colspan="5"><span class="glyphicon glyphicon-warning-sign"></span> No data to display</td></tr>';
}
else{ //3
foreach ($job_presets as $row) { //4
echo "<tr>";
printf('<td>%s</td>', $row->get_name());
printf('<td>%s</td>', $row->get_desc());
echo '<td class="options"><a href="#" class="EditJobPresets" data-id="'.$row->get_preset_id().'" data-name="'.$row->get_name().'" data-desc="'.$row->get_desc().'">Edit</a> <a href="php/settings_delete_job_preset.php?ID='.$row->get_preset_id().'" class="DeleteJobPresets">Delete</a></td>';
echo "</tr>";
}
}
}
/*
A function to validate the data sent from the extra shift info form. The parameters are the name and the current user id.
1. Create an empty errors array.
2. Check the name has been entered.
3. If there is no errors create the new record.
4. Return the errors.
*/
function validate_extra_shift_info($name, $user_id){
$errors = []; //1
if($name == ""){ //2
$errors[] = "Name is required.";
}
if(count($errors) == 0){ //3
ShiftDefinedField::create_shift_defined_field($name, $user_id);
}
return $errors; //4
}
/*
A function to load the extra shift info into a table. The parameter is the current user.
1. Load all the fields.
2. If no data display a warning.
3. If there is data.
4. Loop over each record and print the table.
*/
function load_extra_shift_info($user){
$fields = ShiftDefinedField::load_all($user); //1
if(count($fields) == 0){ //2
echo '<tr class="warning no-data-warning"><td colspan="5"><span class="glyphicon glyphicon-warning-sign"></span> No data to display</td></tr>';
}
else{ //3
foreach ($fields as $row) { //4
echo "<tr>";
printf('<td>%s</td>', $row->get_name());
echo '<td class="options"><a href="#" class="EditExtraShiftInfo" data-id="'.$row->get_field_id().'" data-name="'.$row->get_name().'">Edit</a> <a href="php/settings_delete_extra_shift_info.php?ID='.$row->get_field_id().'" class="DeleteExtraShiftInfo">Delete</a></td>';
echo "</tr>";
}
}
}
/*
A function to validate the data sent from the extra shift info form when editing a record. The parameters are the field, name and the current user id.
1. Create an empty errors array.
2. Check the name has been entered.
3. If there is no errors edit the record.
4. Return the errors.
*/
function validate_edit_extra_shift_info($field, $name, $user){
$errors = []; //1
if($name == ""){ //2
$errors[] = "Name is required.";
}
if(count($errors) == 0){ //3
$field->edit($name);
}
return $errors; //4
}
?><file_sep>$(function(){
//Add the click listener to the objects with the class 'button'.
$(".button").on('click', function(){
//Get the link which was clicked.
var link = $(this);
//Get the user ID.
var id = link.data("id");
//Get the function of the link.
var func = link.data("function");
//If the function is "ADD".
if(func == "ADD"){
//Post the ID to the search_add_coworker.php file.
$.post("php/search_add_coworker.php", {ID: id}, function(data){
//Add 'okbutton' class to the link.
link.addClass("okbutton");
//Find the span inside the link.
var span = link.find("span");
//Remove the plus icon and add the ok icon.
span.removeClass("glyphicon-plus-sign");
span.addClass("glyphicon-ok-sign");
//Change the function to "DEL".
link.data("function", "DEL");
});
}
//If the function is "DEL"
else if(func == "DEL"){
//Post the ID to the search_del_coworker.php file.
$.post("php/search_del_coworker.php", {ID: id}, function(data){
//Remove the 'okbutton' class.
link.removeClass("okbutton");
//Find the span inside the link.
var span = link.find("span");
//Remove the ok icon and the remove icon and add the plus icon.
span.removeClass("glyphicon-ok-sign");
span.removeClass("glyphicon-remove-sign");
span.addClass("glyphicon-plus-sign");
//Change the function to "ADD".
link.data("function", "ADD");
});
}
//Return false to stop the browser following the link.
return false;
});
//Add the mouseover event to the buttons.
$(".button").on('mouseover', function(){
//Get the link.
var link = $(this);
//Get the function.
var func = link.data("function");
//If the function is "DEL"
if(func == "DEL"){
//Add the delete class.
link.addClass("delete");
//Find the span inside the link.
var span = link.find("span");
//Add the remove icon and remove the ok icon.
span.addClass("glyphicon-remove-sign");
span.removeClass("glyphicon-ok-sign");
}
});
//Add the mouseout event to the buttons.
$(".button").on('mouseout', function(){
//Get the link.
var link = $(this);
//Get the function.
var func = link.data("function");
//If the function is "DEL".
if(func == "DEL"){
//Remove the delete class.
link.removeClass("delete");
//Find the span inside the link.
var span = link.find("span");
//Remove the remove icon and add the ok icon.
span.removeClass("glyphicon-remove-sign");
span.addClass("glyphicon-ok-sign");
}
});
});<file_sep><?php
//Start the session
session_start();
if(!isset($_SESSION['UserID'])){
header("Location: ./");
}
//Include all the files required.
require_once("model/user.php");
require_once("model/shift_preset.php");
require_once("model/job_preset.php");
require_once("model/shift_defined_field.php");
require_once("php/debug_log.php");
require_once("php/settings_functions.php");
//Create a new user variable.
$User = new User();
//Empty error array for storing errors.
$errors = [];
//If the Form variable is posted then a form on the page has been submitted.
if(isset($_POST['Form'])){
$form = $_POST['Form']; //Get the Form variable posted to find which form was posted.
//If the form is the Personal information form
if($form == "Personal"){
//Get the variables posted.
$first_name = trim($_POST['FName']);
$last_name = trim($_POST['LName']);
$email = trim($_POST['Email']);
$company = trim($_POST['Company']);
//Call the validate_personal function and store the errors returned.
$errors = validate_personal($first_name, $last_name, $email, $company, $User);
//If there are no errors
if(count($errors) == 0){
//Redirect the user.
header("Location: Settings?".$form);
}
}
//If the form is the Password form
if($form == "Password"){
//Get the variables posted.
$current = trim($_POST['Current']);
$new = trim($_POST['New']);
$retype = trim($_POST['NewRetype']);
//Call the validate_password function and store the errors returned.
$errors = validate_password($current, $new, $retype, $User);
//If there are no errors
if(count($errors) == 0){
//Redirect the user
header("Location: Settings?".$form);
}
}
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/job_preset.php");
//If there is post variables
if(count($_POST) > 0){
//Get the post variables
$name = trim($_POST['Name']);
$desc = trim($_POST['Desc']);
//Create a new user
$user = new User();
//Call the validate_job_preset function
$errors = validate_job_preset($name, $desc, $user->get_id());
//Return the errors in json format
echo json_encode($errors);
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
//If data has been posted
if(count($_POST) > 0){
//Get the posted variables
$first_name = trim($_POST['FName']);
$last_name = trim($_POST['LName']);
$email = trim($_POST['Email']);
$company = trim($_POST['Company']);
//Create a new user object
$User = new User();
//Call the validate_personal function
$errors = validate_personal($first_name, $last_name, $email, $company, $User);
//Print the errors in json format
echo json_encode($errors);
}
?><file_sep><?php
//Include the required files.
require_once('database.php');
//A class to store data about a shift defined value.
class ShiftDefinedValue{
//Private variables.
private $DefinedValueID; // The defined value ID.
private $DefinedFieldID; // The defined field ID.
private $ShiftID; // The shift ID this belongs to.
private $Value; // Its value.
/*
A public contructor which sets the private variables to those passed as parameters.
1. Set the variables.
*/
function __construct($defined_value_id, $defined_field_id, $shift_id, $value){
$this->DefinedValueID = $defined_value_id; //1
$this->DefinedFieldID = $defined_field_id;
$this->ShiftID = $shift_id;
$this->Value = $value;
}
/*
A public static function to create a new shift defined value. The parameters are the field ID, the value and the shift ID.
1. Create a new database connection.
2. Prepare a statement to call the ADD_SHIFT_DEFINED_VALUE stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public static function create_new($field_id, $value, $shift_id){
$conn = db_connect(); //1
$stmt = $conn->prepare('CALL ADD_SHIFT_DEFINED_VALUE(:fid, :sid, :val)'); //2
$stmt->bindParam(':fid', $field_id); //3
$stmt->bindParam(':sid', $shift_id);
$stmt->bindParam(':val', $value);
$stmt->execute(); //4
}
/*
A public static function to edit a shift defined value. The parameters are the field ID, the value and the shift ID.
1. Create a new connection.
2. Prepare a new statement to call the EDIT_SHIFT_DEFINED_VALUE stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public static function edit($field_id, $value, $shift_id){
$conn = db_connect(); //1
$stmt = $conn->prepare('CALL EDIT_SHIFT_DEFINED_VALUE(:fid, :sid, :val)'); //2
$stmt->bindParam(':fid', $field_id); //3
$stmt->bindParam(':sid', $shift_id);
$stmt->bindParam(':val', $value);
$stmt->execute(); //4
}
//Getter functions which return private variables.
public function get_defined_value_id(){
return $this->DefinedValueID;
}
public function get_defined_field_id(){
return $this->DefinedFieldID;
}
public function get_shift_id(){
return $this->ShiftID;
}
public function get_value(){
return $this->Value;
}
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
//If there is posted variables
if(count($_POST) > 0){
//Get the variables
$name = trim($_POST['Name']);
$value = trim($_POST['Value']);
$private = filter_var($_POST['Private'], FILTER_VALIDATE_BOOLEAN);
//Create a new user
$User = new User();
//Call the validate_edit_extra_information function
$errors = validate_edit_extra_information($name, $value, $private, $User);
//Return the errors
echo json_encode($errors);
}
?><file_sep><?php $page = strtolower($_SERVER['SCRIPT_NAME']); ?>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Shift Planner</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav">
<span class="sr-only">Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="main-nav">
<ul class="nav navbar-nav navbar-right">
<li <?php if(strpos($page, 'summary')) echo'class="active"'; ?>><a href="Summary">Summary</a></li>
<li <?php if(strpos($page, 'calendar')) echo'class="active"'; ?>><a href="Calendar">Calendar</a></li>
<li <?php if(strpos($page, 'search')) echo'class="active"'; ?>><a href="Search">Search</a></li>
<li <?php if(strpos($page, 'coworkers')) echo'class="active"'; ?>><a href="Coworkers">Coworkers</a></li>
<li <?php if(strpos($page, 'settings')) echo'class="active"'; ?>><a href="Settings">Settings</a></li>
<li><a href="php/logout.php">Logout</a></li>
</ul>
</div>
</div>
</nav><file_sep><?php
//Start the session
session_start();
//If the user is not logged in redirect them to the homepage.
if(!isset($_SESSION['UserID'])){
header("Location: ./");
}
//Include the required files.
require_once("model/user.php");
require_once("model/coworker.php");
//Create a new user object.
$user = new User();
//Find all the coworker requests.
$requests = Coworker::find_requests($user->get_id());
//Get all accepted coworkers.
$coworkers = Coworker::get_coworkers($user->get_id());
//If the del variable is set.
if(isset($_GET['del'])){
//Get the ID to delete.
$id = $_GET['del'];
//Delete the coworker.
Coworker::delete($id, $user->get_id());
//Redirect to the coworkers page.
header("Location: Coworkers");
}
//If the add variable is set.
if(isset($_GET['add'])){
//Get the ID to accept.
$id = $_GET['add'];
//Add the coworker.
Coworker::add($id, $user->get_id());
//Redirect to the coworkers page.
header("Location: Coworkers");
}
?><file_sep><?php
//Include the database functions
require_once("database.php");
//A class which stores data about a user and has functions for creating and updating users etc.
class Coworker{
//Private variables
private $UserID; //The user ID stored in the session used to interact with the database.
private $UserFirstName; // The user's first name from the database.
private $UserLastName; // The user's last name from the database.
private $UserCompany; // The user's company from the database.
private $UserEmail; // The user's email from the database.
private $UserDefinedFields; // The user's defined fields from the database.
/*
A public constructor which takes the user id, first name, last name, company and email.
1. Set the private variables.
2. Load the user defined fields.
*/
function __construct($user_id, $user_first, $user_last, $user_company, $user_email){
$this->UserID = $user_id;//1
$this->UserFirstName = $user_first;
$this->UserLastName = $user_last;
$this->UserCompany = $user_company;
$this->UserEmail = $user_email;
$this->load_user_defined_fields(); //2
}
/*
A public static function to search for users.
1. Create a new database connection.
2. Prepare a new statement to call the SEARCH_USERS stored procedure.
3. Bind the parameter.
4. Set the fetch mode to FETCH_ASSOC.
5. Execute the statement.
6. Create an empty array for the output.
7. Loop over each record and add a new coworker to the array.
8. Return the array.
*/
public static function search($search){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL SEARCH_USERS(:search)"); //2
$stmt->bindParam(":search", $search); //3
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$output = []; //6
foreach($stmt->fetchAll() as $row){ //7
$output[] = new Coworker($row['UserID'], $row['UserFirstName'], $row['UserSurname'], $row['UserCompany'], $row['UserEmail']);
}
return $output; //8
}
/*
A public static function to delete a coworker record. The parameters are the 2 user IDs.
1. Create a new database connection.
2. Prepare a stored procedure to call the DELETE_COWORKER_REQUEST stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public static function delete($id1, $id2){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL DELETE_COWORKER_REQUEST(:id1, :id2)"); //2
$stmt->bindParam(":id1", $id1); //3
$stmt->bindParam(":id2", $id2);
$stmt->execute(); //4
}
/*
A public static function to accept a coworker. The parameters are the 2 user IDs.
1. Create a new database connection.
2. Prepare a stored procedure to call the ADD_COWORKER stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public static function add($id1, $id2){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL ADD_COWORKER(:id1, :id2)"); //2
$stmt->bindParam(":id1", $id1); //3
$stmt->bindParam(":id2", $id2);
$stmt->execute(); //4
}
/*
A public static function to create a coworker request. The parameters are the 2 user IDs.
1. Create a new database connection.
2. Prepare a stored procedure to call the CREATE_COWORKER_REQUEST stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public static function create_request($user1, $user2){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL CREATE_COWORKER_REQUEST(:id1, :id2)"); //2
$stmt->bindParam(":id1", $user1); //3
$stmt->bindParam(":id2", $user2);
$stmt->execute(); //4
}
/*
A public static function to find all requests for a user. The parameter is the user ID.
1. Create a new database connection.
2. Prepare a stored procedure to call the FIND_REQUESTS stored procedure.
3. Bind the parameters.
4. Set the fetch mode to FETCH_ASSOC.
5. Execute the statement.
6. Create an empty array for the output.
7. For each record add a new coworker to the output.
8. Return the output.
*/
public static function find_requests($id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL FIND_REQUESTS(:id)"); //2
$stmt->bindParam(":id", $id); //3
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$output = []; //6
foreach($stmt->fetchAll() as $row){ //7
$output[] = new Coworker($row['UserID'], $row['UserFirstName'], $row['UserSurname'], $row['UserCompany'], $row['UserEmail']);
}
return $output; //8
}
/*
A public static function to find all accepted coworkers for a user. The parameter is the user ID.
1. Create a new database connection.
2. Prepare a stored procedure to call the GET_COWORKERS stored procedure.
3. Bind the parameters.
4. Set the fetch mode to FETCH_ASSOC.
5. Execute the statement.
6. Create an empty array for the output.
7. For each record add a new coworker to the output.
8. Return the output.
*/
public static function get_coworkers($id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_COWORKERS(:id)"); //2
$stmt->bindParam(":id", $id); //3
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$output = []; //6
foreach($stmt->fetchAll() as $row){ //7
$output[] = new Coworker($row['UserID'], $row['UserFirstName'], $row['UserSurname'], $row['UserCompany'], $row['UserEmail']);
}
return $output; //8
}
/*
A public static function to create a new coworker from the user ID. The parameter is the user ID.
1. Create a new database connection.
2. Prepare a statement to call the LOAD_USER stored procedure.
3. Bind the parameter.
4. Execute the statement.
5. If there is 1 record.
6. Fetch the result.
7. Return a new coworker object.
*/
public static function from_id($id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL LOAD_USER(:ID)"); //2
$stmt->bindParam(":ID", $id); //3
$stmt->execute(); //4
if($stmt->rowCount() == 1){ //5
$result = $stmt->fetch(); //6
return new Coworker($id, $result['UserFirstName'], $result['UserSurname'], $result['UserCompany'], $result['UserEmail']); //7
}
}
/*
A public function to load all the user defined fields.
1. Create a new database connection.
2. Prepare a new statement to call the GET_EXTRA_USER_INFO stored procedure.
3. Bind the parameters.
4. Set the fetch mode to assoc.
5. Execute the statement.
6. Set the user defined field variable to the array returned.
*/
public function load_user_defined_fields(){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_EXTRA_USER_INFO(:id)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$this->UserDefinedFields = $stmt->fetchAll(); //6
}
/*
A public function to check if a request has been sent. The parameter is the other user ID.
1. Create a new database connection.
2. Prepare a statement to call the IS_COWORKER_SENT stored procedure.
3. Bind the parameters.
4. Execute the statement.
5. Return a boolean which is true if there is 1 record and false otherwise.
*/
public function is_sent($id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL IS_COWORKER_SENT(:id1, :id2)"); //2
$stmt->bindParam(":id1", $this->UserID); //3
$stmt->bindParam(":id2", $id);
$stmt->execute(); //4
return $stmt->rowCount() == 1; //5
}
/*
A public function to check if a coworker has been accepted. The parameter is the other user ID.
1. Create a new database connection.
2. Prepare a statement to call the IS_COWORKER_ACCEPTED stored procedure.
3. Bind the parameters.
4. Execute the statement.
5. Return a boolean which is true if there is 1 record and false otherwise.
*/
public function is_accepted($id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL IS_COWORKER_ACCEPTED(:id1, :id2)"); //2
$stmt->bindParam(":id1", $this->UserID); //3
$stmt->bindParam(":id2", $id);
$stmt->execute(); //4
return $stmt->rowCount() == 1; //5
}
//Getter functions which return private variables
public function get_id(){
return $this->UserID;
}
public function get_first_name(){
return $this->UserFirstName;
}
public function get_last_name(){
return $this->UserLastName;
}
public function get_company(){
return $this->UserCompany;
}
public function get_email(){
return $this->UserEmail;
}
public function get_user_defined_fields(){
return $this->UserDefinedFields;
}
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("../model/user.php");
require_once("../model/shift_defined_field.php");
//If the ID is set.
if(isset($_GET['ID'])){
//Get the ID
$id = trim($_GET['ID']);
//Create a new user
$user = new User();
//Get the shift defined field from the id
$field = ShiftDefinedField::create_new_from_id($id, $user->get_id());
//If it loads delete the field
if($field->is_loaded()){
$field->delete();
}
//If not sent with AJAX then redirect to the settings page
if(!isset($_GET['Ajax'])){
header("Location: ../Settings");
}
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/job_preset.php");
//Create a new user
$user = new User();
//Load the job presets
load_job_presets($user);
?><file_sep><?php
//Start the session
session_start();
//Import required files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/shift_defined_field.php");
//If there is post variables
if(count($_POST) > 0){
//Get the post variables
$name = trim($_POST['Name']);
//Create a new user
$user = new User();
//Call the validate_extra_shift_info function
$errors = validate_extra_shift_info($name, $user->get_id());
//Return the errors in json format
echo json_encode($errors);
}
?><file_sep><?php
//Start the session
session_start();
//If the user is not logged in redirect them to the homepage.
if(!isset($_SESSION['UserID'])){
header("Location: ./");
}
//Include the required files.
require_once("model/user.php");
require_once("php/debug_log.php");
require_once("model/shift_pattern.php");
require_once("model/shift_preset.php");
require_once("php/calendar_functions.php");
//Get the current month and year
$month = date("F");
$year = date("Y");
//Create a new user object
$user = new User();
//Create a new shift pattern object
$shift_pattern = new ShiftPattern($user->get_id());
//If there is post variables
if(count($_POST) > 0){
//Create a new pattern string.
$pattern = "";
//Loop over every post variable and add it to the pattern.
foreach ($_POST as $key => $value) {
if($value != -1)
$pattern .= $value . ',';
}
//Remove the last character from the string which will be a ','
$pattern = substr($pattern, 0, -1);
//If the pattern is loaded then update the existing pattern.
if($shift_pattern->is_loaded()){
$shift_pattern->update($pattern);
}
//If there is not pattern loaded then add a new pattern.
else{
$shift_pattern->add($pattern);
}
//Redirect to the Calendar page which will clear the post variables.
header("Location: Calendar");
}
//If the get variable clear is set
if(isset($_GET['Clear'])){
//Delete the shift pattern.
$shift_pattern->del();
//Redirect to the Calendar page which will clear the post variables.
header("Location: Calendar");
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/shift_preset.php");
//Create a new user object
$user = new User();
//Load the shift presets
load_shift_presets($user);
?><file_sep><?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('./controllers/worker_controller.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Shift Planner - <?php echo "Worker" ?></title>
<meta name="description" content="A shift planner for people who work shifts.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/main.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<noscript>
<div class="container-fluid" id="NoScriptError">
<h4><span class="glyphicon glyphicon-warning-sign"></span> Please enable javascript for a better experience!</h4>
</div>
</noscript>
<?php include_once("navigation.php"); ?>
<?php
if($accepted):
?>
<div class="container">
<div class="row UserRow">
<div><h3><?php echo $user->get_first_name() . " " . $user->get_last_name(); ?></h3></div>
<div><p><?php echo $user->get_email(); ?></p></div>
<?php
if($user->get_company() != ""){
printf('<div><p>%s</p></div>', $user->get_company());
}
foreach($user->get_user_defined_fields() as $row){
if($row["Private"] == "N") printf('<div><p><b>%s</b> %s</p></div>', $row["FieldName"], $row["FieldValue"]);
}
?>
</div>
</div>
<div class="container" id="calendar-container">
<div class="row">
<h5 class="text-center">
<a href="#" class="pull-left" id="cal-prev">Previous</a>
<span id="cal-title"><?php printf("%s %s", $month, $year); ?></span>
<a href="#" class="pull-right" id="cal-next">Next</a>
</h5>
</div>
<div class="row">
<div class="table-responsive">
<table class="table table-bordered" id="calendar-table">
</table>
</div>
</div>
</div>
<div class="modal fade" id="Calendar-Modal" tabindex="-1" role="dialog" aria-labelledby="Calendar-Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="Calendar-Label">Shift Info</h4>
</div>
<div class="modal-body" id="Calendar-Modal-Body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php
else:
echo '<p class="text-center">You are not coworkers with this person.</p>';
endif;
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<?php if($accepted) echo '<script src="js/worker.js"></script>'; ?>
</body>
</html>
<file_sep><?php
//Start the session.
session_start();
//Include the required files.
require_once("../model/coworker.php");
require_once("../model/shift_pattern.php");
require_once("../model/shift_preset.php");
require_once("../model/shift.php");
//If there is post variables.
if(count($_POST) > 0){
//Create a new user object.
$user = Coworker::from_id($_POST['ID']);
//Get the shift pattern for that user.
$pattern = new ShiftPattern($user->get_id());
//Get the month number.
$month_num = $_POST["Month"];
//Get the year.
$year = $_POST["Year"];
//Calculate the days in the month.
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month_num, $year);
//Get all the shift presets.
$shift_presets = ShiftPreset::load_all_assoc($user);
//Get all the shifts for this month.
$shifts = Shift::load_month($month_num, $year, $user->get_id());
//Create a counter variable.
$i = 0;
//Calculate the number of rows in the calendar.
$rows = ceil($days_in_month / 7);
//Loop over each row in the calendar.
for($j = 0; $j<$rows; $j++){
//Write the html for a new row.
echo '<tr>';
//For each day of that week.
for($k = 0; $k<7; $k++){
//Increase the counter.
$i++;
//If the counter is less than or equal to the days in the month.
if($i <= $days_in_month){
//Create the date string for that day. In the form mm/dd/yyyy.
$dateStr = $month_num . "/" . $i . "/" . $year;
//Create a new DateTime object for that date.
$date = new DateTime($dateStr);
//get the preset id for that day of the year.
$id = $pattern->get_shift_preset_id(date('z', $date->getTimestamp()));
//Get the preset object.
$preset = $shift_presets[$id];
//Get the shift object.
$shift = $shifts[$dateStr];
//If the shift is set.
if(isset($shift)){
//Create an empty string for the colour bar.
$colour_bar = "";
//Get the preset for that shift.
$preset = $shift_presets[$shift->get_preset_id()];
//If the shift is a holiday make the colour bar a 'hol'.
if($shift->is_holiday()){
$colour_bar = "hol";
}
//If the shift is a shift meeting make the colour bar a 'sm'.
else if($shift->is_shift_meeting()){
$colour_bar = "sm";
}
//Print the td for that day.
printf('<td class="shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="%s" data-preset="%s" data-date="%s">
<div class="colour-bar %s"></div>
<div class="info-bar">%s</div>
<div class="body small">%s</div>
</td>', $shift->get_shift_id(), $id, $dateStr, $colour_bar, $i, (isset($preset)?$preset->get_key():'-'));
}
//If the preset is set and the shift isn't.
elseif(isset($preset)){
//Print the td for that day.
printf('<td class="shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="%s" data-preset="%s" data-date="%s">
<div class="colour-bar"></div>
<div class="info-bar">%s</div>
<div class="body small">%s</div>
</td>', -1, $id, $dateStr, $i, $preset->get_key());
}
//If the shift isn't set and the preset isn't set.
else{
printf('<td class="shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="%s" data-preset="%s">
<div class="colour-bar"></div>
<div class="info-bar">%s</div>
<div class="body small">%s</div>
</td>', -1, -1, $i, "-");
}
}
//If the counter is greater than the days in the month.
else{
printf('<td class="shift-section small"></td>');
}
}
//Close the row.
echo '</tr>';
}
}
?><file_sep><?php
require_once('./controllers/summary_controller.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Shift Planner - Summary</title>
<meta name="description" content="A shift planner for people who work shifts.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/main.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<noscript>
<div class="container-fluid" id="NoScriptError">
<h4><span class="glyphicon glyphicon-warning-sign"></span> Please enable javascript for a better experience!</h4>
</div>
</noscript>
<?php include_once("navigation.php"); ?>
<div class="container">
<div class="row">
<div class="col-sm-5 col-sm-offset-1 shift-section" data-toggle="modal" data-target="#Calendar-Modal" data-shift="<?php echo $summary[0]['ShiftID']; ?>" data-preset="<?php echo $summary[0]['PresetID']; ?>" data-date="<?php echo $summary[0]['SQLDate']; ?>">
<div class="colour-bar <?php echo $summary[0]['Hol']; echo $summary[0]['SM']; ?>"></div>
<div class="info-bar">
<b>Today</b>
<span class="pull-right"><?php echo $summary[0]["Date"]; ?></span>
</div>
<div class="body large"><?php echo $summary[0]["Shift"]; ?></div>
<div class="info-bar">
<b>Job</b>
<span class="pull-right"><?php echo $summary[0]["Job"]; ?></span>
</div>
</div>
<div class="col-sm-5 shift-section" data-toggle="modal" data-target="#Calendar-Modal" data-shift="<?php echo $summary[1]['ShiftID']; ?>" data-preset="<?php echo $summary[1]['PresetID']; ?>" data-date="<?php echo $summary[1]['SQLDate']; ?>">
<div class="colour-bar <?php echo $summary[1]['Hol']; echo $summary[1]['SM']; ?>"></div>
<div class="info-bar">
<b>Tomorrow</b>
<span class="pull-right"><?php echo $summary[1]["Date"]; ?></span>
</div>
<div class="body large"><?php echo $summary[1]["Shift"]; ?></div>
<div class="info-bar">
<b>Job</b>
<span class="pull-right"><?php echo $summary[1]["Job"]; ?></span>
</div>
</div>
</div>
<div class="row" style="margin-top:10px;">
<div class="col-sm-2 col-sm-offset-1 shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="<?php echo $summary[2]['ShiftID']; ?>" data-preset="<?php echo $summary[2]['PresetID']; ?>" data-date="<?php echo $summary[2]['SQLDate']; ?>">
<div class="colour-bar <?php echo $summary[2]['Hol']; echo $summary[2]['SM']; ?>"></div>
<div class="info-bar"><?php echo $summary[2]["Date"]; ?></div>
<div class="body small"><?php echo $summary[2]["Shift"]; ?></div>
</div>
<div class="col-sm-2 shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="<?php echo $summary[3]['ShiftID']; ?>" data-preset="<?php echo $summary[3]['PresetID']; ?>" data-date="<?php echo $summary[3]['SQLDate']; ?>">
<div class="colour-bar <?php echo $summary[3]['Hol']; echo $summary[3]['SM']; ?>"></div>
<div class="info-bar"><?php echo $summary[3]["Date"]; ?></div>
<div class="body small"><?php echo $summary[3]["Shift"]; ?></div>
</div>
<div class="col-sm-2 shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="<?php echo $summary[4]['ShiftID']; ?>" data-preset="<?php echo $summary[4]['PresetID']; ?>" data-date="<?php echo $summary[4]['SQLDate']; ?>">
<div class="colour-bar <?php echo $summary[4]['Hol']; echo $summary[4]['SM']; ?>"></div>
<div class="info-bar"><?php echo $summary[4]["Date"]; ?></div>
<div class="body small"><?php echo $summary[4]["Shift"]; ?></div>
</div>
<div class="col-sm-2 shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="<?php echo $summary[5]['ShiftID']; ?>" data-preset="<?php echo $summary[5]['PresetID']; ?>" data-date="<?php echo $summary[5]['SQLDate']; ?>">
<div class="colour-bar <?php echo $summary[5]['Hol']; echo $summary[5]['SM']; ?>"></div>
<div class="info-bar"><?php echo $summary[5]["Date"]; ?></div>
<div class="body small"><?php echo $summary[5]["Shift"]; ?></div>
</div>
<div class="col-sm-2 shift-section small" data-toggle="modal" data-target="#Calendar-Modal" data-shift="<?php echo $summary[6]['ShiftID']; ?>" data-preset="<?php echo $summary[6]['PresetID']; ?>" data-date="<?php echo $summary[6]['SQLDate']; ?>">
<div class="colour-bar <?php echo $summary[6]['Hol']; echo $summary[6]['SM']; ?>"></div>
<div class="info-bar"><?php echo $summary[6]["Date"]; ?></div>
<div class="body small"><?php echo $summary[6]["Shift"]; ?></div>
</div>
</div>
</div>
<div class="modal fade" id="Calendar-Modal" tabindex="-1" role="dialog" aria-labelledby="Calendar-Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="Calendar-Label">Edit Shift</h4>
</div>
<div class="modal-body" id="Calendar-Modal-Body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="SaveButton">Save</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/summary.js"></script>
</body>
</html>
<file_sep><?php
//Include the required files.
require_once('database.php');
require_once('shift_defined_value.php');
//A class to contain all the Shift data and functions to manipulate a shift record.
class Shift{
//Private variables
private $ShiftID; // The shift record ID.
private $ShiftDate; // The date this shift object is for.
private $UserID; // The user who owns this shift object.
private $PresetID; // The shift preset for this shift.
private $JobID; // The job preset for this shift.
private $Notes; // The notes for this shift.
private $ShiftMeeting; // A boolean indicating that this shift is or isn't a shift meeting.
private $Holiday; // A boolean indicating that this shift is or isn't a holiday day.
private $Loaded; // A boolean indicating that the shift has or hasn't been loaded.
private $UserDefinedFields = []; // An array of user defined field objects.
/*
A public constructor which creates a new Shift object with the data provided.
1. Sets the private variables with the data passed in as the parameters.
2. Load the user defined fields from the shift ID.
*/
function __construct($shift_id, $shift_date, $user_id, $preset_id, $job_id, $notes, $shift_meeting, $holiday, $loaded){
$this->ShiftID = $shift_id; //1
$this->ShiftDate = $shift_date;
$this->UserID = $user_id;
$this->PresetID = $preset_id;
$this->JobID = $job_id;
$this->Notes = $notes;
$this->ShiftMeeting = $shift_meeting;
$this->Holiday = $holiday;
$this->Loaded = $loaded;
$this->load_user_defined_fields($this->ShiftID); //2
}
/*
A private function to load the user defined fields. The parameter is the shift ID the fields belong to.
1. Create a new database connection.
2. Prepare the statement to call the GET_SHIFT_DEFINED_VALUES stored procedure.
3. Bind the parameters to the statement.
4. Set the fetch mode to FETCH_ASSOC so that the result will be an associative array.
5. Execute the statement.
6. Loop over the results and add each record to the user defined fields array.
*/
private function load_user_defined_fields($id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_SHIFT_DEFINED_VALUES(:id)"); //2
$stmt->bindParam(":id", $id); //3
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$results = $stmt->fetchAll(); //6
foreach ($results as $row) { //7
$this->UserDefinedFields[$row["DefinedFieldID"]] = new ShiftDefinedValue($row["DefinedValueID"], $row["DefinedFieldID"], $row["ShiftID"], $row["Value"]);
}
}
/*
A public static function to create a new shift. The parameters are the user id, the shift preset id, the job preset id, the notes, holiday flag, shift meeting flag and the date.
1. Create a new connection.
2. Prepare a statement to call the ADD_SHIFT stored procedure.
3. Bind the parameters to the statement.
4. Execute the statement.
5. Return the inserted id of the shift record.
*/
public static function create_new($user_id, $shift_preset, $job_preset, $notes, $holiday, $sm, $date){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL ADD_SHIFT(:uid, :shift_preset, :job_preset, :notes, :holiday, :sm, :date)"); //2
$stmt->bindParam(":uid", $user_id); //3
$stmt->bindParam(":shift_preset", $shift_preset);
$stmt->bindParam(":job_preset", $job_preset);
$stmt->bindParam(":notes", $notes);
$stmt->bindParam(":holiday", $holiday);
$stmt->bindParam(":sm", $sm);
$stmt->bindParam(":date", $date);
$stmt->execute(); //4
return $conn->query("SELECT LAST_INSERT_ID()")->fetchColumn(0); //5
}
/*
A public static function to load all shifts for a specific month and year. The parameters are the month, year and user id to search for.
1. Create a date string to search the database for.
2. Create a new connection.
3. Prepare a new statement to call the SHIFT_LOAD_MONTH stored procedure.
4. Bind the parameters to the statement.
5. Set the fetch mode to FETCH_ASSOC so that an associative array is returned.
6. Execute the statement.
7. Fetch all the results and store in an array.
8. Create an empty shifts array.
9. Loop over each record and add a new Shift object to the array.
10. Return the array.
*/
public static function load_month($month, $year, $user_id){
$date = $month . '/%/' . $year; //1
$conn = db_connect(); //2
$stmt = $conn->prepare("CALL SHIFT_LOAD_MONTH(:date, :uid)"); //3
$stmt->bindParam(":date", $date); //4
$stmt->bindParam(":uid", $user_id);
$stmt->setFetchMode(PDO::FETCH_ASSOC); //5
$stmt->execute(); //6
$results = $stmt->fetchAll(); //7
$shifts = []; //8
foreach ($results as $row) { //9
$shifts[$row['ShiftDate']] = new Shift($row['ShiftID'], $row['ShiftDate'], $row['UserID'], $row['PresetID'], $row['JobID'], $row['Notes'], $row['ShiftMeeting'], $row['Holiday'], true);
}
return $shifts; //10
}
/*
A public static function to load a shift from its ID. The parameter is the shift ID.
1. Create a new database connection.
2. Prepare a new statement to call the GET_SHIFT stored procedure.
3. Bind the parameters.
4. Set the fetch mode to FETCH_ASSOC so that the result is an associative array.
5. Execute the statement.
6. Fetch the first row and store it.
7. Return a new shift object with the data from the row.
*/
public static function load_from_id($shift_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_SHIFT(:id)"); //2
$stmt->bindParam(":id", $shift_id); //3
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$row = $stmt->fetch(); //6
return new Shift($row['ShiftID'], $row['ShiftDate'], $row['UserID'], $row['PresetID'], $row['JobID'], $row['Notes'], $row['ShiftMeeting'], $row['Holiday'], true); //7
}
/*
A public static function which loads a shift from a specific date. The parameters are the date and the user ID.
1. Create a new connection.
2. Prepare a statement to call the GET_SHIFT_FROM_DATE stored procedure.
3. Bind the parameters.
4. Set the fetch mode to FETCH_ASSOC so that the result is an associative array.
5. Execute the statement.
6. If there is 1 row.
7. Fetch the first row.
8. Return the shift.
*/
public static function load_from_date($date, $user_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_SHIFT_FROM_DATE(:date, :uid)"); //2
$stmt->bindParam(":date", $date); //3
$stmt->bindParam(":uid", $user_id);
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
if($stmt->rowCount() == 1){ //6
$row = $stmt->fetch(); //7
return new Shift($row['ShiftID'], $row['ShiftDate'], $row['UserID'], $row['PresetID'], $row['JobID'], $row['Notes'], $row['ShiftMeeting'], $row['Holiday'], true); //8
}
}
/*
A public static function to edit a shift. The parameters are the user id, the shift preset id, the job preset id, the notes, holiday flag, shift meeting flag, the date and the shift id to update.
1. Create a new connection.
2. Prepate a new statement to call the EDIT_SHIFT stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public static function edit($user_id, $shift_preset, $job_preset, $notes, $holiday, $sm, $date, $shift_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL EDIT_SHIFT(:uid, :shift_preset, :job_preset, :notes, :holiday, :sm, :date, :sid)"); //2
$stmt->bindParam(":uid", $user_id); //3
$stmt->bindParam(":shift_preset", $shift_preset);
$stmt->bindParam(":job_preset", $job_preset);
$stmt->bindParam(":notes", $notes);
$stmt->bindParam(":holiday", $holiday);
$stmt->bindParam(":sm", $sm);
$stmt->bindParam(":date", $date);
$stmt->bindParam(":sid", $shift_id);
$stmt->execute(); //4
}
//Getter functions which return private variables.
public function get_shift_id(){
return $this->ShiftID;
}
public function get_shift_date(){
return $this->ShiftDate;
}
public function get_preset_id(){
return $this->PresetID;
}
public function get_job_id(){
return $this->JobID;
}
public function get_notes(){
return $this->Notes;
}
public function is_shift_meeting(){
return ($this->ShiftMeeting == 'Y')?true:false;
}
public function is_holiday(){
return ($this->Holiday == 'Y')?true:false;
}
public function get_user_defined_values(){
return $this->UserDefinedFields;
}
}
?><file_sep><?php
//Start the session
session_start();
//If the user is not logged in redirect them to the homepage.
if(!isset($_SESSION['UserID'])){
header("Location: ./");
}
//Include the required files.
require_once("model/user.php");
require_once("model/coworker.php");
//Create a new user object.
$user = new User();
//Create a users variable.
$users;
//If the search variable is set.
if(isset($_POST['Search'])){
//Get the search data.
$search = trim($_POST['Search']);
//If it is not empty.
if($search != ""){
//Replace spaces with vertical lines.
$search = str_replace(" ", "|", $search);
//Search for the users that match this search query.
$users = Coworker::search($search);
}
}
?><file_sep><?php
//Start the session.
session_start();
//If the UserID session is set then redirect the user to the summary page.
if(isset($_SESSION['UserID'])){
header("Location: Summary");
}
//Include user class.
require_once("model/user.php");
//Empty error array for storing errors.
$errors = [];
//If the form has been submitted.
if(!empty($_POST)){
//Get the email and password fields.
$email = trim($_POST["Email"]);
$password = trim($_POST["Password"]);
//Checks to see if there is an email value.
if($email == ""){
$errors[] = "Email is required.";
}
//Checks to see if there is a password value.
if($password == ""){
$errors[] = "Password is required.";
}
//Checks to see if the email value is valid.
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){
$errors[] = "Email is not valid.";
}
//Login specific validation.
if(isset($_GET["login"])){
//Checks to see if the email is already in use.
if(User::check_email($email)){
$errors[] = "There is no account with that email.";
}
}
//Registration specific validation.
else if(isset($_GET["reg"])){
//Checks the length of the password to make sure it isn't too long or short.
if(strlen($password) < 6){
$errors[] = "Password must be more than 6 characters.";
}
if(strlen($password) > 29){
$errors[] = "Password must be less than 30 characters.";
}
//If the emails is already being used.
if(!User::check_email($email)){
$errors[] = "That email is already being used.";
}
}
//If there is no errors.
if(count($errors) == 0){
//If Login button has been pressed.
if(isset($_GET["login"])){
//Try to login. If the login function returns true then redirect to the summary page.
if(User::login($email, $password)){
header("Location: Summary");
}
//If the password is incorrect.
else{
$errors[] = "Password is incorrect.";
}
}
//If the Register button has been pressed.
else if(isset($_GET["reg"])){
//Encrypt the password.
$hash_pass = crypt($password, <PASSWORD>");
//Create the new user.
User::create_user($email, $hash_pass);
}
}
}
?><file_sep><?php
//Start the session
session_start();
//Import the require files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/shift_preset.php");
//If there is post variables
if(count($_POST) > 0){
//Get the post variables
$key = trim($_POST['Key']);
$name = trim($_POST['Name']);
$start = trim($_POST['Start']);
$end = trim($_POST['End']);
//Create a new user object
$user = new User();
//Call the validate_shift_presets function
$errors = validate_shift_presets($key, $name, $start, $end, $user);
//Return the errors in json format
echo json_encode($errors);
}
?><file_sep><?php
/*
A function to create a database connection.
1. Create the variables for the host, user and password.
2. Creates a new PDO object using the variables. Sets the error mode to exception and returns the connection object.
3. If there is an exception print and error message.
*/
function db_connect(){
$db_host = "localhost";//1
$db_user = "root";
$db_password = "<PASSWORD>";
try {
$conn = new PDO("mysql:host=$db_host;dbname=ShiftPlanner", $db_user, $db_password);//2
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (Exception $e) {
echo 'Connection Failed: ' . $e->getMessage();//3
}
}
?><file_sep><?php
//Start the session
session_start();
//Include the required files.
require_once("../model/user.php");
require_once("../model/coworker.php");
//If there is post variables being sent.
if(count($_POST) > 0){
//Create a new user object.
$user = new User();
//Get the other ID.
$id = $_POST['ID'];
//Create the request.
Coworker::create_request($user->get_id(), $id);
}
?><file_sep><?php
require_once("database.php");
require_once("user.php");
//A class which stores data about a job preset and allows interaction with the job preset e.g. updating and deleting job presets.
class JobPreset{
//Private variables
private $PresetID; //The ID of the preset.
private $PresetName; //The preset name.
private $PresetDesc; //The preset description.
private $UserID; //The user ID who owns this job preset.
private $Loaded = false; //A boolean which indicates that the user has been loaded from the database.
/*
Public constructor which sets the private variables of a job preset.
1. Sets the private variables given as parameters.
*/
function __construct($preset_id, $name, $desc, $user_id, $loaded){
$this->PresetID = $preset_id; //1
$this->PresetName = $name;
$this->PresetDesc = $desc;
$this->UserID = $user_id;
$this->Loaded = $loaded;
}
/*
A static function which loads a job preset from the database. The parameters are the preset id and the user id.
1. Create a new database connection.
2. Prepare the statement to call the GET_JOB_PRESET stored procedure.
3. Bind the parameters to the stored procedure.
4. Set the fetch mode to assoc so that an associative array is returned.
5. Execute the stored procedure.
6. Fetch the first row.
7. Return a new JobPreset.
*/
public static function create_new_from_id($preset_id, $user_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_JOB_PRESET(:preset_id, :user_id)"); //2
$stmt->bindParam(':preset_id', $preset_id); //3
$stmt->bindParam(':user_id', $user_id);
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$row = $stmt->fetch(); //6
return new JobPreset($preset_id, $row['JobName'], $row['JobDescription'], $user_id, $stmt->rowCount() == 1); //7
}
/*
A static function to create a new job preset. The parameters are the name, description and user id.
1. Create a new database connection.
2. Create a statement to call the ADD_JOB_PRESET stored procedure.
3. Bind the parameters to the statement.
4. Execute the statement.
*/
public static function create_job_preset($name, $desc, $user_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL ADD_JOB_PRESET(:name, :desc, :id)"); //2
$stmt->bindParam(':name', $name); //3
$stmt->bindParam(':desc', $desc);
$stmt->bindParam(':id', $user_id);
$stmt->execute(); //4
}
/*
A static function to load all the job presets. The parameter is the current user.
1. Create an empty array to store all the presets.
2. Get the user id.
3. Create a new database connection.
4. Prepare a new statement to call the GET_ALL_JOB_PRESETS stored procedure.
5. Bind the parameters to the statement.
6. Set the fetch mode to assoc to return an associative array.
7. Execute the statement.
8. Loop through each record.
9. Add the record to the array.
10. Return the presets array.
*/
public static function load_all($user){
$presets = []; //1
$user_id = $user->get_id(); //2
$conn = db_connect(); //3
$stmt = $conn->prepare("CALL GET_ALL_JOB_PRESETS(:id)"); //4
$stmt->bindParam(':id', $user_id); //5
$stmt->setFetchMode(PDO::FETCH_ASSOC); //6
$stmt->execute(); //7
foreach ($stmt->fetchAll() as $row) { //8
$presets[] = new JobPreset($row['JobID'], $row['JobName'], $row['JobDescription'], $user_id, true); //9
}
return $presets; //10
}
/*
A static function to load all the job presets. The parameter is the current user.
1. Create an empty array to store all the presets.
2. Get the user id.
3. Create a new database connection.
4. Prepare a new statement to call the GET_ALL_JOB_PRESETS stored procedure.
5. Bind the parameters to the statement.
6. Set the fetch mode to assoc to return an associative array.
7. Execute the statement.
8. Loop through each record.
9. Add the record to the array.
10. Return the presets array.
*/
public static function load_all_assoc($user){
$presets = []; //1
$user_id = $user->get_id(); //2
$conn = db_connect(); //3
$stmt = $conn->prepare("CALL GET_ALL_JOB_PRESETS(:id)"); //4
$stmt->bindParam(':id', $user_id); //5
$stmt->setFetchMode(PDO::FETCH_ASSOC); //6
$stmt->execute(); //7
foreach ($stmt->fetchAll() as $row) { //8
$presets[$row['JobID']] = new JobPreset($row['JobID'], $row['JobName'], $row['JobDescription'], $user_id, true); //9
}
return $presets; //10
}
/*
A public function to edit the current job preset. The parameters are the new name and description.
1. If the job preset is loaded.
2. Create a new database connection.
3. Prepare a new statement to call the EDIT_JOB_PRESET stored procedure.
4. Bind the parameters.
5. Execute the statement.
*/
public function edit($name, $desc){
if($this->Loaded){ //1
$conn = db_connect(); //2
$stmt = $conn->prepare("CALL EDIT_JOB_PRESET(:name, :desc, :pid, :uid)"); //3
$stmt->bindParam(':name', $name); //4
$stmt->bindParam(':desc', $desc);
$stmt->bindParam(':uid', $this->UserID);
$stmt->bindParam(':pid', $this->PresetID);
$stmt->execute(); //5
}
}
/*
A public function to delete the current job preset.
1. If the job preset is loaded.
2. Create a new database connection.
3. Prepare a new statement to call the DEL_JOB_PRESET stored procedure.
4. Bind the parameters.
5. Execute the statement.
*/
public function delete(){
if($this->Loaded){ //1
$conn = db_connect(); //2
$stmt = $conn->prepare("CALL DEL_JOB_PRESET(:pid, :uid)"); //3
$stmt->bindParam(':pid', $this->PresetID); //4
$stmt->bindParam(':uid', $this->UserID);
$stmt->execute(); //5
}
}
//Getter functions which return private variables.
public function get_preset_id(){
return $this->PresetID;
}
public function get_name(){
return $this->PresetName;
}
public function get_desc(){
return $this->PresetDesc;
}
public function get_user_id(){
return $this->UserID;
}
public function is_loaded(){
return $this->Loaded;
}
}
?><file_sep>$(function(){
//Calculate the current date.
var todayDate = new Date();
//Create a variable to hold the next ID of a shift pattern section.
var new_id = 0;
//Get the current month and year.
var currentMonth = todayDate.getMonth();
var currentYear = todayDate.getFullYear();
//Create an empty variable to hold the pattern section html.
var pattern_section;
//An array of month names.
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
//Enable tooltips.
$('[data-toggle="tooltip"]').tooltip();
/*
A function which loads the calendar html.
1. Use AJAX to load the calendar_get_cal.php file passing in the month and year.
2. Set the calendar table html.
3. Change the title.
*/
function loadCalendar(){
$.post("php/calendar_get_cal.php", {Month: (currentMonth+1), Year: currentYear}, function(data){ //1
$("#calendar-table").html(data); //2
});
$("#cal-title").html(monthNames[currentMonth] + " " + currentYear); //3
}
//Gets the pattern section for the user using AJAX.
$.get('php/calendar_pattern_section.php', function(data){
pattern_section = data;
});
//Sets up the shift pattern section.
$("#pattern-container .shift-section:not(#plus)").each(function(){
$(this).find(".info-bar").html(++new_id);
$(this).find("select").attr("name", new_id);
});
//Adds the click listener to the button with ID 'plus'.
$('#plus').on('click', function(){
//Create a new element from the pattern_section html.
var new_el = $(pattern_section);
//Find the info bar and set the html to the new ID. Also increment the new_id variable.
new_el.find(".info-bar").html(++new_id);
//Find the select and change the name to the new_id variable.
new_el.find("select").attr("name", new_id);
//Add the new section before the plus button.
$(this).before(new_el);
});
//Adds the click listener to cal-next link.
$("#cal-next").on('click', function(){
//Increase the current month.
currentMonth++;
//If the month equals 12 set it to 0 and increase the year.
if(currentMonth == 12){
currentMonth = 0;
currentYear++;
}
//Load the new calendar.
loadCalendar();
//Return false to stop following the link.
return false;
});
//Adds the click listener to the cal-prev link.
$("#cal-prev").on('click', function(){
//Decrease the current month.
currentMonth--;
//If the current month is -1 then set it to 11 and decrease the year.
if(currentMonth == -1){
currentMonth = 11;
currentYear--;
}
//Load the new calendar.
loadCalendar();
//Return false to stop following the link.
return false;
});
//Adds the show listener to the calendar dropdown.
$('#Calendar-Modal').on('show.bs.modal', function (event) {
//Get the sender object.
var sender = $(event.relatedTarget);
//Get the shift_id.
var shift_id = sender.data("shift");
//Get the preset_id.
var preset_id = sender.data("preset");
//Get the date of the sender.
var date = sender.data("date");
//Load the form html and set the modal to it.
$.post("php/calendar_load_form.php", {ShiftID: shift_id, PresetID: preset_id, ShiftDate: date}, function(data){
$("#Calendar-Modal-Body").html(data);
});
});
//Add the click listener to the save button on the modal.
$('#SaveButton').on('click', function(event){
//Get the shift ID.
var shift_id = $("#Calendar-Shift-ID").val().trim();
//Get the shift preset.
var shift_preset = $("#Calendar-Shift").val().trim();
//Get the job preset.
var job_preset = $("#Calendar-Job").val().trim();
//Get the notes.
var notes = $("#Calendar-Notes").val().trim();
//Get the holiday.
var holiday = $("#Calendar-Holiday").is(':checked');
//Get the shift meeting.
var shift_meeting = $("#Calendar-SM").is(':checked');
//Get the date.
var date = $("#Calendar-Date").val().trim();
//Check if the user is editing or adding a new shift.
var is_edit = (shift_id > 0)?true:false;
//Create an empty array for the user defined fields.
var user_defined_fields = {};
//Loop over each input with the class user-defined-field.
$(".user-defined-field").each(function(){
//Get the field id.
var field_id = $(this).data('fid');
//Get the value.
var value = $(this).val();
//Add it to the user_defined_fields array.
user_defined_fields[field_id.toString()] = value;
});
//If editing.
if(is_edit){
//Post the values to the calendar_edit_shift.php file.
$.post('php/calendar_edit_shift.php', {ShiftPreset: shift_preset, JobPreset: job_preset, Notes: notes, Holiday: holiday, ShiftMeeting: shift_meeting, ShiftDate: date, UserDefined: JSON.stringify(user_defined_fields), ShiftID:shift_id}, function(data){
//Hide the modal.
$("#Calendar-Modal").modal('hide');
//Load the calendar.
loadCalendar();
});
}
//If adding a new record.
else{
//Post the values to the calendar_add_shift.php file.
$.post('php/calendar_add_shift.php', {ShiftPreset: shift_preset, JobPreset: job_preset, Notes: notes, Holiday: holiday, ShiftMeeting: shift_meeting, ShiftDate: date, UserDefined: JSON.stringify(user_defined_fields)}, function(data){
//Hide the modal.
$("#Calendar-Modal").modal('hide');
//Load the calendar.
loadCalendar();
});
}
});
//Load the calendar.
loadCalendar();
});<file_sep>$(function(){
/*
A show event attached to the calendar-modal object.
1. Get the sender.
2. Get the shift id.
3. Get the preset id.
4. Get the date.
5. Load the calendar_load_form.php file.
6. Add the results to the modal body.
*/
$('#Calendar-Modal').on('show.bs.modal', function (event) {
var sender = $(event.relatedTarget); //1
var shift_id = sender.data("shift"); //2
var preset_id = sender.data("preset"); //3
var date = sender.data("date"); //4
$.post("php/calendar_load_form.php", {ShiftID: shift_id, PresetID: preset_id, ShiftDate: date}, function(data){ //5
$("#Calendar-Modal-Body").html(data); //6
});
});
/*
A click event attached to the save button.
1. Get all the data from the form.
2. Create an array to hold the user defined fields.
3. Loop over the inputs with the class 'user-defined-field'.
4. Get the field id and the value.
5. Add it to the array.
6. If editing post the data to the calendar_edit_shift.php file. Then redirect to the Summary page.
7. If adding post the data to the calendar_add_shift.php file. Then redirect to the Summary page.
*/
$('#SaveButton').on('click', function(event){
var shift_id = $("#Calendar-Shift-ID").val().trim(); //1
var shift_preset = $("#Calendar-Shift").val().trim();
var job_preset = $("#Calendar-Job").val().trim();
var notes = $("#Calendar-Notes").val().trim();
var holiday = $("#Calendar-Holiday").is(':checked');
var shift_meeting = $("#Calendar-SM").is(':checked');
var date = $("#Calendar-Date").val().trim();
var is_edit = (shift_id > 0)?true:false;
var user_defined_fields = {}; //2
$(".user-defined-field").each(function(){ //3
var field_id = $(this).data('fid'); //4
var value = $(this).val();
user_defined_fields[field_id.toString()] = value; //5
});
if(is_edit){ //6
$.post('php/calendar_edit_shift.php', {ShiftPreset: shift_preset, JobPreset: job_preset, Notes: notes, Holiday: holiday, ShiftMeeting: shift_meeting, ShiftDate: date, UserDefined: JSON.stringify(user_defined_fields), ShiftID:shift_id}, function(data){
window.location.replace("Summary");
});
}
else{ //7
$.post('php/calendar_add_shift.php', {ShiftPreset: shift_preset, JobPreset: job_preset, Notes: notes, Holiday: holiday, ShiftMeeting: shift_meeting, ShiftDate: date, UserDefined: JSON.stringify(user_defined_fields)}, function(data){
window.location.replace("Summary");
});
}
});
});<file_sep><?php
//Start the session.
session_start();
//Include the required files.
require_once("../model/user.php");
require_once("../model/shift_pattern.php");
require_once("../model/shift_preset.php");
require_once("../model/job_preset.php");
require_once("../model/shift_defined_value.php");
require_once("../model/shift.php");
//If there is post variables.
if(count($_POST) > 0){
//Create a new user object.
$user = new User();
//Get the shift id to edit.
$shift_id = $_POST['ShiftID'];
//Get the shift preset.
$shift_preset = $_POST['ShiftPreset'];
//Get the job preset.
$job_preset = $_POST['JobPreset'];
//Get the notes.
$notes = $_POST['Notes'];
//Get the holiday.
$holiday = (filter_var($_POST['Holiday'], FILTER_VALIDATE_BOOLEAN))?'Y':'N';
//Get the shift meeting.
$sm = (filter_var($_POST['ShiftMeeting'], FILTER_VALIDATE_BOOLEAN))?'Y':'N';
//Get the date.
$date = $_POST['ShiftDate'];
//Get the user defined values.
$user_defined_fields = json_decode($_POST['UserDefined']);
//If the user is loaded.
if($user->is_loaded()){
//Edit the shift.
Shift::edit($user->get_id(), $shift_preset, $job_preset, $notes, $holiday, $sm, $date, $shift_id);
//For each user defined value.
foreach ($user_defined_fields as $field_id => $value) {
//Edit the shift defined value.
ShiftDefinedValue::edit($field_id, $value, $shift_id);
}
}
}
?><file_sep><?php
require_once("database.php");
require_once("user.php");
//A class which stores data about a shift user defined field.
class ShiftDefinedField{
//Private variables
private $DefinedFieldID; //The ID of the defined field.
private $DefinedFieldName; //The defined field name.
private $UserID; //The user ID who created this field.
private $Loaded = false; //A boolean which indicates that the user has been loaded from the database.
/*
Public constructor which sets the private variables of a shift user defined field.
1. Sets the private variables given as parameters.
*/
function __construct($defined_id, $name, $user_id, $loaded){
$this->DefinedFieldID = $defined_id; //1
$this->DefinedFieldName = $name;
$this->UserID = $user_id;
$this->Loaded = $loaded;
}
/*
A static function which loads a ShiftDefinedField from the database. The parameters are the field id and the user id.
1. Create a new database connection.
2. Prepare the statement to call the GET_SHIFT_DEFINED_FIELD stored procedure.
3. Bind the parameters to the stored procedure.
4. Set the fetch mode to assoc so that an associative array is returned.
5. Execute the stored procedure.
6. Fetch the first row.
7. Return a new ShiftDefinedField.
*/
public static function create_new_from_id($defined_id, $user_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_SHIFT_DEFINED_FIELD(:defined_id, :user_id)"); //2
$stmt->bindParam(':defined_id', $defined_id); //3
$stmt->bindParam(':user_id', $user_id);
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$row = $stmt->fetch(); //6
return new ShiftDefinedField($defined_id, $row['FieldName'], $user_id, $stmt->rowCount() == 1); //7
}
/*
A static function to create a new shift user defined field. The parameters are the name and user id.
1. Create a new database connection.
2. Create a statement to call the ADD_SHIFT_DEFINED_FIELD stored procedure.
3. Bind the parameters to the statement.
4. Execute the statement.
*/
public static function create_shift_defined_field($name, $user_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL ADD_SHIFT_DEFINED_FIELD(:name, :id)"); //2
$stmt->bindParam(':name', $name); //3
$stmt->bindParam(':id', $user_id);
$stmt->execute(); //4
}
/*
A static function to load all the shift user defined fields. The parameter is the current user.
1. Create an empty array to store all the fields.
2. Get the user id.
3. Create a new database connection.
4. Prepare a new statement to call the GET_ALL_SHIFT_DEFINED_FIELD stored procedure.
5. Bind the parameters to the statement.
6. Set the fetch mode to assoc to return an associative array.
7. Execute the statement.
8. Loop through each record.
9. Add the record to the array.
10. Return the presets array.
*/
public static function load_all($user){
$presets = []; //1
$user_id = $user->get_id(); //2
$conn = db_connect(); //3
$stmt = $conn->prepare("CALL GET_ALL_SHIFT_DEFINED_FIELD(:id)"); //4
$stmt->bindParam(':id', $user_id); //5
$stmt->setFetchMode(PDO::FETCH_ASSOC); //6
$stmt->execute(); //7
foreach ($stmt->fetchAll() as $row) { //8
$presets[] = new ShiftDefinedField($row['DefinedFieldID'], $row['FieldName'], $user_id, true);
}
return $presets;
}
/*
A public function to edit the current shift user defined field. The parameters are the new name.
1. If the field is loaded.
2. Create a new database connection.
3. Prepare a new statement to call the EDIT_SHIFT_DEFINED_FIELD stored procedure.
4. Bind the parameters.
5. Execute the statement.
*/
public function edit($name){
if($this->Loaded){ //1
$conn = db_connect(); //2
$stmt = $conn->prepare("CALL EDIT_SHIFT_DEFINED_FIELD(:name, :fid, :uid)"); //3
$stmt->bindParam(':name', $name); //4
$stmt->bindParam(':uid', $this->UserID);
$stmt->bindParam(':fid', $this->DefinedFieldID);
$stmt->execute(); //5
}
}
/*
A public function to delete the current field.
1. If the field is loaded.
2. Create a new database connection.
3. Prepare a new statement to call the DEL_SHIFT_DEFINED_FIELD stored procedure.
4. Bind the parameters.
5. Execute the statement.
*/
public function delete(){
if($this->Loaded){ //1
$conn = db_connect(); //2
$stmt = $conn->prepare("CALL DEL_SHIFT_DEFINED_FIELD(:fid, :uid)"); //3
$stmt->bindParam(':fid', $this->DefinedFieldID); //4
$stmt->bindParam(':uid', $this->UserID);
$stmt->execute(); //5
}
}
//Getter functions which return private variables.
public function get_field_id(){
return $this->DefinedFieldID;
}
public function get_name(){
return $this->DefinedFieldName;
}
public function get_user_id(){
return $this->UserID;
}
public function is_loaded(){
return $this->Loaded;
}
}
?><file_sep><?php
require_once('./controllers/search_controller.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Shift Planner - Search</title>
<meta name="description" content="A shift planner for people who work shifts.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/main.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<noscript>
<div class="container-fluid" id="NoScriptError">
<h4><span class="glyphicon glyphicon-warning-sign"></span> Please enable javascript for a better experience!</h4>
</div>
</noscript>
<?php include_once("navigation.php"); ?>
<div class="container">
<div class="row">
<form action="Search" method="post">
<div class="form-group" style="margin-bottom:5px;">
<input type="text" class="form-control" placeholder="Name e.g. <NAME>" name="Search" value="<?php echo $_POST['Search']; ?>">
</div>
<button type="submit" class="btn btn-default pull-right">Search</button>
</form>
</div>
<?php
foreach($users as $row){
if($row->get_id() == $user->get_id()) continue;
$sent = $row->is_sent($user->get_id());
$accepted = $row->is_accepted($user->get_id());
echo '<div class="row UserRow">';
echo '<a href="#" class="pull-right '.(($sent)?'okbutton':'').' button" style="margin-top:20px;" data-id="'.$row->get_id().'" data-function="'.(($sent)?'DEL':'ADD').'"><span class="glyphicon glyphicon-'.(($sent)?'ok':'plus').'-sign"></span></a>';
printf('<div><h3><a href="%s">%s %s</a></h3></div>', ($accepted)?("Worker?ID=" . $row->get_id()):"#", $row->get_first_name(), $row->get_last_name());
printf('<div><p>%s</p></div>', $row->get_email());
if($row->get_company() != ""){
printf('<div><p>%s</p></div>', $row->get_company());
}
echo '</div>';
}
?>
<!--
<div class="row UserRow">
<a class="pull-right button" style="margin-top:20px;"><span class="glyphicon glyphicon-plus-sign"></span></a>
<div><h3><NAME></h3></div>
<div><p><EMAIL></p></div>
<div><p>Company Here</p></div>
</div>
<div class="row UserRow">
<a class="pull-right button ok" style="margin-top:20px;"><span class="glyphicon glyphicon-ok-sign"></span></a>
<div><h3><NAME></h3></div>
<div><p><EMAIL></p></div>
<div><p>Company Here</p></div>
</div>
<div class="row UserRow">
<a class="pull-right button" style="margin-top:20px;"><span class="glyphicon glyphicon-plus-sign"></span></a>
<div><h3><NAME></h3></div>
<div><p><EMAIL></p></div>
<div><p>Company Here</p></div>
</div> -->
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/search.js"></script>
</body>
</html>
<file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/shift_defined_field.php");
//If there is post variables
if(count($_POST) > 0){
//get the variables
$pid = trim($_POST['ID']);
$name = trim($_POST['Name']);
//Create a new user
$user = new User();
//Get the field from the ID
$field = ShiftDefinedField::create_new_from_id($pid, $user->get_id());
//Call the validate_edit_extra_shift_info function
$errors = validate_edit_extra_shift_info($field, $name, $user);
//Return the errors
echo json_encode($errors);
}
?><file_sep><?php
//Include all required files.
require_once("database.php");
//A class which stores data about a users shift pattern and has functions for interaction with the database.
class ShiftPattern{
//Private variables
private $PatternString; // This is the pattern string from database.
private $PatternArray = []; // This is the pattern array.
private $UserID; // This is the user ID.
private $Loaded = false; // This is a boolean to indicate if the data has been loaded.
/*
A public constructor which loads the pattern string and array. The parameter is the user id.
1. Sets the user ID variable.
2. Load the pattern string.
3. If loaded get the pattern array.
*/
function __construct($user_id){
$this->UserID = $user_id; //1
$this->load_pattern_string(); //2
if($this->Loaded) $this->get_pattern_array(); //3
}
/*
A private function that loads the pattern string from the database.
1. Create a new connection.
2. Prepare a new statement to call the GET_SHIFT_PATTERN stored procedure.
3. Bind the parameters.
4. Execute the statement.
5. If the row count equals 1.
6. Set the pattern string to the first column.
7. Set loaded to true.
*/
private function load_pattern_string(){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_SHIFT_PATTERN(:id)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->execute(); //4
if($stmt->rowCount() == 1){ //5
$this->PatternString = $stmt->fetchColumn(0); //6
$this->Loaded = true; //7
}
}
/*
A private function to get the pattern array from the pattern string.
1. Explode the pattern string by the ',' character to get the individual IDs.
*/
private function get_pattern_array(){
$this->PatternArray = explode(",", $this->PatternString); //1
}
/*
A public function to get the preset id for a particular day of the year. The parameter is the day of the year.
1. Return the ID at index day modulo number of items in the array.
*/
public function get_shift_preset_id($day){
return $this->PatternArray[($day)%count($this->PatternArray)]; //1
}
/*
A public function to update the pattern in the database. The parameter is the new pattern.
1. Create a database connection.
2. Prepare a new statement to call the UPDATE_SHIFT_PATTERN stored procedure.
3. Bind the parameters.
4. Execute the statement.
5. Update the pattern string.
6. Get the pattern array.
*/
public function update($pattern){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL UPDATE_SHIFT_PATTERN(:id, :pattern)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->bindParam(":pattern", $pattern);
$stmt->execute(); //4
$this->PatternString = $pattern; //5
$this->get_pattern_array(); //6
}
/*
A public function to add the pattern to the database. The parameter is the patter to add.
1. Create a database connection.
2. Prepare a new statement to call the ADD_SHIFT_PATTERN stored procedure.
3. Bind the parameters.
4. Execute the statement.
5. Update the pattern string.
6. Get the pattern array.
*/
public function add($pattern){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL ADD_SHIFT_PATTERN(:id, :pattern)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->bindParam(":pattern", $pattern);
$stmt->execute(); //4
$this->PatternString = $pattern; //5
$this->get_pattern_array(); //6
}
/*
A public function to delete the pattern.
1. Create a new database connection.
2. Prepare a statement to call the DEL_SHIFT_PATTERN stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public function del(){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL DEL_SHIFT_PATTERN(:id)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->execute(); //4
}
//Getter functions which return private variables.
public function is_loaded(){
return $this->Loaded;
}
public function get_array(){
return $this->PatternArray;
}
}
?><file_sep><?php
//Start the session.
session_start();
//Include the required files.
require_once("../model/user.php");
require_once("../model/shift_pattern.php");
require_once("../model/shift_preset.php");
require_once("../model/job_preset.php");
require_once("../model/shift_defined_field.php");
require_once("../model/shift_defined_value.php");
require_once("../model/shift.php");
//If there is post variables.
if(count($_POST) > 0){
//Create a new user object.
$user = new User();
//Get the shift id.
$shift_id = $_POST['ShiftID'];
//Get the preset id.
$preset_id = $_POST['PresetID'];
//Get the date.
$date = $_POST['ShiftDate'];
//Create a shift id variable.
$shift = -1;
//Create a job id variable.
$job = -1;
//Create an empty string for the notes.
$notes = "";
//Create a shift meeting boolean set to false.
$shift_meeting = false;
//Create a holiday boolean set to false.
$holiday = false;
//Create an empty array for the user defined values.
$user_defined_values = [];
//If the user is loaded.
if($user->is_loaded()){
//Load all the shift presets.
$presets = ShiftPreset::load_all($user);
//Load all the job presets.
$jobs = JobPreset::load_all($user);
//Load all the user defined fields.
$user_defined_fields = ShiftDefinedField::load_all($user);
//Print the html for the form.
echo '<form id="Calendar-Form" action="Calendar" method="post">';
//Print html for the hidden date and shift id.
echo '<input type="hidden" id="Calendar-Shift-ID" value="'.$shift_id.'">';
echo '<input type="hidden" id="Calendar-Date" value="'.$date.'">';
//If the shift id is greater than 0.
if($shift_id > 0){
//Load the shift object.
$shift_obj = Shift::load_from_id($shift_id);
//Set the variables to those from the shift object.
$shift = $shift_obj->get_preset_id();
$job = $shift_obj->get_job_id();
$notes = $shift_obj->get_notes();
$shift_meeting = $shift_obj->is_shift_meeting();
$holiday = $shift_obj->is_holiday();
$user_defined_values = $shift_obj->get_user_defined_values();
}
//If the preset id is greater than 0 then set the shift to the preset id.
else if($preset_id > 0){
$shift = $preset_id;
}
//Print the html for the shifts.
echo '<div class="form-group"><label for="Calendar-Shift" class="control-label">Shift</label>';
echo '<select id="Calendar-Shift" class="form-control">';
echo '<option value="-1">-</option>';
foreach ($presets as $preset) {
printf('<option value="%s" %s>%s</option>', $preset->get_preset_id(), (($preset->get_preset_id() == $shift)?'selected':''), $preset->get_key());
}
echo '</select></div>';
//Print the html for the jobs.
echo '<div class="form-group"><label for="Calendar-Job" class="control-label">Job</label>';
echo '<select id="Calendar-Job" class="form-control">';
echo '<option value="-1">-</option>';
foreach ($jobs as $row) {
printf('<option value="%s" %s>%s</option>', $row->get_preset_id(), (($row->get_preset_id()==$job)?'selected':''), $row->get_name());
}
echo '</select></div>';
//Print the html for the user defined fields.
foreach ($user_defined_fields as $field) {
$value = "";
if(isset($user_defined_values[$field->get_field_id()])) $value = $user_defined_values[$field->get_field_id()]->get_value();
printf('<div class="form-group"><label for="Calendar-UDF-%s" class="control-label">%s</label><input type="text" id="Calendar-UDF-%s" class="form-control user-defined-field" value="%s" data-fid="%s"></div>', $field->get_field_id(), $field->get_name(), $field->get_field_id(), $value, $field->get_field_id());
}
//Write the html for the notes, holiday and shift meeting.
echo '<div class="form-group"><label for="Calendar-Notes" class="control-label">Notes</label><textarea id="Calendar-Notes" class="form-control">'.$notes.'</textarea></div>';
echo '<div class="form-group"><label for="Calendar-Holiday" class="control-label">Mark as Holiday <input type="checkbox" id="Calendar-Holiday" '.(($holiday)?"checked":"").'></label></div>';
echo '<div class="form-group"><label for="Calendar-SM" class="control-label">Mark as Shift Meeting <input type="checkbox" id="Calendar-SM" '.(($shift_meeting)?"checked":"").'></label></div>';
//Write the html to close the form.
echo '</form>';
}
}
?><file_sep><?php
//Start the session.
session_start();
//Include the required files.
require_once("../model/user.php");
require_once("../model/coworker.php");
//If there is post variables being sent.
if(count($_POST) > 0){
//Create a new user object.
$user = new User();
//Get the other user ID.
$id = $_POST['ID'];
//Delete the coworker.
Coworker::delete($user->get_id(), $id);
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("../model/user.php");
//If the name is set
if(isset($_GET['Name'])){
//Get the name
$name = trim($_GET['Name']);
//Create a new user object
$user = new User();
//Delete the user defined field
$user->delete_user_defined_field($name);
//If not sent with ajax then redirect to the settings page.
if(!isset($_GET['Ajax'])){
header("Location: ../Settings");
}
}
?><file_sep>function showToast(Text, Duration){
if(window.jQuery){
$("<p></p>").html(Text).appendTo("#WebToast").hide().fadeIn(function(){
var x = $(this);
setTimeout(function(){
x.fadeOut({
duration: 200,
complete: function(){
x.remove();
}
});
}, Duration);
});
}
else{
console.log("jQuery is required to use WebToasts");
}
}
$(function(){
if($("#WebToast").length == 0){
$('<div id="WebToast"></div>').appendTo("body");
}
});<file_sep><?php
//Start the session
session_start();
//If the user is not logged in redirect them to the homepage.
if(!isset($_SESSION['UserID'])){
header("Location: ./");
}
if(!isset($_GET['ID'])){
header("Location: ./");
}
//Include the required files.
require_once("model/user.php");
require_once("model/coworker.php");
require_once("model/shift_pattern.php");
require_once("model/shift_preset.php");
require_once("php/calendar_functions.php");
//Get the current month and year
$month = date("F");
$year = date("Y");
//Create a new user object
$user = Coworker::from_id($_GET['ID']);
$viewer = new User();
//Create a new shift pattern object
$shift_pattern = new ShiftPattern($user->get_id());
//Check that the coworker is accepted.
$accepted = $user->is_accepted($viewer->get_id());
//If the user is looking at their page then redirect to the calendar.
if($user->get_id() == $viewer->get_id()){
header("Location: Calendar");
}
?><file_sep><?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('./controllers/calendar_controller.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Shift Planner - Calendar</title>
<meta name="description" content="A shift planner for people who work shifts.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/main.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<noscript>
<div class="container-fluid" id="NoScriptError">
<h4><span class="glyphicon glyphicon-warning-sign"></span> Please enable javascript for a better experience!</h4>
</div>
</noscript>
<?php include_once("navigation.php"); ?>
<div class="container" id="calendar-container">
<div class="row">
<h5 class="text-center">
<a href="#" class="pull-left" id="cal-prev">Previous</a>
<span id="cal-title"><?php printf("%s %s", $month, $year); ?></span>
<a href="#" class="pull-right" id="cal-next">Next</a>
</h5>
</div>
<div class="row">
<div class="table-responsive">
<table class="table table-bordered" id="calendar-table">
</table>
</div>
</div>
<div class="row">
<form method="post" id="PatternForm">
<h3>
Shift Pattern <span class="glyphicon glyphicon-info-sign" data-toggle="tooltip" data-placement="right" title="List your shifts startng from the 1st of January until it repeats. You can edit individual shifts in the calendar above."></span>
</h3>
<div id="pattern-container">
<!-- <div class="shift-section">
<div class="info-bar">2</div>
<div class="body">XX</div>
</div> -->
<?php
foreach ($shift_pattern->get_array() as $id) {
get_pattern_section($id);
}
?>
<div class="shift-section" id="plus" style="cursor:pointer;">
<div class="info-bar"> </div>
<div class="body">Add</div>
</div>
</div>
<button type="submit" class="btn btn-default" style="margin:10px;">Update</button>
<a href="Calendar?Clear" class="btn btn-default">Clear</a>
</form>
</div>
</div>
<div class="modal fade" id="Calendar-Modal" tabindex="-1" role="dialog" aria-labelledby="Calendar-Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="Calendar-Label">Edit Shift</h4>
</div>
<div class="modal-body" id="Calendar-Modal-Body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="SaveButton">Save</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/calendar.js"></script>
</body>
</html>
<file_sep><?php
require_once("database.php");
require_once("user.php");
//A class which stores data about shift presets and allows interaction with the database.
class ShiftPreset{
//Private variables
private $PresetID; //The preset ID
private $PresetKey; //The preset key
private $PresetName; //The shift name
private $PresetStart; //The shift start time
private $PresetEnd; //The shift end time
private $UserID; //The user ID who created it.
private $Loaded = false; //A boolean which indicates that the user has been loaded from the database.
/*
Public constructor which sets the private variables of a shift preset.
1. Sets the private variables given as parameters.
*/
function __construct($preset_id, $key, $name, $start, $end, $user_id, $loaded){
$this->PresetID = $preset_id; //1
$this->PresetKey = $key;
$this->PresetName = $name;
$this->PresetStart = $start;
$this->PresetEnd = $end;
$this->UserID = $user_id;
$this->Loaded = $loaded;
}
/*
A static function which loads a shift preset from the database. The parameters are the field id and the user id.
1. Create a new database connection.
2. Prepare the statement to call the GET_SHIFT_PRESET stored procedure.
3. Bind the parameters to the stored procedure.
4. Set the fetch mode to assoc so that an associative array is returned.
5. Execute the stored procedure.
6. Fetch the first row.
7. Return a new ShiftPreset object.
*/
public static function create_new_from_id($preset_id, $user_id){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_SHIFT_PRESET(:preset_id, :user_id)"); //2
$stmt->bindParam(':preset_id', $preset_id); //3
$stmt->bindParam(':user_id', $user_id);
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$row = $stmt->fetch(); //6
return new ShiftPreset($preset_id, $row['PresetKey'], $row['PresetName'], $row['PresetStartTime'], $row['PresetEndTime'], $user_id, $stmt->rowCount() == 1); //7
}
/*
A static function to create a new shift preset. The parameters are the key, name, start time, end time and user id.
1. Create a new database connection.
2. Create a statement to call the ADD_SHIFT_PRESET stored procedure.
3. Bind the parameters to the statement.
4. Execute the statement.
*/
public static function create_shift_preset($key, $name, $start, $end, $user){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL ADD_SHIFT_PRESET(:key, :name, :start, :end, :id)"); //2
$stmt->bindParam(':key', $key); //3
$stmt->bindParam(':name', $name);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':id', $user->get_id());
$stmt->execute(); //4
}
/*
A static function to load all the shift presets. The parameter is the current user.
1. Create an empty array to store all the presets.
2. Get the user id.
3. Create a new database connection.
4. Prepare a new statement to call the GET_ALL_SHIFT_PRESET stored procedure.
5. Bind the parameters to the statement.
6. Set the fetch mode to assoc to return an associative array.
7. Execute the statement.
8. Loop through each record.
9. Add the record to the array.
10. Return the presets array.
*/
public static function load_all($user){
$presets = []; //1
$user_id = $user->get_id(); //2
$conn = db_connect(); //3
$stmt = $conn->prepare("CALL GET_ALL_SHIFT_PRESET(:id)"); //4
$stmt->bindParam(':id', $user_id); //5
$stmt->setFetchMode(PDO::FETCH_ASSOC); //6
$stmt->execute(); //7
foreach ($stmt->fetchAll() as $row) { //8
$presets[] = new ShiftPreset($row['PresetID'], $row['PresetKey'], $row['PresetName'], $row['PresetStartTime'], $row['PresetEndTime'], $user_id, true); //9
}
return $presets; //10
}
/*
A static function to load all the shift presets as an associative array where the index is the preset ID. The parameter is the current user.
1. Create an empty array to store all the presets.
2. Get the user id.
3. Create a new database connection.
4. Prepare a new statement to call the GET_ALL_SHIFT_PRESET stored procedure.
5. Bind the parameters to the statement.
6. Set the fetch mode to assoc to return an associative array.
7. Execute the statement.
8. Loop through each record.
9. Add the record to the array at the index of the preset ID.
10. Return the presets array.
*/
public static function load_all_assoc($user){
$presets = []; //1
$user_id = $user->get_id(); //2
$conn = db_connect(); //3
$stmt = $conn->prepare("CALL GET_ALL_SHIFT_PRESET(:id)"); //4
$stmt->bindParam(':id', $user_id); //5
$stmt->setFetchMode(PDO::FETCH_ASSOC); //6
$stmt->execute(); //7
foreach ($stmt->fetchAll() as $row) { //8
$presets[$row['PresetID']] = new ShiftPreset($row['PresetID'], $row['PresetKey'], $row['PresetName'], $row['PresetStartTime'], $row['PresetEndTime'], $user_id, true); //9
}
return $presets; //10
}
/*
A public function to edit the current shift presets. The parameters are the new key, name, start time and end time.
1. If the preset is loaded.
2. Create a new database connection.
3. Prepare a new statement to call the EDIT_SHIFT_PRESET stored procedure.
4. Bind the parameters.
5. Execute the statement.
*/
public function edit($key, $name, $start, $end){
if($this->Loaded){ //1
$conn = db_connect(); //2
$stmt = $conn->prepare("CALL EDIT_SHIFT_PRESET(:key, :name, :start, :end, :pid, :uid)"); //3
$stmt->bindParam(':key', $key); //4
$stmt->bindParam(':name', $name);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':uid', $this->UserID);
$stmt->bindParam(':pid', $this->PresetID);
$stmt->execute(); //5
}
}
/*
A public function to delete the current preset.
1. If the preset is loaded.
2. Create a new database connection.
3. Prepare a new statement to call the DEL_SHIFT_PRESET stored procedure.
4. Bind the parameters.
5. Execute the statement.
*/
public function delete(){
if($this->Loaded){ //1
$conn = db_connect(); //2
$stmt = $conn->prepare("CALL DEL_SHIFT_PRESET(:pid, :uid)"); //3
$stmt->bindParam(':pid', $this->PresetID); //4
$stmt->bindParam(':uid', $this->UserID);
$stmt->execute(); //5
}
}
//Getter functions which return private variables.
public function get_preset_id(){
return $this->PresetID;
}
public function get_key(){
return $this->PresetKey;
}
public function get_name(){
return $this->PresetName;
}
public function get_start(){
return $this->PresetStart;
}
public function get_end(){
return $this->PresetEnd;
}
public function get_user_id(){
return $this->UserID;
}
public function is_loaded(){
return $this->Loaded;
}
}
?><file_sep><?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once("./controllers/index_controller.php");
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Shift Planner</title>
<meta name="description" content="A shift planner for people who work shifts.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/main.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<noscript>
<div class="container-fluid" id="NoScriptError">
<h4><span class="glyphicon glyphicon-warning-sign"></span> Please enable javascript for a better experience!</h4>
</div>
</noscript>
<div class="container">
<h1 id="Logo">Shift Planner</h1>
</div>
<div class="container" id="LogRegContainer">
<?php
//If there is errors.
if(count($errors) > 0){
//Display the error alert
echo '<div class="alert alert-danger"><ul>';
//Display each error
foreach ($errors as $error) {
printf('<li>%s</li>', $error);
}
echo '</ul></div>';
}
?>
<form method="post">
<div class="form-group">
<label for="Email">Email</label>
<input type="email" name="Email" class="form-control" id="Email" placeholder="Enter Email" required value="<?php echo (isset($_POST['Email']))?$_POST['Email']:""; ?>">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="<PASSWORD>" name="Password" class="form-control" id="Password" placeholder="Enter Password" required value="<?php echo (isset($_POST['Password']))?$_POST['Password']:""; ?>">
</div>
<div class="btn-group btn-group-justified">
<div class="btn-group"><button type="submit" class="btn btn-default" formaction="./?login">Login</button></div>
<div class="btn-group"><button type="submit" class="btn btn-default" formaction="./?reg">Register</button></div>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
</body>
</html>
<file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/job_preset.php");
//If there is post variables
if(count($_POST) > 0){
//Get the posted variables
$pid = trim($_POST['ID']);
$name = trim($_POST['Name']);
$desc = trim($_POST['Desc']);
//Create a new user object
$user = new User();
//Load the job preset from the ID
$job_preset = JobPreset::create_new_from_id($pid, $user->get_id());
//Call the validate_edit_job_preset function.
$errors = validate_edit_job_preset($job_preset, $name, $desc, $user);
//Return the errors
echo json_encode($errors);
}
?><file_sep><?php
//Include the database functions
require_once("database.php");
//A class which stores data about a user and has functions for creating and updating users etc.
class User{
//Private variables
private $UserID; //The user ID stored in the session used to interact with the database.
private $UserFirstName; // The user's first name from the database.
private $UserLastName; // The user's last name from the database.
private $UserCompany; // The user's company from the database.
private $UserEmail; // The user's email from the database.
private $UserPassword; // The user's password from the database.
private $UserDefinedFields; // The user's defined fields from the database.
private $Loaded = false; // A boolean which indicates that the user has been loaded from the database.
/*
Public constructor which loads the user from the database.
1. Get and store the user's ID from the session variable.
2. Create a database connection so the database can be interacted with.
3. Prepare a statement to run the LOAD_USER stored procedure.
4. Bind the ID to the statement.
5. Run the stored procedure.
6. If there is one record returned from the database.
7. Fetch the first record from the statement.
8. Store the variables from the database result.
9. Change the loaded variable to true to indicate the the data has been loaded correctly.
10. Loads the user defined info fields from the database.
*/
function __construct(){
$this->UserID = $_SESSION['UserID'];//1
$conn = db_connect();//2
$stmt = $conn->prepare("CALL LOAD_USER(:ID)");//3
$stmt->bindParam(":ID", $this->UserID);//4
$stmt->execute();//5
if($stmt->rowCount() == 1){//6
$result = $stmt->fetch();//7
$this->UserFirstName = $result['UserFirstName'];//8
$this->UserLastName = $result['UserSurname'];
$this->UserCompany = $result['UserCompany'];
$this->UserEmail = $result['UserEmail'];
$this->UserPassword = $result['UserPassword'];
$this->Loaded = true;//9
$this->load_user_defined_fields();//10
}
}
/*
A static function which creates a new user. The parameters are the users email and password which should have already been validated.
1. Create a database connection.
2. Prepare a statement to run the CREATE_USER stored procedure.
3. Bind the parameters to the statement.
4. Run the stored procedure.
*/
public static function create_user($email, $password){
$conn = db_connect();//1
$stmt = $conn->prepare("CALL CREATE_USER(:email, :password)");//2
$stmt->bindParam(":email", $email);//3
$stmt->bindParam(":password", $password);
$stmt->execute();//4
}
/*
A static function which checks the email to see if it is already being used.
1. Create a database connection.
2. Prepare the statement to run the USER_COUNT stored procedure.
3. Bind the email parameter to the statement.
4. Run the stored procedure.
5. Fetch the first column from the result.
6. If there it is 0 then there is no records and it returns true otherwise it returns false.
*/
public static function check_email($email){
$conn = db_connect();//1
$stmt = $conn->prepare("CALL USER_COUNT(:email)");//2
$stmt->bindParam(":email", $email);//3
$stmt->execute();//4
if($stmt->fetchColumn(0) == 0){//5
//6
return true;
}
else{
return false;
}
}
/*
A static function to login the user given an email and password.
1. Creates a database connection.
2. Prepares a statement to run the LOGIN stored procedure.
3. Binds the email to the statement.
4. Runs the stored procedure.
5. Fetches the first row from the result.
6. Stores the ID and password from the result.
7. If the password is correct. Has to use the php crypt function for encryption.
8. Sets the session variable to the ID and returns true to indicate that the password was correct.
9. Returns false if the password was incorrect.
*/
public static function login($email, $password){
$conn = db_connect();//1
$stmt = $conn->prepare("CALL LOGIN(:email)");//2
$stmt->bindParam(":email", $email);//3
$stmt->execute();//4
$result = $stmt->fetch();//5
$id = $result["UserID"];//6
$pass = $result["UserPassword"];
if(hash_equals($pass, crypt($password, $pass))){//7
$_SESSION['UserID'] = $id;//8
return true;
}
else{
return false;//9
}
}
/*
A public function to update the user's personal information. The parameters are the new first name, last name, email and company.
1. Create a new database connection.
2. Prepare a new statement to call the UPDATE_PERSONAL stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public function update_personal($first_name, $last_name, $email, $company){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL UPDATE_PERSONAL(:fname, :lname, :email, :company, :id)"); //2
$stmt->bindParam(":fname", $first_name); //3
$stmt->bindParam(":lname", $last_name);
$stmt->bindParam(":email", $email);
$stmt->bindParam(":company", $company);
$stmt->bindParam(":id", $this->UserID);
$stmt->execute(); //4
}
/*
A public function to update the password. The parameter is the new password.
1. Create a new database connection.
2. Prepare a new statement to call the UPDATE_PASSWORD stored procedure.
3. Bind the parameters to the statement.
4. Execute the statement.
*/
public function update_password($password){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL UPDATE_PASSWORD(:id, :password)"); //2
$stmt->bindParam(":password", $password); //3
$stmt->bindParam(":id", $this->UserID);
$stmt->execute(); //4
}
/*
A public function to add extra information. The parameters are the name of the extra information, the value and a private flag.
1. Create a new database connection.
2. Prepare a new statement to call the ADD_EXTRA_INFO stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public function add_extra_info($name, $value, $private){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL ADD_EXTRA_INFO(:name, :value, :id, :private)"); //2
$stmt->bindParam(":name", $name); //3
$stmt->bindParam(":value", $value);
$stmt->bindParam(":private", $private);
$stmt->bindParam(":id", $this->UserID);
$stmt->execute(); //4
}
/*
A public function to edit extra information. The parameters are the name of the extra information, the new value and the private flag.
1. Create a new database connection.
2. Prepare a new statement to call the EDIT_EXTRA_INFO stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public function edit_extra_info($name, $value, $private){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL EDIT_EXTRA_INFO(:id, :name, :value, :private)"); //2
$stmt->bindParam(":name", $name); //3
$stmt->bindParam(":value", $value);
$stmt->bindParam(":private", $private);
$stmt->bindParam(":id", $this->UserID);
$stmt->execute(); //4
}
/*
A public function to check if the key for an extra information record is already taken. The parameter is the name of the record.
1. Create a new database connection.
2. Prepare a new statement to call the CHECK_EXTRA_INFO_NAME stored procedure.
3. Bind the parameters.
4. Execute the statement.
5. Fetch the first column and if it equals 0 return true.
6. Return false if it doesn't equal 0.
*/
public function extra_info_key_free($name){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL CHECK_EXTRA_INFO_NAME(:name, :id)"); //2
$stmt->bindParam(":name", $name); //3
$stmt->bindParam(":id", $this->UserID);
$stmt->execute(); //4
if($stmt->fetchColumn(0) == 0){ //5
return true;
}
else{
return false; //6
}
}
/*
A public function to load all the user defined fields.
1. Create a new database connection.
2. Prepare a new statement to call the GET_EXTRA_USER_INFO stored procedure.
3. Bind the parameters.
4. Set the fetch mode to assoc.
5. Execute the statement.
6. Set the user defined field variable to the array returned.
*/
public function load_user_defined_fields(){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL GET_EXTRA_USER_INFO(:id)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->setFetchMode(PDO::FETCH_ASSOC); //4
$stmt->execute(); //5
$this->UserDefinedFields = $stmt->fetchAll(); //6
}
/*
A public function to delete a user defined field. The parameter is the name of the field to be deleted.
1. Create a new database connection.
2. Prepare a new statement to call the DEL_EXTRA_USER_INFO stored procedure.
3. Bind the parameters.
4. Execute the statement.
*/
public function delete_user_defined_field($name){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL DEL_EXTRA_USER_INFO(:id, :name)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->bindParam(":name", $name);
$stmt->execute(); //4
}
/*
A public function to get the number of holiday days in the current year.
1. Create a new connection.
2. Prepare a statement to call the COUNT_HOLIDAYS stored procedure.
3. Bind the parameter.
4. Execute the statement.
5. Return the first column.
*/
public function get_holiday_days(){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL COUNT_HOLIDAYS(:id)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->execute(); //4
return $stmt->fetchColumn(0); //5
}
/*
A public function to get the number of shift meeting days in the current year.
1. Create a new connection.
2. Prepare a statement to call the COUNT_SHIFT_MEETINGS stored procedure.
3. Bind the parameter.
4. Execute the statement.
5. Return the first column.
*/
public function get_shift_meetings(){
$conn = db_connect(); //1
$stmt = $conn->prepare("CALL COUNT_SHIFT_MEETINGS(:id)"); //2
$stmt->bindParam(":id", $this->UserID); //3
$stmt->execute(); //4
return $stmt->fetchColumn(0); //5
}
//Getter functions which return private variables
public function get_id(){
return $this->UserID;
}
public function get_first_name(){
return $this->UserFirstName;
}
public function get_last_name(){
return $this->UserLastName;
}
public function get_company(){
return $this->UserCompany;
}
public function get_email(){
return $this->UserEmail;
}
public function get_password(){
return $this->UserPassword;
}
public function is_loaded(){
return $this->Loaded;
}
public function get_user_defined_fields(){
return $this->UserDefinedFields;
}
}
?><file_sep><?php
//Start the session.
session_start();
//Include the required files.
require_once("../model/coworker.php");
require_once("../model/shift_pattern.php");
require_once("../model/shift_preset.php");
require_once("../model/job_preset.php");
require_once("../model/shift_defined_field.php");
require_once("../model/shift_defined_value.php");
require_once("../model/shift.php");
//If there is post variables.
if(count($_POST) > 0):
//Create a new coworker object.
$user = Coworker::from_id($_POST['ID']);
//Get the shift id.
$shift_id = $_POST['ShiftID'];
//Get the preset id.
$preset_id = $_POST['PresetID'];
//Get the date.
$date = $_POST['ShiftDate'];
$shift_text = "-";
$job_text = "-";
//Create an empty string for the notes.
$notes = "";
//Create a shift meeting boolean set to false.
$shift_meeting = false;
//Create a holiday boolean set to false.
$holiday = false;
//Create an empty array for the user defined values.
$user_defined_values = [];
//Load all the shift presets.
$presets = ShiftPreset::load_all_assoc($user);
//Load all the job presets.
$jobs = JobPreset::load_all_assoc($user);
//Load all the user defined fields.
$user_defined_fields = ShiftDefinedField::load_all($user);
//If the shift id is greater than 0.
if($shift_id > 0){
//Load the shift object.
$shift_obj = Shift::load_from_id($shift_id);
//Set the variables to those from the shift object.
$shift_text = isset($presets[$shift_obj->get_preset_id()])?$presets[$shift_obj->get_preset_id()]->get_key():"-";
$job_text = isset($jobs[$shift_obj->get_job_id()])?$jobs[$shift_obj->get_job_id()]->get_name():"-";
$notes = $shift_obj->get_notes();
$shift_meeting = $shift_obj->is_shift_meeting();
$holiday = $shift_obj->is_holiday();
$user_defined_values = $shift_obj->get_user_defined_values();
}
//If the preset id is greater than 0 then set the shift to the preset id.
else if($preset_id > 0){
$shift_text = isset($presets[$preset_id])?$presets[$preset_id]->get_key():"-";
}
?>
<table class="table table-striped">
<tbody>
<tr>
<td>Shift</td>
<td><?php echo $shift_text; ?></td>
</tr>
<tr>
<td>Job</td>
<td><?php echo $job_text; ?></td>
</tr>
<?php
//Print the html for the user defined fields.
foreach ($user_defined_fields as $field) {
$value = "";
if(isset($user_defined_values[$field->get_field_id()])) $value = $user_defined_values[$field->get_field_id()]->get_value();
printf('<tr><td>%s</td><td>%s</tr>', $field->get_name(), $value);
}
?>
<tr>
<td>Notes</td>
<td><?php echo $notes; ?></td>
</tr>
<tr>
<td>Holiday</td>
<td><?php echo (($holiday)?'<span class="glyphicon glyphicon-ok"></span>':""); ?></td>
</tr>
<tr>
<td>Shift Meeting</td>
<td><?php echo (($shift_meeting)?'<span class="glyphicon glyphicon-ok"></span>':""); ?></td>
</tr>
</tbody>
</table>
<?php
endif;
?><file_sep><?php
//Starts the session.
session_start();
//Unsets all session variables.
session_unset();
//Destroys the session.
session_destroy();
//Redirects the user to the index page.
header("Location: ../");
?><file_sep><?php
//Start the session
session_start();
if(!isset($_SESSION['UserID'])){
header("Location: ./");
}
//Include the required files.
require_once("model/user.php");
require_once("model/shift_pattern.php");
require_once("model/shift_preset.php");
require_once("model/job_preset.php");
require_once("model/shift.php");
//Create a new user object.
$user = new User();
//Get the shift pattern for that user.
$pattern = new ShiftPattern($user->get_id());
//Get the shift presets for that user is an associative array.
$shift_presets = ShiftPreset::load_all_assoc($user);
//Get the job presets for that user in an associative array.
$job_presets = JobPreset::load_all_assoc($user);
//Create an empty array to hold all the data.
$summary = [];
//Loop over the code 7 times.
for($i = 0; $i<7; $i++){
//Add the Date and SQLDate to the array.
$summary[$i] = ["Date"=>date("d/m/Y", time() + 86400 * $i), "SQLDate"=>date("n/j/Y", time() + 86400 * $i)];
//Get the pattern id for the current day.
$pattern_id = $pattern->get_shift_preset_id(date("z", time() + 86400 * $i));
//Get the shift for that day.
$shift = Shift::load_from_date(date("n/j/Y", time() + 86400 * $i), $user->get_id());
//Get the shift preset for that day.
$preset = $shift_presets[$pattern_id];
//If the shift is set.
if(isset($shift)){
//Set the shift ID, preset ID, shift, job, shift meeting and holiday with the data.
$summary[$i]["ShiftID"] = $shift->get_shift_id();
$summary[$i]["PresetID"] = $pattern_id;
$summary[$i]["Shift"] = $shift_presets[$shift->get_preset_id()]->get_key();
$summary[$i]["Job"] = isset($job_presets[$shift->get_job_id()])?($job_presets[$shift->get_job_id()]->get_name()):'-';
$summary[$i]["SM"] = ($shift->is_shift_meeting() && !$shift->is_holiday())?'sm':'';
$summary[$i]["Hol"] = ($shift->is_holiday())?'hol':'';
}
//If the preset is set.
else if(isset($preset)){
//Set the shift ID, preset ID, shift, job, shift meeting and holiday with the data.
$summary[$i]["ShiftID"] = -1;
$summary[$i]["PresetID"] = $pattern_id;
$summary[$i]["Shift"] = $preset->get_key();
$summary[$i]["Job"] = "-";
$summary[$i]["SM"] = '';
$summary[$i]["Hol"] = '';
}
//If the shift isn't set and the preset isn't set.
else{
//Set the shift ID, preset ID, shift, job, shift meeting and holiday.
$summary[$i]["ShiftID"] = -1;
$summary[$i]["PresetID"] = -1;
$summary[$i]["Shift"] = "No Data";
$summary[$i]["Job"] = "-";
$summary[$i]["SM"] = '';
$summary[$i]["Hol"] = '';
}
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
//If there is posted variables
if(count($_POST) > 0){
//Get the variables
$current = trim($_POST['Current']);
$new = trim($_POST['New']);
$retype = trim($_POST['NewRetype']);
//Create a new user
$User = new User();
//Call the validate_password function.
$errors = validate_password($current, $new, $retype, $User);
//Print the errors in json format.
echo json_encode($errors);
}
?><file_sep><?php
//Start the session.
session_start();
//Include the required files.
require_once("../model/user.php");
require_once("../model/shift_preset.php");
require_once("calendar_functions.php");
//Call the function to get the pattern section.
get_pattern_section();
?><file_sep><?php
//Start the session
session_start();
//Import require files
require_once("./settings_functions.php");
require_once("../model/user.php");
//If there are post variables
if(count($_POST) > 0){
//Load the post variables
$name = trim($_POST['Name']);
$value = trim($_POST['Value']);
$private = filter_var($_POST['Private'], FILTER_VALIDATE_BOOLEAN);
//Create a new user object
$User = new User();
//Call the validate_extra_information function
$errors = validate_extra_information($name, $value, $private, $User);
//Return the errors in json format.
echo json_encode($errors);
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/shift_preset.php");
//If there is posted variables
if(count($_POST) > 0){
//Get the variables
$pid = trim($_POST['ID']);
$key = trim($_POST['Key']);
$name = trim($_POST['Name']);
$start = trim($_POST['Start']);
$end = trim($_POST['End']);
//Create a new user object
$user = new User();
//Get the shift preset from the id
$shift_preset = ShiftPreset::create_new_from_id($pid, $user->get_id());
//Call the validate_edit_shift_presets function
$errors = validate_edit_shift_presets($shift_preset, $key, $name, $start, $end, $user);
//Return the errors
echo json_encode($errors);
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("../model/user.php");
require_once("../model/job_preset.php");
//If the ID is set
if(isset($_GET['ID'])){
//Get the ID
$id = trim($_GET['ID']);
//Create a new user
$user = new User();
//Get the job preset from the ID
$job_preset = JobPreset::create_new_from_id($id, $user->get_id());
//If the field loads delete the field
if($job_preset->is_loaded()){
$job_preset->delete();
}
//If not sent with AJAX then redirect to settings page
if(!isset($_GET['Ajax'])){
header("Location: ../Settings");
}
}
?><file_sep><?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('./controllers/settings_controller.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Shift Planner - Settings</title>
<meta name="description" content="A shift planner for people who work shifts.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/main.css">
<link rel="stylesheet" href="./css/webtoasts.css">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<noscript>
<div class="container-fluid" id="NoScriptError">
<h4><span class="glyphicon glyphicon-warning-sign"></span> Please enable javascript. It is required for this page!</h4>
</div>
</noscript>
<?php include_once("navigation.php"); ?>
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h3>Personal Information</h3>
<?php
if(isset($_POST['Form']) && $_POST['Form'] == "Personal"){
//If there is errors and the form has been submitted.
if(count($errors) > 0){
//Display the error alert
echo '<div class="alert alert-danger"><ul>';
//Display each error
foreach ($errors as $error) {
printf('<li>%s</li>', $error);
}
echo '</ul></div>';
}
}
if(count($errors) == 0 && isset($_GET['Personal'])){
echo '<div class="alert alert-success">Your personal information has been updated.</div>';
}
?>
<div class="alert hidden" id="Personal-Alert">
</div>
<form class="form-horizontal" method="post" action="Settings" id="Personal-Form">
<input type="hidden" value="Personal" name="Form">
<div class="form-group">
<label for="Personal-FName" class="col-sm-3 control-label">First Name</label>
<div class="col-sm-9"><input type="text" class="form-control" id="Personal-FName" name="FName" value="<?php echo (isset($_POST['Form']) && $_POST['Form'] == "Personal")? $_POST['FName'] : $User->get_first_name(); ?>"></div>
</div>
<div class="form-group">
<label for="Personal-LName" class="col-sm-3 control-label">Last Name</label>
<div class="col-sm-9"><input type="text" class="form-control" id="Personal-LName" name="LName" value="<?php echo (isset($_POST['Form']) && $_POST['Form'] == "Personal")? $_POST['LName'] : $User->get_last_name(); ?>"></div>
</div>
<div class="form-group">
<label for="Personal-Email" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9"><input type="text" class="form-control" id="Personal-Email" name="Email" value="<?php echo (isset($_POST['Form']) && $_POST['Form'] == "Personal")? $_POST['Email'] : $User->get_email(); ?>"></div>
</div>
<div class="form-group">
<label for="Personal-Company" class="col-sm-3 control-label">Company</label>
<div class="col-sm-9"><input type="text" class="form-control" id="Personal-Company" name="Company" value="<?php echo (isset($_POST['Form']) && $_POST['Form'] == "Personal")? $_POST['Company'] : $User->get_company(); ?>"></div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button class="btn btn-default pull-right">Update</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h3>Change Password</h3>
<?php
if(isset($_POST['Form']) && $_POST['Form'] == "Password"){
//If there is errors and the form has been submitted.
if(count($errors) > 0){
//Display the error alert
echo '<div class="alert alert-danger"><ul>';
//Display each error
foreach ($errors as $error) {
printf('<li>%s</li>', $error);
}
echo '</ul></div>';
}
}
if(count($errors) == 0 && isset($_GET['Password'])){
echo '<div class="alert alert-success">Your password has been updated.</div>';
}
?>
<div class="alert hidden" id="Password-Alert"></div>
<form class="form-horizontal" action="Settings" method="post" id="Password-Form">
<input type="hidden" value="Password" name="Form">
<div class="form-group">
<label for="Password-Current" class="col-sm-3 control-label">Current Password</label>
<div class="col-sm-9"><input type="password" class="form-control" id="Password-Current" name="Current" <?php if(isset($_POST['Form']) && $_POST['Form'] == "Password") printf('value="%s"', $_POST['Current']); ?>></div>
</div>
<div class="form-group">
<label for="Password-New" class="col-sm-3 control-label">New Password</label>
<div class="col-sm-9"><input type="password" class="form-control" id="Password-New" name="New" <?php if(isset($_POST['Form']) && $_POST['Form'] == "Password") printf('value="%s"', $_POST['New']); ?>></div>
</div>
<div class="form-group">
<label for="Password-NewRetype" class="col-sm-3 control-label">Retype New Password</label>
<div class="col-sm-9"><input type="password" class="form-control" id="Password-NewRetype" name="NewRetype" <?php if(isset($_POST['Form']) && $_POST['Form'] == "Password") printf('value="%s"', $_POST['NewRetype']); ?>></div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button class="btn btn-default pull-right">Update</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h3>Extra Information <span class="glyphicon glyphicon-info-sign" data-toggle="tooltip" data-placement="right" title="These are key/value pairs for extra personal information."></span></h3>
<?php
if(isset($_POST['Form']) && $_POST['Form'] == "ExtraInformation"){
//If there is errors and the form has been submitted.
if(count($errors) > 0){
//Display the error alert
echo '<div class="alert alert-danger"><ul>';
//Display each error
foreach ($errors as $error) {
printf('<li>%s</li>', $error);
}
echo '</ul></div>';
}
}
?>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Options</th>
</tr>
</thead>
<tbody id="ExtraInformation-Table">
<?php
load_extra_information($User);
?>
</tbody>
</table>
</div>
<button class="btn btn-default pull-right" data-toggle="modal" data-target="#ExtraInformation-Modal">Add</button>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h3>Shift Presets <span class="glyphicon glyphicon-info-sign" data-toggle="tooltip" data-placement="right" title="These are the different shifts that you work."></span></h3>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Key</th>
<th>Name</th>
<th>Start Time</th>
<th>End Time</th>
<th>Options</th>
</tr>
</thead>
<tbody id="ShiftPresets-Table">
<tr class="warning no-data-warning">
<?php
load_shift_presets($User);
?>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-default pull-right" data-toggle="modal" data-target="#ShiftPresets-Modal">Add</button>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h3>Job Presets <span class="glyphicon glyphicon-info-sign" data-toggle="tooltip" data-placement="right" title="These are the different jobs that you do at work."></span></h3>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Options</th>
</tr>
</thead>
<tbody id="JobPresets-Table">
<?php
load_job_presets($User);
?>
</tbody>
</table>
</div>
<button class="btn btn-default pull-right" data-toggle="modal" data-target="#JobPresets-Modal">Add</button>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h3>Extra Shift Information <span class="glyphicon glyphicon-info-sign" data-toggle="tooltip" data-placement="right" title="This is extra information which is needed for a shift. These are set when you add or edit a shift."></span></h3>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
<tbody id="ExtraShiftInfo-Table">
<?php load_extra_shift_info($User); ?>
</tbody>
</table>
</div>
<button class="btn btn-default pull-right" data-toggle="modal" data-target="#ExtraShiftInfo-Modal">Add</button>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<p><b>Holiday Days Booked</b>: <?php echo $User->get_holiday_days(); ?></p>
<p><b>Shift Meetings Booked</b>: <?php echo $User->get_shift_meetings(); ?></p>
</div>
</div>
</div>
<div class="modal fade" id="ExtraInformation-Modal" tabindex="-1" role="dialog" aria-labelledby="ExtraInformation-Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="ExtraInformation-Label">Extra Information</h4>
</div>
<div class="modal-body">
<div class="alert hidden" id="ExtraInformation-Alert"></div>
<form id="ExtraInformation-Form" action="Settings" method="post">
<input type="hidden" value="ExtraInformation" name="Form">
<input type="hidden" name="Edit" value="0" id="ExtraInformation-Edit">
<div class="form-group"><label for="ExtraInformation-Name" class="control-label">Name</label><input type="text" id="ExtraInformation-Name" name="Name" class="form-control"></div>
<div class="form-group"><label for="ExtraInformation-Value" class="control-label">Value</label><input type="text" id="ExtraInformation-Value" name="Value" class="form-control"></div>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="checkbox" autocomplete="off" id="ExtraInformation-Private" name="Private" value="1"> Private
</label>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary" form="ExtraInformation-Form">Save</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="ShiftPresets-Modal" tabindex="-1" role="dialog" aria-labelledby="ShiftPresets-Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="ShiftPresets-Label">Shift Presets</h4>
</div>
<div class="modal-body">
<div class="alert hidden" id="ShiftPresets-Alert"></div>
<form id="ShiftPresets-Form" action="Settings" method="post">
<input type="hidden" name="Edit" value="0" id="ShiftPresets-Edit">
<div class="form-group"><label for="ShiftPresets-Key" class="control-label">Key</label><input type="text" id="ShiftPresets-Key" class="form-control"></div>
<div class="form-group"><label for="ShiftPresets-Name" class="control-label">Name</label><input type="text" id="ShiftPresets-Name" class="form-control"></div>
<div class="form-group"><label for="ShiftPresets-Start" class="control-label">Start Time</label><input type="time" id="ShiftPresets-Start" class="form-control"></div>
<div class="form-group"><label for="ShiftPresets-End" class="control-label">End Time</label><input type="time" id="ShiftPresets-End" class="form-control"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary" form="ShiftPresets-Form">Save</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="JobPresets-Modal" tabindex="-1" role="dialog" aria-labelledby="JobPresets-Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="JobPresets-Label">Job Presets</h4>
</div>
<div class="modal-body">
<div class="alert hidden" id="JobPresets-Alert"></div>
<form id="JobPresets-Form" action="Settings" method="post">
<input type="hidden" name="Edit" value="0" id="JobPresets-Edit">
<div class="form-group"><label for="JobPresets-Name" class="control-label">Name</label><input type="text" id="JobPresets-Name" class="form-control"></div>
<div class="form-group"><label for="JobPresets-Desc" class="control-label">Description</label><input type="text" id="JobPresets-Desc" class="form-control"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary" form="JobPresets-Form">Save</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="ExtraShiftInfo-Modal" tabindex="-1" role="dialog" aria-labelledby="ExtraShiftInfo-Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="ExtraShiftInfo-Label">Extra Shift Information</h4>
</div>
<div class="modal-body">
<div class="alert hidden" id="ExtraShiftInfo-Alert"></div>
<form id="ExtraShiftInfo-Form" action="Settings" method="post">
<input type="hidden" name="Edit" value="0" id="ExtraShiftInfo-Edit">
<div class="form-group"><label for="ExtraShiftInfo-Name" class="control-label">Name</label><input type="text" id="ExtraShiftInfo-Name" class="form-control"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary" form="ExtraShiftInfo-Form">Save</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/settings.js"></script>
<script src="js/webtoasts.js"></script>
</body>
</html>
<file_sep><?php
/*
A function to get the pattern section html for the shift pattern. The parameter is the selected id.
1. Create a new user object.
2. If the user is loaded.
3. Load all the shift presets for that user.
4. Print the html.
5. Loop over each preset and add the html for an option.
6. Print the html to close the tags.
*/
function get_pattern_section($default = -1){
$user = new User(); //1
if($user->is_loaded()){ //2
$presets = ShiftPreset::load_all($user); //3
echo '<div class="shift-section">'; //4
echo '<div class="info-bar"> </div>';
echo '<div class="body">';
echo '<select>';
echo '<option value="-1">-</option>';
foreach ($presets as $preset) { //5
printf('<option value="%s" %s>%s</option>', $preset->get_preset_id(), ($preset->get_preset_id() == $default)?"selected":"", $preset->get_key());
}
echo '</select>'; //6
echo '</div>';
echo '</div>';
}
}
?><file_sep><?php
//Start the session
session_start();
//Import the required files.
require_once("./settings_functions.php");
require_once("../model/user.php");
require_once("../model/shift_defined_field.php");
//Create a new user
$user = new User();
//Load the extra shift info.
load_extra_shift_info($user);
?><file_sep><?php
//Start the session
session_start();
//Import the required files
require_once("../model/user.php");
require_once("../model/shift_preset.php");
//If the ID is set
if(isset($_GET['ID'])){
//Get the ID
$id = trim($_GET['ID']);
//Create a new user
$user = new User();
//Get the shift preset from the ID
$shift_preset = ShiftPreset::create_new_from_id($id, $user->get_id());
//If the preset loads then delete it.
if($shift_preset->is_loaded()){
$shift_preset->delete();
}
//If not sent with AJAX redirect to the settings page
if(!isset($_GET['Ajax'])){
header("Location: ../Settings");
}
}
?> | fc58f686783df581e79de269d53429e0de83d572 | [
"JavaScript",
"PHP"
] | 54 | PHP | jamienet/ShiftPlanner | 09f69e4fa2af6af53fc48703064c5e892e36a6c1 | c6d75cbb49eb0d0c1e78915a862c15f5ffdf3946 |
refs/heads/master | <file_sep>###############################################################
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
import os
import re
import redis
import base64
import config
import zipfile
import hashlib
import logging
import requests
import tempfile
import subprocess
import jsonpickle
import semantic_version
from collections import OrderedDict
from distutils.dir_util import remove_tree
from github3 import login, GitHubError, utils
_log = logging.getLogger(__name__)
class RepoDetail(object):
"""
Basic structure to hold all desired repo details in cache
"""
def __init__(self, repo=None):
# These hold binary github objects
self.repo = repo
self.tags = {}
self.releases = {}
# These hold simple information
self.reponame = repo.name if repo else ""
self.description = repo.description if repo else ""
self.homepage = repo.homepage if repo else ""
self.owner = repo.owner if repo else ""
self.tagnames = {}
self.downloads = {}
self.newest_version = None
self.newest_zip = None
self.newest_tagname = None
self.addon_xml = None
def __getstate__(self):
d = self.__dict__
del d['repo']
del d['tags']
del d['releases']
return d
def __setstate__(self, d):
self.__dict__.update(d)
def repositories():
"""
Gets list of repository objects for each configured repository name
"""
_log.info("Getting configured repositories details...")
_repos = []
_github = login(token=config.github_personal_access_token)
url_re = re.compile('github\.com/(.*?)/(.*?)(?:\.git$|$)')
for repo_url in config.repositories:
repo_parts = re.findall(url_re, repo_url)
if repo_parts:
user, repo = repo_parts[0][0:2]
try:
github_repo = _github.repository(user,repo)
except GitHubError:
raise Exception("Github error: %s/%s"%(user, repo))
_repos.append(github_repo)
return _repos
def vers_from_tag(tagname):
tag_vers = None
tag_vers_match = re.findall(r'(\d+\.\d+\.\d+.*?) ?', tagname)
if tag_vers_match:
tag_vers = tag_vers_match[0]
return tag_vers
def repo_tags(repo):
"""
Parses all git tags on the repo for semantic version numbers
"""
tags = {}
for tag in repo.iter_tags():
name = tag.name
tag_vers = vers_from_tag(name)
if tag_vers:
tags[tag_vers] = tag
return tags
def repo_releases(repo, tags):
"""
finds matching release for each tag. Creates one if not available
"""
releases = {vers_from_tag(rel.tag_name) : rel for rel in repo.iter_releases()}
# for release in repo.iter_releases():
# name = release.tag_name
for vers, tag in tags.items():
if vers not in releases:
# create release
_log.warning('Generating new release for %s:%s' % (repo.name, tag.name))
release = repo.create_release(tag.name)
releases[vers] = release
return releases
def repo_downloads(repo, releases, tags):
"""
finds matching download for each release. Creates one if not available
"""
downloads = {}
# for release in repo.iter_releases():
# name = release.tag_name
for vers, release in releases.items():
download_url = None
download_asset = None
download_asset_name = repo.name + ".zip"
for asset in release.iter_assets():
if asset.name == download_asset_name:
download_asset = asset
break
if not download_asset:
# Create download... this will take a while
_log.warning('Generating new release download zip for %s:%s' % (repo.name, vers))
zip_url = tags[vers].zipball_url
temp_dir = tempfile.mkdtemp()
try:
zip_dlfile = os.path.join(temp_dir, download_asset_name)
_log.warning('downloading')
download(zip_url, zip_dlfile)
if os.path.exists(zip_dlfile):
_log.warning('extracting')
# outdir = extract(zip_dlfile)
outdir = os.path.splitext(zip_dlfile)[0]
subprocess.check_output(['/usr/bin/unzip', zip_dlfile, '-d', outdir])
contents = os.listdir(outdir)
_log.warning('renaming')
if len(contents) == 1 and os.path.isdir(os.path.join(outdir,contents[0])):
innerdir = contents[0]
newdir = os.path.join(outdir,innerdir)
if innerdir != repo.name:
os.rename(newdir, os.path.join(outdir,repo.name))
outdir = os.path.join(outdir,repo.name)
os.rename(zip_dlfile, zip_dlfile+".dl")
_log.warning('zipping')
zipdir(dirPath=outdir, zipFilePath=zip_dlfile, includeDirInZip=True, excludeDotFiles=True)
if os.path.exists(zip_dlfile):
with open(zip_dlfile, 'rb') as assetfile:
_log.warning('uploading')
download_asset = release.upload_asset(
content_type='application/zip, application/octet-stream',
name=download_asset_name,
asset=assetfile)
_log.warning('Finished new release download zip for %s:%s' % (repo.name, vers))
except:
_log.exception("zip_url: %s"%zip_url)
finally:
remove_tree(temp_dir)
if download_asset:
download_url = download_asset.browser_download_url
downloads[vers] = download_url
return downloads
def newest_repo_version(tags):
newest_version = None
newest_semvers = None
for entry in tags.keys():
try:
semvers = semantic_version.Version(entry)
if newest_semvers is None or (semvers > newest_semvers and not semvers.prerelease):
newest_version = entry
newest_semvers = semvers
except ValueError as ex:
_log.exception("invalid tag version (%s) from %s" % (entry, tags[entry][1]))
return newest_version, tags[newest_version]
def kodi_repos(repos):
"""
For all repositories in provided list, construct a RepoDetail container with details we need
"""
# Get list of repository objects and wrap in RepoDetail class
details = OrderedDict([
(repo.name, RepoDetail(repo)) for repo in sorted(repos, key=lambda r:r.name)
])
for repo_det in details.values():
# Get latest version
tags = repo_tags(repo_det.repo)
repo_det.tags = tags
repo_det.tagnames = {vers:tag.name for vers,tag in tags.items()}
releases = repo_releases(repo_det.repo, tags)
repo_det.releases = releases
downloads = repo_downloads(repo_det.repo, releases, tags)
repo_det.downloads = downloads
version, newest_tag = newest_repo_version(tags)
repo_det.newest_version = version
repo_det.newest_tagname = newest_tag.name
# Grab a copy of addon.xml from the latest version
addon_xml_handle = repo_det.repo.contents('addon.xml',repo_det.newest_tagname)
if addon_xml_handle.encoding == 'base64':
addon_xml = base64.b64decode(addon_xml_handle.content)
else:
addon_xml = addon_xml_handle.content
_log.warning('Unexpected encoding (%s) on file: %s' % (addon_xml_handle.encoding, addon_xml_handle.name))
repo_det.addon_xml = addon_xml
return details
def addons_xml(details):
"""
Generate kodi repo addons.xml with md5 hash
"""
# repo addons header
_addons_xml = u"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<addons>\n"
# add addon.xml from each addon verbatim
for repo_det in details.values():
xml = repo_det.addon_xml.rstrip()
if isinstance(xml, bytes):
xml = xml.decode()
if xml.startswith('<?xml'):
xml = xml[xml.index('\n'):]
_addons_xml += xml + u"\n\n"
# clean and add closing tag
_addons_xml = _addons_xml.strip() + u"\n</addons>\n"
_addons_xml_md5 = hashlib.md5(_addons_xml.encode()).digest()
return _addons_xml, _addons_xml_md5
def update_kodi_repos_redis():
"""
Generate details of all repos and the addons.xml then store them to redis cache
"""
_redisStore = redis.StrictRedis(**config.redis_server)
_details = kodi_repos(repositories())
_addons_xml = addons_xml(_details)
# Don't store reference to repo object to reduce serialiser load
for repo_det in _details.values():
repo_det.repo = None
_redisStore.set(config.redis_keys.details, jsonpickle.encode(_details))
_redisStore.set(config.redis_keys.addons_xml, jsonpickle.encode(_addons_xml))
## The functions below are used for creating the assets for a release
def download(url, path=''):
"""Download the data for this asset.
:param path: (optional), path where the file should be saved
to, default is the filename provided in the headers and will be
written in the current directory.
it can take a file-like object as well
:type path: str, file
:returns: name of the file, if successful otherwise ``None``
:rtype: str
"""
# headers = {
# 'Accept': 'application/zip, application/octet-stream'
# }
headers = {}
resp = None
status_code = 302
while status_code == 302:
resp = requests.get(url, allow_redirects=False, stream=True, headers=headers)
status_code = resp.status_code
if status_code == 302:
url = resp.headers['location']
# Amazon S3 will reject the redirected request unless we omit
# certain request headers
if 's3' in resp.headers['location']:
headers.update({'Content-Type': None})
if resp and resp_check(resp, 200, 404):
return utils.stream_response_to_file(resp, path)
return None
def resp_check(response, true_code, false_code):
if response is not None:
status_code = response.status_code
if status_code == true_code:
return True
if status_code != false_code and status_code >= 400:
response.raise_for_status()
return False
## This is failing for unicode errors with some zip's
## https://bugs.python.org/issue20329
# def extract(filename):
# folder, extension = os.path.splitext(filename)
# if extension.endswith('zip'):
# import zipfile
# if os.path.exists(folder):
# remove_tree(folder)
# if not os.path.exists(folder):
# os.makedirs(folder)
# zip = zipfile.ZipFile(filename, 'r')
# zip.extractall(folder)
# return folder
def zipdir(dirPath=None, zipFilePath=None, includeDirInZip=True, excludeDotFiles=True):
"""Create a zip archive from a directory.
Note that this function is designed to put files in the zip archive with
either no parent directory or just one parent directory, so it will trim any
leading directories in the filesystem paths and not include them inside the
zip archive paths. This is generally the case when you want to just take a
directory and make it into a zip file that can be extracted in different
locations.
Keyword arguments:
dirPath -- string path to the directory to archive. This is the only
required argument. It can be absolute or relative, but only one or zero
leading directories will be included in the zip archive.
zipFilePath -- string path to the output zip file. This can be an absolute
or relative path. If the zip file already exists, it will be updated. If
not, it will be created. If you want to replace it from scratch, delete it
prior to calling this function. (default is computed as dirPath + ".zip")
includeDirInZip -- boolean indicating whether the top level directory should
be included in the archive or omitted. (default True)
"""
if not zipFilePath:
zipFilePath = dirPath + ".zip"
if not os.path.isdir(dirPath):
raise OSError("dirPath argument must point to a directory. "
"'%s' does not." % dirPath)
parentDir, dirToZip = os.path.split(dirPath)
#Little nested function to prepare the proper archive path
def trimPath(path):
archivePath = path.replace(parentDir, "", 1)
if parentDir:
archivePath = archivePath.replace(os.path.sep, "", 1)
if not includeDirInZip:
archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1)
return os.path.normcase(archivePath)
outFile = zipfile.ZipFile(zipFilePath, "w",
compression=zipfile.ZIP_DEFLATED)
for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath):
if excludeDotFiles:
fileNames = [f for f in fileNames if not f[0] == '.']
dirNames[:] = [d for d in dirNames if not d[0] == '.']
for fileName in fileNames:
filePath = os.path.join(archiveDirPath, fileName)
outFile.write(filePath, trimPath(filePath))
#Make sure we get empty directories as well
if not fileNames and not dirNames:
zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/")
#some web sites suggest doing
#zipInfo.external_attr = 16
#or
#zipInfo.external_attr = 48
#Here to allow for inserting an empty directory. Still TBD/TODO.
outFile.writestr(zipInfo, "")
outFile.close()
if __name__ == '__main__':
import pprint
logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%Y%m%d %H:%M',
level=logging.INFO)
repos = repositories()
details = kodi_repos(repos)
pprint.pprint(details)
print(addons_xml(details))
<file_sep># kodi_github_repo
Kodi repository flask webapp that dynamically serves addons from github repos
All addons must be hosted on github in a flat structure such that a direct zip download will create a normal kodi module zip.
This seems to be the most common way for addons to be on github anyway, so should rarely be an issue.
Then just list the module's github url in config.py
When a new version of an addon is ready simply git tag the commit with a semantic version number, eg. v1.1.0
The webapp will check for updated versions in the background and serve the latest of each dynamically.
To install (on ubuntu-ish linux with upstart), choose where you'll store the program on your system, perhaps in home dir, or in var.
I'll call it /path/to/kodi_repo, replace this below with your own desired location
```
apt-get install nginx redis python3 python3-pip
KODI_REPO=/path/to/kodi_repo
mkdir - $KODI_REPO/run
cd $KODI_REPO
git clone https://github.com/andrewleech/kodi_github_repo.git
pip3 install virtualenv
python3 virtualenv virtualenv
source virtualenv/bin/activate
pip3 install --requirement kodi_github_repo/requirements.txt
## System startup scripts
sudo cp kodi_github_repo/upstart_scripts/* /etc/init/
## nginx hosting script
sudo cp kodi_github_repo/nginx_scripts/kodi_github_repo.conf /etc/nginx/sites-available/
sudo ln -s /etc/nginx/sites-available/kodi_github_repo.conf /etc/nginx/sites-enabled/kodi_github_repo.conf
```
Then update the three system config files:
- /etc/init/kodi_repo_uwsgi.conf
- /etc/init/kodi_repo_celery.conf
- /etc/nginx/sites-enabled/kodi_github_repo.conf
replacing /path/to/kodi_repo as needed and setting up the virtualhost in nginx conf to suit your server.
```
sudo service nginx start
sudo service redis start
sudo service kodi_repo_celery start
sudo service kodi_repo_uwsgi start
```
and it should all be running!
You'll want a repository addon to point towards your new repo, something like: https://github.com/andrewleech/repository.alelec<file_sep>amqp==1.4.6
anyjson==0.3.3
billiard==3.3.0.20
celery==3.1.18
Flask==0.10.1
Flask-Cache==0.13.1
github3.py==0.9.4
itsdangerous==0.24
Jinja2==2.8
jsonpickle==0.9.2
kombu==3.0.26
MarkupSafe==0.23
pytz==2015.4
PyYAML==3.11
redis==2.10.3
requests==2.7.0
semantic-version==2.4.2
uritemplate.py==0.3.0
uWSGI==2.0.11.1
Werkzeug==0.10.4
wheel==0.24.0
<file_sep>###############################################################
# -*- coding: utf-8 -*-
#!/usr/bin/env python
__author__ = "<NAME>"
__copyright__ = "Copyright 2015, alelec"
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
from flask import Flask, redirect, abort, url_for, render_template, send_from_directory, request
from flask.ext.cache import Cache
import os
import redis
import config
import pprint
import jsonpickle
import github_handler
import semantic_version
from functools import wraps
app = Flask(__name__)
cache = Cache(app,config={'CACHE_TYPE': 'redis',
'CACHE_KEY_PREFIX': 'kodi_repo_app',
'CACHE_REDIS_URL': config.redis_url
})
redisStore = redis.StrictRedis(**config.redis_server)
app.config['PROPAGATE_EXCEPTIONS'] = True
if not app.debug and config.logfile:
import logging
from logging.handlers import TimedRotatingFileHandler
logfile = config.logfile
if not os.path.isabs(logfile):
logfile = os.path.abspath(os.path.join(os.path.dirname(__file__), logfile))
file_handler = TimedRotatingFileHandler(logfile, backupCount=7)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
app.logger.addHandler(file_handler)
app.logger.warn("startup")
def log_exception(exception=Exception, logger=app.logger):
def deco(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exception as err:
if logger:
logger.exception(err)
raise
return wrapper
return deco
@app.route('/favicon.<ext>')
def favicon(ext):
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.'+ext)
@app.errorhandler(404)
@log_exception()
def page_not_found(e):
app.logger.error("%s : %s" % (e, request.path))
return render_template('404.html'), 404
@app.route('/')
# @cache.cached(timeout=5*60)
@log_exception()
def home():
details = jsonpickle.decode(redisStore.get(config.redis_keys.details).decode())
return render_template('home.html', details=details)
@app.route('/repo/addons.xml')
@cache.cached(timeout=5*60)
@log_exception()
def addons_xml_page():
addons_xml, addons_xml_md5 = jsonpickle.decode(redisStore.get(config.redis_keys.addons_xml).decode())
return addons_xml
@app.route('/repo/addons.xml.md5')
@cache.cached(timeout=5*60)
@log_exception()
def addons_xml_md5_page():
addons_xml, addons_xml_md5 = jsonpickle.decode(redisStore.get(config.redis_keys.addons_xml).decode())
return addons_xml_md5
@app.route('/repo/<addon_id>')
@cache.cached(timeout=5*60)
@log_exception()
def addon_page(addon_id):
details = jsonpickle.decode(redisStore.get(config.redis_keys.details).decode())
if addon_id in details:
# return render_template('addon.html', repo=details[addon_id])
repo = details[addon_id]
url = "https://github.com/{owner}/{reponame}/tree/{newest_tagname}".format(
owner=repo.owner, reponame=repo.reponame, newest_tagname=repo.newest_tagname)
return redirect(url)
else:
return abort(404)
@app.route('/repo/<addon_id>/<zip_addon_id>-<vers>.zip')
@app.route('/repo/<addon_id>/<zip_addon_id>.zip')
@cache.cached(timeout=5*60)
@log_exception()
def zip_url(addon_id, zip_addon_id, vers=None):
url = None
details = jsonpickle.decode(redisStore.get(config.redis_keys.details).decode())
if (addon_id == zip_addon_id or zip_addon_id is None) and addon_id in details:
repo_dets = details[zip_addon_id]
assert isinstance(repo_dets, github_handler.RepoDetail)
if not vers:
vers = sorted(repo_dets.downloads.keys(), key=lambda v:semantic_version.Version(v))[-1]
if vers and vers in repo_dets.downloads:
url = repo_dets.downloads[vers]
if url:
return redirect(url)
else:
return abort(404)
if __name__ == '__main__':
from werkzeug.contrib.profiler import ProfilerMiddleware
app.config['PROFILE'] = True
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
app.run(debug=True, host='0.0.0.0', port=config.debug_server.port)
<file_sep>###############################################################
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
import os
import yaml
class dotdict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'config.yaml')
## Startup
assert os.path.exists(CONFIG_FILE), "Please create config file in format similar to example: " + CONFIG_FILE
with open(CONFIG_FILE, 'r') as configfile:
config = yaml.load(configfile)
assert config.get('kodi_github_repo'), "Incorrect format of config file, missing kodi_github_repo section"
config = config.get('kodi_github_repo')
assert isinstance(config.get('repositories'), list) and len(config.get('repositories')), "Missing repositories from config"
## Defaults
github_personal_access_token = None
repositories = []
debug_server = dotdict(
port = 8000,
)
redis_server = dotdict(
host='localhost',
port=6379,
db=0)
logfile = None
## Set up shared static config for app
redis_url = "redis://{host}:{port}/{db}".format(**redis_server)
class redis_keys(object):
details = "kodi_github_repo__details"
addons_xml = "kodi_github_repo__addons_xml"
# Add config.yaml keys directly to module
for key in config:
val = config[key]
val = dotdict(val) if isinstance(val, dict) else val
vars()[key] = val<file_sep>###############################################################
# -*- coding: utf-8 -*-
#!/usr/bin/env python
__author__ = "<NAME>"
__copyright__ = "Copyright 2015, alelec"
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import config
import github_handler
from celery import Celery
from datetime import timedelta
app = Celery('kodi_repo_task',
broker=config.redis_url,
backend=config.redis_url,
)
app.conf.update(
CELERY_ACCEPT_CONTENT = ['json'],
CELERY_TASK_SERIALIZER = 'json',
CELERY_RESULT_SERIALIZER = 'json',
CELERYBEAT_SCHEDULE = {
'update_kodi_repos_details': {
'task': 'kodi_repo_task.periodic_update_kodi_repos_details',
'schedule': timedelta(minutes=15),
},
}
)
# @app.on_after_configure.connect
# def setup_periodic_tasks(sender, **kwargs):
# # Calls test('hello') every 10 seconds.
# sender.add_periodic_task(15*60, periodic_update_kodi_repos_details.s(), name='update_kodi_repos_details')
# # # Executes every Monday morning at 7:30 A.M
# # sender.add_periodic_task(
# # crontab(hour=7, minute=30, day_of_week=1),
# # test.s('Happy Mondays!'),
@app.task
def periodic_update_kodi_repos_details():
return github_handler.update_kodi_repos_redis()
# Update cached details once at startup
periodic_update_kodi_repos_details.delay()
<file_sep>###############################################################
# -*- coding: utf-8 -*-
#!/usr/bin/env python
__author__ = "<NAME>"
__copyright__ = "Copyright 2015, alelec"
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
| 35e2a548286301c00657d5a85c1ca8e62795f1a3 | [
"Markdown",
"Python",
"Text"
] | 7 | Python | andrewleech/kodi_github_repo | d9d22fc4a382f9ca6247f605e873bbed16ba9e59 | 5705eed833079f9ffa7ecab5048ba9fd2e050ce9 |
refs/heads/master | <repo_name>Spaig/The-Blunder-Games<file_sep>/landmarks.py
import unittest
from landmarksInterface import landmarksInterface
class Landmarks(landmarksInterface):
def __init__(self, name, clue, question, answer):
self.name = name
self.clue = clue
self.question = question
self.answer = answer
def getName(self):
return self.name
def setClue(self, clue): # to be called by gamemaker
self.clue = clue
def getClue(self):
return self.clue
def setQuestion(self, question): # to be called by gamemaker
self.question = question
def getQuestion(self):
return self.question
def setAnswer(self, answer): # to be called by gamemaker
self.answer = answer
def getAnswer(self):
return self.answer
class TestSetClue(unittest.TestCase):
def setUp(self):
self.Landmark = Landmarks("Central Park", "Near the dumpster", "What is the meaning of the universe?",
"The guy right behind you")
def test_normalSetClue(self):
self.assertEqual(self.Landmark.clue, "Near the dumpster", "Clue is incorrect to start")
self.Landmark.setClue("So many tests")
self.assertEqual(self.Landmark.clue, "So many tests", "Clue not changed on call to setClue()")
class TestGetClue(unittest.TestCase):
def setUp(self):
self.Landmark = Landmarks("Central Park", "Near the dumpster", "What is the meaning of the universe?",
"The guy right behind you")
def test_getClue(self):
self.assertEqual(self.Landmark.getClue(), "Near the dumpster", "Clue is not correct")
class TestGetQuestion(unittest.TestCase):
def setUp(self):
self.Landmark = Landmarks("Central Park", "Near the dumpster", "What is the meaning of the universe?",
"The guy right behind you")
def test_getQuestion(self):
self.assertEqual(self.Landmark.getQuestion(), "What is the meaning of the universe?",
"GetQuestion() returns incorrect question")
class TestSetQuestion(unittest.TestCase):
def setUp(self):
self.Landmark = Landmarks("Central Park", "Near the dumpster", "What is the meaning of the universe?",
"The guy right behind you")
def test_normalSetQuestion(self):
self.Landmark.setQuestion("Who wrote the declaration of independence?")
self.assertEqual(self.Landmark.question, "Who wrote the declaration of independence?",
"Question not set correctly after call to setQuestion()")
class TestSetAnswer(unittest.TestCase):
def setUp(self):
self.Landmark = Landmarks("Central Park", "Near the dumpster", "What is the meaning of the universe?",
"The guy right behind you")
def test_normalSetAnswer(self):
self.Landmark.setAnswer("Bologna")
self.assertEqual(self.Landmark.answer, "Bologna", "Answer not set correctly after call to setAnswer()")
<file_sep>/userInterface.py
import abc
class userInterface(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def answer_question(self, answer):
pass
@abc.abstractmethod
def get_question(self):
pass
@abc.abstractmethod
def get_status(self):
pass
@abc.abstractmethod
def create_game(self, landmark, teams):
pass
@abc.abstractmethod
def start_game(self):
pass
@abc.abstractmethod
def end_game(self):
pass
@abc.abstractmethod
def create_landmark(self, name, clue, question, answer):
pass
<file_sep>/system.py
import landmarks
import unittest
import interface
class System:
# pseudo database, way to interact with lists
def __init__(self):
self.landmarks = [] # [landmark objects]
#self.users = [User("admin","kittens")] # [user objects] - FOR SPRINT 2
self.teams = {'admin': "kittens"} # gamemaker hardcoded - disabled due to user becoming an object(?)
def addLandmark(self, lm):
self.landmarks.append(lm)
def addTeam(self, tm, pw):
self.teams[tm] = pw
def getLandmark(self, lm):
ret = None
x = 0
for i in self.landmarks:
if self.landmarks[x].name == lm:
return self.landmarks[x]
x +=1
print("Invalid landmark")
return ret
'''
try:
x = self.landmarks.index(lm)
ret = self.landmarks[x]
except ValueError:
print("Invalid landmark")
return ret
'''
def getTeam(self, tm):
ret = None
for key in self.teams:
if tm == key:
return key
print("Invalid team name")
return ret
def getTeamPassword(self, username):
ret = None
try:
ret = self.teams[username]
except KeyError:
print("Invalid username")
return ret
'''
USER OBJECT VERSION OF GETTEAMPASSWORD:
try:
for key in self.users:
if tm == self.users[key].getName():
return self.users[key].getPassword
except KeyError:
print("Invalid username")
return ret
'''
'''
class TestAddTeam(unittest.TestCase):
def setUp(self):
self.Interface = interface.Interface()
self.User = user.User()
self.User.currentUser = "admin" #admin is logged in to make changes
self.System = System()
def test_AdminAddTeam(self):
self.System.addTeam("user","password")
self.assertEquals(self.System.teams, {"admin":"kittens","user":"password"}, "New user not added correctly")
def test_NonAdminAdd(self):
self.User.currentUser = "notadmin"
self.System.addTeam("user","password")
self.assertEquals(self.System.teams, {"admin":"kittens"}, "Non-admin user should not be able to add new teams")
'''
class TestAddTeamAcceptance(unittest.TestCase):
def setUp(self):
self.Interface = interface.Interface()
self.System = System()
def test_AdminAddTeam(self):
self.Interface.command("CREATEUSER newteam passw0rd")
self.assertEquals(self.System.teams, {"admin":"kittens","newteam":"passw0rd"}, "New user not added correctly")
self.Interface.command("CREATEUSER anotherteam wow")
self.assertEquals(self.System.teams, {"admin":"kittens","newteam":"passw0rd","anotherteam":"wow"}, "New user not added correctly")
<file_sep>/game.py
import unittest
import landmarks
import time
import system
import user
from gameInterface import gameInterface
class Game(gameInterface):
def __init__(self, currentsystem):
##THE ~FUTURE~ self.clock = 0 # need to import time or some other 3rd party clock
self.isActive = False # game is active when gamemaker calls startGame (and startClock)
self.landmarkList = [] # ordered list of landmarks
self.System = currentsystem # needs to have system passed in from controller so to have access to landmarks/teams in DB
self.teams = [] # list of user objects in game to retain stateful data of each team
# holds game landmarks, anything stored within the game
def addTeamToGame(self, teamName, password):
usr = user.User(teamName, password)
self.teams.append(usr)
def checkIfWin(self, x):
return x == (len(self.landmarkList))
##THE ~FUTURE~ def getClock(self):
##THE ~FUTURE~ return self.clock
def getLandmarkList(self):
return self.landmarkList
def getTeams(self):
return self.teams
# Sets landmarkList to a given list of landmarks passed in. Must be game maker.
def setLandmarkList(self, landmarks):
if landmarks != None:
self.landmarkList = landmarks
##THE ~FUTURE~ def startClock(self):
##THE ~FUTURE~ pass
##THE ~FUTURE~ def stopClock(self):
##THE ~FUTURE~ pass
def toggleActive(self):
if (self.isActive):
##THE ~FUTURE~ self.stopClock()
self.isActive = False
else:
##THE ~FUTURE~ self.startClock()
self.isActive = True
class TestAddTeamsToGame(unittest.TestCase): # Thomas
def setUp(self):
self.User = user.User()
self.System = system.System()
self.Game = Game(self.System)
self.System.teams = {"username": "password", "TeamB": "otherpass", "TeamC": "Lincoln"}
def test_AddUser(self):
self.Game.addTeamToGame("TeamB")
self.assertEquals(self.Game.teams[0], "TeamB", "TeamB should be first in currentTeams")
self.Game.addTeamToGame("TeamC")
self.assertEquals(len(self.Game.teams), 2, "Should have two teams in the game")
def test_NotGameMaker(self):
self.User.currentUser = "username"
self.assertEquals(self.Game.addTeamToGame("TeamB"), "ERROR", "Game maker must be current user to add to game.")
class TestGetLandmarkList(unittest.TestCase):
def setUp(self):
self.System = system.System()
self.Game = Game(self.System)
self.Game.landmarkList = ["Road", "Park"]
def test_normalGetLandmark(self):
self.assertEqual(self.Game.getLandmarkList(), ["Road", "Park"], "Return of getLandmarkList() not accurate")
self.Game.landmarkList = ["Apartment", "The Alamo"]
self.assertEqual(self.Game.getLandmarkList(), ["Apartment", "The Alamo"], "LandmarkList incorrect after change")
def test_emptyGetLandmark(self):
self.Game.landmarkList = []
self.assertEqual(self.Game.getLandmarkList(), [],
"Call to getLandmarkList() when list is empty should return an empty list")
class TestToggleActive(unittest.TestCase):
def setUp(self):
self.System = system.System()
self.Game = Game(self.System)
def test_normalToggle(self):
self.assertFalse(self.Game.isActive, "Game starting out active")
self.Game.toggleActive()
self.assertTrue(self.Game.isActive, "Game is not active after call to toggleActive()")
<file_sep>/main.py
import controller
import interface
c = controller.Controller()
i = interface.Interface(c)
active = True
print("Scavenger hunt program now running. Enter -1 to quit")
while active == True:
ret = input(">")
if ret == "-1":
active = False
else:
i.command(ret)
'''
print("test game setup\n")
i.command("login admin kittens")
i.command("create landmark l1 c1 q1 a1")
i.command("create landmark l2 c2 q2 a2")
i.command("create team t1 p1")
i.command("create game l1,l2,l3 t1,t2") #should fail
i.command("create game l1,l2 t1")
i.command("start")
if(c.Game.isActive):
print("success!\n")
print("test game interaction GM")
i.command("get status") #GM status, all teams
i.command("end")
i.command("logout")
if(c.Game.isActive == False):
print("success!\n")
c.Game.isActive = True
print("test game interaction user")
i.command("login t1 p1")
i.command("create team t2 p2")
i.command("login t2 p2")
i.command("get status")
#i.command("
'''
<file_sep>/controller.py
import unittest
import system
import user
import game
import landmarks
class Controller:
def __init__(self):
self.currentUser = None
self.Game = None
self.System = system.System()
def check(self, parsedText): # where parsedText is a list of strings
# if user=None, don't accept any method except login
# elif tree of different methods depending on first index of parsedText
# a = eval('A')
command = parsedText[0].upper() # commands should be toUpper
if self.Game != None:
team = None
i = 0
for i in range(len(self.Game.teams)):
if self.currentUser == self.Game.teams[i].getName():
team = self.Game.teams[i]
break
if command == 'LOGIN':
self.login(parsedText[1], parsedText[2])
elif command == 'LOGOUT':
self.logout()
elif command == 'START':
self.start_game()
#first command is create, can create a game, landmark, user.
elif command == 'CREATE':
if parsedText[1].upper() == 'GAME':
self.create_game(parsedText[2], parsedText[3])
elif parsedText[1].upper() == 'LANDMARK':
self.create_landmark(parsedText[2], parsedText[3], parsedText[4], parsedText[5])
elif parsedText[1].upper() == 'USER':
self.create_team(parsedText[2], parsedText[3])
else:
print("Invalid command")
elif command == 'END':
self.end_game()
#User calls
elif command == 'ANSWER' and parsedText[1].upper() == 'QUESTION':
j=2
newAnswer = ""
for i in range(2,(len(parsedText))):
newAnswer += parsedText[j] + " "
j+=1
newAnswer = newAnswer.rstrip()
self.answer_question(newAnswer, team)
#if that answer is the last one, game ends they win
if team.currentLandmark > len(self.Game.landmarkList):
print('You win!')
self.Game.toggleActive()
elif command == 'GET' and parsedText[1].upper() == 'STATUS':
team.get_status()
elif command == 'GET' and parsedText[1].upper() == 'CLUE':
print(self.Game.landmarkList[team.currentLandmark].getClue())
elif command == 'GET' and parsedText[1].upper() == 'QUESTION':
print(self.Game.landmarkList[team.currentLandmark].getQuestion())
else:
print('Invalid command.')
# def getInstance(self):
# Game maker must be first to log in?
def login(self, username, password):
if self.currentUser is None:
if self.System.getTeamPassword(username) == password:
self.currentUser = username
print("Successfully logged in")
else:
print("Username or password is incorrect")
else:
print('Another user is currently logged in.')
def logout(self):
if self.currentUser == None:
print("No user is logged in")
else:
self.currentUser = None
print("User logged out")
def create_game(self, landmark, teams):
# instantiates new game object and calls setLandmarkList & setTeams in Game class. Current user is admin
if self.currentUser != "admin":
print("Cannot create game if not game maker")
return
if landmark is None or teams is None:
print("Landmarks or teams must not be null: Needs to be in format: landmark1,landmark2 teamA,teamB")
return
lmstrings = landmark.split(",")
tmstrings = teams.split(",")
self.Game = game.Game(self.System)
lm = []
for l in lmstrings:
returnedLandmark = self.System.getLandmark(l)
if returnedLandmark is None:
print("Could not add " + l + " as it does not exist in system!")
return
else:
lm.append(returnedLandmark)
self.Game.setLandmarkList(lm)
for t in tmstrings:
returnedTeamName = self.System.getTeam(t)
if returnedTeamName is None:
print("Could not add " + t + "as it does not exist in system!")
else:
password = self.System.getTeamPassword(t)
self.Game.addTeamToGame(t, password)
print("Game created!")
def start_game(self):
# only accessible if game maker. This method calls startClock() in Game class
if (self.currentUser == "admin"):
if self.Game == None:
self.Game = game.Game(self.System)
print("Game started")
if self.Game.isActive:
print("There is already an active game")
else:
self.Game.toggleActive()
else:
print("Cannot start game if not game maker")
def end_game(self):
# only accessible if game maker
if (self.currentUser == "admin"):
if not self.Game.isActive:
print("There is no active game")
else:
self.Game.toggleActive()
# more?
else:
print("Cannot end game if not game maker")
pass # TODO
def create_landmark(self, name, clue, question, answer):
if self.currentUser != "admin":
print("Must be admin to create landmark")
return
if name == "" or clue == "" or question == "" or answer == "":
print("Invalid landmark argument(s)")
return
landmark = landmarks.Landmarks(name, clue, question, answer)
self.System.addLandmark(landmark)
print("Landmark created")
def create_team(self, username, password):
if self.currentUser != "admin":
print("Must be admin to create landmark")
return
if username == "" or password == "" or username =='admin':
print("Invalid team credentials.")
return
self.System.teams[username] = password
print("Team created")
def answer_question(self, answer, team):
if team != None:
if self.Game.landmarkList[team.currentLandmark].getAnswer() == answer:
print('Correct!')
team.currentLandmark += 1
# need to be able to print the clue
if self.Game.checkIfWin(team.currentLandmark) == True:
print('You win!')
return
else:
print('Your next clue is: ')
print(self.Game.landmarkList[team.currentLandmark].getClue())
else:
print('Incorrect answer, try again.')
# Eventually add penalty.
# if answer is correct: automatically provide next clue, increments currentLandmark if correct
class TestAcceptanceLogin(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.Interface = interface.Interface()
def test_NormalLogin(self):
self.Interface.command("LOGIN admin kittens")
self.assertEqual(self.con.currentUser, "admin", "Current user is not admin")
def test_LoginWithOtherUser(self):
self.con.currentUser = "admin"
self.con.System.teams = {"admin":"kittens","other":"otherpass"}
self.Interface.command("LOGIN other otherpass")
self.assertEqual(self.con.currentUser, "admin", "Current user should not be changed when call to login while there is a current user")
def test_BadLogin(self):
self.Interface.command("LOGIN badname badpass")
self.assertEqual(self.con.currentUser, None, "Incorrect username & password should fail")
self.Interface.command("LOGIN admin badpass")
self.assertEqual(self.con.currentUser, None, "Incorrect password should fail")
self.Interface.command("LOGIN baduser kittens")
self.assertEqual(self.con.currentUser, None, "Incorrect username should fail")
class TestAcceptanceLogout(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.Interface = interface.Interface()
def test_NormalLogout(self):
self.con.currentUser = "admin"
self.Interface.command("LOGOUT")
self.assertEqual(self.con.currentUser, None, "Logout was unsuccessful")
def test_LogoutOnNoCurrentUser(self):
self.Interface.command("LOGOUT")
self.assertEqual(self.con.currentUser, None, "Logout on no current user should not change anything")
class TestAcceptanceCreateGame(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.Interface = interface.Interface()
def test_NormalCreateGame(self):
self.Interface.command("CREATE GAME landmark1,landmark2 teamA,teamB")
self.assertEquals(self.con.Game.landmarkList, [landmark1,landmark2], "Landmarks not created correctly")
self.assertEquals(self.con.Game.teams, [teamA,teamB], "Teams not created correctly")
def test_noLandmarks(self):
self.Interface.command("CREATE GAME teamA,teamB")
self.assertEquals(self.con.Game.landmarkList, [], "No landmarks should be created")
self.assertEquals(self.con.Game.teams, [], "No teams should be created")
def test_createEmptyGame(self):
self.Interface.command("CREATE GAME")
self.assertEquals(self.con.Game.landmarkList, [], "No landmarks should be created")
self.assertEquals(self.con.Game.teams, [], "No teams should be created")
class TestAcceptanceCreateLandmark(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.Interface = interface.Interface()
def test_NormalCreateLandmark(self):
self.Interface.command("CREATE LANDMARK newplace this,is,a,clue this,is,a,question answer")
self.assertEquals(self.con.System.landmarks[0].getName(), "newplace", "Name not set corectly")
self.assertEquals(self.con.System.landmarks[0].getClue(), "this is a clue", "Clue not set correctly")
self.assertEquals(self.con.System.landmarks[0].getQuestion(), "this is a question", "Question not set correctly")
self.asswerEquals(self.con.System.landmarks[0].getAnswer(), "answer", "Answer not set correctly")
def test_badCreateLandmark(self):
self.Interface.command("CREATE LANDMARK")
self.assertRaises(ValueError, self.con.System.landmarks[0], "Nothing at index 0 of landmarks")
class TestAcceptanceEnd(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.Interface = interface.Interface()
self.Game = game.Game(self.con.System)
def test_NormalEndGame(self):
self.Game.isActive = True
self.Interface.command("END")
self.assertFalse(self.Game.isActive, "Game's isActive should be set to False after call to end game")
def test_EndGameWhileNoActiveGame(self):
self.Game.isActive = False
self.Interface.command("END")
self.assertFalse(self.Game.isActive, "Game's isActive should be False after call to end game when there is no active game")
class TestAcceptanceAnswerQuestion(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.con.currentUser = "name"
self.Interface = interface.Interface()
self.Game = game.Game(self.con.System)
self.Game.teams = [User("name","pass")]
self.Game.landmarkList = [Landmarks("name", "clue", "question", "answer")]
def test_CorrectAnswer(self):
self.Interface.command("ANSWER QUESTION answer")
assertEquals(self.Game.teams[0].currentLandmark, 1, "CurrentLandmark should be incremented")
def test_BadAnswer(self):
self.Interface.command("ANSWER QUESTION badanswer")
assertEquals(self.Game.teams[0].currentLandmark, 1, "CurrentLandmark should be incremented")
class TestAcceptanceGetStatus(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.Interface = interface.Interface()
class TestGMCreateGame(unittest.TestCase): # <NAME> tests
def setUp(self):
self.con = Controller()
self.con.currentUser = "admin"
self.con.System.teams = {"admin": "kitten", "teamA": "passwordA", "teamB": "passwordB"}
x = landmarks.Landmarks("park", "", "", "")
y = landmarks.Landmarks("lab", "", "", "")
z = landmarks.Landmarks("library", "", "", "")
self.con.System.landmarks = [x, y, z]
def test_createGame(self):
listoflandmarks = ["park", "lab", "library"]
teamnames = ["teamA", "teamB"]
self.con.create_game("park,lab,library", "teamA,teamB")
self.assertEquals(self.con.Game.getLandmarkList(), listoflandmarks, "Assigned landmarks in game not correct")
self.assertIn(teamnames, self.con.Game.getTeams(), "Assigned teams in game not correct")
self.assertEqual(self.con.Game.clock, 0, "Clock should not be started until Game maker initiates game")
self.assertFalse(self.con.Game.isActive, "Game should not be active until started.")
class TestGMAddLandmark(unittest.TestCase): # <NAME>
def setUp(self):
self.con = Controller()
self.con.currentUser = "admin"
def test_AddLandMark(self):
self.con.create_landmark("park", "there are benches", "who is fountain dedicated to?", "St. Python")
landmark = self.con.System.getLandmark("park")
self.assertEquals(landmark.name, "park", "Landmark name is not correct")
self.assertEquals(landmark.clue, "there are benches", "Landmark question is not correct")
self.assertEquals(landmark.question, "who is the fountain dedicated to?",
"Landmark question is not correct")
self.assertEquals(landmark.answer, "St. Python", "Landmark answer is not correct")
def test_AddBadLandmark(self):
self.assertEquals(self.con.create_landmark("", "", "", ""), "Invalid landmark argument(s)",
"Adding blank landmark should fail")
class LoginTest(unittest.TestCase):
def setUp(self):
self.con = Controller()
def test_badlogin(self):
self.con.login("cheater", "sargreat")
self.assertEqual(self.con.currentUser, None, "Nice try, User scum. Bad username test.")
self.con.login("admin", "sarpoo")
self.assertEqual(self.con.currentUser, None, "Nice try, User scum. Bad password test.")
def test_goodlogin(self):
self.con.login("admin", "kittens")
self.assertEqual(self.con.currentUser, "admin", "Admin not successfully logged in.")
class LogoutTest(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.con.username = "admin"
def test_goodlogout(self):
self.con.logout()
self.assertEqual(self.con.currentUser, None, "Current user should be null after logout")
class TestStartGame(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.User = user.User()
self.User.name = "admin"
self.Game = game.Game(self.con.System)
def test_goodstart(self):
self.con.start_game()
self.assertTrue(self.Game.isActive, "Game not begun successfully!")
def test_badStart(self):
self.Game.isActive = True
self.con.start_game()
self.assertTrue(self.Game.isActive, "Calling start game on an active game should do nothing")
class TestEndGame(unittest.TestCase):
def setUp(self):
self.con = Controller()
self.User = user.User()
self.User.name = "admin"
self.Game = game.Game(self.con.System)
self.Game.isActive = True
def test_endGame(self):
self.con.end_game()
self.assertFalse(self.Game.isActive, "End game did not successfully stop the game")
def test_endGameOnAlreadyEndedGame(self):
self.Game.isActive = False
self.con.end_game()
self.assertFalse(self.Game.isActive, "End game on a non-active game should stay non-active")
<file_sep>/landmarksInterface.py
import abc
class landmarksInterface(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def setClue(self, clue): # to be called by gamemaker
pass
@abc.abstractmethod
def setQuestion(self, question): # to be called by gamemaker
pass
@abc.abstractmethod
def setAnswer(self, answer): # to be called by gamemaker
pass
<file_sep>/gameInterface.py
import abc
class gameInterface(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def getClock(self):
pass
@abc.abstractmethod
def setLandmarkList(self, landmarks):
pass
@abc.abstractmethod
def setTeams(self, teams): # add existing team to current game?
pass
##THE ~FUTURE~ @abc.abstractmethod
##THE ~FUTURE~ def startClock(self):
##THE ~FUTURE~ pass
##THE ~FUTURE~ @abc.abstractmethod
##THE ~FUTURE~ def stopClock(self):
##THE ~FUTURE~ pass
<file_sep>/README.md
[](https://floobits.com/delta5800/The-Blunder-Games/redirect)
# The-Blunder-Games
for cs361
<file_sep>/interface.py
import controller
# if __name__ == '__main__': This is for things called by import statements
class Interface:
def __init__(self, c):
self.Controller = c
def command(self, commandString): # breaks input into list of commands. list[0] being the action/method to call. Sends list and currentUser to controller class
if commandString != None:
commandList = commandString.split()
self.Controller.check(commandList)
'''
class TestCommand(unittest.TestCase):
def setUp(self):
pass
def testParseInput(self):
self.Interface.command("login admin pass")
self.assertEquals(parsedList[0], "login", "Should correctly parse for login.")
'''
<file_sep>/user.py
import unittest
from userInterface import userInterface
import landmarks
import system
import game
#Changing User implementation Sprint 2. Will only contain Name, pass, and currentLandmark.
class User(userInterface):
# team is treated as individual, will include gamemaker - test!
def __init__(self, username, password):
# self.penalties = 0
# self.timePenalty = 0 WILL IMPLEMENT LATER :)
self.name = username
self.password = <PASSWORD>
self.System = system.System
self.currentLandmark = 0 # indicates position in game's landmarkList
# self.Game = game.Game(self.System)
def getName(self):
return self.name
def getPassword(self):
return <PASSWORD>
def get_status(self):
# returns current time, location (penalties accounted for in later iteration)
#if gm
#implement gm total status sprint 2
print("Stats for %s", self.name)
#print("Current time: %d", self.Game.clock) # TODO: need to fix this line
print("You are on landmark %d !", self.currentLandmark) # Prints name of landmark
class TestAcceptanceQuestions(unittest.TestCase):
def setUp(self):
self.system = system.System()
self.user = self.user()
# self.controller = controller.Controller()
river = self.system.landmarks("River", "test1", "test2", "test3")
tree = self.system.landmarks("Tree", "blah1", "blah2", "blah3")
place = self.system.landmarks("Place", "asdf1", "asdf2", "asdf3")
self.system.landmarks = [tree, river]
def test_answer_question_correct(self):
self.user.currentLandmark = 0
self.assertEquals(self.user.answer_question("test3"), "Correct!", "Should be the correct answer.")
def test_answer_question_wrong(self):
self.user.currentLandmark = 0
self.assertEquals(self.user.answer_question("Cats r kewl"), "Wrong, try again", "Incorrect answer entered")
class TestAcceptanceUserStatus(unittest.TestCase):
def setUp(self):
self.game = game.Game()
# self.controller = controller.Controller()
self.user = self.user()
def test_userStatusCurrent(self):
self.game.isActive = True
self.game.clock = 5
self.user.currentLandmark = 1
self.assertEquals(self.user.get_status(), "Time: 5, Landmark: 2", "User cannot access current status during game")
class TestAcceptanceGMStatus(unittest.TestCase): # TODO
def setup(self):
self.game = game.Game()
def test_gm_status_current(self):
pass
# Is this class needed here? -Derek
class TestGame(unittest.TestCase):
def setUp(self):
self.Game = game.Game()
self.user = User("admin", "kittens")
def test_game_start(self):
pass
def test_game_end_gm(self):
pass
def test_gameEndUser(self):
self.Game.isActive = True
self.user.currentLandmark = 4
self.assertFalse(self.Game.isActive, "Game is not over")
'''
class TestLogin(unittest.TestCase): # derek's tests
def setUp(self):
self.User = User()
self.System = system.System()
self.System.teams = {"username": "password", "Gerard": "otherpass", "Humphrey": "Lincoln"}
def test_NormalLogin(self):
self.User.login("username", "<PASSWORD>")
self.assertEquals(self.User.name, "username", "Current user is not username")
self.User.login("Gerard", "otherpass")
self.assertEquals(self.User.name, "Gerard", "Current user is not Gerard");
self.User.login("Humphrey", "Lincoln")
self.assertEquals(self.User.name, "Humphrey", "Current user is not Humphrey")
def test_BadPassword(self):
self.User.login("username", "badpass")
self.assertEquals(self.User.name, "", "Current user should still be empty on a wrong password")
def test_BadUsername(self):
self.User.login("Gerry", "otherpass")
self.assertEquals(self.User.name, "", "Current user should still be empty on a wrong username")
def test_BadUsernameAndPass(self):
self.User.login("Hrey", "Locolon")
self.assertEquals(self.User.name, "", "Current user should still be empty on a wrong username and password")
def test_EmptyLogin(self):
self.User.login("", "")
self.assertEquals(self.User.name, "", "Current user should still be empty on nothing entered")
'''
'''
class TestLoginAcceptance(unittest.TestCase):
def setUp(self):
self.Interface = Interface()
self.User = User()
self.System = System()
self.System.teams = {"username":"password","Gerard":"otherpass","Humphrey":"Lincoln"}
def test_NormalLogin(self):
self.Interface.command("login(\"username\",\"password\")")
self.assertEquals(self.User.currentUser, "username", "Current user is not username")
self.Interface.command("login(\"Gerard\",\"otherpass\")")
self.assertEquals(self.User.currentUser, "Gerard", "Current user is not Gerard");
self.Interface.command("login(\"Humphrey\",\"Lincoln\""))
self.assertEquals(self.User.currentUser, "Humphrey", "Current user is not Humphrey")
def testBadPassword(self):
self.Interface.command("login(\"username\",\"badpass\")")
self.assertEquals(self.User.currentUser, "", "Current user should still be empty on a wrong password")
def testBadUsername(self):
self.Interface.command("login(\"Gerry\",\"otherpass\")")
self.assertEquals(self.User.currentUser, "", "Current user should still be empty on a wrong username")
def testBadUsernameAndPass(self):
self.Interface.command("login(\"Idontexist\",\"help\")")
self.assertEquals(self.User.currentUser, "", "Current user should still be empty on a wrong username and password")
def testEmptyLogin(self):
self.Interface.command("login(\"\",\"\")")
self.assertEquals(self.User.currentUser, "", "Current user should still be empty on nothing entered")
''' | f9d5a2adb141faed90f279ad2f7c8e25666f54e7 | [
"Markdown",
"Python"
] | 11 | Python | Spaig/The-Blunder-Games | dcfa7001f4136f4fe89714b4434a6aa7ed2d8f9d | d866a907159a37f58d52e2a8bfe6820b48d8ec67 |
refs/heads/master | <file_sep>using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using electo.Models.SP_Models;
using static electo.Models.SP_Models.StoredProcedureModels;
using electo.Models;
using electo.Models.BaseClass;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class RunningCampaignController : BaseClass
{
// GET: RunningCampaign
private readonly IElectionService _ElectionService;
private CampaignService cmpSer = new CampaignService();
private readonly IstateService _stateService;
private readonly IPoliticalPartyService _PoliticalPartyService;
private readonly ILSCServices _LSCServices;
private readonly IVSCServices _VSCServices;
private readonly IwardServices _WardServices;
private readonly IPollingBooth _PollingBoothService;
private readonly IAccountServices _AccountServices;
public RunningCampaignController()
{
_ElectionService = new ElectionService();
_stateService = new stateService();
_PoliticalPartyService = new PoliticalPartyService();
_LSCServices = new LSCServices();
_VSCServices = new VSCServices();
_WardServices = new wardServices();
_PollingBoothService = new PollingBoothService();
_AccountServices = new AccountServices();
}
public ActionResult RunningCampaigns()
{
ViewBag.ElectionType = new SelectList((_ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME })), "electionTypeID", "electionTypeNAME");
ViewBag.PoliticalParties = new SelectList((_AccountServices.getAllPoliticalParty().Select(e => new { e.politicalPartyID, e.politicalPartyName })), "politicalPartyID", "politicalPartyName");
return View();
}
public JsonResult getCampaignNames(string prefix)
{
var names = cmpSer.getCampaignNames(prefix).Select(e=> new { e.campaignName }).Take(10);
string result = Newtonsoft.Json.JsonConvert.SerializeObject(names);
return Json(names, JsonRequestBehavior.AllowGet);
}
public ActionResult _partialRunningCampaigns(string electionTypeNAME, string electionYear, string politicalPartyName, string campaignName)
{
return PartialView("_partialRunningCampaigns", cmpSer.SearchRunningCampaigns_Result(electionTypeNAME, electionYear, politicalPartyName, campaignName));
}
[HttpGet]
public ActionResult _partialActivateDeactiveateCampaign(long cID)
{
cmpSer.get(cID);
return PartialView("_partialActivateDeactiveateCampaign", cmpSer.get(cID));
}
[HttpPost]
public ActionResult _partialActivateDeactiveateCampaign(campaign _cmp)
{
cmpSer._save(_cmp);
TempData["Result"] = "Success";
return RedirectToAction("RunningCampaigns", "RunningCampaign");
}
[HttpGet]
public ActionResult CampaignPriceList()
{
ViewBag.ElectionType = new SelectList((_ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME })), "electionTypeID", "electionTypeNAME");
return View();
}
public ActionResult _partialCampaignPrices(string electionTypeNAME, string year, bool isActive)
{
return PartialView("_partialCampaignPrices", cmpSer.sp_SearchCampaignPrices_Result(electionTypeNAME, year, isActive));
}
[HttpGet]
public ActionResult _partialNewPrice()
{
campaignPrice _cmpPrice = new campaignPrice();
//ViewBag.ElectionType = new SelectList((_ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME })), "electionTypeID", "electionTypeNAME");
ViewBag.electionTypeID = _ElectionService.getElectionTypes();
return PartialView("_partialNewPrice", _cmpPrice);
}
[HttpPost]
public ActionResult NewPrice(campaignPrice _newCmpPrice)
{
campaignPrice newCmpPrice_ = new campaignPrice();
newCmpPrice_.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
newCmpPrice_.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
newCmpPrice_.dataIsCreated = BaseUtil.GetCurrentDateTime();
newCmpPrice_.dataIsUpdated = BaseUtil.GetCurrentDateTime();
newCmpPrice_.electionTypeID = _newCmpPrice.electionTypeID;
newCmpPrice_.isActive = _newCmpPrice.isActive;
newCmpPrice_.price = _newCmpPrice.price;
newCmpPrice_.year = _newCmpPrice.year;
int addResult = 0;
addResult = cmpSer.createCampaignPrice(newCmpPrice_);
TempData["Result"] = "Edited";
return RedirectToAction("CampaignPriceList", "RunningCampaign");
}
[HttpGet]
public ActionResult CreateCampaign()
{
ViewBag.electionTypeID = _ElectionService.getElectionTypes();
ViewBag.electionID = _ElectionService.getAllElections();
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.lokSabhaConstituencyID = _LSCServices.getAlllokSabhaConstituencyConstituency(1).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
ViewBag.vidhanSabhaConstituencyID = _VSCServices.getvidhanSabhaConstituencyByStateID(1).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
ViewBag.wardID = _WardServices.getZoneByStateIDAndMUncipalCorporationID(1, 1, 0,0).Select(e => new { e.wardID, e.wardName });
//ViewBag.politicalparty = _PoliticalPartyService.getAll_PoliticalPartyListByStateID(1, "");
return View();
}
[HttpPost]
public ActionResult CreateCampaign(campaign _campaign)
{
_campaign.campaignName = _campaign.campaignName;
_campaign.electionTypeID = _campaign.electionTypeID;
_campaign.electionID = _campaign.electionID;
_campaign.politicalPartyID = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.politicalPartyID.ToString()));
if (_campaign.electionTypeID == 1)
{
_campaign.lokSabhaConstituencyID = _campaign.lokSabhaConstituencyID;
_campaign.vidhanSabhaConstituencyID = null;
_campaign.wardID = null;
}
if (_campaign.electionTypeID == 2)
{
_campaign.lokSabhaConstituencyID = null;
_campaign.vidhanSabhaConstituencyID = _campaign.vidhanSabhaConstituencyID;
_campaign.wardID = null;
}
_campaign.volunteerID = Convert.ToUInt32(BaseUtil.GetSessionValue(AdminInfo.volunteerID.ToString()));
_campaign.dataIsCreated = BaseUtil.GetCurrentDateTime();
_campaign.dataIsUpdated = BaseUtil.GetCurrentDateTime();
_campaign.isActive = true;
_campaign.isOLD = false;
_campaign.isPaymentComplete = false;
_campaign.createdBy = Convert.ToUInt32(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
_campaign.modifiedBy = Convert.ToUInt32(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
_campaign.price = 0;
try
{
if (ModelState.IsValid)
{
cmpSer.createCampaign(_campaign);
TempData["result"] = "Success";
}
}
catch (Exception e)
{
TempData["result"] = e.Message;
}
return RedirectToAction("CreateCampaign", "RunningCampaign");
}
[HttpGet]
public ActionResult MyCampaigns()
{
IEnumerable<campaign> _cmp;
_cmp = cmpSer.getMyCampaigns(Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.volunteerID.ToString()))).ToList();
return View(_cmp);
}
[HttpGet]
public ActionResult AssignVolunteers(int ?cmpID)
{ if (cmpID != null)
{
var c = cmpSer.get((Int32)cmpID);
if (c != null)
{
ViewBag.campaignName = ((campaign)c).campaignName;
}
else
{
ViewBag.campaignName = "";
}
}
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.lokSabhaConstituencyID = _LSCServices.getAlllokSabhaConstituencyConstituency(1).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
ViewBag.vidhanSabhaConstituencyID = _VSCServices.getvidhanSabhaConstituencyByStateID(1).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
return View();
}
[HttpPost]
public ActionResult _partialAssign(string cmpID, string stateID, string lkID, string vsID)
{
string pID = BaseUtil.GetSessionValue(AdminInfo.politicalPartyID.ToString());
ViewBag.usertypes = cmpSer.get().Select(e => new { e.userTypeID, e.userTypeName }).OrderByDescending(e => e.userTypeID).Take(3);
var result = cmpSer.getVolunteers(cmpID,pID, stateID, lkID, vsID);
TempData["cID"] = cmpID;
return PartialView(result);
}
[HttpPost]
public string assignVolunteer(string usertype, string vID, string cID)
{
string result = "Error";
if (cmpSer.createVolunteerRelationship(usertype, vID, cID) == 1) {
result = "Success";
}
return result;
}
public ActionResult _partialAssignAreaPageIncharge(string usertype, string vID, string cID, string voterName)
{
ViewBag.areaList = cmpSer.getAreaListByCampignID(Convert.ToInt32(cID)).Select(e => new { e.areaID, e.areaName });
PageInchargeAssignAreaviewmodel _assigarea = new PageInchargeAssignAreaviewmodel();
_assigarea.volunteerID = Convert.ToInt32(vID);
_assigarea.campaignID = Convert.ToInt32(cID);
_assigarea.voterName= voterName;
return PartialView("_partialAssignAreaPageIncharge", _assigarea);
}
public ActionResult AssignAreaPageIncharge(PageInchargeAssignAreaviewmodel _obj)
{
int result = 0;
result = cmpSer.assignPageInchargeArea(_obj);
if (result == 1)
{
TempData["Creation"] = "Success";
return RedirectToAction("AssignVolunteers", new { cmpID = _obj.campaignID });
}
TempData["Creation"] = "unsuccess";
return View(_obj);
}
[HttpGet]
public ActionResult _partialAssignPollingBooth(Int64 cID, Int64 vID, string voterName)
{
AssignPollingBoothToPollingBoothIncharge oAssignPollingBoothToPollingBoothIncharge = new AssignPollingBoothToPollingBoothIncharge();
oAssignPollingBoothToPollingBoothIncharge.voluntearID = vID;
oAssignPollingBoothToPollingBoothIncharge.campaignid = cID;
oAssignPollingBoothToPollingBoothIncharge.voterName = voterName;
ViewBag.pollingBoothID_ = _PollingBoothService.get_PollingBoothListByCampaignID(cID).Select(e => new { e.pollingBoothID, e.pollingBoothName, e.address });
return PartialView("_partialAssignPollingBooth", oAssignPollingBoothToPollingBoothIncharge);
}
[HttpPost]
public ActionResult _partialAssignPollingBooth(AssignPollingBoothToPollingBoothIncharge oAssignPollingBoothToPollingBoothIncharge)
{
int result = 0;
result= _PollingBoothService.AssignPollingBoothToAssignPollingBoothIncharge(oAssignPollingBoothToPollingBoothIncharge);
if (result == 1)
{
TempData["Creation"] = "Success";
return RedirectToAction("AssignVolunteers", new { cmpID = oAssignPollingBoothToPollingBoothIncharge.campaignid });
}
TempData["Creation"] = "unsuccess";
return View(oAssignPollingBoothToPollingBoothIncharge);
}
[HttpPost]
public int DeletecampaignVolunteerRelationShip(Int64 cID, Int64 vID)
{
int result = 0;
result = cmpSer.DeletecampaignVolunteerRelationShip(cID,vID);
return result;
}
[HttpGet]
public ActionResult PresentRelationships(int ?cmpID)
{
if (cmpID != null)
{
var c = cmpSer.get((Int32)cmpID);
if (c != null)
{
ViewBag.campaignName = ((campaign)c).campaignName;
}
else
{
ViewBag.campaignName = "";
}
}
ViewBag.usertypes = cmpSer.get().Select(e => new { e.userTypeID, e.userTypeName }).OrderByDescending(e=>e.userTypeID).Take(3);
ViewBag.campaignID = cmpID;
return View();
}
[HttpPost]
public ActionResult PresentRelationships(string cmpID,string userTypeID)
{
var result = cmpSer.getAllRelationshipsInCampaignByUserType(cmpID, userTypeID);
return PartialView("_partialViewAllRelationships", result);
}
public ActionResult getElectionByElectionTypeID(int ElectionTypeID)
{
var electionList= _ElectionService.getAllElections().Where(e => e.electionTypeID == ElectionTypeID).Select(e=>new { e.electionID,e.electionName1,e.electionYear});
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(electionList);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using electo.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class VidhanSabhaController : BaseClass
{
private readonly IVSCServices _VSCServices;
private readonly IstateService _stateService;
private readonly ILSCServices _LSCServices;
private readonly IDistrictServices _DistrictServices;
public VidhanSabhaController()
{
_VSCServices = new VSCServices();
_stateService = new stateService();
_LSCServices = new LSCServices();
_DistrictServices = new DistrictServices();
}
// GET: VidhanSabha
public ActionResult Index()
{
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult GetLOCKSABHAConstituencyLsit(int stateId)
{
var lstConstituency = _LSCServices.getAlllokSabhaConstituencyConstituency(stateId).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(lstConstituency);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult getDistrictListByStateID(int stateId)
{
var DistrictList = _DistrictServices.getDistrictByStateID(stateId).Select(e => new { e.districtID, e.districtName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(DistrictList);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult getvidhanSabhaConstituencyByStateID(int stateId)
{
var DistrictList = _VSCServices.getvidhanSabhaConstituencyByStateID(stateId).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(DistrictList);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult _partialVidhanSabhaList(int stateId, int LSCID, string VSC_NAME)
{
var vidhanSabha = _VSCServices.getvidhanSabhaConstituencyByStateIDANDLKSCID(stateId, LSCID, VSC_NAME);
return PartialView("_partialVidhanSabhaList", vidhanSabha);
}
public ActionResult getvidhanSabhaConstituencyByStateIDANDLKSCID(int stateId, int LSCID)
{
var vidhanSabha = _VSCServices.getvidhanSabhaConstituencyByStateIDANDLKSCID(stateId,LSCID,"").Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(vidhanSabha);
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
ViewBag.lokSabhaConstituencyID = _LSCServices.getAlllokSabhaConstituencyConstituency(1).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
ViewBag.msg = "";
return View();
}
[HttpPost]
public ActionResult Create(vidhanSabhaConstituency ovidhanSabhaConstituency, FormCollection frm)
{
bool result = false;
ovidhanSabhaConstituency.dataIsCreated = BaseUtil.GetCurrentDateTime();
ovidhanSabhaConstituency.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ovidhanSabhaConstituency.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ovidhanSabhaConstituency.dataIsUpdated = BaseUtil.GetCurrentDateTime();
ovidhanSabhaConstituency.isActive = true;
if (ModelState.IsValid)
{
result = _VSCServices.CreateVidhanSabha(ovidhanSabhaConstituency);
}
if (result)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
ViewBag.msg = "Error ! Data not saved";
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
ViewBag.lokSabhaConstituencyID = _LSCServices.getAlllokSabhaConstituencyConstituency(1).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
TempData["Result"] = "unsuccess";
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IbiographyServices
{
int createbiography(Biography_s Biography_s_);
Biography_s Find(int id);
int updatebiography(Biography_s Biography_s_);
IEnumerable<sp_getAllBiographiesStartwithLetter_Result> getListStartWith(string Variable_);
}
}
<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class zoneController : BaseClass
{
private readonly IstateService _stateService;
private readonly ImuncipalCorporationServices _muncipalCorporationServices;
private readonly IzoneServices _zoneServices;
private readonly IDistrictServices _DistrictServices;
public zoneController()
{
_zoneServices = new zoneServices();
_stateService = new stateService();
_muncipalCorporationServices = new muncipalCorporationServices();
_DistrictServices = new DistrictServices();
}
// GET: zone
public ActionResult Index()
{
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult getMuncipalCorporationListByStateID(int stateId)
{
var muncipalList = _muncipalCorporationServices.getmuncipalCorporationByStateID(stateId).Select(e => new { e.municipalCorporationID, e.municipalCorporationName1 });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(muncipalList);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult getDistrictListByStateID(int stateId)
{
var districtList = _DistrictServices.getDistrictByStateID(stateId).Select(e => new { e.districtID, e.districtName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(districtList);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult getZoneListBymuncipalCorpID(int stateId, int MPCorporation)
{
var ZoneList = _zoneServices.getZoneByStateIDAndMUncipalCorporationID(stateId, MPCorporation).Select(e => new { e.zoneID, e.zoneName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(ZoneList);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult _partialZoneList(int stateId, int MPCorporation)
{
var ZoneList = _zoneServices.getZoneByStateIDAndMUncipalCorporationID(stateId, MPCorporation);
return PartialView("_partialZoneList", ZoneList);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.municipalCorporationID = _muncipalCorporationServices.getmuncipalCorporationByStateID(1).Select(e => new { e.municipalCorporationID, e.municipalCorporationName1 });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
return View();
}
[HttpPost]
public ActionResult Create(zoneMunicipality ozoneMunicipality)
{
bool result = false;
ozoneMunicipality.dataIsCreated = BaseUtil.GetCurrentDateTime();
ozoneMunicipality.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ozoneMunicipality.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ozoneMunicipality.dataIsUpdatd = BaseUtil.GetCurrentDateTime();
if (ModelState.IsValid)
{
result = _zoneServices.CreateVidhanSabha(ozoneMunicipality);
}
if (result)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.municipalCorporationID = _muncipalCorporationServices.getmuncipalCorporationByStateID(1).Select(e => new { e.municipalCorporationID, e.municipalCorporationName1 });
TempData["Result"] = "unuccess";
return View();
}
}
}<file_sep>using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.IRepositories
{
interface IEventServices
{
#region HR IService Function
IEnumerable<sp_Event_GetByCampaignId_Result> GetByCampaignId(long Id);
IEnumerable<sp_Event_GetByEventTypeId_Result> GetByEventTypeId(long Id);
IEnumerable<sp_Event_GetByCampaignIdANDEventTypeID_Result> GetByCampaignIdANDEventTypeID(long Id, int EventTypeId);
#endregion
int createEvent(sp_createEvent osp_createEvent);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using electo.Models.ViewModels;
using electo.Models.Repositories;
using electo.Models;
using electo.Models.BaseClass;
namespace electo.Controllers
{
[CustomErrorHandling]
public class dashboardController : BaseClass
{
// GET: dashboard
private DashBoardServices _objectDashBoardServices = new DashBoardServices();
public ActionResult Dashboard()
{
DashBoardViewModels _objectDashBoardViewModels = new DashBoardViewModels();
_objectDashBoardViewModels.newCampaignRequests = _objectDashBoardServices.GetNewCampaignRequests_Result();
_objectDashBoardViewModels.getUpcomingElections = _objectDashBoardServices.GetUpcomingElections_Result();
_objectDashBoardViewModels.getRunningCampaigns = _objectDashBoardServices.GetRunningCampaigns_Result();
_objectDashBoardViewModels.getNewEnquiries = _objectDashBoardServices.GetNewEnquiries_Result();
var newCampaignCount = _objectDashBoardViewModels.newCampaignRequests.Count();
var upComingElectionCount = _objectDashBoardViewModels.getUpcomingElections.Count();
var runningCampaignCount= _objectDashBoardViewModels.getRunningCampaigns.Count();
var newEnquiriesCount = _objectDashBoardViewModels.getNewEnquiries.Count();
ViewBag.newCampaignCount = newCampaignCount;
ViewBag.upComingElectionCount = upComingElectionCount;
ViewBag.runningCampaignCount = runningCampaignCount;
ViewBag.newEnquiriesCount = newEnquiriesCount;
return View(_objectDashBoardViewModels);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
namespace electo.WebServicesController
{
public class SurveysController : ApiController
{
//private electoEntities db = new electoEntities();
private readonly ISurveyServices _surveyServices;
public SurveysController()
{
_surveyServices = new SurveyServices();
}
public IHttpActionResult GetSurveys()
{
var objSurveyList = _surveyServices.GetAll();
if (objSurveyList != null)
{
var surveyEntities = objSurveyList as List<sp_Survey_GetAll_Result> ?? objSurveyList.ToList();
if (surveyEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, surveyEntities);
return Json(new { status = "Success", msg = "Record found", data = surveyEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Survey data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
public IHttpActionResult GetByCampaign(long Id)
{
var objSurveyList = _surveyServices.GetByCampaignId(Id);
if (objSurveyList != null)
{
var surveyEntities = objSurveyList as List<sp_Survey_GetByCampaignId_Result> ?? objSurveyList.ToList();
if (surveyEntities.Any())
{
// return Request.CreateResponse(HttpStatusCode.OK, surveyEntities);
return Json(new { status = "Success", msg = "Record found", data = surveyEntities });
}
}
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Survey data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//// GET: api/Surveys
//public IQueryable<survey> Getsurveys()
//{
// return db.surveys;
//}
//// GET: api/Surveys/5
//[ResponseType(typeof(survey))]
//public IHttpActionResult Getsurvey(long id)
//{
// survey survey = db.surveys.Find(id);
// if (survey == null)
// {
// return NotFound();
// }
// return Ok(survey);
//}
//// PUT: api/Surveys/5
//[ResponseType(typeof(void))]
//public IHttpActionResult Putsurvey(long id, survey survey)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// if (id != survey.surveyID)
// {
// return BadRequest();
// }
// db.Entry(survey).State = EntityState.Modified;
// try
// {
// db.SaveChanges();
// }
// catch (DbUpdateConcurrencyException)
// {
// if (!surveyExists(id))
// {
// return NotFound();
// }
// else
// {
// throw;
// }
// }
// return StatusCode(HttpStatusCode.NoContent);
//}
//// POST: api/Surveys
//[ResponseType(typeof(survey))]
//public IHttpActionResult Postsurvey(survey survey)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// db.surveys.Add(survey);
// db.SaveChanges();
// return CreatedAtRoute("DefaultApi", new { id = survey.surveyID }, survey);
//}
//// DELETE: api/Surveys/5
//[ResponseType(typeof(survey))]
//public IHttpActionResult Deletesurvey(long id)
//{
// survey survey = db.surveys.Find(id);
// if (survey == null)
// {
// return NotFound();
// }
// db.surveys.Remove(survey);
// db.SaveChanges();
// return Ok(survey);
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// db.Dispose();
}
base.Dispose(disposing);
}
//private bool surveyExists(long id)
//{
// return db.surveys.Count(e => e.surveyID == id) > 0;
//}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class SurveyQuestionServices : ISurveyQuestionServices
{
private readonly UnitOfWork uow;
public SurveyQuestionServices()
{
uow = new UnitOfWork();
}
#region HR Service Function
public IEnumerable<sp_SurveyQuestion_GetBySurveyId_Result> GetBySurveyId(long Id)
{
var SurveyId = new SqlParameter("@SurveyId", Id);
var SurveyQuestionId = uow.sp_SurveyQuestion_GetBySurveyId_Result_.SQLQuery<sp_SurveyQuestion_GetBySurveyId_Result>("sp_SurveyQuestion_GetBySurveyId @SurveyId", SurveyId).ToList();
if (SurveyQuestionId != null)
{
return SurveyQuestionId;
}
return null;
}
#endregion
public int CreateSurveyQuestion(surveyQuestionViewModel osurveyQuestionViewModel)
{
var surveyID = new SqlParameter("@surveyID", osurveyQuestionViewModel.surveyID);
var questionSerial = new SqlParameter("@questionSerial", osurveyQuestionViewModel.questionSerial);
var question = new SqlParameter("@question", osurveyQuestionViewModel.question);
var dataIsCreated = new SqlParameter("@dataIsCreated", BaseUtil.GetCurrentDateTime());
var createdBy = new SqlParameter("@createdBy", Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString())));
var questionTypeID = new SqlParameter("@questionTypeID", osurveyQuestionViewModel.questionTypeID);
var op1 = new SqlParameter("@op1", osurveyQuestionViewModel.questionOP1);
var op2 = new SqlParameter("@op2", osurveyQuestionViewModel.questionOP2);
var op3 = new SqlParameter("@op3", SqlString.Null);
var op4 = new SqlParameter("@op4", SqlString.Null);
int result = 0;
try
{
string q = string.Empty;
if (osurveyQuestionViewModel.questionTypeID == 1)
{
result = uow.sp_createParty_Result_.SQLQuery<int>("sp_createSurveyQuestion @surveyID, @questionSerial,@question, @dataIsCreated,@createdBy,@questionTypeID,@op1,@op2", surveyID, questionSerial, question, dataIsCreated, createdBy, questionTypeID, op1, op2).FirstOrDefault();
}
if (osurveyQuestionViewModel.questionTypeID == 2)
{
op3 = new SqlParameter("@op3", osurveyQuestionViewModel.questionOP3);
op4 = new SqlParameter("@op4", osurveyQuestionViewModel.questionOP4);
result = uow.sp_createParty_Result_.SQLQuery<int>("sp_createSurveyQuestion @surveyID, @questionSerial,@question, @dataIsCreated,@createdBy,@questionTypeID,@op1,@op2,@op3,@op4", surveyID, questionSerial, question, dataIsCreated, createdBy, questionTypeID, op1, op2,op3,op4).FirstOrDefault();
}
}
catch { }
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IAccountServices
{
sp_LoginUser_Result UserLogin(String userID, string password);
string forgetpassword(string Email);
int ResetPassword(string newPassword, long LoginID);
IEnumerable<politicalParty> getAll();
IEnumerable<userType> getAllUserTypes();
IEnumerable< sp_getVoterDetailsByVoterID_Result> getDet(string voterIDNumber);
string createUser(string _voterID, string _politicalPartyID, string _dataIsCreated, string _dataIsUpdated, string _createdBy, string _modifiedBy, string _userID, string _mobile, string _fullName, bool _isActive,bool _isBlocked, string AAdharNumber, int userTypeid);
int ActivateCreateCompaign(long volunteerID);
IEnumerable<sp_getAllParties_NoParams_Result> getAllPoliticalParty();
loginVolunteer getUserDetails(long loginID);
int saveUserDetails(loginVolunteer _loginVolunteer);
int saveLogoutDetails(long loginID, DateTime currentDateTime);
IEnumerable<sp_searchUserLoginStatus_Result> getUserLoginStatus(int userTypeID, string userID);
sp_LoginUser_App_Result UserLoginApp(String userID, string password, int userTypeID);
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class biographyServices: IbiographyServices
{
private readonly UnitOfWork uow;
public biographyServices()
{
uow = new UnitOfWork();
}
public int createbiography(Biography_s Biography_s_)
{
int result=0;
try
{
Biography_s_.createdBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
Biography_s_.modifiedBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
Biography_s_.dataIsCreated = BaseUtil.GetCurrentDateTime();
Biography_s_.dataIsUpdated = BaseUtil.GetCurrentDateTime();
uow.Biography_s_.Add(Biography_s_);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
public Biography_s Find(int id) {
var Biography_s_ = uow.Biography_s_.GetByID(id);
if (Biography_s_ != null)
{
return Biography_s_;
}
else {
return null;
}
}
public int updatebiography(Biography_s Biography_s_)
{
int result = 0;
try
{
Biography_s_.modifiedBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
Biography_s_.dataIsUpdated = BaseUtil.GetCurrentDateTime();
uow.Biography_s_.Update(Biography_s_);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
public IEnumerable<sp_getAllBiographiesStartwithLetter_Result> getListStartWith(string Variable_)
{
var Variable_letter = new SqlParameter("@NAME", SqlString.Null);
if (Variable_!=null)
{
Variable_letter = new SqlParameter("@NAME", Variable_);
}
try
{
return uow.Biography_s_.SQLQuery<sp_getAllBiographiesStartwithLetter_Result>("sp_getAllBiographiesStartwithLetter @NAME", Variable_letter).ToList();
}
catch (Exception e){ }
return null;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
namespace electo.WebServicesController
{
public class AreasController : ApiController
{
//private electoEntities db = new electoEntities();
private readonly IAreaService _areaService;
public AreasController()
{
_areaService = new AreaService();
}
public IHttpActionResult GetAreas()
{
var objAreaList = _areaService.GetAll();
if (objAreaList != null)
{
var areaEntity = objAreaList as List<sp_Area_GetAll_Result> ?? objAreaList.ToList();
if (areaEntity != null)
{
//return Request.CreateResponse(HttpStatusCode.OK, areaEntity);
return Json(new { status = "Success", msg = "Record found", data = areaEntity });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Area data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//public IEnumerable<sp_Area_GetByPageInchargeId_Result> GetByPageInchargeId(long Id)
public IHttpActionResult GetByPageInchargeId(long Id)
{
var objAreaList = _areaService.GetByPageInchargeId(Id);
if (objAreaList != null)
{
var areaEntities = objAreaList as List<sp_Area_GetByPageInchargeId_Result> ?? objAreaList.ToList();
if (areaEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, areaEntities);
return Json(new { status = "Success", msg = "Record found", data = areaEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Area data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//// GET: api/Areas
//public IQueryable<areaName> GetareaNames()
//{
// return db.areaNames;
//}
//// GET: api/Areas/5
//[ResponseType(typeof(areaName))]
//public IHttpActionResult GetareaName(long id)
//{
// areaName areaName = db.areaNames.Find(id);
// if (areaName == null)
// {
// return NotFound();
// }
// return Ok(areaName);
//}
//// PUT: api/Areas/5
//[ResponseType(typeof(void))]
//public IHttpActionResult PutareaName(long id, areaName areaName)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// if (id != areaName.areaID)
// {
// return BadRequest();
// }
// db.Entry(areaName).State = EntityState.Modified;
// try
// {
// db.SaveChanges();
// }
// catch (DbUpdateConcurrencyException)
// {
// if (!areaNameExists(id))
// {
// return NotFound();
// }
// else
// {
// throw;
// }
// }
// return StatusCode(HttpStatusCode.NoContent);
//}
//// POST: api/Areas
//[ResponseType(typeof(areaName))]
//public IHttpActionResult PostareaName(areaName areaName)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// db.areaNames.Add(areaName);
// db.SaveChanges();
// return CreatedAtRoute("DefaultApi", new { id = areaName.areaID }, areaName);
//}
//// DELETE: api/Areas/5
//[ResponseType(typeof(areaName))]
//public IHttpActionResult DeleteareaName(long id)
//{
// areaName areaName = db.areaNames.Find(id);
// if (areaName == null)
// {
// return NotFound();
// }
// db.areaNames.Remove(areaName);
// db.SaveChanges();
// return Ok(areaName);
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// db.Dispose();
}
base.Dispose(disposing);
}
//private bool areaNameExists(long id)
//{
// return db.areaNames.Count(e => e.areaID == id) > 0;
//}
}
}<file_sep>using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace electo.WebServicesController
{
public class biographyController : ApiController
{
private readonly IbiographyServices biographyServices_;
public biographyController()
{
biographyServices_ = new biographyServices();
}
public IHttpActionResult getBiographyListStartWithcharacter(string name)
{
var biographyList_ = biographyServices_.getListStartWith(name);
if (biographyList_ != null)
{
var biographyList = biographyList_ as List<sp_getAllBiographiesStartwithLetter_Result> ?? biographyList_.ToList();
if (biographyList != null)
{
//return Request.CreateResponse(HttpStatusCode.OK, biographyList);
return Json(new { status = "Success", msg = "Record found", data = biographyList });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Record not found");
return Json(new { status = "Error", msg = "Record not found" });
}
}
}
<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
[CustomErrorHandling]
public class DistrictController : BaseClass
{
private readonly IDistrictServices _DistrictServices;
private readonly IstateService _stateService;
public DistrictController()
{
_DistrictServices = new DistrictServices();
_stateService = new stateService();
}
// GET: District
public ActionResult Index()
{
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult _partialDistrictList(int stateId) {
var _DistrictList = _DistrictServices.getDistrictByStateID(stateId);
return PartialView("_partialDistrictList", _DistrictList);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.stateID = _stateService.getAllStates();
return View();
}
[HttpPost]
public ActionResult Create(district odistrict)
{
int result = 0;
result = _DistrictServices.create(odistrict);
if (result == 1)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
else
{
TempData["Result"] = "unsuccess";
ViewBag.stateID = _stateService.getAllStates();
return View();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
namespace electo.WebServicesController
{
public class EnquiriesController : ApiController
{
private electoEntities db = new electoEntities();
// GET: api/Enquiries
public IQueryable<enquiry> Getenquiries()
{
return db.enquiries;
}
// GET: api/Enquiries/5
[ResponseType(typeof(enquiry))]
public IHttpActionResult Getenquiry(long id)
{
enquiry enquiry = db.enquiries.Find(id);
if (enquiry == null)
{
return NotFound();
}
return Ok(enquiry);
}
// PUT: api/Enquiries/5
[ResponseType(typeof(void))]
public IHttpActionResult Putenquiry(long id, enquiry enquiry)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != enquiry.enquiryID)
{
return BadRequest();
}
db.Entry(enquiry).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!enquiryExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Enquiries
[ResponseType(typeof(enquiry))]
public IHttpActionResult Postenquiry(enquiry enquiry)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.enquiries.Add(enquiry);
try
{
db.SaveChanges();
}
catch (Exception e)
{
}
return CreatedAtRoute("DefaultApi", new { id = enquiry.enquiryID }, enquiry);
}
// DELETE: api/Enquiries/5
[ResponseType(typeof(enquiry))]
public IHttpActionResult Deleteenquiry(long id)
{
enquiry enquiry = db.enquiries.Find(id);
if (enquiry == null)
{
return NotFound();
}
db.enquiries.Remove(enquiry);
db.SaveChanges();
return Ok(enquiry);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool enquiryExists(long id)
{
return db.enquiries.Count(e => e.enquiryID == id) > 0;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using electo.Models.Repositories;
using electo.WebServicesController;
using static electo.Models.SP_Models.StoredProcedureModels;
using electo.Models.SP_Models;
namespace electo.Models.Repositories
{
public class UnitOfWork : IDisposable
{
private readonly electoEntities _context;
private Repositories<sp_LoginUser_Result> _loginVolunteerRepository { get; set; }
private Repositories<sp_GetNewCampaignRequests_Result> _getNewCampaignRequests_Result { get; set; }
private Repositories<sp_GetUpcomingElections_Result> _getUpcomingElections_Result { get; set; }
private Repositories<sp_GetRunningCampaigns_Result> _getRunningCampaigns_Result { get; set; }
private Repositories<sp_GetNewEnquiries_Result> _getNewEnquiries_Result { get; set; }
private Repositories<electionType> _electionType { get; set; }
private Repositories<enquiryType> _enquiryType { get; set; }
private Repositories<sp_electionList_Result> _sp_electionList_Result { get; set; }
private Repositories<sp_GetRunningCampaigns_Result> _RunningCampaigns_Result { get; set; }
private Repositories<campaign> _getDetails1 { get; set; }
private Repositories<campaign> _saveDetails { get; set; }
private Repositories<campaignPrice> _savePriceDetails { get; set; }
private Repositories<state> _state { get; set; }
private Repositories<district> _district { get; set; }
private Repositories<vidhanSabhaConstituency> _VidhanSabhaConsistuency { get; set; }
private Repositories<lokSabhaConstituency> _lokSabhaConstituency { get; set; }
private Repositories<sp_areaList_Result> _sp_areaList_Result { get; set; }
private Repositories<sp_getVidhanSabhaLsit_Result> _sp_getVidhanSabhaLsit_Result { get; set; }
private Repositories<sp_pollingBoothList_Result> _sp_pollingBoothList_Result { get; set; }
private Repositories<sp_GetNewEnquiries_Result> _sp_GetNewEnquiries_Result { get; set; }
private Repositories<enquiry> _getEnquiryDetails { get; set; }
private Repositories<enquiry> _saveEnquiryDetails { get; set; }
private Repositories<eventType> _eventType { get; set; }
private Repositories<questionType> _questionType { get; set; }
private Repositories<sp_politicalPartyList_Result> _sp_politicalPartyList_Result { get; set; }
private Repositories<sp_createParty_Result> _sp_createParty_Result { get; set; }
private Repositories<campaignPrice> _newCampaignPrice { get; set; }
private Repositories<sp_SearchCampaignPrices_Result> _sp_SearchCampaignPrices_Result { get; set; }
private Repositories<campaignPrice> _getPriceDetails { get; set; }
private Repositories<sp_partyAddressList_Result> _sp_partyAddressList_Result { get; set; }
private Repositories<politicalParty> _politicalParty { get; set; }
private Repositories<politicalPartyAddress> _politicalPartyAddress { get; set; }
private Repositories<loginVolunteer> _loginVolunteer { get; set; }
private Repositories<userType> _userType { get; set; }
private Repositories<sp_getVoterDetailsByVoterID_Result> _sp_getVoterDetailsByVoterID_Result { get; set; }
private Repositories<sp_CreateUser> _sp_CreateUser { get; set; }
private Repositories<monthName> _monthName { get; set; }
private Repositories<tblyear> _tblyear { get; set; }
private Repositories<electionName> _electionName { get; set; }
private Repositories<municipalCorporationName> _municipalCorporationName { get; set; }
private Repositories<zoneMunicipality> _zoneMunicipality { get; set; }
private Repositories<wardConstituency> _wardConstituency { get; set; }
private Repositories<areaName> _createArea { get; set; }
private Repositories<pollingBooth> _createPollingBooth { get; set; }
private Repositories<electionName> _getAllElections { get; set; }
private Repositories<loginVolunteer> _getUserDetails { get; set; }
private Repositories<loginVolunteer> _saveUserDetails { get; set; }
private Repositories<loginVolunteer> _saveLogoutDetails { get; set; }
private Repositories<campaignPrice> _getAllPrices { get; set; }
private Repositories<campaign> _createCampaign { get; set; }
private Repositories<campaign> _getMyCampaigns { get; set; }
private Repositories<sp_GetVolunteers_Result> _Assign { get; set; }
private Repositories<userType> _get { get; set; }
private Repositories<compaignVolunteerRelationship> _createVolunteerRelationship { get; set; }
public Repositories<sp_CheckUserInCampaign_Result> _checkUser { get; set; }
public Repositories<compaignVolunteerRelationship> _updateRelationShip { get; set; }
public Repositories<news> _createNews { get; set; }
public Repositories<sp_GetLatestNews_Result> _getNews { get; set; }
public Repositories<sp_getAreaListByCampignID_Result> _getAreaListByCampignID { get; set; }
public Repositories<pageInchargeAssignedArea> _assignPageInchargeArea { get; set; }
public Repositories<sp_GetAllSectionInchargeByCampaign_Result> _getAllSectionInchargeByCampaign { get; set; }
public Repositories<sp_getAllRelationshipsInCampaignByUserType_Result_> _getAllRelationshipsInCampaignByUserType { get; set; }
public Repositories<sp_GetVoters_List_Result> _getVoters { get; set; }
public Repositories<sp_GetAllEventTypes_Result> _getEventTypes { get; set; }
public Repositories<surveyRespons> _submitResponse { get; set; }
public Repositories<campaign> _getCampaignNames { get; set; }
private Repositories <language> _language { get; set; }
private Repositories<sp_getAllParties_NoParams_Result> _sp_getAllParties_NoParams_Result { get; set; }
private Repositories<survey> _survey { get; set; }
private Repositories<sp_createSurveyQuestion_Result> _sp_createSurveyQuestion_Result { get; set; }
private Repositories<sp_createEvent> _sp_createEvent { get; set; }
private Repositories<Biography_s> _Biography_s { get; set; }
private Repositories<sp_GetAllDataEntryOperators_Result> _getAllDataEntryOperators { get; set; }
private Repositories<pollingBooth_andInchargRelationship> _pollingBooth_andInchargRelationship { get; set; }
#region HR Property 1
private Repositories<sp_Campaigns_GetAll_Result> _sp_Campaigns_GetAll { get; set; }
private Repositories<sp_Campaigns_GetByElectionId_Result> _sp_Campaigns_GetByElectionId { get; set; }
private Repositories<sp_Campaigns_GetByElectionTypeId_Result> _sp_Campaigns_GetByElectionTypeId { get; set; }
private Repositories<sp_Campaigns_GetById_Result> _sp_Campaigns_GetById { get; set; }
private Repositories<sp_Campaigns_GetByLokSabhaConstituencyId_Result> _sp_Campaigns_GetByLokSabhaConstituencyId { get; set; }
private Repositories<sp_Campaigns_GetByPoliticalPartyId_Result> _sp_Campaigns_GetByPoliticalPartyId { get; set; }
private Repositories<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result> _sp_Campaigns_GetByVidhanSabhaConstituencyId { get; set; }
private Repositories<sp_Campaigns_GetByVolunteerId_Result> _sp_Campaigns_GetByVolunteerId { get; set; }
private Repositories<sp_Campaigns_GetByWardId_Result> _sp_Campaigns_GetByWardId { get; set; }
//20180222
private Repositories<sp_Area_GetAll_Result> _sp_Area_GetAll { get; set; }
private Repositories<sp_Area_GetByPageInchargeId_Result> _sp_Area_GetByPageInchargeId { get; set; }
//private Repositories<sp_Area_GetByVolunteerId_Result> _sp_Area_GetByVolunteerId { get; set; }
private Repositories<sp_Event_GetByCampaignIdANDEventTypeID_Result> _sp_Event_GetByCampaignId { get; set; }
private Repositories<sp_Event_GetByEventTypeId_Result> _sp_Event_GetByEventTypeId { get; set; }
private Repositories<sp_Survey_GetAll_Result> _sp_Survey_GetAll { get; set; }
private Repositories<sp_Survey_GetByCampaignId_Result> _sp_Survey_GetByCampaignId { get; set; }
private Repositories<sp_SurveyQuestion_GetBySurveyId_Result> _sp_SurveyQuestion_GetBySurveyId { get; set; }
private Repositories<sp_Voters_GetAll_Result> _sp_Voters_GetAll { get; set; }
private Repositories<sp_Voters_GetById_Result> _sp_Voters_GetById { get; set; }
private Repositories<sp_Voters_GetByPageInchargeId_Result> _sp_Voters_GetByPageInchargeId { get; set; }
//20180228
private Repositories<sp_Voters_GetByStateId_Result> _sp_Voters_GetByStateId { get; set; }
private Repositories<sp_Voters_GetByAreaId_Result> _sp_Voters_GetByAreaId { get; set; }
private Repositories<sp_Voters_GetByVidhanSabhaConstituencyId_Result> _sp_Voters_GetByVidhanSabhaConstituencyId { get; set; }
private Repositories<sp_Voters_GetByLokSabhaConstituencyId_Result> _sp_Voters_GetByLokSabhaConstituencyId { get; set; }
private Repositories<sp_Voters_GetByWardId_Result> _sp_Voters_GetByWardId { get; set; }
//20180312
private Repositories<sp_PageInchargeComments_ByCampaignId_Result> _sp_PageInchargeComments_ByCampaignId { get; set; }
//20180313
private Repositories<sp_SurveyAnalysis_BySurveyId_Result> _sp_SurveyAnalysis_BySurveyId { get; set; }
private Repositories<sp_Voters_DeleteByVoterId> _sp_Voters_DeleteByVoterId { get; set; }
//20180314
private Repositories<sp_Voters_UpdateDetail> _sp_Voters_UpdateDetail { get; set; }
//20180319
private Repositories<sp_Voters_VerifyByPageIncharge> _sp_Voters_VerifyVoterByPageIncharge { get; set; }
//20180322
private Repositories<sp_SectionIncharge_GetAllByBoothIncharge_Result> _sp_SectionIncharge_GetAllByBoothIncharge_Result { get; set; }
#endregion
private Repositories<voterList> _voterList { get; set; }
public UnitOfWork()
{
_context = new electoEntities();
}
public Repositories<campaign> getCampaignNames_
{
get
{
if (this._getCampaignNames == null)
this._getCampaignNames = new Repositories<campaign>(_context);
return _getCampaignNames;
}
}
public Repositories<surveyRespons> submitResponse_
{
get
{
if (this._submitResponse == null)
this._submitResponse = new Repositories<surveyRespons>(_context);
return _submitResponse;
}
}
public Repositories<sp_GetAllEventTypes_Result> getEventTypes_
{
get
{
if (this._getEventTypes == null)
this._getEventTypes = new Repositories<sp_GetAllEventTypes_Result>(_context);
return _getEventTypes;
}
}
public Repositories<sp_GetVoters_List_Result> getVoters_
{
get
{
if (this._getVoters == null)
this._getVoters = new Repositories<sp_GetVoters_List_Result>(_context);
return _getVoters;
}
}
public Repositories<sp_GetAllDataEntryOperators_Result> getAllDataEntryOperators_
{
get
{
if (this._getAllDataEntryOperators == null)
this._getAllDataEntryOperators = new Repositories<sp_GetAllDataEntryOperators_Result>(_context);
return _getAllDataEntryOperators;
}
}
public Repositories<voterList> voterList_
{
get
{
if (this._voterList == null)
this._voterList = new Repositories<voterList>(_context);
return _voterList;
}
}
public Repositories<sp_getAllRelationshipsInCampaignByUserType_Result_> getAllRelationshipsInCampaignByUserType_
{
get
{
if (this._getAllRelationshipsInCampaignByUserType == null)
this._getAllRelationshipsInCampaignByUserType = new Repositories<sp_getAllRelationshipsInCampaignByUserType_Result_>(_context);
return _getAllRelationshipsInCampaignByUserType;
}
}
public Repositories<sp_GetAllSectionInchargeByCampaign_Result> getAllSectionInchargeByCampaign_
{
get
{
if (this._getAllSectionInchargeByCampaign == null)
this._getAllSectionInchargeByCampaign = new Repositories<sp_GetAllSectionInchargeByCampaign_Result>(_context);
return _getAllSectionInchargeByCampaign;
}
}
public Repositories<pollingBooth_andInchargRelationship> pollingBooth_andInchargRelationship_
{
get
{
if (this._pollingBooth_andInchargRelationship == null)
this._pollingBooth_andInchargRelationship = new Repositories<pollingBooth_andInchargRelationship>(_context);
return _pollingBooth_andInchargRelationship;
}
}
public Repositories<pageInchargeAssignedArea> assignPageInchargeArea_
{
get
{
if (this._assignPageInchargeArea == null)
this._assignPageInchargeArea = new Repositories<pageInchargeAssignedArea>(_context);
return _assignPageInchargeArea;
}
}
public Repositories<sp_getAreaListByCampignID_Result> getAreaListByCampignID_
{
get
{
if (this._getAreaListByCampignID == null)
this._getAreaListByCampignID = new Repositories<sp_getAreaListByCampignID_Result>(_context);
return _getAreaListByCampignID;
}
}
public Repositories<sp_GetLatestNews_Result> getNews_
{
get
{
if (this._getNews == null)
this._getNews = new Repositories<sp_GetLatestNews_Result>(_context);
return _getNews;
}
}
public Repositories<news> createNews_
{
get
{
if (this._createNews == null)
this._createNews = new Repositories<news>(_context);
return _createNews;
}
}
public Repositories<Biography_s> Biography_s_
{
get
{
if (this._Biography_s == null)
this._Biography_s = new Repositories<Biography_s>(_context);
return _Biography_s;
}
}
public Repositories<compaignVolunteerRelationship> updateRelationShip_
{
get
{
if (this._updateRelationShip == null)
this._updateRelationShip = new Repositories<compaignVolunteerRelationship>(_context);
return _updateRelationShip;
}
}
public Repositories<sp_CheckUserInCampaign_Result> checkUser_
{
get
{
if (this._checkUser == null)
this._checkUser = new Repositories<sp_CheckUserInCampaign_Result>(_context);
return _checkUser;
}
}
public Repositories<compaignVolunteerRelationship> createVolunteerRelationship_
{
get
{
if (this._createVolunteerRelationship == null)
this._createVolunteerRelationship = new Repositories<compaignVolunteerRelationship>(_context);
return _createVolunteerRelationship;
}
}
public Repositories<userType> get_
{
get
{
if (this._get == null)
this._get = new Repositories<userType>(_context);
return _get;
}
}
public Repositories<sp_GetVolunteers_Result> Assign_
{
get
{
if (this._Assign == null)
this._Assign = new Repositories<sp_GetVolunteers_Result>(_context);
return _Assign;
}
}
public Repositories<campaign> getMyCampaigns_
{
get
{
if (this._getMyCampaigns == null)
this._getMyCampaigns = new Repositories<campaign>(_context);
return _getMyCampaigns;
}
}
public Repositories<sp_createEvent> sp_createEvent_
{
get
{
if (this._sp_createEvent == null)
this._sp_createEvent = new Repositories<sp_createEvent>(_context);
return _sp_createEvent;
}
}
public Repositories<campaign> createCampaign_
{
get
{
if (this._createCampaign == null)
this._createCampaign = new Repositories<campaign>(_context);
return _createCampaign;
}
}
public Repositories<campaignPrice> getAllPrices_
{
get
{
if (this._getAllPrices == null)
this._getAllPrices = new Repositories<campaignPrice>(_context);
return _getAllPrices;
}
}
public Repositories<sp_createSurveyQuestion_Result> sp_createSurveyQuestion_Result_
{
get
{
if (this._sp_createSurveyQuestion_Result == null)
this._sp_createSurveyQuestion_Result = new Repositories<sp_createSurveyQuestion_Result>(_context);
return _sp_createSurveyQuestion_Result;
}
}
public Repositories<survey> survey_
{
get
{
if (this._survey == null)
this._survey = new Repositories<survey>(_context);
return _survey;
}
}
public Repositories<loginVolunteer> saveLogoutDetails_
{
get
{
if (this._saveLogoutDetails == null)
this._saveLogoutDetails = new Repositories<loginVolunteer>(_context);
return _saveLogoutDetails;
}
}
public Repositories<loginVolunteer> saveUserDetails_
{
get
{
if (this._saveUserDetails == null)
this._saveUserDetails = new Repositories<loginVolunteer>(_context);
return _saveUserDetails;
}
}
public Repositories<loginVolunteer> getUserDetails_
{
get
{
if (this._getUserDetails == null)
this._getUserDetails = new Repositories<loginVolunteer>(_context);
return _getUserDetails;
}
}
public Repositories<electionName> getAllElections_
{
get
{
if (this._getAllElections == null)
this._getAllElections = new Repositories<electionName>(_context);
return _getAllElections;
}
}
public Repositories<pollingBooth> createPollingBooth_
{
get
{
if (this._createPollingBooth == null)
this._createPollingBooth = new Repositories<pollingBooth>(_context);
return _createPollingBooth;
}
}
public Repositories<areaName> createArea_
{
get
{
if (this._createArea == null)
this._createArea = new Repositories<areaName>(_context);
return _createArea;
}
}
public Repositories<language> language_
{
get
{
if (this._language == null)
this._language = new Repositories<language>(_context);
return _language;
}
}
public Repositories<wardConstituency> wardConstituency_
{
get
{
if (this._wardConstituency == null)
this._wardConstituency = new Repositories<wardConstituency>(_context);
return _wardConstituency;
}
}
public Repositories<zoneMunicipality> zoneMunicipality_
{
get
{
if (this._zoneMunicipality == null)
this._zoneMunicipality = new Repositories<zoneMunicipality>(_context);
return _zoneMunicipality;
}
}
public Repositories<municipalCorporationName> municipalCorporationName_
{
get
{
if (this._municipalCorporationName == null)
this._municipalCorporationName = new Repositories<municipalCorporationName>(_context);
return _municipalCorporationName;
}
}
public Repositories<sp_getAllParties_NoParams_Result> sp_getAllParties_NoParams_Result_
{
get
{
if (this._sp_getAllParties_NoParams_Result == null)
this._sp_getAllParties_NoParams_Result = new Repositories<sp_getAllParties_NoParams_Result>(_context);
return _sp_getAllParties_NoParams_Result;
}
}
public Repositories<tblyear> tblyear_
{
get
{
if (this._tblyear == null)
this._tblyear = new Repositories<tblyear>(_context);
return _tblyear;
}
}
public Repositories<electionName> electionName_
{
get
{
if (this._electionName == null)
this._electionName = new Repositories<electionName>(_context);
return _electionName;
}
}
public Repositories<monthName> monthName_
{
get
{
if (this._monthName == null)
this._monthName = new Repositories<monthName>(_context);
return _monthName;
}
}
public Repositories<sp_CreateUser> sp_CreateUser_
{
get
{
if (this._sp_CreateUser == null)
this._sp_CreateUser = new Repositories<sp_CreateUser>(_context);
return _sp_CreateUser;
}
}
public Repositories<sp_Campaigns_GetByWardId_Result> sp_Campaigns_GetByWardId_
{
get
{
if (this._sp_Campaigns_GetByWardId == null)
this._sp_Campaigns_GetByWardId = new Repositories<sp_Campaigns_GetByWardId_Result>(_context);
return _sp_Campaigns_GetByWardId;
}
}
public Repositories<userType> userType_
{
get
{
if (this._userType == null)
this._userType = new Repositories<userType>(_context);
return _userType;
}
}
public Repositories<politicalParty> politicalParty_
{
get
{
if (this._politicalParty == null)
this._politicalParty = new Repositories<politicalParty>(_context);
return _politicalParty;
}
}
public Repositories<loginVolunteer> loginVolunteer_
{
get
{
if (this._loginVolunteer == null)
this._loginVolunteer = new Repositories<loginVolunteer>(_context);
return _loginVolunteer;
}
}
public Repositories<campaignPrice> newCampaignPrice_
{
get
{
if (this._newCampaignPrice == null)
this._newCampaignPrice = new Repositories<campaignPrice>(_context);
return _newCampaignPrice;
}
}
public Repositories<politicalPartyAddress> politicalPartyAddress_
{
get
{
if (this._politicalPartyAddress == null)
this._politicalPartyAddress = new Repositories<politicalPartyAddress>(_context);
return _politicalPartyAddress;
}
}
public Repositories<sp_partyAddressList_Result> sp_partyAddressList_Result_
{
get
{
if (this._sp_partyAddressList_Result == null)
this._sp_partyAddressList_Result = new Repositories<sp_partyAddressList_Result>(_context);
return _sp_partyAddressList_Result;
}
}
public Repositories<campaignPrice> savePriceDetails_
{
get
{
if (this._savePriceDetails == null)
this._savePriceDetails = new Repositories<campaignPrice>(_context);
return _savePriceDetails;
}
}
public Repositories<campaignPrice> _getPriceDetails_
{
get
{
if (this._getPriceDetails == null)
this._getPriceDetails = new Repositories<campaignPrice>(_context);
return _getPriceDetails;
}
}
public Repositories<sp_SearchCampaignPrices_Result> sp_SearchCampaignPrices_Result_
{
get
{
if (this._sp_SearchCampaignPrices_Result == null)
this._sp_SearchCampaignPrices_Result = new Repositories<sp_SearchCampaignPrices_Result>(_context);
return _sp_SearchCampaignPrices_Result;
}
}
public Repositories<sp_createParty_Result> sp_createParty_Result_
{
get
{
if (this._sp_createParty_Result == null)
this._sp_createParty_Result = new Repositories<sp_createParty_Result>(_context);
return _sp_createParty_Result;
}
}
public Repositories<sp_politicalPartyList_Result> sp_politicalPartyList_Result_
{
get
{
if (this._sp_politicalPartyList_Result == null)
this._sp_politicalPartyList_Result = new Repositories<sp_politicalPartyList_Result>(_context);
return _sp_politicalPartyList_Result;
}
}
public Repositories<questionType> questionType_
{
get
{
if (this._questionType == null)
this._questionType = new Repositories<questionType>(_context);
return _questionType;
}
}
public Repositories<eventType> eventType_
{
get
{
if (this._eventType == null)
this._eventType = new Repositories<eventType>(_context);
return _eventType;
}
}
public Repositories<enquiry> saveDetails
{
get
{
if (this._saveEnquiryDetails == null)
this._saveEnquiryDetails = new Repositories<enquiry>(_context);
return _saveEnquiryDetails;
}
}
public Repositories<enquiry> GetEnquiryDetails
{
get
{
if (this._getEnquiryDetails == null)
this._getEnquiryDetails = new Repositories<enquiry>(_context);
return _getEnquiryDetails;
}
}
public Repositories<sp_GetNewEnquiries_Result> sp_GetNewEnquiries_Result
{
get
{
if (this._sp_GetNewEnquiries_Result == null)
this._sp_GetNewEnquiries_Result = new Repositories<sp_GetNewEnquiries_Result>(_context);
return _sp_GetNewEnquiries_Result;
}
}
public Repositories<sp_getVidhanSabhaLsit_Result> sp_getVidhanSabhaLsit_Result_
{
get
{
if (this._sp_getVidhanSabhaLsit_Result == null)
this._sp_getVidhanSabhaLsit_Result = new Repositories<sp_getVidhanSabhaLsit_Result>(_context);
return _sp_getVidhanSabhaLsit_Result;
}
}
public Repositories<state> state_
{
get
{
if (this._state == null)
this._state = new Repositories<state>(_context);
return _state;
}
}
public Repositories<district> district_
{
get
{
if (this._district == null)
this._district = new Repositories<district>(_context);
return _district;
}
}
public Repositories<vidhanSabhaConstituency> VidhanSabhaConsistuency_
{
get
{
if (this._VidhanSabhaConsistuency == null)
this._VidhanSabhaConsistuency = new Repositories<vidhanSabhaConstituency>(_context);
return _VidhanSabhaConsistuency;
}
}
public Repositories<lokSabhaConstituency> _lokSabhaConstituency_
{
get
{
if (this._lokSabhaConstituency == null)
this._lokSabhaConstituency = new Repositories<lokSabhaConstituency>(_context);
return _lokSabhaConstituency;
}
}
public Repositories<sp_areaList_Result> sp_areaList_Result_
{
get
{
if (this._sp_areaList_Result == null)
this._sp_areaList_Result = new Repositories<sp_areaList_Result>(_context);
return _sp_areaList_Result;
}
}
public Repositories<sp_pollingBoothList_Result> sp_pollingBoothList_Result_
{
get
{
if (this._sp_pollingBoothList_Result == null)
this._sp_pollingBoothList_Result = new Repositories<sp_pollingBoothList_Result>(_context);
return _sp_pollingBoothList_Result;
}
}
public Repositories<sp_GetRunningCampaigns_Result> RunningCampaigns_Result
{
get
{
if (this._RunningCampaigns_Result == null)
this._RunningCampaigns_Result = new Repositories<sp_GetRunningCampaigns_Result>(_context);
return _RunningCampaigns_Result;
}
}
public Repositories<campaign> GetDetails_
{
get
{
if (this._getDetails1 == null)
this._getDetails1 = new Repositories<campaign>(_context);
return _getDetails1;
}
}
public Repositories<campaign> SaveDetails
{
get
{
if (this._saveDetails == null)
this._saveDetails = new Repositories<campaign>(_context);
return _saveDetails;
}
}
public Repositories<electionType> electionType
{
get
{
if (this._electionType == null)
this._electionType = new Repositories<electionType>(_context);
return _electionType;
}
}
public Repositories<enquiryType> enquiryType
{
get
{
if (this._enquiryType == null)
this._enquiryType = new Repositories<enquiryType>(_context);
return _enquiryType;
}
}
public Repositories<sp_electionList_Result> sp_electionList_Result
{
get
{
if (this._sp_electionList_Result == null)
this._sp_electionList_Result = new Repositories<sp_electionList_Result>(_context);
return _sp_electionList_Result;
}
}
public Repositories<sp_LoginUser_Result> loginVolunteerRepository
{
get
{
if (this._loginVolunteerRepository == null)
this._loginVolunteerRepository = new Repositories<sp_LoginUser_Result>(_context);
return _loginVolunteerRepository;
}
}
public Repositories<sp_GetNewCampaignRequests_Result> getNewCampaignRequests_Result
{
get
{
if (this._getNewCampaignRequests_Result == null)
this._getNewCampaignRequests_Result = new Repositories<sp_GetNewCampaignRequests_Result>(_context);
return _getNewCampaignRequests_Result;
}
}
public Repositories<sp_GetUpcomingElections_Result> GetUpcomingElections_Result
{
get
{
if (this._getUpcomingElections_Result == null)
this._getUpcomingElections_Result = new Repositories<sp_GetUpcomingElections_Result>(_context);
return _getUpcomingElections_Result;
}
}
public Repositories<sp_GetRunningCampaigns_Result> GetRunningCampaigns_Result
{
get
{
if (this._getRunningCampaigns_Result == null)
this._getRunningCampaigns_Result = new Repositories<sp_GetRunningCampaigns_Result>(_context);
return _getRunningCampaigns_Result;
}
}
public Repositories<sp_GetNewEnquiries_Result> GetNewEnquiries_Result
{
get
{
if (this._getNewEnquiries_Result == null)
this._getNewEnquiries_Result = new Repositories<sp_GetNewEnquiries_Result>(_context);
return _getNewEnquiries_Result;
}
}
#region HR Property 2
public Repositories<sp_Campaigns_GetAll_Result> sp_Campaigns_GetAll_Result_
{
get
{
if (this._sp_Campaigns_GetAll == null)
{
this._sp_Campaigns_GetAll = new Repositories<sp_Campaigns_GetAll_Result>(_context);
}
return _sp_Campaigns_GetAll;
}
}
public Repositories<sp_Campaigns_GetById_Result> sp_Campaigns_GetById_Result_
{
get
{
if (this._sp_Campaigns_GetById == null)
{
this._sp_Campaigns_GetById = new Repositories<sp_Campaigns_GetById_Result>(_context);
}
return _sp_Campaigns_GetById;
}
}
public Repositories<sp_Campaigns_GetByElectionTypeId_Result> sp_Campaigns_GetByElectionTypeId_Result_
{
get
{
if (this._sp_Campaigns_GetByElectionTypeId == null)
{
this._sp_Campaigns_GetByElectionTypeId = new Repositories<sp_Campaigns_GetByElectionTypeId_Result>(_context);
}
return _sp_Campaigns_GetByElectionTypeId;
}
}
public Repositories<sp_Campaigns_GetByElectionId_Result> sp_Campaigns_GetByElectionId_Result_
{
get
{
if (this._sp_Campaigns_GetByElectionId == null)
{
this._sp_Campaigns_GetByElectionId = new Repositories<sp_Campaigns_GetByElectionId_Result>(_context);
}
return _sp_Campaigns_GetByElectionId;
}
}
public Repositories<sp_Campaigns_GetByLokSabhaConstituencyId_Result> _getDetails
{
get
{
if (this._sp_Campaigns_GetByLokSabhaConstituencyId == null)
{
this._sp_Campaigns_GetByLokSabhaConstituencyId = new Repositories<sp_Campaigns_GetByLokSabhaConstituencyId_Result>(_context);
}
return _sp_Campaigns_GetByLokSabhaConstituencyId;
}
}
public Repositories<sp_Campaigns_GetByPoliticalPartyId_Result> sp_Campaigns_GetByPoliticalPartyId_Result_
{
get
{
if (this._sp_Campaigns_GetByPoliticalPartyId == null)
{
this._sp_Campaigns_GetByPoliticalPartyId = new Repositories<sp_Campaigns_GetByPoliticalPartyId_Result>(_context);
}
return _sp_Campaigns_GetByPoliticalPartyId;
}
}
public Repositories<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result> sp_Campaigns_GetByVidhanSabhaConstituencyId_Result_
{
get
{
if (this._sp_Campaigns_GetByVidhanSabhaConstituencyId == null)
{
this._sp_Campaigns_GetByVidhanSabhaConstituencyId = new Repositories<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result>(_context);
}
return _sp_Campaigns_GetByVidhanSabhaConstituencyId;
}
}
public Repositories<sp_Campaigns_GetByVolunteerId_Result> sp_Campaigns_GetByVolunteerId_Result_
{
get
{
if (this._sp_Campaigns_GetByVolunteerId == null)
{
this._sp_Campaigns_GetByVolunteerId = new Repositories<sp_Campaigns_GetByVolunteerId_Result>(_context);
}
return _sp_Campaigns_GetByVolunteerId;
}
}
public Repositories<sp_Campaigns_GetByWardId_Result> sp_Campaigns_GetByWardId_Result_
{
get
{
if (this._sp_Campaigns_GetByWardId == null)
{
this._sp_Campaigns_GetByWardId = new Repositories<sp_Campaigns_GetByWardId_Result>(_context);
}
return _sp_Campaigns_GetByWardId;
}
}
//20180222
//private Repositories<sp_Area_GetAll_Result> _sp_Area_GetAll { get; set; }
public Repositories<sp_Area_GetAll_Result> sp_Area_GetAll_Result_
{
get
{
if (this._sp_Area_GetAll == null)
{
this._sp_Area_GetAll = new Repositories<sp_Area_GetAll_Result>(_context);
}
return _sp_Area_GetAll;
}
}
//private Repositories<sp_Area_GetByPageInchargeId_Result> _sp_Area_GetByPageInchargeId { get; set; }
public Repositories<sp_Area_GetByPageInchargeId_Result> sp_Area_GetByPageInchargeId_Result_
{
get
{
if (this._sp_Area_GetByPageInchargeId == null)
{
this._sp_Area_GetByPageInchargeId = new Repositories<sp_Area_GetByPageInchargeId_Result>(_context);
}
return _sp_Area_GetByPageInchargeId;
}
}
////private Repositories<sp_Area_GetByVolunteerId_Result> _sp_Area_GetByVolunteerId { get; set; }
//public Repositories<sp_Area_GetByVolunteerId_Result> sp_Area_GetByVolunteerId_Result_
//{
// get
// {
// if (this._sp_Area_GetByVolunteerId == null)
// {
// this._sp_Area_GetByVolunteerId = new Repositories<sp_Area_GetByVolunteerId_Result>(_context);
// }
// return _sp_Area_GetByVolunteerId;
// }
//}
//private Repositories<sp_Event_GetByCampaignId_Result> _sp_Event_GetByCampaignId { get; set; }
public Repositories<sp_Event_GetByCampaignIdANDEventTypeID_Result> sp_Event_GetByCampaignId_Result_
{
get
{
if (this._sp_Event_GetByCampaignId == null)
{
this._sp_Event_GetByCampaignId = new Repositories<sp_Event_GetByCampaignIdANDEventTypeID_Result>(_context);
}
return _sp_Event_GetByCampaignId;
}
}
//private Repositories<sp_Event_GetByEventTypeId_Result> _sp_Event_GetByEventTypeId { get; set; }
public Repositories<sp_Event_GetByEventTypeId_Result> sp_Event_GetByEventTypeId_Result_
{
get
{
if (this._sp_Event_GetByEventTypeId == null)
{
this._sp_Event_GetByEventTypeId = new Repositories<sp_Event_GetByEventTypeId_Result>(_context);
}
return _sp_Event_GetByEventTypeId;
}
}
//private repositories<sp_survey_getall_result> _sp_survey_getall { get; set; }
//private Repositories<sp_Survey_GetAll_Result> _sp_Survey_GetAll { get; set; }
public Repositories<sp_Survey_GetAll_Result> sp_Survey_GetAll_Result_
{
get
{
if (this._sp_Survey_GetAll == null)
{
this._sp_Survey_GetAll = new Repositories<sp_Survey_GetAll_Result>(_context);
}
return _sp_Survey_GetAll;
}
}
//private repositories<sp_survey_getbycampaignid_result> _sp_survey_getbycampaignid { get; set; }
public Repositories<sp_Survey_GetByCampaignId_Result> sp_Survey_GetByCampaignId_Result_
{
get
{
if (this._sp_Survey_GetByCampaignId == null)
{
this._sp_Survey_GetByCampaignId = new Repositories<sp_Survey_GetByCampaignId_Result>(_context);
}
return _sp_Survey_GetByCampaignId;
}
}
//private repositories<sp_surveyquestion_getbysurveyid_result> _sp_surveyquestion_getbysurveyid { get; set; }
public Repositories<sp_SurveyQuestion_GetBySurveyId_Result> sp_SurveyQuestion_GetBySurveyId_Result_
{
get
{
if (this._sp_SurveyQuestion_GetBySurveyId == null)
{
this._sp_SurveyQuestion_GetBySurveyId = new Repositories<sp_SurveyQuestion_GetBySurveyId_Result>(_context);
}
return _sp_SurveyQuestion_GetBySurveyId;
}
}
//private repositories<sp_voters_getall_result> _sp_voters_getall { get; set; }
public Repositories<sp_Voters_GetAll_Result> sp_Voters_GetAll_Result_
{
get
{
if (this._sp_Voters_GetAll == null)
{
this._sp_Voters_GetAll = new Repositories<sp_Voters_GetAll_Result>(_context);
}
return _sp_Voters_GetAll;
}
}
//private repositories<sp_voters_getbyid_result> _sp_voters_getbyid { get; set; }
public Repositories<sp_Voters_GetById_Result> sp_Voters_GetById_Result_
{
get
{
if (this._sp_Voters_GetById == null)
{
this._sp_Voters_GetById = new Repositories<sp_Voters_GetById_Result>(_context);
}
return _sp_Voters_GetById;
}
}
//private repositories<sp_voters_getbypageinchargeid_result> _sp_voters_getbypageinchargeid { get; set; }
public Repositories<sp_Voters_GetByPageInchargeId_Result> sp_Voters_GetByPageInchargeId_Result_
{
get
{
if (this._sp_Voters_GetByPageInchargeId == null)
{
this._sp_Voters_GetByPageInchargeId = new Repositories<sp_Voters_GetByPageInchargeId_Result>(_context);
}
return _sp_Voters_GetByPageInchargeId;
}
}
//20180228
//private Repositories<sp_Voters_GetByStateId_Result> _sp_Voters_GetByStateId { get; set; }
public Repositories<sp_Voters_GetByStateId_Result> sp_Voters_GetByStateId_Result_
{
get
{
if (this._sp_Voters_GetByStateId == null)
{
this._sp_Voters_GetByStateId = new Repositories<sp_Voters_GetByStateId_Result>(_context);
}
return _sp_Voters_GetByStateId;
}
}
//private Repositories<sp_Voters_GetByAreaId_Result> _sp_Voters_GetByAreaId { get; set; }
public Repositories<sp_Voters_GetByAreaId_Result> sp_Voters_GetByAreaId_Result_
{
get
{
if (this._sp_Voters_GetByAreaId == null)
{
this._sp_Voters_GetByAreaId = new Repositories<sp_Voters_GetByAreaId_Result>(_context);
}
return _sp_Voters_GetByAreaId;
}
}
//private Repositories<sp_Voters_GetByVidhanSabhaConstituencyId_Result> _sp_Voters_GetByVidhanSabhaConstituencyId { get; set; }
public Repositories<sp_Voters_GetByVidhanSabhaConstituencyId_Result> sp_Voters_GetByVidhanSabhaConstituencyId_Result_
{
get
{
if (this._sp_Voters_GetByVidhanSabhaConstituencyId == null)
{
this._sp_Voters_GetByVidhanSabhaConstituencyId = new Repositories<sp_Voters_GetByVidhanSabhaConstituencyId_Result>(_context);
}
return _sp_Voters_GetByVidhanSabhaConstituencyId;
}
}
//private Repositories<sp_Voters_GetByLokSabhaConstituencyId_Result> _sp_Voters_GetByLokSabhaConstituencyId { get; set; }
public Repositories<sp_Voters_GetByLokSabhaConstituencyId_Result> sp_Voters_GetByLokSabhaConstituencyId_Result_
{
get
{
if (this._sp_Voters_GetByLokSabhaConstituencyId == null)
{
this._sp_Voters_GetByLokSabhaConstituencyId = new Repositories<sp_Voters_GetByLokSabhaConstituencyId_Result>(_context);
}
return _sp_Voters_GetByLokSabhaConstituencyId;
}
}
//private Repositories<sp_Voters_GetByWardId_Result> _sp_Voters_GetByWardId { get; set; }
public Repositories<sp_Voters_GetByWardId_Result> sp_Voters_GetByWardId_Result_
{
get
{
if (this._sp_Voters_GetByWardId == null)
{
this._sp_Voters_GetByWardId = new Repositories<sp_Voters_GetByWardId_Result>(_context);
}
return _sp_Voters_GetByWardId;
}
}
//private Repositories<sp_PageInchargeComments_ByCampaignId_Result> _sp_PageInchargeComments_ByCampaignId { get; set; }
public Repositories<sp_PageInchargeComments_ByCampaignId_Result> sp_PageInchargeComments_ByCampaignId_Result_
{
get
{
if (this._sp_PageInchargeComments_ByCampaignId == null)
{
this._sp_PageInchargeComments_ByCampaignId = new Repositories<sp_PageInchargeComments_ByCampaignId_Result>(_context);
}
return _sp_PageInchargeComments_ByCampaignId;
}
}
//private Repositories<sp_SurveyAnalysis_BySurveyId_Result> _sp_SurveyAnalysis_BySurveyId { get; set; }
public Repositories<sp_SurveyAnalysis_BySurveyId_Result> sp_SurveyAnalysis_BySurveyId_Result_
{
get
{
if (this._sp_SurveyAnalysis_BySurveyId == null)
{
this._sp_SurveyAnalysis_BySurveyId = new Repositories<sp_SurveyAnalysis_BySurveyId_Result>(_context);
}
return _sp_SurveyAnalysis_BySurveyId;
}
}
//private Repositories<sp_Voters_DeleteByVoterId> _sp_Voters_DeleteByVoterId { get; set; }
public Repositories<sp_Voters_DeleteByVoterId> sp_Voters_DeleteByVoterId_
{
get
{
if (this._sp_Voters_DeleteByVoterId == null)
this._sp_Voters_DeleteByVoterId = new Repositories<sp_Voters_DeleteByVoterId>(_context);
return _sp_Voters_DeleteByVoterId;
}
}
//private Repositories<sp_Voters_UpdateDetail> _sp_Voters_UpdateDetail { get; set; }
public Repositories<sp_Voters_UpdateDetail> sp_Voters_UpdateDetail_
{
get
{
if (this._sp_Voters_UpdateDetail == null)
this._sp_Voters_UpdateDetail = new Repositories<sp_Voters_UpdateDetail>(_context);
return _sp_Voters_UpdateDetail;
}
}
//private Repositories<sp_Voters_VerifyByPageIncharge> _sp_Voters_VerifyVoterByPageIncharge { get; set; }
//public Repositories <sp_Voters_VerifyByPageIncharge> sp_Voters_VerifyByPageIncharge_
//{
// get
// {
// if (this._sp_Voters_VerifyVoterByPageIncharge == null)
// {
// this._sp_Voters_VerifyVoterByPageIncharge = new Repositories<sp_Voters_VerifyByPageIncharge>(_context);
// }
// return _sp_Voters_VerifyVoterByPageIncharge;
// }
//}
//20180322
public Repositories<sp_SectionIncharge_GetAllByBoothIncharge_Result> sp_SectionIncharge_GetAllByBoothIncharge_Result_
{
get
{
if (this._sp_SectionIncharge_GetAllByBoothIncharge_Result == null)
this._sp_SectionIncharge_GetAllByBoothIncharge_Result = new Repositories<sp_SectionIncharge_GetAllByBoothIncharge_Result>(_context);
return _sp_SectionIncharge_GetAllByBoothIncharge_Result;
}
}
#endregion
// public IAuthorRepository Authors { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IAreaService
{
IEnumerable<sp_areaList_Result> getAll_areaList(int ElectionTypeId, int stateId, int ddl_Constituency);
int createArea(areaName areaName_);
#region HR IService Function
//20180222
IEnumerable<sp_Area_GetAll_Result> GetAll();
IEnumerable<sp_Area_GetByPageInchargeId_Result> GetByPageInchargeId(long Id);
//IEnumerable<sp_Area_GetByVolunteerId_Result> GetByVolunteerId(long VolunteerId);
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IzoneServices
{
IEnumerable<sp_getZoneByStateIDAndMUncipalCorporationID_Result> getZoneByStateIDAndMUncipalCorporationID(int stateId, int MPCorporation);
bool CreateVidhanSabha(zoneMunicipality ozoneMunicipality);
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class LSCServices : ILSCServices
{
private readonly UnitOfWork uow;
public LSCServices()
{
uow = new UnitOfWork();
}
public IEnumerable<lokSabhaConstituency> getAllvidhanSabhaConstituency()
{
var _lokSabhaConstituencyList = uow._lokSabhaConstituency_.GetAll().ToList();
return _lokSabhaConstituencyList;
}
public IEnumerable<lokSabhaConstituency> getAlllokSabhaConstituencyConstituency(int stateID)
{
var _lokSabhaConstituencyList = uow._lokSabhaConstituency_.Find(e=>e.stateID== stateID).ToList();
return _lokSabhaConstituencyList;
}
public int create(lokSabhaConstituency olkSabha)
{
int result = 0;
olkSabha.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
olkSabha.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
olkSabha.dataIsCreated = BaseUtil.GetCurrentDateTime();
olkSabha.dataIsUpdated = BaseUtil.GetCurrentDateTime();
olkSabha.isActive = true;
try
{
uow._lokSabhaConstituency_.Add(olkSabha);
result = 1;
}
catch { }
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System.IO;
using electo.Models.BaseClass;
namespace electo.Controllers
{
public class NewsController : BaseClass
{
private electoEntities db = new electoEntities();
private readonly IElectionService _ElectionService;
private readonly INewsServices _NewsServices;
public NewsController()
{
_ElectionService = new ElectionService();
_NewsServices = new NewsServices();
}
// GET: News/Create
public ActionResult Create()
{
ViewBag.electionTypeID = _ElectionService.getElectionTypes();
return View();
}
// POST: News/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "electionTypeID,title,description,imageURL")] news news, HttpPostedFileBase files)
{
String fileName = "";
if (files != null)
{
fileName = Guid.NewGuid() + "_" + Path.GetFileName(files.FileName);
var path = Path.Combine(Server.MapPath("~/newsImages/"), fileName);
files.SaveAs(path);
news.imageURL = "http://electo.qendidate.com/newsImages/" + fileName;
news.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
news.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
try
{
_NewsServices.createNews(news);
TempData["Result"] = "Success";
}
catch(Exception e)
{
TempData["Result"] = "Error";
}
}
return RedirectToAction("Create", "News");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IwardServices
{
IEnumerable<sp_getWardByStateIDAndMUncipalCorporationID_Result> getZoneByStateIDAndMUncipalCorporationID(int stateId, int MPCorporation, int districtID, int vidhanSabhaConstituencyID);
bool CreateWardConstituency(wardConstituency owardConstituency);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.SP_Models
{
public class sp_Campaigns_GetAll
{
public long campaignID { get; set; }
public string campaignName { get; set; }
public int electionTypeID { get; set; }
public int electionID { get; set; }
public int politicalPartyID { get; set; }
public Nullable<int> lokSabhaConstituencyID { get; set; }
public Nullable<int> vidhanSabhaConstituencyID { get; set; }
public Nullable<int> wardID { get; set; }
public long volunteerID { get; set; }
public System.DateTime dataIsCreated { get; set; }
public System.DateTime dataIsUpdated { get; set; }
public long createdBy { get; set; }
public long modifiedBy { get; set; }
public bool isActive { get; set; }
public bool isOLD { get; set; }
public bool isPaymentComplete { get; set; }
public Nullable<int> price { get; set; }
public string electionTypeNAME { get; set; }
public string electionName { get; set; }
public string lokSabhaConstituencyName { get; set; }
public string vidhanSabhaConstituencyName { get; set; }
public string wardName { get; set; }
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
[CustomErrorHandling]
public class EventTypeController : BaseClass
{
private readonly IEventTypeService _EventTypeService;
public EventTypeController()
{
_EventTypeService = new EventTypeService();
}
// GET: EventType
public ActionResult Index()
{
var EventTypeList_ = _EventTypeService.GetEventTypeList();
return View(EventTypeList_);
}
[HttpGet]
public ActionResult create()
{
eventType oeventType = new eventType();
return View(oeventType);
}
[HttpPost]
public ActionResult create(eventType oeventType)
{
bool result = false;
oeventType.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oeventType.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oeventType.isActive = true;
oeventType.dataIsCreated = BaseUtil.GetCurrentDateTime();
oeventType.dataIsUpdated = BaseUtil.GetCurrentDateTime();
result = _EventTypeService.addNewEventType(oeventType);
if (result)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
TempData["Result"] = "unsuccess";
return View(oeventType);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.IRepositories
{
interface IDashBoardServices
{
IEnumerable<sp_GetNewCampaignRequests_Result> GetNewCampaignRequests_Result();
IEnumerable<sp_GetNewEnquiries_Result> GetNewEnquiries_Result();
IEnumerable<sp_GetRunningCampaigns_Result> GetRunningCampaigns_Result();
IEnumerable<sp_GetUpcomingElections_Result> GetUpcomingElections_Result();
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class DistrictServices: IDistrictServices
{
private readonly UnitOfWork uow;
public DistrictServices()
{
uow = new UnitOfWork();
}
public IEnumerable<district> getDistrictByStateID(int stateID)
{
var _districtList = uow.district_.Find(e => e.stateID == stateID).ToList();
return _districtList;
}
public int create(district odistrict)
{
int result = 0;
odistrict.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
odistrict.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
odistrict.dataIsCreated = BaseUtil.GetCurrentDateTime();
odistrict.dataIsUpdated = BaseUtil.GetCurrentDateTime();
odistrict.isActive = true;
try
{
uow.district_.Add(odistrict);
result = 1;
}
catch { }
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.SP_Models
{
public class StoredProcedureModels
{
public class sp_GetNewEnquiries_Result
{
public long enquiryID { get; set; }
public string enquiryTypeName { get; set; }
public string enquirerName { get; set; }
public DateTime dataIsCreated { get; set; }
public string mobile { get; set; }
public bool isTaskComplete { get; set; }
}
public class sp_CheckUserInCampaign_Result
{
public long volunteerID { get; set; }
}
public class sp_SearchRunningCampaigns_Result
{
public long campaignID { get; set; }
public string campaignName { get; set; }
public string voterName { get; set; }
public string electionTypeNAME { get; set; }
public int electionYear { get; set; }
public string politicalPartyName { get; set; }
public bool isActive { get; set; }
}
public class sp_SearchCampaignPrices_Result
{
public int campaignPriceID { get; set; }
public int price { get; set; }
public string electionTypeNAME { get; set; }
public string year { get; set; }
public DateTime dataIsCreated { get; set; }
public DateTime dataIsUpdated { get; set; }
public bool isActive { get; set; }
}
public class sp_CreateUser
{
int result { get; set; }
}
public class sp_createEvent {
public int eventTypeID { get; set; }
public Int64 campaignID { get; set; }
public Int64 createdBy { get; set; }
public string eventTitle { get; set; }
public string eventDescription { get; set; }
public string mediaURL { get; set; }
}
public class sp_getAllRelationshipsInCampaignByUserType_Result_
{
public string voterName { get; set; }
public string WorkingArea { get; set; }
public string address { get; set; }
}
public class sp_Voters_DeleteByVoterId
{
int result { get; set; }
}
//public class sp_GetVoters_List_Result
//{
// public long voterID { get; set; }
// public string voterName { get; set; }
// public string voterLastName { get; set; }
// public string voterFather_HusbandName { get; set; }
// public int vidhanSabhaConstituencyID { get; set; }
// public int lokSabhaConstituencyID { get; set; }
// public int wardID { get; set; }
// public int stateID { get; set; }
// public long areaID { get; set; }
// public System.DateTime dataIsCreated { get; set; }
// public System.DateTime dataIsUpdated { get; set; }
// public long createdBy { get; set; }
// public long modifiedBy { get; set; }
// public string plotNo { get; set; }
// public string streetNo { get; set; }
// public string address1 { get; set; }
// public string address2 { get; set; }
// public int pincode { get; set; }
// public int genderID { get; set; }
// public Nullable<System.DateTime> dateOfBirth { get; set; }
// public string voterAadharNumber { get; set; }
// public string voterIDNumber { get; set; }
// public Nullable<System.DateTime> voterIDIssueDate { get; set; }
// public Nullable<bool> isMarried { get; set; }
// public string voterImageURL { get; set; }
// public bool isActive { get; set; }
// public Nullable<int> regionalLanguage { get; set; }
// public string mobileNo { get; set; }
// public Nullable<int> age { get; set; }
// public string vidhanSabhaConstituencyName { get; set; }
// public string lokSabhaConstituencyName { get; set; }
// public string wardName { get; set; }
// public string stateName { get; set; }
// public string areaName { get; set; }
// public string gender { get; set; }
//}
public class sp_getVoterDetailsByVoterIDApp
{
public long voterID { get; set; }
public string Regional_Name { get; set; }
public string voterFather_HusbandName { get; set; }
public string voterIDNumber { get; set; }
public System.DateTime dateOfBirth { get; set; }
public string address { get; set; }
public Nullable<long> volunteerID { get; set; }
}
public class CreateVolunteerLoginApp
{
public int politicalPartyID { get; set; }
public string mobile { get; set; }
public string fullName { get; set; }
public string userID { get; set; }
public string voterID { get; set; }
public string AadharCardNumber { get; set; }
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using electo.Models.SP_Models;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.ViewModels
{
public class DashBoardViewModels
{
public IEnumerable<sp_GetNewCampaignRequests_Result> newCampaignRequests { get; set; }
public IEnumerable<sp_GetNewEnquiries_Result> getNewEnquiries { get; set; }
public IEnumerable<sp_GetRunningCampaigns_Result> getRunningCampaigns { get; set; }
public IEnumerable<sp_GetUpcomingElections_Result> getUpcomingElections { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using electo.Models;
using electo.Models.Repositories;
using electo.Models.IRepositories;
using electo.Models.BaseClass;
namespace electo.Controllers
{
public class voterListController : BaseClass
{
private electoEntities db = new electoEntities();
private readonly IvoterListService voterListService_;
private readonly ILSCServices LSCServices_;
private readonly IVSCServices VSCServices_;
private readonly IstateService stateService_;
private readonly IAreaService AreaService_;
private readonly IwardServices wardServices_;
private readonly IlanguageServices languageServices_;
private readonly IDistrictServices DistrictServices_;
public voterListController()
{
LSCServices_ = new LSCServices();
VSCServices_ = new VSCServices();
voterListService_ = new voterListService();
stateService_ = new stateService();
AreaService_ = new AreaService();
wardServices_ = new wardServices();
languageServices_ = new languageServices();
DistrictServices_ = new DistrictServices();
}
// GET: voterList
public ActionResult Index()
{
int usertypeID = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.userType.ToString()));
if (usertypeID == 1)
{
ViewBag.dataEntryOperators = new SelectList((voterListService_.getAllDataEntryOperators().Select(e => new { e.loginID, e.fullName })), "loginID", "fullName");
}
return View();
}
[HttpPost]
public ActionResult _partialVoterDetails(string voterID, string date, string userID)
{
var result = voterListService_.getVoters(voterID, date, userID);
return PartialView("_partialVoterDetails", result);
}
// GET: voterList/Create
public ActionResult Create()
{
ViewBag.regionalLanguage = languageServices_.getAll_LangaugeList();//, "languageID", "language1");
ViewBag.areaID = db.areaNames.Select(e => new { e.areaID, e.areaName1 }).ToList(); //, "areaID", "areaName1");
ViewBag.lokSabhaConstituencyID = LSCServices_.getAlllokSabhaConstituencyConstituency(1);// "lokSabhaConstituencyID", "lokSabhaConstituencyName");
ViewBag.stateID = stateService_.getAllStates();//, "stateID", "stateName");
ViewBag.vidhanSabhaConstituencyID = VSCServices_.getvidhanSabhaConstituencyByStateIDANDLKSCID(1, 1, "");//, "vidhanSabhaConstituencyID", "vidhanSabhaConstituencyName");
ViewBag.wardID = wardServices_.getZoneByStateIDAndMUncipalCorporationID(1, 1, 1,1);//, "wardID", "wardName");
ViewBag.genderID = db.genders.Select(e=>new { e.genderId,e.gender1}).ToList();
voterList ovoterList= new voterList();
return View(ovoterList);
}
public ActionResult Create1(voterList ovoterList)
{
ViewBag.regionalLanguage = languageServices_.getAll_LangaugeList();//, "languageID", "language1");
ViewBag.areaID = db.areaNames.Select(e => new { e.areaID, e.areaName1 }).ToList();//, "areaID", "areaName1");
ViewBag.lokSabhaConstituencyID = db.lokSabhaConstituencies.Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });// "lokSabhaConstituencyID", "lokSabhaConstituencyName");
ViewBag.stateID = db.states.Select(e => new { e.stateID, e.stateName });//, "stateID", "stateName");
ViewBag.vidhanSabhaConstituencyID = db.vidhanSabhaConstituencies.Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });//, "vidhanSabhaConstituencyID", "vidhanSabhaConstituencyName");
ViewBag.wardID = db.wardConstituencies.Select(e => new { e.wardID, e.wardName });//, "wardID", "wardName");
ViewBag.genderID = db.genders.Select(e => new { e.genderId, e.gender1 }).ToList();
return View("Create", ovoterList);
}
public ActionResult _partialVoterDetails()
{
return PartialView();
}
[HttpPost]
public ActionResult Create(electo.Models.voterList voterList)
{
int result = 0;
if (ModelState.IsValid)
{
result= voterListService_.createNewVoter(voterList);
}
if (result == 1)
{
TempData["Creation"] = "Success";
}
else {
TempData["Creation"] = "unsuccess";
}
return RedirectToAction("Create1",voterList);
}
// GET: voterList/Edit/5
public ActionResult Edit(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
voterList voterList = null;
voterList = voterListService_.getVoterByID((long)id);
if (voterList == null)
{
return HttpNotFound();
}
ViewBag.regionalLanguage = languageServices_.getAll_LangaugeList();//, "languageID", "language1");
ViewBag.areaID = db.areaNames.Select(e => new { e.areaID, e.areaName1 }).ToList();//, "areaID", "areaName1");
ViewBag.lokSabhaConstituencyID = db.lokSabhaConstituencies.Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });// "lokSabhaConstituencyID", "lokSabhaConstituencyName");
ViewBag.stateID = db.states.Select(e => new { e.stateID, e.stateName });//, "stateID", "stateName");
ViewBag.vidhanSabhaConstituencyID = db.vidhanSabhaConstituencies.Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });//, "vidhanSabhaConstituencyID", "vidhanSabhaConstituencyName");
ViewBag.wardID = db.wardConstituencies.Select(e => new { e.wardID, e.wardName });//, "wardID", "wardName");
ViewBag.genderID = db.genders.Select(e => new { e.genderId, e.gender1 }).ToList();
return View(voterList);
}
[HttpPost]
public ActionResult Edit(voterList voterList)
{
int result = 0;
if (ModelState.IsValid)
{
result = voterListService_.UpdateVoter(voterList);
}
if (result == 1)
{
TempData["Creation"] = "Success";
}
else
{
TempData["Creation"] = "unsuccess";
}
ViewBag.regionalLanguage = languageServices_.getAll_LangaugeList();//, "languageID", "language1");
ViewBag.areaID = db.areaNames.Select(e => new { e.areaID, e.areaName1 }).ToList();//, "areaID", "areaName1");
ViewBag.lokSabhaConstituencyID = db.lokSabhaConstituencies.Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });// "lokSabhaConstituencyID", "lokSabhaConstituencyName");
ViewBag.stateID = db.states.Select(e => new { e.stateID, e.stateName });//, "stateID", "stateName");
ViewBag.vidhanSabhaConstituencyID = db.vidhanSabhaConstituencies.Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });//, "vidhanSabhaConstituencyID", "vidhanSabhaConstituencyName");
ViewBag.wardID = db.wardConstituencies.Select(e => new { e.wardID, e.wardName });//, "wardID", "wardName");
ViewBag.genderID = db.genders.Select(e => new { e.genderId, e.gender1 }).ToList();
return View(voterList);
}
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.Repositories
{
public class DashBoardServices : IDashBoardServices
{
private readonly UnitOfWork uow;
public DashBoardServices()
{
uow = new UnitOfWork();
}
public IEnumerable<sp_GetNewCampaignRequests_Result> GetNewCampaignRequests_Result()
{
var GetNewCampaignRequests_Result = uow.getNewCampaignRequests_Result.SQLQuery<sp_GetNewCampaignRequests_Result>("sp_GetNewCampaignRequests");
return GetNewCampaignRequests_Result;
}
public IEnumerable<sp_GetNewEnquiries_Result> GetNewEnquiries_Result()
{
var GetRunningCampaigns_Result = uow.getNewCampaignRequests_Result.SQLQuery<sp_GetNewEnquiries_Result>("sp_GetNewEnquiries");
return GetRunningCampaigns_Result;
}
public IEnumerable<sp_GetRunningCampaigns_Result> GetRunningCampaigns_Result()
{
var GetRunningCampaigns_Result = uow.getNewCampaignRequests_Result.SQLQuery<sp_GetRunningCampaigns_Result>("sp_GetRunningCampaigns");
return GetRunningCampaigns_Result;
}
public IEnumerable<sp_GetUpcomingElections_Result> GetUpcomingElections_Result()
{
var GetUpcomingElections_Result = uow.getNewCampaignRequests_Result.SQLQuery<sp_GetUpcomingElections_Result>("sp_GetUpcomingElections");
return GetUpcomingElections_Result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.SP_Models
{
public class sp_Voters_VerifyByPageIncharge
{
public long CampaignId { get; set; }
public long PageInchargeId { get; set; }
public long VoterId { get; set; }
public float latitude { get; set; }
public float longitude { get; set; }
}
}<file_sep>using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using electo.Models;
using electo.Models.IRepositories;
using Newtonsoft.Json;
namespace electo.WebServicesController
{
public class NewsController : ApiController
{
private readonly INewsServices _NewsServices;
public NewsController()
{
_NewsServices = new NewsServices();
}
[HttpGet]
public IHttpActionResult getAllNews()
{
var result = (_NewsServices.getNews());
if (result != null)
{
var newsList = result as List<sp_GetLatestNews_Result> ?? result.ToList();
if (newsList != null)
{
// return Request.CreateResponse(HttpStatusCode.OK, newsList);
return Json(new { status = "Success", msg = "Record found", data = newsList });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Records");
return Json(new { status = "Error", msg = "Record not found" });
}
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class ElectionService: IElectionService
{
private readonly UnitOfWork uow;
public ElectionService()
{
uow = new UnitOfWork();
}
public IEnumerable<electionType>getElectionTypes()
{
var _objelectionType = uow.electionType.GetAll().ToList();
return _objelectionType;
}
public IEnumerable<sp_electionList_Result> getElectionNameList(int ElectionType, int ddl_year, int ddl_month)
{
var ElectionType_ = new SqlParameter("@ElectionType", ElectionType);
var ddl_year_ = new SqlParameter("@ddl_year", ddl_year);
var ddl_month_ = new SqlParameter("@ddl_month", ddl_month);
var _sp_electionList_Result = uow.sp_electionList_Result.SQLQuery<sp_electionList_Result>("sp_electionList @ElectionType,@ddl_year,@ddl_month", ElectionType_, ddl_year_, ddl_month_).ToList();
return _sp_electionList_Result;
}
public IEnumerable<monthName> getAllMonthName()
{
var monthNameList_ = uow.monthName_.GetAll().ToList();
return monthNameList_;
}
public IEnumerable<tblyear> getAllYears()
{
var yearList_ = uow.tblyear_.GetAll().ToList();
return yearList_;
}
public int create(electionName oelectionName)
{
int result = 0;
oelectionName.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oelectionName.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oelectionName.dataIsCreated = BaseUtil.GetCurrentDateTime();
oelectionName.dataIsUpdated = BaseUtil.GetCurrentDateTime();
oelectionName.isActive = true;
try
{
uow.electionName_.Add(oelectionName);
result = 1;
}
catch { }
return result;
}
public IEnumerable<electionName> getAllElections()
{
var result = uow.getAllElections_.GetAll().ToList();
return result;
}
}
//election
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
namespace electo.WebServicesController
{
public class EventTypesController : ApiController
{
//private electoEntities db = new electoEntities();
private readonly IEventServices _eventServices;
private readonly IEventTypeService _eventTypeService;
public EventTypesController()
{
_eventServices = new EventServices();
_eventTypeService = new EventTypeService();
}
// public IEnumerable<sp_Event_GetByCampaignId_Result> GetByCampaignId(long Id)
public IHttpActionResult GetEventsByCampaignId(long Id)
{
var objEventList = _eventServices.GetByCampaignId(Id);
if (objEventList != null)
{
var eventEntities = objEventList as List<sp_Event_GetByCampaignId_Result> ?? objEventList.ToList();
if (eventEntities.Any())
{
// return Request.CreateResponse(HttpStatusCode.OK, eventEntities);
return Json(new { status = "Success", msg = "Record found", data = eventEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Event data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
// Get all Event Types
public IHttpActionResult Getallevents()
{
var objEventList = _eventTypeService.getEventTypes();
if (objEventList != null)
{
var eventEntities = objEventList as List<sp_GetAllEventTypes_Result> ?? objEventList.ToList();
if (eventEntities.Any())
{
// return Request.CreateResponse(HttpStatusCode.OK, eventEntities);
return Json(new { status = "Success", msg = "Record found", data = eventEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Event data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//public IEnumerable<sp_Event_GetByEventTypeId_Result> GetByEventTypeId(long Id)
public IHttpActionResult GetEventsByEventTypeId(long Id)
{
var objEventList = _eventServices.GetByEventTypeId(Id);
if (objEventList != null)
{
var eventEntities = objEventList as List<sp_Event_GetByEventTypeId_Result> ?? objEventList.ToList();
if (eventEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, eventEntities);
return Json(new { status = "Success", msg = "Record found", data = eventEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Event data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// db.Dispose();
}
base.Dispose(disposing);
}
//private bool eventTypeExists(int id)
//{
// return db.eventTypes.Count(e => e.eventTypeID == id) > 0;
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface ILSCServices
{
IEnumerable<lokSabhaConstituency> getAllvidhanSabhaConstituency();
IEnumerable<lokSabhaConstituency> getAlllokSabhaConstituencyConstituency(int stateID);
int create(lokSabhaConstituency olkSabha);
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class stateService: IstateService
{
private readonly UnitOfWork uow;
public stateService()
{
uow = new UnitOfWork();
}
public IEnumerable<state> getAllStates()
{
var _statesList = uow.state_.GetAll().ToList();
return _statesList;
}
public int create(string stateName)
{
int result = 0;
state ostate = new state();
ostate.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ostate.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ostate.dataIsCreated = BaseUtil.GetCurrentDateTime();
ostate.dataIsUpdated = BaseUtil.GetCurrentDateTime();
ostate.isActive = true;
ostate.stateName = stateName;
try
{
uow.state_.Add(ostate);
result =1;
}
catch { }
return result;
}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.Repositories
{
public class EventServices : IEventServices
{
private readonly UnitOfWork uow;
public EventServices()
{
uow = new UnitOfWork();
}
//IEnumerable<sp_Event_GetByCampaignId_Result> GetByCampaignId(long Id);
public IEnumerable<sp_Event_GetByCampaignId_Result> GetByCampaignId(long Id)
{
var CampaignId = new SqlParameter("@CampaignId", Id);
var objEventList = uow.sp_Event_GetByCampaignId_Result_.SQLQuery<sp_Event_GetByCampaignId_Result>("sp_Event_GetByCampaignId @CampaignId", CampaignId).ToList();
if (objEventList != null)
{
return objEventList;
}
return null;
}
//IEnumerable<sp_Event_GetByEventTypeId_Result> GetByEventTypeId(long Id);
public IEnumerable<sp_Event_GetByEventTypeId_Result> GetByEventTypeId(long Id)
{
var EventTypeId = new SqlParameter("@EventTypeId", Id);
var objEventList = uow.sp_Event_GetByEventTypeId_Result_.SQLQuery<sp_Event_GetByEventTypeId_Result>("sp_Event_GetByEventTypeId @EventTypeId", EventTypeId).ToList();
if (objEventList != null)
{
return objEventList;
}
return null;
}
public IEnumerable<sp_Event_GetByCampaignIdANDEventTypeID_Result> GetByCampaignIdANDEventTypeID(long Id,int EventTypeId)
{
var CampaignId = new SqlParameter("@CampaignId", Id);
var eventTypeID_ = new SqlParameter("@eventTypeID", EventTypeId);
var objEventList = uow.sp_Event_GetByCampaignId_Result_.SQLQuery<sp_Event_GetByCampaignIdANDEventTypeID_Result>("sp_Event_GetByCampaignIdANDEventTypeID @CampaignId, @eventTypeID", CampaignId, eventTypeID_).ToList();
try
{
if (objEventList != null)
{
return objEventList;
}
}
catch { }
return null;
}
public int createEvent(sp_createEvent osp_createEvent)
{
int result;
var eventTypeID_ = new SqlParameter("@eventTypeID", osp_createEvent.eventTypeID);
var campaignID_ = new SqlParameter("@campaignID", osp_createEvent.campaignID);
var dataIsCreated_ = new SqlParameter("@dataIsCreated", BaseUtil.GetCurrentDateTime());
var createdBy_ = new SqlParameter("@createdBy", osp_createEvent.createdBy);
var eventTitle_ = new SqlParameter("@eventTitle", osp_createEvent.eventTitle);
var eventDescription_ = new SqlParameter("@eventDescription", osp_createEvent.eventDescription);
var mediaURL_ = new SqlParameter("@mediaURL", SqlString.Null);
if (osp_createEvent.mediaURL != null)
{
mediaURL_ = new SqlParameter("@mediaURL", osp_createEvent.mediaURL);
}
try
{
// string q = "sp_createEvent @eventTypeID='" + osp_createEvent.eventTypeID + "',@campaignID='" + osp_createEvent.campaignID + "',@dataIsCreated='" + BaseUtil.GetCurrentDateTime() + "',@createdBy='" + osp_createEvent .createdBy + "',@eventTitle='" + osp_createEvent.eventTitle + "',@eventDescription='" + osp_createEvent.eventDescription + "',@mediaURL='" + osp_createEvent.mediaURL+"'" ;
result = uow.sp_createEvent_.SQLQuery<int>("sp_createEvent @eventTypeID,@campaignID,@dataIsCreated,@createdBy,@eventTitle,@eventDescription,@mediaURL", eventTypeID_, campaignID_, dataIsCreated_, createdBy_, eventTitle_, eventDescription_, mediaURL_).FirstOrDefault();
}
catch (Exception e)
{
result = 0;
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using electo.Models.IRepositories;
using static electo.Models.SP_Models.StoredProcedureModels;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace electo.Models.Repositories
{
public class CampaignService : ICampaignService
{
private readonly UnitOfWork uow;
public CampaignService()
{
uow = new UnitOfWork();
}
public IEnumerable<sp_SearchRunningCampaigns_Result> SearchRunningCampaigns_Result(string electionTypeNAME, string electionYear, string politicalPartyName, string campaignName)
{
var PartyName_ = new SqlParameter("@partyname", SqlString.Null);
var campaignname_ = new SqlParameter("@campaignname", SqlString.Null);
if (politicalPartyName == "")
{
PartyName_ = new SqlParameter("@partyname", SqlString.Null);
}
else
{
PartyName_ = new SqlParameter("@partyname", politicalPartyName);
}
if (campaignName == "")
{
campaignname_ = new SqlParameter("@campaignname", SqlString.Null);
}
else
{
campaignname_ = new SqlParameter("@campaignname", campaignName);
}
var ElectionType_ = new SqlParameter("@electiontype", electionTypeNAME);
var year_ = new SqlParameter("@year", electionYear);
var RunningCampaigns_Result = uow.RunningCampaigns_Result.SQLQuery<sp_SearchRunningCampaigns_Result>("sp_SearchRunningCampaigns @electiontype,@partyname,@year,@campaignname", ElectionType_, PartyName_, year_, campaignname_).ToList();
return RunningCampaigns_Result;
}
public IEnumerable<campaign> getCampaignNames(string prefix)
{
// var names = uow.getCampaignNames_.Find(prefix)
electoEntities db = new electoEntities();
var names = db.campaigns.Where(e => e.campaignName.StartsWith(prefix)).ToList();
return names;
}
public IEnumerable<campaign> getCompaignListByElectionIDandCreatedByID(Int64 createdBy)
{
var campaignList = uow.GetDetails_.Find(e => e.createdBy == createdBy ).ToList();
return campaignList;
}
public campaign get(long cID)
{
var campaignDetails = uow.GetDetails_.GetByID(cID);
return campaignDetails;
}
public campaign _save(campaign _campaign)
{
_campaign.dataIsUpdated = BaseUtil.GetCurrentDateTime();
_campaign.modifiedBy =Convert.ToInt64( BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
uow.SaveDetails.Update(_campaign);
return _campaign;
}
public IEnumerable<sp_SearchCampaignPrices_Result> sp_SearchCampaignPrices_Result(string electionTypeNAME, string year, bool isActive)
{
var ElectionType_ = new SqlParameter("@electiontype", electionTypeNAME);
var year_ = new SqlParameter("@year", year);
var isActive_ = new SqlParameter("@isActive", isActive);
var CampaignPrices_Result = uow.sp_SearchCampaignPrices_Result_.SQLQuery<sp_SearchCampaignPrices_Result>("sp_SearchCampaignPrices @electiontype,@year,@isActive", ElectionType_, year_, isActive_).ToList();
return CampaignPrices_Result;
}
public campaignPrice getCampaign(int ID)
{
var priceDetails = uow._getPriceDetails_.GetByID(ID);
return priceDetails;
}
public int createCampaignPrice(campaignPrice newCmpPrice_)
{
var electionTypeID_ = new SqlParameter("@electiontype", newCmpPrice_.electionTypeID);
var year_ = new SqlParameter("@year", newCmpPrice_.year);
var price_ = new SqlParameter("@price", newCmpPrice_.price);
var dataIsCreated_ = new SqlParameter("@dataIsCreated", newCmpPrice_.dataIsCreated);
var dataIsUpdated_ = new SqlParameter("@dataIsUpdated", newCmpPrice_.dataIsUpdated);
var createdBy_ = new SqlParameter("@createdBy", newCmpPrice_.createdBy);
var modifiedBy_ = new SqlParameter("@modifiedBy", newCmpPrice_.modifiedBy);
var isActive_ = new SqlParameter("@isActive", newCmpPrice_.isActive);
int result = 0;
try
{
result = uow.newCampaignPrice_.SQLQuery<int>("sp_AddNewCampaignPrice @electiontype, @year, @price, @dataIsCreated, @dataIsUpdated, @createdBy, @modifiedBy, @isActive",
electionTypeID_, year_, price_, dataIsCreated_, dataIsUpdated_, createdBy_, modifiedBy_, isActive_).FirstOrDefault();
}
catch (Exception e)
{
}
return result;
}
public IEnumerable<campaignPrice> getAllPrices(int electionTypeID)
{
var result = uow.getAllPrices_.Find(e => e.electionTypeID == electionTypeID);
return result;
}
public void createCampaign(campaign _campaign)
{
uow.createCampaign_.Add(_campaign);
}
public IEnumerable<campaign> getMyCampaigns(int volunteerID)
{
var result = uow.getMyCampaigns_.Find(e => e.volunteerID == volunteerID);
return result;
}
public IEnumerable<sp_GetVolunteers_Result> getVolunteers(string cmpID, string pID, string stateID, string lkID, string vsID)
{
var politicalParty_ = new SqlParameter("@politicalParty", 1);
var stateID_ = new SqlParameter("@stateID", SqlString.Null);
var vsID_ = new SqlParameter("@vidhanSabhaConstituencyID", SqlString.Null);
var lkID_ = new SqlParameter("@lokSabhaConstituencyID", SqlString.Null);
var cmpID_ = new SqlParameter("@campaignID",cmpID);
if (stateID == "")
{
stateID_ = new SqlParameter("@stateID", SqlString.Null);
}
else
{
stateID_ = new SqlParameter("@stateID", stateID);
}
if (lkID == "")
{
lkID_ = new SqlParameter("@lokSabhaConstituencyID", SqlString.Null);
}
else
{
lkID_ = new SqlParameter("@lokSabhaConstituencyID", lkID);
}
if (vsID == "")
{
vsID_ = new SqlParameter("@vidhanSabhaConstituencyID", SqlString.Null);
}
else
{
vsID_ = new SqlParameter("@vidhanSabhaConstituencyID", vsID);
}
var result = uow.Assign_.SQLQuery<sp_GetVolunteers_Result>("sp_GetVolunteers @politicalParty,@stateID,@vidhanSabhaConstituencyID,@lokSabhaConstituencyID,@campaignID", politicalParty_, stateID_, vsID_, lkID_, cmpID_).ToList();
return result;
}
public IEnumerable<userType> get()
{
var result = uow.get_.GetAll();
return result;
}
public sp_CheckUserInCampaign_Result checkUser(long volunteerID,long campaignID)
{
var volunteerID_ = new SqlParameter("@volunteerID", volunteerID);
var campaignID_ = new SqlParameter("@campaignID", campaignID);
var result = uow.checkUser_.SQLQuery<sp_CheckUserInCampaign_Result>("sp_CheckUserInCampaign @volunteerID,@campaignID", volunteerID_, campaignID_).FirstOrDefault();
return result;
}
public IEnumerable<sp_getAreaListByCampignID_Result> getAreaListByCampignID(long cmpID)
{
var cmpID_ = new SqlParameter("@CampignID", cmpID);
var result = uow.getAreaListByCampignID_.SQLQuery<sp_getAreaListByCampignID_Result>("sp_getAreaListByCampignID @CampignID", cmpID_).ToList();
return result;
}
public int assignPageInchargeArea(PageInchargeAssignAreaviewmodel _obj)
{
int result;
pageInchargeAssignedArea opollingBooth_andInchargRelationship = new pageInchargeAssignedArea();
opollingBooth_andInchargRelationship.campaignID = _obj.campaignID;
opollingBooth_andInchargRelationship.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
opollingBooth_andInchargRelationship.dataIsCreated = BaseUtil.GetCurrentDateTime();
opollingBooth_andInchargRelationship.dataIsUpdated = BaseUtil.GetCurrentDateTime();
opollingBooth_andInchargRelationship.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
opollingBooth_andInchargRelationship.areaID = _obj.areaID;
opollingBooth_andInchargRelationship.volunteerID = _obj.volunteerID;
opollingBooth_andInchargRelationship.isActive = true;
try
{
uow.assignPageInchargeArea_.Add(opollingBooth_andInchargRelationship);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
public IEnumerable<sp_GetAllSectionInchargeByCampaign_Result> getAllSectionInchargeByCampaign(long cmpID)
{
var cmpID_ = new SqlParameter("@cmpID", cmpID);
var result = uow.getAllSectionInchargeByCampaign_.SQLQuery<sp_GetAllSectionInchargeByCampaign_Result>("sp_GetAllSectionInchargeByCampaign @cmpID", cmpID_).ToList();
return result;
}
#region HR Service Function
public IEnumerable<sp_Campaigns_GetAll_Result> GetAll()
{
var objCampaignList = uow.sp_Campaigns_GetAll_Result_.SQLQuery<sp_Campaigns_GetAll_Result>("sp_Campaigns_GetAll");
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
public sp_Campaigns_GetById_Result GetById(long Id)
{
var CampaignId = new SqlParameter("@CampaignId", Id);
var objCampaign = uow.sp_Campaigns_GetById_Result_.SQLQuery<sp_Campaigns_GetById_Result>("sp_Campaigns_GetById @CampaignId", CampaignId).SingleOrDefault();
if (objCampaign != null)
{
return objCampaign;
}
return null;
}
public IEnumerable<sp_Campaigns_GetByElectionTypeId_Result> GetByElectionTypeId(long Id)
{
var ElectionTypeId = new SqlParameter("@ElectionTypeId", Id);
var objCampaignList = uow.sp_Campaigns_GetByElectionTypeId_Result_.SQLQuery<sp_Campaigns_GetByElectionTypeId_Result>("sp_Campaigns_GetByElectionTypeId @ElectionTypeId", ElectionTypeId).ToList();
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
public IEnumerable<sp_Campaigns_GetByElectionId_Result> GetByElectionId(long Id)
{
var ElectionId = new SqlParameter("@ElectionId", Id);
var objCampaignList = uow.sp_Campaigns_GetByElectionId_Result_.SQLQuery<sp_Campaigns_GetByElectionId_Result>("sp_Campaigns_GetByElectionId @ElectionId", ElectionId).ToList();
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
public IEnumerable<sp_Campaigns_GetByLokSabhaConstituencyId_Result> GetByLokSabhaConstituencyId(long Id)
{
var LokSabhaConstituencyId = new SqlParameter("@LokSabhaConstituencyId", Id);
var objCampaignList = uow._getDetails.SQLQuery<sp_Campaigns_GetByLokSabhaConstituencyId_Result>("sp_Campaigns_GetByLokSabhaConstituencyId @LokSabhaConstituencyId", LokSabhaConstituencyId).ToList();
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
public IEnumerable<sp_Campaigns_GetByPoliticalPartyId_Result> GetByPoliticalPartyId(long Id)
{
var PoliticalPartyId = new SqlParameter("@PoliticalPartyId", Id);
var objCampaignList = uow.sp_Campaigns_GetByPoliticalPartyId_Result_.SQLQuery<sp_Campaigns_GetByPoliticalPartyId_Result>("sp_Campaigns_GetByPoliticalPartyId @PoliticalPartyId", PoliticalPartyId).ToList();
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
public IEnumerable<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result> GetByVidhanSabhaConstituencyId(long Id)
{
var VidhanSabhaConstituencyId = new SqlParameter("@VidhanSabhaConstituencyId", Id);
var objCampaignList = uow.sp_Campaigns_GetByVidhanSabhaConstituencyId_Result_.SQLQuery<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result>("sp_Campaigns_GetByVidhanSabhaConstituencyId @VidhanSabhaConstituencyId", VidhanSabhaConstituencyId).ToList();
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
public IEnumerable<sp_Campaigns_GetByVolunteerId_Result> GetByVolunteerId(long Id)
{
var VolunteerId = new SqlParameter("@VolunteerId", Id);
var objCampaignList = uow.sp_Campaigns_GetByVolunteerId_Result_.SQLQuery<sp_Campaigns_GetByVolunteerId_Result>("sp_Campaigns_GetByVolunteerId @VolunteerId", VolunteerId).ToList();
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
public IEnumerable<sp_Campaigns_GetByWardId_Result> GetByWardId(long Id)
{
var WardId = new SqlParameter("@WardId", Id);
var objCampaignList = uow.sp_Campaigns_GetByWardId_Result_.SQLQuery<sp_Campaigns_GetByWardId_Result>("sp_Campaigns_GetByWardId @WardId", WardId).ToList();
if (objCampaignList != null)
{
return objCampaignList;
}
return null;
}
#endregion
public int createVolunteerRelationship(string usertype, string vID, string cID)
{
int result=0;
string sqlQuery = "sp_assignRelationshipBetweenVolunteerANDCampaign @campaignID='" + cID + "', @volunteerID='" + vID + "'," +
"@dataIsUpdated='" + BaseUtil.GetCurrentDateTime() + "'," +
"@modifiedBy='" + Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString())) + "',@userTypeID='" + usertype + "', @insert=1";
try
{
result = uow.assignPageInchargeArea_.SQLQuery<int>(sqlQuery).FirstOrDefault();
}
catch (Exception e)
{
result = 0;
}
return result;
}
public int DeletecampaignVolunteerRelationShip(Int64 cID, Int64 vID)
{
int result = 0;
string sqlQuery = "sp_assignRelationshipBetweenVolunteerANDCampaign @campaignID='" + cID + "', @volunteerID='" + vID + "'";
try
{
result = uow.assignPageInchargeArea_.SQLQuery<int>(sqlQuery).FirstOrDefault();
}
catch (Exception e)
{
result = 0;
}
return result;
}
public IEnumerable<sp_getAllRelationshipsInCampaignByUserType_Result_> getAllRelationshipsInCampaignByUserType(string cmpID, string userTypeID)
{
var userTypeID_ = new SqlParameter("@userTypeID", userTypeID);
var cmpID_ = new SqlParameter("@cmpID", cmpID);
var result = uow.getAllRelationshipsInCampaignByUserType_.SQLQuery<sp_getAllRelationshipsInCampaignByUserType_Result_>("sp_getAllRelationshipsInCampaignByUserType @userTypeID ,@cmpID", userTypeID_, cmpID_).ToList();
return result;
}
public IEnumerable<campaign> getCompaignListByElectionIDandCreatedByID(Int64 createdBy)
{
var campaignList = uow.GetDetails_.Find(e => e.createdBy == createdBy).ToList();
return campaignList;
}
}
}<file_sep># electo
electo
<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
[CustomErrorHandling]
public class QuestionTypeController : BaseClass
{
private readonly IQuestionService _QuestionService;
public QuestionTypeController()
{
_QuestionService = new QuestionService();
}
// GET: QuestionType
public ActionResult Index()
{
var questionTypeList_ = _QuestionService.GetQuestionTypeList();
return View(questionTypeList_);
}
[HttpGet]
public ActionResult create()
{
questionType oquestionType = new questionType();
return View(oquestionType);
}
[HttpPost]
public ActionResult create(questionType oquestionType)
{
bool result = false;
oquestionType.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oquestionType.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oquestionType.isActve = true;
oquestionType.dataIsCreated = BaseUtil.GetCurrentDateTime();
oquestionType.dataIsUpdated = BaseUtil.GetCurrentDateTime();
result = _QuestionService.addNewQuestionType(oquestionType);
if (result)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
TempData["Result"] = "unsuccess";
return View(oquestionType);
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class LokSabhaController : BaseClass
{
private readonly ILSCServices _ILSCServices;
private readonly IstateService _stateService;
private readonly IDistrictServices _DistrictServices;
public LokSabhaController()
{
_ILSCServices = new LSCServices();
_stateService = new stateService();
_DistrictServices = new DistrictServices();
}
// GET: District
public ActionResult Index()
{
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult _partialLoKSabhaList(int stateId)
{
var ILSC_List = _ILSCServices.getAlllokSabhaConstituencyConstituency(stateId);
return PartialView("_partialLoKSabhaList", ILSC_List);
}
public ActionResult getDistrictListByStateID(int stateId)
{
var DistrictList = _DistrictServices.getDistrictByStateID(stateId).Select(e => new { e.districtID, e.districtName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(DistrictList);
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
ViewBag.stateID = _stateService.getAllStates();
return View();
}
[HttpPost]
public ActionResult Create(lokSabhaConstituency olokSabhaConstituency)
{
int result = 0;
result = _ILSCServices.create(olokSabhaConstituency);
if (result == 1)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
else
{
TempData["Result"] = "unsuccess";
return View(olokSabhaConstituency);
}
}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.Repositories
{
public class voterListService: IvoterListService
{
private readonly UnitOfWork uow;
public voterListService()
{
uow = new UnitOfWork();
}
public int createNewVoter(voterList ovoterList_Copy)
{
ovoterList_Copy.createdBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ovoterList_Copy.modifiedBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ovoterList_Copy.dataIsCreated = BaseUtil.GetCurrentDateTime();
ovoterList_Copy.dataIsUpdated = BaseUtil.GetCurrentDateTime();
ovoterList_Copy.isActive = true;
ovoterList_Copy.mobileNo = null;
ovoterList_Copy.voterAadharNumber = null;
ovoterList_Copy.voterIDIssueDate = null;
ovoterList_Copy.voterImageURL = null;
int result;
try
{
uow.voterList_.Add(ovoterList_Copy);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
public IEnumerable<sp_GetAllDataEntryOperators_Result> getAllDataEntryOperators()
{
var result = uow.getAllDataEntryOperators_.SQLQuery<sp_GetAllDataEntryOperators_Result>("sp_GetAllDataEntryOperators").ToList();
return result;
}
public IEnumerable<sp_GetVoters_List_Result> getVoters(string voterID, string date, string userID)
{
var voterID_ = new SqlParameter("@VoterIdNumber", SqlString.Null);
var userID_ = new SqlParameter("@createdBy", userID);
var date_ = new SqlParameter("@createdDate", SqlString.Null);
if (voterID != "")
{
voterID_ = new SqlParameter("@VoterIdNumber", voterID);
}
if (date != "")
{
date_ = new SqlParameter("@createdDate", date);
}
var result = uow.getVoters_.SQLQuery<sp_GetVoters_List_Result>("sp_GetVoters_List @VoterIdNumber,@createdBy,@createdDate", voterID_, userID_, date_).ToList();
return result;
}
public voterList getVoterByID(long voterID)
{
var voterList_ = uow.voterList_.GetByID(voterID);
return voterList_;
}
public int UpdateVoter(voterList ovoterList_Copy)
{
ovoterList_Copy.modifiedBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
ovoterList_Copy.dataIsUpdated = BaseUtil.GetCurrentDateTime();
ovoterList_Copy.isActive = true;
ovoterList_Copy.mobileNo = null;
ovoterList_Copy.voterAadharNumber = null;
ovoterList_Copy.voterIDIssueDate = null;
ovoterList_Copy.voterImageURL = null;
int result;
try
{
uow.voterList_.Update(ovoterList_Copy);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using static electo.Models.SP_Models.StoredProcedureModels;
using System.Data.SqlTypes;
namespace electo.Models.Repositories
{
public class EnquiryServices : IEnquiryServices
{
private readonly UnitOfWork uow;
public EnquiryServices()
{
uow = new UnitOfWork();
}
public IEnumerable<enquiryType> getEnquiryTypes()
{
var _objelectionType = uow.enquiryType.GetAll().ToList();
return _objelectionType;
}
public IEnumerable<sp_GetNewEnquiries_Result> GetNewEnquiries_Result(string enquirytype, string date, string mobile, bool isTaskCompleted)
{
var enquirytype_ = new SqlParameter("@enquirytype", SqlString.Null);
if (enquirytype != "")
{
enquirytype_ = new SqlParameter("@enquirytype", enquirytype);
}
var date_ = new SqlParameter("@date", SqlString.Null);
DateTime date__;
if (date == "")
{
date__ = DateTime.Now;
date_ = new SqlParameter("@date", date__);
}
else
{
date__ = Convert.ToDateTime(date);
date_ = new SqlParameter("@date", date__);
}
var mobile_ = new SqlParameter("@mobile", mobile);
var isTaskCompleted_ = new SqlParameter("@isTaskCompleted", isTaskCompleted);
var EnquiryResult = uow.sp_GetNewEnquiries_Result.SQLQuery<sp_GetNewEnquiries_Result>("sp_GetNewEnquiries @enquirytype,@date,@mobile,@isTaskCompleted", enquirytype_, date_, mobile_, isTaskCompleted_).ToList();
return EnquiryResult;
}
public enquiry get(long eID)
{
var enquiryDetails = uow.GetEnquiryDetails.GetByID(eID);
return enquiryDetails;
}
public enquiry _save(enquiry _enq)
{
try
{
_enq.dataIsUpdated = BaseUtil.GetCurrentDateTime();
_enq.modifiedBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
uow.saveDetails.Update(_enq);
}
catch (Exception e)
{
}
return _enq;
}
public enquiry create(enquiry _enq)
{
try
{
_enq.dataIsCreated = BaseUtil.GetCurrentDateTime();
_enq.dataIsUpdated = BaseUtil.GetCurrentDateTime();
_enq.modifiedBy = Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
uow.saveDetails.Add(_enq);
}
catch {}
return _enq;
}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using electo.Models;
using System.Data.SqlTypes;
namespace electo.Models.Repositories
{
public class PoliticalPartyService: IPoliticalPartyService
{
private readonly UnitOfWork uow;
public PoliticalPartyService()
{
uow = new UnitOfWork();
}
public IEnumerable<sp_politicalPartyList_Result> getAll_PoliticalPartyListByStateID( int stateId, string PoliticalPartyName)
{
var stateId_ = new SqlParameter("@stateID", stateId);
var partyName_ = new SqlParameter("@partyName", PoliticalPartyName);
var _sp_politicalPartyList_Result = uow.sp_politicalPartyList_Result_.SQLQuery<sp_politicalPartyList_Result>("sp_politicalPartyList @stateID, @partyName", stateId_, partyName_).ToList();
return _sp_politicalPartyList_Result;
}
public int createParty(CreatePartyViewModel oCreatePartyViewModel)
{
var politicalPartyName_= new SqlParameter("@politicalPartyName ", oCreatePartyViewModel._politicalParty.politicalPartyName);
var politicalPartyLogo_= new SqlParameter("@politicalPartyLogo", oCreatePartyViewModel._politicalParty.politicalPartyLogo);
var politicalPartyWebsiteUrl_= new SqlParameter("@politicalPartyWebsiteUrl", oCreatePartyViewModel._politicalParty.politicalPartyWebsiteUrl);
var politicalPartyEmail_ = new SqlParameter("@politicalPartyEmail", oCreatePartyViewModel._politicalParty.politicalPartyEmail);
var dataIsCreated_ = new SqlParameter("@dataIsCreated", oCreatePartyViewModel._politicalParty.dataIsCreated);
var createdBy_= new SqlParameter("@createdBy", oCreatePartyViewModel._politicalParty.createdBy);
var districtID_ = new SqlParameter("@districtID", oCreatePartyViewModel._politicalPartyAddress.districtID);
var stateId_ = new SqlParameter("@stateID", oCreatePartyViewModel._politicalPartyAddress.stateID);
var plotNo_ = new SqlParameter("@plotNo", SqlString.Null);
if (oCreatePartyViewModel._politicalPartyAddress.plotNo != null)
{
plotNo_ = new SqlParameter("@plotNo", oCreatePartyViewModel._politicalPartyAddress.plotNo);
}
var streetNo_ = new SqlParameter("@streetNo", SqlString.Null);
if (oCreatePartyViewModel._politicalPartyAddress.streetNo != null)
{
streetNo_ = new SqlParameter("@streetNo", oCreatePartyViewModel._politicalPartyAddress.streetNo);
}
var address1_ = new SqlParameter("@address1", SqlString.Null);
if (oCreatePartyViewModel._politicalPartyAddress.address1!= null)
{
address1_ = new SqlParameter("@address1", oCreatePartyViewModel._politicalPartyAddress.address1);
}
var address2_ = new SqlParameter("@address2", SqlString.Null);
if (oCreatePartyViewModel._politicalPartyAddress.address2 != null)
{
address2_ = new SqlParameter("@address2", oCreatePartyViewModel._politicalPartyAddress.address2);
}
var pincode_ = new SqlParameter("@pincode", oCreatePartyViewModel._politicalPartyAddress.pincode);
var telephone_ = new SqlParameter("@telephone", oCreatePartyViewModel._politicalPartyAddress.telephone);
int result = 0;
try
{
result = uow.sp_createParty_Result_.SQLQuery<int>("sp_createParty @politicalPartyName, @politicalPartyLogo, @politicalPartyWebsiteUrl, @politicalPartyEmail, @dataIsCreated, @createdBy, @districtID, @stateID, @plotNo, @streetNo, @address1, @address2, @pincode, @telephone",
politicalPartyName_, politicalPartyLogo_, politicalPartyWebsiteUrl_, politicalPartyEmail_, dataIsCreated_, createdBy_, districtID_, stateId_, plotNo_, streetNo_, address1_, address2_, pincode_, telephone_).FirstOrDefault();
}
catch (Exception e)
{
}
return result;
}
public IEnumerable<sp_partyAddressList_Result> PoliticalPartyAddressList(int politicalPartyId)
{
var politicalPartyId_ = new SqlParameter("@politicalPartyID", politicalPartyId);
var sp_partyAddressList_Result_ = uow.sp_partyAddressList_Result_.SQLQuery<sp_partyAddressList_Result>("sp_partyAddressList @politicalPartyID", politicalPartyId_).ToList();
return sp_partyAddressList_Result_;
}
public bool saveNewAddress(politicalPartyAddress opoliticalPartyAddress)
{
bool result = false;
try
{
uow.politicalPartyAddress_.Add(opoliticalPartyAddress);
result = true;
}
catch (Exception e){ }
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace electo
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//GlobalConfiguration.Configuration.Formatters.Clear();
//GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
//var newjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
//newjson.UseDataContractJsonSerializer = true;
//GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
//var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
//formatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings {
// Formatting = Newtonsoft.Json.Formatting.Indented,
// TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects
//};
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
}
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class languageServices: IlanguageServices
{
private readonly UnitOfWork uow;
public languageServices()
{
uow = new UnitOfWork();
}
public IEnumerable<language> getAll_LangaugeList()
{
var _LangaugeList = uow.language_.GetAll().ToList();
return _LangaugeList;
}
public int create(language Olanguage)
{
int result = 0;
try
{
uow.language_.Add(Olanguage);
result = 1;
}
catch { }
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using electo.Models.SP_Models;
using System.Web.Mvc;
namespace electo.WebServicesController
{
public class VotersController : ApiController
{
//private electoEntities db = new electoEntities();
private readonly IVotersServices _voterServices;
public VotersController()
{
_voterServices = new VotersServices();
}
public IHttpActionResult GetVoters()
{
var objVoterList = _voterServices.GetAll();
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_Voters_GetAll_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voters data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
public IHttpActionResult GetVoters(long Id)
{
var objVoter = _voterServices.GetById(Id);
if (objVoter != null)
{
var voterEntity = objVoter as sp_Voters_GetById_Result ?? objVoter;
if (voterEntity != null)
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntity);
return Json(new { status = "Success", msg = "Record found", data = voterEntity });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
public IHttpActionResult GetByPageIncharge(long Id)
{
var objVoterList = _voterServices.GetByPageInchargeId(Id);
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_Voters_GetByPageInchargeId_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//20180228
//IEnumerable<sp_Voters_GetByStateId_Result> GetByStateId(long Id);
public IHttpActionResult GetByState(long Id)
{
var objVoterList = _voterServices.GetByStateId(Id);
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_Voters_GetByStateId_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Voters_GetByAreaId_Result> GetByAreaId(long Id);
public IHttpActionResult GetByArea(long Id)
{
var objVoterList = _voterServices.GetByAreaId(Id);
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_Voters_GetByAreaId_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Voters_GetByVidhanSabhaConstituencyId_Result> GetByVidhanSabhaConstituencyId(long Id);
public IHttpActionResult GetByVidhanSabhaConstituency(long Id)
{
var objVoterList = _voterServices.GetByVidhanSabhaConstituencyId(Id);
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_Voters_GetByVidhanSabhaConstituencyId_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Voters_GetByLokSabhaConstituencyId_Result> GetByLokSabhaConstituencyId(long Id);
public IHttpActionResult GetByLokSabhaConstituency(long Id)
{
var objVoterList = _voterServices.GetByLokSabhaConstituencyId(Id);
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_Voters_GetByLokSabhaConstituencyId_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Voters_GetByWardId_Result> GetByWardId(long Id);
public IHttpActionResult GetByWard(long Id)
{
var objVoterList = _voterServices.GetByWardId(Id);
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_Voters_GetByWardId_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//public string DeleteVoter(long Id)
[System.Web.Http.HttpPost]
public IHttpActionResult DeleteVoter(long Id)
{
string result = string.Empty;
result = _voterServices.DeleteVoter(Id);
//return Request.CreateResponse(HttpStatusCode.OK, result);
return Json(new { status = "Success", msg = "Record found" });
}
//20180314
[System.Web.Mvc.HttpPost]
public IHttpActionResult Update([FromBody]sp_Voters_UpdateDetail objVoter)
{
//sp_Voters_UpdateDetail objVoter = new sp_Voters_UpdateDetail();
//objVoter.VoterName =
int result = _voterServices.UpdateDetail(objVoter);
if (result == 1)
{
return Json(new { status = "Success", msg = "Record updated", data = result });
//return Request.CreateResponse(HttpStatusCode.OK, "Voter detail updated successfully.");
//return Ok("Voter detail updated successfully.");
}
else
{
return Json(new { status = "Error", msg = "Record not updated", data = result });
//return Request.CreateResponse(HttpStatusCode.OK, "Error in update. Try again.");
}
}
[System.Web.Mvc.HttpPost]
public IHttpActionResult VerifyVoterByPageIncharge([FromBody]sp_Voters_VerifyByPageIncharge objVoter)
{
int result = _voterServices.VerifyVoterByPageIncharge(objVoter);
if (result == 1)
{
return Json(new { status = "Success", msg = "Verified", data = result });
}
else
{
return Json(new { status = "Error", msg = "Try again", data = result });
}
}
//20180322
//public IEnumerable<sp_SectionIncharge_GetAllByBoothIncharge_Result> GetAllByBoothIncharge(long CampaignId, long BoothInchargeId)
public IHttpActionResult GetAllByBoothIncharge(long CampaignId, long BoothInchargeId)
{
var objVoterList = _voterServices.GetAllByBoothIncharge(CampaignId, BoothInchargeId);
if (objVoterList != null)
{
var voterEntities = objVoterList as List<sp_SectionIncharge_GetAllByBoothIncharge_Result> ?? objVoterList.ToList();
if (voterEntities.Any())
{
//return Request.CreateResponse(HttpStatusCode.OK, voterEntities);
return Json(new { status = "Success", msg = "Record found", data = voterEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
public IHttpActionResult getPageInchargeLocation(long CampaignId, long PageInchargeId, DateTime VisitedDate)
{
var PageInchargeLocationList = _voterServices.getPageInchargeLocation(CampaignId, PageInchargeId, VisitedDate);
if (PageInchargeLocationList != null)
{
return Json(new { status = "Success", msg = "Record found", data = PageInchargeLocationList });
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Voter data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using electo.Models.SP_Models;
namespace electo.Models.Repositories
{
public class VotersServices : IVotersServices
{
private readonly UnitOfWork uow;
public VotersServices()
{
uow = new UnitOfWork();
}
#region HR Service Function
public IEnumerable<sp_Voters_GetAll_Result> GetAll()
{
var objVotersList = uow.sp_Voters_GetAll_Result_.SQLQuery<sp_Voters_GetAll_Result>("sp_Voters_GetAll").ToList();
if (objVotersList != null)
{
return objVotersList;
}
return null;
}
public sp_Voters_GetById_Result GetById(long Id)
{
var VoterId = new SqlParameter("@VoterId", Id);
var objVoter = uow.sp_Voters_GetById_Result_.SQLQuery<sp_Voters_GetById_Result>("sp_Voters_GetById @VoterId", VoterId).SingleOrDefault();
if (objVoter != null)
{
return objVoter;
}
return null;
}
//IEnumerable<sp_Voters_GetByPageInchargeId_Result> GetByPageInchargeId(long Id);
public IEnumerable<sp_Voters_GetByPageInchargeId_Result> GetByPageInchargeId(long Id)
{
var PageInchargeId = new SqlParameter("@PageInchargeId", Id);
var objVoterList = uow.sp_Voters_GetByPageInchargeId_Result_.SQLQuery<sp_Voters_GetByPageInchargeId_Result>("sp_Voters_GetByPageInchargeId @PageInchargeId", PageInchargeId).ToList();
if (objVoterList != null)
{
return objVoterList;
}
return null;
}
//20180228
//IEnumerable<sp_Voters_GetByStateId_Result> GetByStateId(long Id);
public IEnumerable<sp_Voters_GetByStateId_Result> GetByStateId(long Id)
{
var StateId = new SqlParameter("@StateId", Id);
var objVoterList = uow.sp_Voters_GetByStateId_Result_.SQLQuery<sp_Voters_GetByStateId_Result>("sp_Voters_GetByStateId @StateId", StateId).ToList();
if (objVoterList != null)
{
return objVoterList;
}
return null;
}
//IEnumerable<sp_Voters_GetByAreaId_Result> GetByAreaId(long Id);
public IEnumerable<sp_Voters_GetByAreaId_Result> GetByAreaId(long Id)
{
var AreaId = new SqlParameter("@AreaId", Id);
var objVoterList = uow.sp_Voters_GetByAreaId_Result_.SQLQuery<sp_Voters_GetByAreaId_Result>("sp_Voters_GetByAreaId @AreaId", AreaId).ToList();
if (objVoterList != null)
{
return objVoterList;
}
return null;
}
//IEnumerable<sp_Voters_GetByVidhanSabhaConstituencyId_Result> GetByVidhanSabhaConstituencyId(long Id);
public IEnumerable<sp_Voters_GetByVidhanSabhaConstituencyId_Result> GetByVidhanSabhaConstituencyId(long Id)
{
var VidhanSabhaConstituencyId = new SqlParameter("@VidhanSabhaConstituencyId", Id);
var objVoterList = uow.sp_Voters_GetByVidhanSabhaConstituencyId_Result_.SQLQuery<sp_Voters_GetByVidhanSabhaConstituencyId_Result>("sp_Voters_GetByVidhanSabhaConstituencyId @VidhanSabhaConstituencyId", VidhanSabhaConstituencyId).ToList();
if (objVoterList != null)
{
return objVoterList;
}
return null;
}
//IEnumerable<sp_Voters_GetByLokSabhaConstituencyId_Result> GetByLokSabhaConstituencyId(long Id);
public IEnumerable<sp_Voters_GetByLokSabhaConstituencyId_Result> GetByLokSabhaConstituencyId(long Id)
{
var LokSabhaConstituencyId = new SqlParameter("@LokSabhaConstituencyId", Id);
var objVoterList = uow.sp_Voters_GetByLokSabhaConstituencyId_Result_.SQLQuery<sp_Voters_GetByLokSabhaConstituencyId_Result>("sp_Voters_GetByLokSabhaConstituencyId @LokSabhaConstituencyId", LokSabhaConstituencyId).ToList();
if (objVoterList != null)
{
return objVoterList;
}
return null;
}
//IEnumerable<sp_Voters_GetByWardId_Result> GetByWardId(long Id);
public IEnumerable<sp_Voters_GetByWardId_Result> GetByWardId(long Id)
{
var WardId = new SqlParameter("@WardId", Id);
var objVoterList = uow.sp_Voters_GetByWardId_Result_.SQLQuery<sp_Voters_GetByWardId_Result>("sp_Voters_GetByWardId @WardId", WardId).ToList();
if (objVoterList != null)
{
return objVoterList;
}
return null;
}
//20180313
//string DeleteVoter(long VoterId);
public string DeleteVoter(long Id)
{
string returnResult = string.Empty;
int result = 0;
var VoterId = new SqlParameter("@VoterId", Id);
try
{
result = uow.sp_Voters_DeleteByVoterId_.SQLQuery<int>("sp_Voters_DeleteByVoterId @VoterId", VoterId).FirstOrDefault();
if (result == 1)
{
returnResult = "Voter data deleted successfully.";
}
else
{
returnResult = "Error in deleting record. Try again.";
}
}
catch (Exception e)
{
}
return returnResult;
}
//20180314
//int UpdateDetail(sp_Voters_UpdateDetail businessObject);
public int UpdateDetail(sp_Voters_UpdateDetail businessObject)
{
int result = 0;
var CampaignId = new SqlParameter("@CampaignId", businessObject.CampaignId);
var PageInchargeId = new SqlParameter("@PageInchargeId", businessObject.PageInchargeId);
var VoterId = new SqlParameter("@VoterId", businessObject.VoterId);
var VoterName = new SqlParameter("@VoterName", businessObject.VoterName);
var VoterLastName = new SqlParameter("@VoterLastName", businessObject.VoterName);
var Father_HusbandName = new SqlParameter("@Father_HusbandName", businessObject.Father_HusbandName);
var Gender = new SqlParameter("@GenderId", businessObject.Gender);
var DOB = new SqlParameter("@DOB", businessObject.DOB);
var Address = new SqlParameter("@Address", businessObject.Address);
var Phone = new SqlParameter("@Phone", businessObject.Phone);
var ChangeType = new SqlParameter("@ChangeType", businessObject.ChangeType);
var CommentDetail = new SqlParameter("@CommentDetail", businessObject.CommentDetail);
var latitude= new SqlParameter("@latitude", businessObject.latitude);
var longitude = new SqlParameter("@longitude", businessObject.longitude);
var dataIsCreated = new SqlParameter("@dataIsCreated", BaseUtil.GetCurrentDateTime());
var volunteerID = new SqlParameter("@volunteerID", businessObject.volunteerID);
var plotNo =new SqlParameter("@plotNo", businessObject.plotNo);
try
{
result = uow.sp_Voters_UpdateDetail_.SQLQuery<int>("sp_Voters_UpdateDetail @CampaignId,@PageInchargeId,@VoterId,@VoterName,@VoterLastName,@Father_HusbandName,@GenderId,@DOB,@Address,@Phone,@ChangeType,@CommentDetail,@latitude, @longitude, @dataIsCreated,@volunteerID,@plotNo", CampaignId, PageInchargeId, VoterId, VoterName, VoterLastName, Father_HusbandName, Gender, DOB, Address, Phone, ChangeType, CommentDetail, latitude, longitude, dataIsCreated,volunteerID, plotNo).FirstOrDefault();
return result;
}
catch (Exception e)
{
return 0;
}
}
//20180319
public int VerifyVoterByPageIncharge(sp_Voters_VerifyByPageIncharge businessObject)
{
int result = 0;
string query = "sp_Voters_VerifyByPageIncharge @CampaignId ='" + businessObject.CampaignId + "'" +
",@PageInchargeId='" + businessObject.PageInchargeId + "'" +
",@VoterId='" + businessObject.VoterId + "'" +
",@latitude='" + businessObject.latitude + "'" +
",@longitude='" + businessObject.longitude + "'" +
", @dataIsCreated ='" +BaseUtil.GetCurrentDateTime() + "'";
try
{
result = uow.sp_Voters_UpdateDetail_.SQLQuery<int>(query).FirstOrDefault();
}
catch { }
return result;
}
//20180322
//IEnumerable<sp_SectionIncharge_GetAllByBoothIncharge_Result> GetAllByBoothIncharge(long CampaignId, long BoothInchargeId);
public IEnumerable<sp_SectionIncharge_GetAllByBoothIncharge_Result> GetAllByBoothIncharge(long CampaignId, long BoothInchargeId)
{
var _CampaignId = new SqlParameter("@CampaignId", CampaignId);
var _BoothInchargeId = new SqlParameter("@BoothInchargeId", BoothInchargeId);
var objVoterList = uow.sp_SectionIncharge_GetAllByBoothIncharge_Result_.SQLQuery<sp_SectionIncharge_GetAllByBoothIncharge_Result>("sp_SectionIncharge_GetAllByBoothIncharge @CampaignId,@BoothInchargeId", _CampaignId, _BoothInchargeId).ToList();
if (objVoterList != null)
{
return objVoterList;
}
return null;
}
#endregion
public IEnumerable<sp_getPageInchargeLocation_Result> getPageInchargeLocation(long CampaignId, long PageInchargeId, DateTime VisitedDate)
{
var _CampaignId = new SqlParameter("@CampaignId", CampaignId);
var _PageInchargeId = new SqlParameter("@PageInchargeId", PageInchargeId);
var _VisitedDate = new SqlParameter("@dataIsCreated", VisitedDate);
var PageInchargeLocation_ = uow.sp_SectionIncharge_GetAllByBoothIncharge_Result_.SQLQuery<sp_getPageInchargeLocation_Result>("sp_getPageInchargeLocation @CampaignId,@PageInchargeId,@dataIsCreated", _CampaignId, _PageInchargeId, _VisitedDate).ToList();
if (PageInchargeLocation_ != null)
{
return PageInchargeLocation_;
}
return null;
}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class PageInchargeComment : IPageInchargeComment
{
private readonly UnitOfWork uow;
public PageInchargeComment()
{
uow = new Models.Repositories.UnitOfWork();
}
#region HR Service Function
//20180312
//IEnumerable<sp_PageInchargeComments_ByCampaignId_Result> GetByCampaignId(long Id);
public IEnumerable<sp_PageInchargeComments_ByCampaignId_Result> GetByCampaignId(long _boothInchargeId, long _campaignId)
{
var BoothInchargeId = new SqlParameter("@BoothInchargeId", _boothInchargeId);
var CampaignId = new SqlParameter("@CampaignId", _campaignId);
var objPageInchargeCommentList = uow.sp_PageInchargeComments_ByCampaignId_Result_.SQLQuery<sp_PageInchargeComments_ByCampaignId_Result>("sp_PageInchargeComments_ByCampaignId @CampaignId,@BoothInchargeId", CampaignId, BoothInchargeId);
if (objPageInchargeCommentList != null)
{
return objPageInchargeCommentList;
}
return null;
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface ImuncipalCorporationServices
{
IEnumerable<municipalCorporationName> getmuncipalCorporationByStateID(int stateID);
int create(municipalCorporationName omunicipalCorporationName);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.SP_Models
{
public class sp_Voters_UpdateDetail
{
public long CampaignId { get; set; }
public long PageInchargeId { get; set; }
public long VoterId { get; set; }
public string VoterName { get; set; }
public string VoterLastName { get; set; }
public string Father_HusbandName { get; set; }
public string Gender { get; set; }
public DateTime DOB { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string ChangeType { get; set; }
public string CommentDetail { get; set; }
public float latitude { get; set; }
public float longitude { get; set; }
public long volunteerID { get; set; }
public string plotNo { get; set; }
}
}<file_sep>using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
public class CampaignActivityController : Controller
{
private readonly ICampaignService _CampaignService;
private readonly IEventServices _eventServices;
private readonly IEventTypeService _EventTypeService;
public CampaignActivityController()
{
_CampaignService = new CampaignService();
_EventTypeService = new EventTypeService();
_eventServices = new EventServices();
}
// GET: CampaignActivity
public ActionResult Index()
{
ViewBag.CampaignList = new SelectList((_CampaignService.getCompaignListByElectionIDandCreatedByID(Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()))).Select(e => new { e.campaignID, e.campaignName })),"campaignID","campaignName");
ViewBag.eventTypeID = new SelectList((_EventTypeService.GetEventTypeList().Select(e => new { e.eventTypeID, e.eventName })), "eventTypeID", "eventName");
return View();
}
public ActionResult _partialActivityList( int eventTypeID ,int CampaignId)
{
var ActivityListLIst = _eventServices.GetByCampaignIdANDEventTypeID(CampaignId, eventTypeID);
return PartialView("_partialActivityList", ActivityListLIst);
}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class zoneServices: IzoneServices
{
private readonly UnitOfWork uow;
public zoneServices()
{
uow = new UnitOfWork();
}
public IEnumerable<sp_getZoneByStateIDAndMUncipalCorporationID_Result> getZoneByStateIDAndMUncipalCorporationID(int stateId, int MPCorporation)
{
var MPCorporation_ = new SqlParameter("@MPCorporation", MPCorporation);
var stateId_ = new SqlParameter("@stateId", stateId);
var _MUncipalCorporationList = uow.zoneMunicipality_.SQLQuery<sp_getZoneByStateIDAndMUncipalCorporationID_Result>("sp_getZoneByStateIDAndMUncipalCorporationID @stateId,@MPCorporation", stateId_, MPCorporation_).ToList();
return _MUncipalCorporationList;
}
public bool CreateVidhanSabha(zoneMunicipality ozoneMunicipality)
{
bool result = false;
try
{
uow.zoneMunicipality_.Add(ozoneMunicipality);
result = true; ;
}
catch (Exception e)
{
result = false;
}
return result;
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class AreaController : BaseClass
{
private readonly IAreaService _AreaServices;
private readonly IstateService _stateService;
private readonly IElectionService _ElectionService;
private readonly IVSCServices _VSCServices;
private readonly IDistrictServices _DistrictServices;
private readonly ILSCServices _LSCServices;
private readonly IwardServices _WardServices;
private readonly IPollingBooth _PollingBoothService;
private readonly ImuncipalCorporationServices _mncipalCorp;
public AreaController()
{
_AreaServices = new AreaService();
_stateService = new stateService();
_ElectionService = new ElectionService();
_VSCServices = new VSCServices();
_DistrictServices = new DistrictServices();
_LSCServices = new LSCServices();
_WardServices = new wardServices();
_mncipalCorp = new muncipalCorporationServices();
_PollingBoothService = new PollingBoothService();
}
public ActionResult GetConstituency(int stateId, int ElectionTypeId) {
string result = string.Empty;
if (ElectionTypeId == 2)
{
var lstConstituency = _VSCServices.getvidhanSabhaConstituencyByStateID(stateId).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
result = javaScriptSerializer.Serialize(lstConstituency);
}
if (ElectionTypeId == 1)
{
var lstConstituency = _LSCServices.getAlllokSabhaConstituencyConstituency(stateId).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
result = javaScriptSerializer.Serialize(lstConstituency);
}
if (ElectionTypeId == 3)
{
var lstConstituency = _mncipalCorp.getmuncipalCorporationByStateID(stateId).Select(e => new { e.municipalCorporationID, e.municipalCorporationName1 });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
result = javaScriptSerializer.Serialize(lstConstituency);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
// GET: Area
public ActionResult Index()
{
ViewBag.ElectionType = new SelectList((_ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME })), "electionTypeID", "electionTypeNAME");
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult _partialAreaLIst(int ElectionTypeId, int stateId, int ddl_Constituency)
{
var AreaLIst = _AreaServices.getAll_areaList(ElectionTypeId,stateId,ddl_Constituency);
return PartialView("_PartialAreaList", AreaLIst);
}
public ActionResult getAll_areaList( Int64 wardID)
{
var _AreaList = _AreaServices.GetAll().Where(e=>e.wardID== wardID).Select(e => new { e.areaID, e.areaName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
var result = javaScriptSerializer.Serialize(_AreaList);
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.lokSabhaConstituencyID = _LSCServices.getAlllokSabhaConstituencyConstituency(1).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
ViewBag.vidhanSabhaConstituencyID = _VSCServices.getvidhanSabhaConstituencyByStateID(1).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
ViewBag.wardID = _WardServices.getZoneByStateIDAndMUncipalCorporationID(1, 1, 0,0).Select(e => new { e.wardID, e.wardName });
ViewBag.electionID = _ElectionService.getAllElections().Select(e => new { e.electionID , e.electionName1});
ViewBag.pollingBoothID = _PollingBoothService.get_PollingBoothList(0,0,0,2).Select(e => new { e.pollingBoothID, e.pollingBoothName });
return View("Create");
}
[HttpPost]
public ActionResult Create (areaName _areaName)
{
areaName areaName_ = new areaName();
areaName_.areaName1 = _areaName.areaName1;
areaName_.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
areaName_.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
areaName_.lokSabhaConstituencyID = _areaName.lokSabhaConstituencyID;
areaName_.vidhanSabhaConstituencyID = _areaName.vidhanSabhaConstituencyID;
areaName_.wardID = _areaName.wardID;
areaName_.districtID = _areaName.districtID;
areaName_.stateID = _areaName.stateID;
areaName_.dataIsCreated = BaseUtil.GetCurrentDateTime();
areaName_.dataIsUpdated = BaseUtil.GetCurrentDateTime();
areaName_.isActive = true;
areaName_.pollingBoothID = _areaName.pollingBoothID;
int result = _AreaServices.createArea(areaName_);
if (result == 1)
{
TempData["Creation"] = "Success";
return RedirectToAction("Index");
}
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.lokSabhaConstituencyID = _LSCServices.getAlllokSabhaConstituencyConstituency(1).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
ViewBag.vidhanSabhaConstituencyID = _VSCServices.getvidhanSabhaConstituencyByStateID(1).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
ViewBag.wardID = _WardServices.getZoneByStateIDAndMUncipalCorporationID(1, 1, 0,0).Select(e => new { e.wardID, e.wardName });
TempData["Creation"] = "unsuccess";
return View(_areaName);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IQuestionService
{
IEnumerable<questionType> GetQuestionTypeList();
bool addNewQuestionType(questionType OquestionType);
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class PollingBoothService: IPollingBooth
{
private readonly UnitOfWork uow;
public PollingBoothService()
{
uow = new UnitOfWork();
}
public IEnumerable<sp_pollingBoothList_Result> get_PollingBoothList(int stateId, int LSCID, int VSCID, int wardID)
{
var LSCID_ = new SqlParameter("lokSabhaId", SqlString.Null);
var stateId_ = new SqlParameter("@stateId", SqlString.Null);
var VSC_ID_ = new SqlParameter("@vidhansabhaID", SqlString.Null);
var ward_id_ = new SqlParameter("@wardID", SqlString.Null);
if (LSCID != 0)
{
LSCID_ = new SqlParameter("@lokSabhaId", LSCID);
}
if (stateId != 0)
{
stateId_ = new SqlParameter("@stateId", stateId);
}
if (VSCID != 0)
{
VSC_ID_ = new SqlParameter("@vidhansabhaID", VSCID);
}
if (wardID != 0)
{
ward_id_ = new SqlParameter("@wardID", wardID);
}
var _pollingBoothListList = uow.sp_getVidhanSabhaLsit_Result_.SQLQuery<sp_pollingBoothList_Result>("sp_pollingBoothList @stateId,@lokSabhaId, @vidhansabhaID,@wardID", stateId_, LSCID_, VSC_ID_, ward_id_).ToList();
return _pollingBoothListList;
}
public int createPollingBooth(pollingBooth pollingBooth_)
{
int result;
try
{
uow.createPollingBooth_.Add(pollingBooth_);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
public IEnumerable<sp_getPoolingBoothByCampignID_Result> get_PollingBoothListByCampaignID(Int64 CampaignID)
{
var CampaignID_ = new SqlParameter("@CampignID", CampaignID);
var _pollingBoothListList = uow.sp_pollingBoothList_Result_.SQLQuery<sp_getPoolingBoothByCampignID_Result>("sp_getPoolingBoothByCampignID @CampignID", CampaignID_).ToList();
return _pollingBoothListList;
}
public int AssignPollingBoothToAssignPollingBoothIncharge(AssignPollingBoothToPollingBoothIncharge oAssignPollingBoothToPollingBoothIncharge)
{
int result;
pollingBooth_andInchargRelationship opollingBooth_andInchargRelationship = new pollingBooth_andInchargRelationship();
opollingBooth_andInchargRelationship.campaignID = oAssignPollingBoothToPollingBoothIncharge.campaignid;
opollingBooth_andInchargRelationship.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
opollingBooth_andInchargRelationship.dataIsCreated = BaseUtil.GetCurrentDateTime();
opollingBooth_andInchargRelationship.dataIsUpdated = BaseUtil.GetCurrentDateTime();
opollingBooth_andInchargRelationship.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
opollingBooth_andInchargRelationship.pollingBoothID = oAssignPollingBoothToPollingBoothIncharge.PollingBoothID;
opollingBooth_andInchargRelationship.volunteerID = oAssignPollingBoothToPollingBoothIncharge.voluntearID;
opollingBooth_andInchargRelationship.isActive = true;
try
{
uow.pollingBooth_andInchargRelationship_.Add(opollingBooth_andInchargRelationship);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using electo.Models;
using electo.Models.Repositories;
using System.IO;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class AccountController : BaseClass
{
private readonly IAccountServices _IAccountServices;
private readonly IElectionService _ElectionService;
private readonly ICampaignService _CampaignService;
public AccountController()
{
_IAccountServices = new AccountServices();
_ElectionService = new ElectionService();
_CampaignService = new CampaignService();
}
private AccountServices _accServices = new AccountServices();
// GET: Account
[HttpGet]
public ActionResult login()
{
LoginViewModel _LoginViewModel = new LoginViewModel();
return View(_LoginViewModel);
}
[HttpPost]
public ActionResult login(LoginViewModel _LoginViewModel)
{
if (ModelState.IsValid)
{
var result = _IAccountServices.UserLogin(_LoginViewModel.Email, _LoginViewModel.Password);
if (result != null)
{
if (result.loginID == 0)
{
ViewBag.msg = result.message;
return View();
}
BaseUtil.SetSessionValue(AdminInfo.LoginID.ToString(), result.loginID.ToString());
BaseUtil.SetSessionValue(AdminInfo.FullName.ToString(), result.voterName.ToString());
BaseUtil.SetSessionValue(AdminInfo.userPhoto.ToString(), result.userPhoto.ToString());
BaseUtil.SetSessionValue(AdminInfo.userType.ToString(), result.userTypeID.ToString());
BaseUtil.SetSessionValue(AdminInfo.volunteerID.ToString(), result.volunteerID.ToString());
BaseUtil.SetSessionValue(AdminInfo.politicalPartyID.ToString(), result.politicalPartyID.ToString());
string pass = BaseUtil.Decrypt(result.password.ToString());
BaseUtil.SetSessionValue(AdminInfo.unikKey.ToString(), pass);
if (result.userTypeID == 3 || result.userTypeID == 1)
{
return RedirectToAction("Dashboard", "dashboard");
}
else if (result.userTypeID == 4)
{
TempData["createNewCompaign"] = result.createNewCompaign.ToString();
return RedirectToAction("MyCampaigns", "RunningCampaign");
}
else {
ViewBag.msg = "You are not authorized to access this website";
return View();
}
}
ViewBag.msg = "Userid and password not found";
return View();
}
ViewBag.msg = "invalid model";
return View();
}
public ActionResult Logout()
{
if (BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()) != "")
{
long loginID = Convert.ToUInt32(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
DateTime currentDateTime = BaseUtil.GetCurrentDateTime();
_accServices.saveLogoutDetails(loginID, currentDateTime);
}
Session.Abandon();
return RedirectToAction("login");
}
[HttpGet]
public ActionResult ForgotPassword()
{
return View();
}
[HttpPost]
public ActionResult ForgotPassword(LoginIdViewModel oLoginIdViewModel)
{
string result = string.Empty;
result = _IAccountServices.forgetpassword(oLoginIdViewModel.Email);
TempData["Result"] = result;
return View("Login");
}
public ActionResult ResetPassword()
{
return View();
}
[HttpPost]
public ActionResult ResetPassword(ChangePasswordViewModel oChangePasswordViewModel)
{
if (oChangePasswordViewModel.OldPassword != BaseUtil.GetSessionValue(AdminInfo.unikKey.ToString()))
{
ViewBag.msg = "old";
return View();
}
bool result = false;
loginVolunteer _loginVolunteer = new loginVolunteer();
result =Convert.ToBoolean( _IAccountServices.ResetPassword(oChangePasswordViewModel.NewPassword, Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()))));
if (result)
{
ViewBag.msg = "Success";
}
else
{
ViewBag.msg = "Failure";
}
return View();
}
public ActionResult SearchVolunteerUser()
{
return View();
}
public ActionResult getVoterDetails(string voterIDNumber)
{
//var result = oWebApiRepositories.getVoterByID("Account", "getVoterByID", voterIDNumber);
var result = _accServices.getDet(voterIDNumber);
return PartialView("_partialVoterDetails", result);
}
public ActionResult CreateUser(long voterID)
{
ViewBag.PoliticalPartyID = _accServices.getAll();
ViewBag.userTypeID = _accServices.getAllUserTypes();
ViewBag.voterID = voterID;
return PartialView("CreateUser");
}
[HttpPost]
public ActionResult Create(CreateVolunteerLogin _createVolunteerLogin)
{
string returnResult = string.Empty;// User created and mail has been sent to user, User created, please recover your password,User not created, user already exists
_createVolunteerLogin.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString())) ;
//string encriptedPwd = BaseUtil.encrypt(_password);
string result = string.Empty;
result = _IAccountServices.createUser(_createVolunteerLogin.voterID,
_createVolunteerLogin.politicalPartyID.ToString(), BaseUtil.GetCurrentDateTime().ToString(), BaseUtil.GetCurrentDateTime().ToString(),
BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()),BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()),
_createVolunteerLogin.userID, _createVolunteerLogin.mobile, _createVolunteerLogin.fullName, _createVolunteerLogin.isActive, _createVolunteerLogin.isBlocked,
_createVolunteerLogin.AadharCardNumber, _createVolunteerLogin.userTypeID);
TempData["returnResult"] = result;
return RedirectToAction("SearchVolunteerUser");
}
public int ActivateCreateCompaign(long volunteerID)
{
int result = 0;
result= _accServices.ActivateCreateCompaign(volunteerID);
return result;
}
[HttpGet]
public ActionResult UpdateProfile(long loginID)
{
loginVolunteer _loginvolunteer = _accServices.getUserDetails(loginID);
return View(_loginvolunteer);
}
[HttpPost]
public ActionResult UpdateProfile(loginVolunteer _loginVolunteer, HttpPostedFileBase files)
{
String fileName = "";
if (files != null)
{
fileName = Guid.NewGuid() + "_" + Path.GetFileName(files.FileName);
var path = Path.Combine(Server.MapPath("~/Logo/"), fileName);
files.SaveAs(path);
_loginVolunteer.userPhoto = "http://electo.qendidate.com/Logo/" + fileName;
}
else
{
_loginVolunteer.userPhoto = "http://electo.qendidate.com/Logo/" + "Emptyuser.jpg";
}
_loginVolunteer.dataIsUpdated = BaseUtil.GetCurrentDateTime();
var modified = BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString());
_loginVolunteer.modifiedBy = Convert.ToUInt32(modified);
int result = _accServices.saveUserDetails(_loginVolunteer);
if (result == 1)
{
TempData["Result"] = "Success";
}
else {
TempData["Result"] = "Failure";
}
return View(_loginVolunteer);
}
public ActionResult Index()
{
ViewBag.userTypeID = new SelectList((_accServices.getAllUserTypes().Select(e => new { e.userTypeID, e.userTypeName })), "userTypeID", "userTypeName");
return View();
}
public ActionResult _partialViewUserLoginStatus(int userTypeID, string userID)
{
var UserLoginStatusList = _accServices.getUserLoginStatus(userTypeID, userID);
return PartialView("_partialViewUserLoginStatus", UserLoginStatusList);
}
public int updateUserLoginStatus(long loginID, bool isActive)
{
int result = 0;
result = _accServices.updateUserLoginStatus(loginID, Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString())), isActive);
return result;
}
//[HttpGet]
//public ActionResult CAdmin()
//{
// ViewBag.electionTypeID = _ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME });//), "electionTypeID", "electionTypeNAME");
// ViewBag.campaignID = _CampaignService.getCompaignListByElectionIDandCreatedByID(0, 0).Select(e=>new { e.campaignID, e.campaignName });
// ViewBag.IsCampaignCreationActive = TempData["createNewCompaign"];
// return View();
//}
[HttpPost]
public ActionResult CAdmin(CompaignAdmin oCompaignAdmin, FormCollection frm)
{
BaseUtil.SetSessionValue(AdminInfo.electionType.ToString(), frm["hdn_electionType"].ToString());
BaseUtil.SetSessionValue(AdminInfo.campaign.ToString(), frm["hdn_campaignID"].ToString());
BaseUtil.SetSessionValue(AdminInfo.campaignID.ToString(), oCompaignAdmin.campaignID.ToString());
return RedirectToAction("Index", "CampaignActivity");
}
//public ActionResult getCampaignList(int ElectionTypeId)
//{
// var CampaignList = _CampaignService.getCompaignListByElectionIDandCreatedByID(Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString())), ElectionTypeId).Select(e => new { e.campaignID, e.campaignName });
// JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
// return Json(javaScriptSerializer.Serialize(CampaignList), JsonRequestBehavior.AllowGet);
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IlanguageServices
{
IEnumerable<language> getAll_LangaugeList();
int create(language Olanguage);
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class AreaService : IAreaService
{
private readonly UnitOfWork uow;
public AreaService()
{
uow = new UnitOfWork();
}
public IEnumerable<sp_areaList_Result> getAll_areaList(int ElectionTypeId, int stateId, int ddl_Constituency)
{
var ElectionTypeId_ = new SqlParameter("@electionTypeID", ElectionTypeId);
var stateId_ = new SqlParameter("@stateID", stateId);
var ddl_Constituency_ = new SqlParameter("@constituencyID", ddl_Constituency);
var _sp_areaList_Result = uow.sp_areaList_Result_.SQLQuery< sp_areaList_Result>("sp_areaList @stateID, @electionTypeID, @constituencyID", stateId_, ElectionTypeId_, ddl_Constituency_).ToList();
return _sp_areaList_Result;
}
public int createArea(areaName areaName_)
{
int result;
try
{
uow.createArea_.Add(areaName_);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
#region HR Service Function
//20180222
public IEnumerable<sp_Area_GetAll_Result> GetAll()
{
var objAreaList = uow.sp_Area_GetAll_Result_.SQLQuery<sp_Area_GetAll_Result>("sp_Area_GetAll");
if (objAreaList != null)
{
return objAreaList;
}
return null;
}
//IEnumerable<sp_Area_GetByPageInchargeId_Result> GetByPageInchargeId();
public IEnumerable<sp_Area_GetByPageInchargeId_Result> GetByPageInchargeId(long Id)
{
var PageInchargeId = new SqlParameter("@PageInchargeId", Id);
var objAreaList = uow.sp_Area_GetByPageInchargeId_Result_.SQLQuery<sp_Area_GetByPageInchargeId_Result>("sp_Area_GetByPageInchargeId @PageInchargeId", PageInchargeId);
if (objAreaList != null)
{
return objAreaList;
}
return null;
}
#endregion
//public IEnumerable<sp_Area_GetByVolunteerId_Result> GetByVolunteerId(long Id)
//{
// var VolunteerId = new SqlParameter("@VolunteerId", Id);
// var objAreaList = uow.sp_Area_GetByVolunteerId_Result_.SQLQuery<sp_Area_GetByVolunteerId_Result>("sp_Area_GetByVolunteerId @VolunteerId", VolunteerId).ToList();
// if (objAreaList != null)
// {
// return objAreaList;
// }
// return null;
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.IRepositories
{
interface IEnquiryServices
{
IEnumerable<sp_GetNewEnquiries_Result> GetNewEnquiries_Result(string enquirytype, string date, string mobile, bool isTaskCompleted);
IEnumerable<enquiryType> getEnquiryTypes();
enquiry get(long eID);
enquiry _save(enquiry _enq);
enquiry create(enquiry _enq);
}
}
<file_sep>using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.WebServicesController
{
public class EventController : ApiController
{
private readonly IEventServices _EventServices;
public EventController()
{
_EventServices = new EventServices();
}
public IHttpActionResult createEvent(sp_createEvent osp_createEvent)
{
int result=0;
result = _EventServices.createEvent(osp_createEvent);
if (result == 1)
{
//return Request.CreateResponse(HttpStatusCode.OK, "success");
return Json(new { status = "Success", msg = "Success"});
}
//return Request.CreateErrorResponse(HttpStatusCode.OK, "failure");
return Json(new { status = "Error", msg = "Failure" });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IEventTypeService
{
IEnumerable<eventType> GetEventTypeList();
bool addNewEventType(eventType OeventType);
IEnumerable<sp_GetAllEventTypes_Result> getEventTypes();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface ISurveyResponseService
{
//20180313
#region HR IService Function
//private Repositories<sp_SurveyAnalysis_BySurveyId_Result> _sp_SurveyAnalysis_BySurveyId { get; set; }
IEnumerable<sp_SurveyAnalysis_BySurveyId_Result> GetBySurveyId(long Id);
#endregion
int submitResponse(IEnumerable<surveyRespons> _surveyResponse);
}
}
<file_sep>using electo.Models;
using electo.Models.BaseClass;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
public class UploadVoterListFromExcelController : BaseClass
{
public ActionResult importExcel()
{
return View();
}
[ActionName("importExcel")]
[HttpPost]
public ActionResult importexcel1()
{
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();
string connString = "";
string[] validFileTypes = { ".xls", ".xlsx", ".csv" };
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName);
if (!Directory.Exists(path1))
{
Directory.CreateDirectory(Server.MapPath("~/Content/Uploads"));
}
if (validFileTypes.Contains(extension))
{
if (System.IO.File.Exists(path1))
{ System.IO.File.Delete(path1); }
Request.Files["FileUpload1"].SaveAs(path1);
if (extension.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
DataTable dt = Utility.ConvertXSLXtoDataTable(path1, connString);
List<excel> excel = new List<excel>();
excel objexcel;
var c = dt.Rows.Count;
for (int i = 0; i < c; i++)
{
objexcel = new excel();
if (dt.Rows[i]["ID"].ToString() != "")
{
objexcel.ID = Convert.ToInt16(dt.Rows[i]["ID"].ToString());
}
if (dt.Rows[i]["statename"].ToString() != "")
{
objexcel.statename = dt.Rows[i]["statename"].ToString();
}
if (dt.Rows[i]["loksabhaname"].ToString() != "")
{
objexcel.loksabhaname = dt.Rows[i]["loksabhaname"].ToString();
}
if (dt.Rows[i]["districtname"].ToString() != "")
{
objexcel.districtname = dt.Rows[i]["districtname"].ToString();
}
if (dt.Rows[i]["vidhansabhaname"].ToString() != "")
{
objexcel.vidhansabhaname = dt.Rows[i]["vidhansabhaname"].ToString();
}
if (dt.Rows[i]["municipalcorporationname"].ToString() != "")
{
objexcel.municipalcorporationname = dt.Rows[i]["municipalcorporationname"].ToString();
}
if (dt.Rows[i]["zonename"].ToString() != "")
{
objexcel.zonename = dt.Rows[i]["zonename"].ToString();
}
if (dt.Rows[i]["wardname"].ToString() != "")
{
objexcel.wardname = dt.Rows[i]["wardname"].ToString();
}
if (dt.Rows[i]["pollingboothname"].ToString() != "")
{
objexcel.pollingboothname = dt.Rows[i]["pollingboothname"].ToString();
}
if (dt.Rows[i]["sectionName"].ToString() != "")
{
objexcel.areaname = dt.Rows[i]["sectionName"].ToString();
}
if (dt.Rows[i]["age"].ToString() != "")
{
objexcel.age = dt.Rows[i]["age"].ToString();
}
if (dt.Rows[i]["voterfirstname"].ToString() != "")
{
objexcel.voterfirstname = dt.Rows[i]["voterfirstname"].ToString();
}
if (dt.Rows[i]["voterlastname"].ToString() != "")
{
objexcel.voterlastname = dt.Rows[i]["voterlastname"].ToString();
}
if (dt.Rows[i]["voteridnumber"].ToString() != "")
{
objexcel.voteridnumber = dt.Rows[i]["voteridnumber"].ToString();
}
if (dt.Rows[i]["FatherName"].ToString() != "")
{
objexcel.FatherName = dt.Rows[i]["FatherName"].ToString();
}
if (dt.Rows[i]["plotno"].ToString() != "")
{
objexcel.plotno = dt.Rows[i]["plotno"].ToString();
}
if (dt.Rows[i]["wardno"].ToString() != "")
{
objexcel.wardno = dt.Rows[i]["wardno"].ToString();
}
if (dt.Rows[i]["gender"].ToString() != "")
{
objexcel.gender = dt.Rows[i]["gender"].ToString();
}
if (dt.Rows[i]["zipCode"].ToString() != "")
{
objexcel.zipCode = dt.Rows[i]["zipCode"].ToString();
}
if (dt.Rows[i]["dateofbirth"].ToString() != "")
{
var dte = Convert.ToDateTime(dt.Rows[i]["dateofbirth"].ToString());
objexcel.dateofbirth = dte;
}
objexcel.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
objexcel.createdDate = BaseUtil.GetCurrentDateTime();
excel.Add(objexcel);
}
electoEntities ee = new electoEntities();
try
{
ee.excels.AddRange(excel);
ee.SaveChanges();
var result = ee.Database.SqlQuery<int>("exec sp_insertVoterListExcel").FirstOrDefault();
}
catch { ViewBag.Error = "errro"; }
ViewBag.Data = dt;
}
else
{
ViewBag.Error = "Please Upload File .xlsx format";
}
}
}
return View();
}
}
}
<file_sep>using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using electo.Models;
using electo.Models.IRepositories;
using Newtonsoft.Json;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.WebServicesController
{
public class AccountController : ApiController
{
private readonly IAccountServices _AccountServices;
public AccountController()
{
_AccountServices = new AccountServices();
}
[HttpPost]
public IHttpActionResult userLogin([FromBody]LoginViewModelApp _LoginViewModel)
{
if (ModelState.IsValid)
{
_LoginViewModel.Password = <PASSWORD>Util.encrypt(_LoginViewModel.Password);
var _objloginVolunteer = _AccountServices.UserLoginApp(_LoginViewModel.Email, _LoginViewModel.Password, _LoginViewModel.userTypeID);
if (_objloginVolunteer != null)
{
var productEntities = _objloginVolunteer as sp_LoginUser_App_Result ?? _objloginVolunteer;
if (productEntities != null)
//return Request.CreateResponse(HttpStatusCode.OK, productEntities);
return Json(new { status = "Success", msg = "Record found", data = productEntities });
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Invalid Model");
return Json(new { status = "Error", msg = "Invalid Model" });
}
[HttpPost]
public IHttpActionResult forgetpassword(string Email)
{
string result = string.Empty;
if (ModelState.IsValid)
{
result = _AccountServices.forgetpassword(Email);
if (result == "success")
{
//return Request.CreateResponse(HttpStatusCode.OK, result);
return Json(new { status = "Success", msg = "Record found", data = result });
}
if(result == "failure")
{
return Json(new { status = "Error", msg = "Error Sending Mail" });
}
}
return Json(new { status = "Error", msg = "user not found" });
}
[HttpGet]
public IHttpActionResult resetPassword(string newPassword, long loginID)
{
bool result = false;
result = Convert.ToBoolean(_AccountServices.ResetPassword(newPassword, loginID));
if(result == true)
{
return Json(new { status = "Success", msg = "Record found"});
}
return Json(new { status = "Error", msg = "Invalid Model" });
}
[HttpGet]
public IHttpActionResult getVoterByID(string voterID)
{
List<sp_getVoterDetailsByVoterIDApp> osp_getVoterDetailsByVoterIDApp_= new List<sp_getVoterDetailsByVoterIDApp>();
var result = _AccountServices.getDet(voterID);
if (result != null)
{
if (result.Count() != 0)
{
sp_getVoterDetailsByVoterIDApp osp_getVoterDetailsByVoterIDApp;
foreach (var list_ in result)
{
osp_getVoterDetailsByVoterIDApp = new sp_getVoterDetailsByVoterIDApp();
osp_getVoterDetailsByVoterIDApp.address = list_.address;
if (list_.dateOfBirth != null)
{
osp_getVoterDetailsByVoterIDApp.dateOfBirth = (DateTime)list_.dateOfBirth;
}
osp_getVoterDetailsByVoterIDApp.Regional_Name = list_.Regional_Name;
osp_getVoterDetailsByVoterIDApp.volunteerID = list_.volunteerID;
osp_getVoterDetailsByVoterIDApp.voterFather_HusbandName = list_.voterFather_HusbandName;
osp_getVoterDetailsByVoterIDApp.voterID = list_.voterID;
osp_getVoterDetailsByVoterIDApp.voterIDNumber = list_.voterIDNumber;
osp_getVoterDetailsByVoterIDApp_.Add(osp_getVoterDetailsByVoterIDApp);
}
return Json(new { status = "Success", msg = "Record found", data = osp_getVoterDetailsByVoterIDApp_ });
}
else {
return Json(new { status = "Success", msg = "user not found" });
}
}
return Json(new { status = "Error", msg = "user not found" });
}
[HttpGet]
public IHttpActionResult getAllPartiees()
{
var result = _AccountServices.getAllPoliticalParty();
if (result != null)
{
return Json(new { status = "Success", msg = "Record found", data = result });
}
return Json(new { status = "Error", msg = "Record not found" });
}
[HttpGet]
public HttpResponseMessage getAllParties()
{
var result = (_AccountServices.getAllPoliticalParty());
var jsonResult = JsonConvert.SerializeObject(result);
return Request.CreateResponse(HttpStatusCode.OK, jsonResult);
}
[HttpPost]
public IHttpActionResult createUser([FromBody] CreateVolunteerLoginApp _createVolunteerLogin)
{
string _voterID = _createVolunteerLogin.voterID.ToString();
string _politicalPartyID = _createVolunteerLogin.politicalPartyID.ToString();
string _dataIsCreated = BaseUtil.GetCurrentDateTime().ToString();
string _dataIsUpdated = BaseUtil.GetCurrentDateTime().ToString();
long _createdBy = 1;
string _userID = _createVolunteerLogin.userID;
string _mobile = _createVolunteerLogin.mobile;
string _fullName = _createVolunteerLogin.fullName;
string _AadharCardNumber = _createVolunteerLogin.AadharCardNumber;
bool _isActive = true;
bool _isBlocked = false;
int userTypeid =4;
string returnResult = string.Empty;
returnResult = _AccountServices.createUser(_voterID, _politicalPartyID, _dataIsCreated, _dataIsUpdated, _createdBy.ToString(), _createdBy.ToString(), _userID, _mobile, _fullName, _isActive, _isBlocked, _AadharCardNumber, userTypeid);
return Json(new { status = "Success", msg = returnResult });
}
[HttpPost]
public HttpResponseMessage userLogin_([FromBody]LoginViewModel _LoginViewModel)
{
if (ModelState.IsValid)
{
_LoginViewModel.Password = <PASSWORD>(_LoginViewModel.Password);
var _objloginVolunteer = _AccountServices.UserLogin(_LoginViewModel.Email, _LoginViewModel.Password);
if (_objloginVolunteer != null)
{
var productEntities = _objloginVolunteer as sp_LoginUser_Result ?? _objloginVolunteer;
if (productEntities != null)
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
}
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found");
}
return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Invalid Model");
}
[HttpPost]
public HttpResponseMessage forgetpassword_(string Email)
{
string result = string.Empty;
if (ModelState.IsValid)
{
result = _AccountServices.forgetpassword(Email);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Invalid Model");
}
[HttpGet]
public HttpResponseMessage resetPassword_(string newPassword, long loginID)
{
bool result = false;
result = Convert.ToBoolean(_AccountServices.ResetPassword(newPassword, loginID));
return Request.CreateResponse(HttpStatusCode.OK, result);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IPoliticalPartyService
{
IEnumerable<sp_politicalPartyList_Result> getAll_PoliticalPartyListByStateID(int stateId, string PoliticalPartyName);
int createParty(CreatePartyViewModel oCreatePartyViewModel);
IEnumerable<sp_partyAddressList_Result> PoliticalPartyAddressList(int politicalPartyId);
bool saveNewAddress(politicalPartyAddress opoliticalPartyAddress);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IPageInchargeComment
{
#region HR IService Function
//20180312
//private Repositories<sp_PageInchargeComments_ByCampaignId_Result> GetByCampaignId { get; set; }
IEnumerable<sp_PageInchargeComments_ByCampaignId_Result> GetByCampaignId(long BoothInchargeId, long CampaignId);
#endregion
}
}
<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class PoliticalPartiesByStateController : BaseClass
{
private readonly IstateService _stateService;
private readonly IPoliticalPartyService _PoliticalPartyService;
private readonly IDistrictServices _DistrictServices;
public PoliticalPartiesByStateController()
{
_stateService = new stateService();
_PoliticalPartyService = new PoliticalPartyService();
_DistrictServices = new DistrictServices();
}
// GET: PoliticalPartiesByState
public ActionResult Index()
{
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult _partialPoliticalPartiesByStateList( int stateId, string partyName)
{ if (partyName == "0" || partyName==null)
{
partyName = "";
}
var AreaLIst = _PoliticalPartyService.getAll_PoliticalPartyListByStateID( stateId, partyName);
return PartialView("_partialPoliticalPartiesByStateList", AreaLIst);
}
[HttpGet]
public ActionResult Create()
{
CreatePartyViewModel oCreatePartyViewModel = new CreatePartyViewModel();
ViewBag.stateID = _stateService.getAllStates();
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
return View(oCreatePartyViewModel);
}
[HttpPost]
public ActionResult Create( CreatePartyViewModel oCreatePartyViewModel, FormCollection frm, HttpPostedFileBase files)
{
String fileName = "";
if (files != null)
{
fileName = Guid.NewGuid() + "_" + Path.GetFileName(files.FileName);
var path = Path.Combine(Server.MapPath("~/Logo/"), fileName);
files.SaveAs(path);
oCreatePartyViewModel._politicalParty.politicalPartyLogo = "http://electo.qendidate.com/Logo/" + fileName;
}
else
{
oCreatePartyViewModel._politicalParty.politicalPartyLogo = "http://electo.qendidate.com/Logo/" + "emptyLogo.jpg";
}
oCreatePartyViewModel._politicalParty.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oCreatePartyViewModel._politicalParty.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oCreatePartyViewModel._politicalParty.dataIsCreated = BaseUtil.GetCurrentDateTime();
oCreatePartyViewModel._politicalParty.dataIsUpdated = BaseUtil.GetCurrentDateTime();
oCreatePartyViewModel._politicalPartyAddress.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oCreatePartyViewModel._politicalPartyAddress.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
oCreatePartyViewModel._politicalPartyAddress.dataIsCreated = BaseUtil.GetCurrentDateTime();
oCreatePartyViewModel._politicalPartyAddress.dataIsUpdated = BaseUtil.GetCurrentDateTime();
int result = 0;
try
{
result = _PoliticalPartyService.createParty(oCreatePartyViewModel);
}
catch { }
if (result == 1)
{
TempData["msg"] = "New party created successfully";
return RedirectToAction("Index");
}
ViewBag.stateID = _stateService.getAllStates();
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
TempData["msg"] = "Data not saved";
return View(oCreatePartyViewModel);
}
public ActionResult GetDistrictbyState(int stateId)
{
var lstDistrict = _DistrictServices.getDistrictByStateID(stateId).Select(e => new { e.districtID, e.districtName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(lstDistrict);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult _partialMorePartyAddress(int politicalPartyID)
{
var MorePartyAddresList = _PoliticalPartyService.PoliticalPartyAddressList(politicalPartyID);
return PartialView("_partialMorePartyAddress", MorePartyAddresList);
}
public ActionResult _PartialNewAddress(int politicalPartyID)
{
ViewBag.stateID = _stateService.getAllStates();
ViewBag.politicalPartyID = politicalPartyID;
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
return PartialView("_PartialNewAddress");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult saveNewAddress(politicalPartyAddress opoliticalPartyAddress , FormCollection frm)
{
opoliticalPartyAddress.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
opoliticalPartyAddress.dataIsCreated = BaseUtil.GetCurrentDateTime();
opoliticalPartyAddress.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
opoliticalPartyAddress.dataIsUpdated = BaseUtil.GetCurrentDateTime();
opoliticalPartyAddress.isActive = true;
opoliticalPartyAddress.isDelete = false;
bool result = false;
if (ModelState.IsValid)
{
result = _PoliticalPartyService.saveNewAddress(opoliticalPartyAddress);
}
if (result)
{
TempData["msg"] = "New address saved";
}
else
{
TempData["msg"] = "Address not saved";
}
TempData["stateID"] = opoliticalPartyAddress.stateID;
ViewBag.stateID = _stateService.getAllStates();
ViewBag.politicalPartyID = opoliticalPartyAddress.politicalPartyID;
return RedirectToAction("Index");
}
}
}<file_sep>using electo.Models;
using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class SurveyResponseService : ISurveyResponseService
{
private readonly UnitOfWork uow;
public SurveyResponseService()
{
uow = new UnitOfWork();
}
#region HR Service Function
//20180313
//IEnumerable<sp_SurveyAnalysis_BySurveyId_Result> GetBySurveyId(long Id);
public IEnumerable<sp_SurveyAnalysis_BySurveyId_Result> GetBySurveyId(long Id)
{
var SurveyId = new SqlParameter("@SurveyId", Id);
var objAreaList = uow.sp_SurveyAnalysis_BySurveyId_Result_.SQLQuery<sp_SurveyAnalysis_BySurveyId_Result>("sp_SurveyAnalysis_BySurveyId @SurveyId", SurveyId);
if (objAreaList != null)
{
return objAreaList;
}
return null;
}
#endregion
public int submitResponse(IEnumerable<surveyRespons> _surveyResponse)
{
int result = 0;
//var surveyQuestionID = new SqlParameter("@surveyQuesID", _surveyResponse.surveyQuesID);
//var surveyQuestionResponseID = new SqlParameter("@SurveyQuestionOptionId", _surveyResponse.SurveyQuestionOptionId);
//var dataIsCreated_ = new SqlParameter("@dataIsCreated", _surveyResponse.dataIsCreated);
//var createdBy_ = new SqlParameter("@createdBy", _surveyResponse.createdBy);
try
{
foreach (var s in _surveyResponse)
{
s.dataIsCreated = BaseUtil.GetCurrentDateTime();
}
uow.submitResponse_.AddRange(_surveyResponse);
result = 1;
// result = uow.submitResponse_.SQLQuery<int>("submitSurveyResponse @surveyQuesID,@SurveyQuestionOptionId,@dataIsCreated,@createdBy", surveyQuestionID, surveyQuestionResponseID, dataIsCreated_, createdBy_).FirstOrDefault();
}
catch (Exception e){}
return result;
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
[CustomErrorHandling]
public class ElectionController : BaseClass
{
private readonly IElectionService _ElectionService;
public ElectionController()
{
_ElectionService = new ElectionService();
}
// GET: Election
public ActionResult Elections()
{
ViewBag.electionYear = new SelectList((_ElectionService.getAllYears().Select(e => new { e.yearID, e.Year })), "yearID", "Year");
ViewBag.ElectionType = new SelectList((_ElectionService.getElectionTypes().Select(e=> new { e.electionTypeID,e.electionTypeNAME})), "electionTypeID", "electionTypeNAME" );
return View();
}
public ActionResult _PartialElections(int ElectionType, int ddl_year, int ddl_month) {
var electionsList = _ElectionService.getElectionNameList(ElectionType, ddl_year, ddl_month);
return PartialView("_PartialElections", electionsList);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.monthId = _ElectionService.getAllMonthName().Select(e => new { e.monthId, e.monthName1 });
ViewBag.electionTypeID = _ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME });
ViewBag.electionYear = _ElectionService.getAllYears().Select(e => new { e.yearID, e.Year });
return View();
}
[HttpPost]
public ActionResult Create(electionName oelectionName, FormCollection frm)
{
int result = 0;
oelectionName.electionYear =Convert.ToInt32( frm["yearName"].ToString());
result = _ElectionService.create(oelectionName);
if (result == 1)
{
TempData["Result"] = "Success";
return RedirectToAction("Elections");
}
else
{
ViewBag.monthId = _ElectionService.getAllMonthName().Select(e => new { e.monthId, e.monthName1 });
ViewBag.electionTypeID = _ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME });
ViewBag.electionYear = _ElectionService.getAllYears().Select(e => new { e.yearID, e.Year });
TempData["Result"] = "unsuccess";
return View();
}
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class PollingBoothController : BaseClass
{
private readonly IVSCServices _VSCServices;
private readonly IstateService _stateService;
private readonly ILSCServices _LSCServices;
private readonly IElectionService _ElectionService;
private readonly IPollingBooth _PollingBooth;
private readonly IDistrictServices _DistrictServices;
private readonly IwardServices _WardServices;
private readonly IAreaService _AreaServices;
private readonly IPollingBooth _pollingBoothService;
public PollingBoothController()
{
_VSCServices = new VSCServices();
_stateService = new stateService();
_LSCServices = new LSCServices();
_ElectionService = new ElectionService();
_PollingBooth = new PollingBoothService();
_DistrictServices = new DistrictServices();
_WardServices = new wardServices();
_AreaServices = new AreaService();
_pollingBoothService = new PollingBoothService();
}
// GET: PollingBooth
public ActionResult Index()
{
ViewBag.ElectionType = new SelectList((_ElectionService.getElectionTypes().Select(e => new { e.electionTypeID, e.electionTypeNAME })), "electionTypeID", "electionTypeNAME");
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult _partialPoolingBoothList(int ElectionTypeId, int stateId,int ddl_Constituency)
{
IEnumerable<sp_pollingBoothList_Result> PoolingBoothList;
if (ElectionTypeId == 1)
{
PoolingBoothList = _PollingBooth.get_PollingBoothList(stateId, ddl_Constituency, 0 ,0);
}
else if (ElectionTypeId ==2)
{
PoolingBoothList = _PollingBooth.get_PollingBoothList(stateId, 0, ddl_Constituency,0);
}
else
{
PoolingBoothList = _PollingBooth.get_PollingBoothList(stateId, 0,0, ddl_Constituency);
}
return PartialView("_partialPoolingBoothLIst", PoolingBoothList);
}
public ActionResult getPollingBoothList(int wardID)
{
var pollingBoothList = _PollingBooth.get_PollingBoothList(0,0,0, wardID).Select(e => new { e.pollingBoothID, e.pollingBoothName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(pollingBoothList);
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.lokSabhaConstituencyID = _LSCServices.getAlllokSabhaConstituencyConstituency(1).Select(e => new { e.lokSabhaConstituencyID, e.lokSabhaConstituencyName });
ViewBag.vidhanSabhaConstituencyID = _VSCServices.getvidhanSabhaConstituencyByStateID(1).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
ViewBag.wardID = _WardServices.getZoneByStateIDAndMUncipalCorporationID(1, 1, 0,0).Select(e => new { e.wardID, e.wardName });
return View();
}
[HttpPost]
public ActionResult Create(pollingBooth _pollingBooth)
{
pollingBooth pollingBooth_ = new pollingBooth();
pollingBooth_.pollingBoothName = _pollingBooth.pollingBoothName;
pollingBooth_.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
pollingBooth_.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
pollingBooth_.lokSabhaConstituencyID = _pollingBooth.lokSabhaConstituencyID;
pollingBooth_.vidhanSabhaConstituencyID = _pollingBooth.vidhanSabhaConstituencyID;
pollingBooth_.wardID = _pollingBooth.wardID;
pollingBooth_.districtID = _pollingBooth.districtID;
pollingBooth_.stateID = _pollingBooth.stateID;
pollingBooth_.dataIsCreated = BaseUtil.GetCurrentDateTime();
pollingBooth_.dataIsUpdated = BaseUtil.GetCurrentDateTime();
pollingBooth_.isActive = true;
pollingBooth_.plotNo = _pollingBooth.plotNo;
pollingBooth_.streetNo = _pollingBooth.streetNo;
pollingBooth_.address1 = _pollingBooth.address1;
pollingBooth_.address2 = _pollingBooth.address2;
pollingBooth_.pincode = _pollingBooth.pincode;
int result = _pollingBoothService.createPollingBooth(pollingBooth_);
if (result == 1)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
else
{
TempData["Result"] = "unsuccess";
return View(pollingBooth_);
}
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace electo.Controllers
{
[CustomErrorHandling]
public class WardController : BaseClass
{
// GET: Ward
private readonly IwardServices wardConstituency_;
private readonly IstateService _stateService;
private readonly ImuncipalCorporationServices _muncipalCorporationServices;
private readonly IzoneServices _zoneServices;
private readonly IDistrictServices _DistrictServices;
private readonly IVSCServices VSCServices_;
public WardController()
{
wardConstituency_ = new wardServices();
_stateService = new stateService();
_muncipalCorporationServices = new muncipalCorporationServices();
_DistrictServices = new DistrictServices();
_zoneServices = new zoneServices();
VSCServices_ = new VSCServices();
}
public ActionResult Index()
{
ViewBag.States = new SelectList((_stateService.getAllStates().Select(e => new { e.stateID, e.stateName })), "stateID", "stateName");
return View();
}
public ActionResult _partialWardList(int stateId, int MPCorporation, int districtID)
{
var wardList = wardConstituency_.getZoneByStateIDAndMUncipalCorporationID(stateId, MPCorporation, districtID,0);
return PartialView("_partialWardList", wardList);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.municipalCorporationID = _muncipalCorporationServices.getmuncipalCorporationByStateID(1).Select(e => new { e.municipalCorporationID, e.municipalCorporationName1 });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
ViewBag.zoneID = _zoneServices.getZoneByStateIDAndMUncipalCorporationID(1,1).Select(e => new { e.zoneID, e.zoneName });
ViewBag.vidhanSabhaConstituencyID = VSCServices_.getvidhanSabhaConstituencyByStateID(1).Select(e => new { e.vidhanSabhaConstituencyID, e.vidhanSabhaConstituencyName });
return View();
}
[HttpPost]
public ActionResult Create(wardConstituency owardConstituency)
{
bool result = false;
owardConstituency.dataIsCreated = BaseUtil.GetCurrentDateTime();
owardConstituency.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
owardConstituency.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
owardConstituency.dataIsUpdated = BaseUtil.GetCurrentDateTime();
if (ModelState.IsValid)
{
result = wardConstituency_.CreateWardConstituency(owardConstituency);
}
if (result)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
ViewBag.stateID = _stateService.getAllStates().Select(e => new { e.stateID, e.stateName });
ViewBag.municipalCorporationID = _muncipalCorporationServices.getmuncipalCorporationByStateID(1).Select(e => new { e.municipalCorporationID, e.municipalCorporationName1 });
ViewBag.districtID = _DistrictServices.getDistrictByStateID(1).Select(e => new { e.districtID, e.districtName });
TempData["Result"] = "unsuccess";
return View(owardConstituency);
}
public ActionResult getWardByStateIDAndMUncipalCorporationID(int stateId, int MPCorporation, int districtID, int vidhanSabhaConstituencyID)
{
var DistrictList = wardConstituency_.getZoneByStateIDAndMUncipalCorporationID(stateId, MPCorporation, districtID, vidhanSabhaConstituencyID).Select(e => new { e.wardID, e.wardName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(DistrictList);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
public class QuestionsController : BaseClass
{
private readonly ISurveyQuestionServices _QuestionService;
private readonly IQuestionService _QuestionTypeService;
public QuestionsController()
{
_QuestionTypeService = new QuestionService();
_QuestionService = new SurveyQuestionServices();
}
// GET: Questions
public ActionResult Index(int surveyID)
{
ViewBag.surveyID = surveyID;
var QuestionList = _QuestionService.GetBySurveyId(surveyID);
return View(QuestionList);
}
[HttpGet]
public ActionResult Create(int surveyID)
{
ViewBag.surveyID = surveyID;
ViewBag.questionTypeID = _QuestionTypeService.GetQuestionTypeList().Select(e => new { e.questionTypeID, e.questionType1 });
return View();
}
[HttpPost]
public ActionResult Create(surveyQuestionViewModel osurveyQuestion)
{
int result=0;
result = _QuestionService.CreateSurveyQuestion(osurveyQuestion);
if (result == 1)
{
TempData["Creation"] = "Success";
return RedirectToAction("Index", new { surveyID = osurveyQuestion.surveyID});
}
else {
ViewBag.surveyID = osurveyQuestion.surveyID;
ViewBag.questionTypeID = _QuestionTypeService.GetQuestionTypeList().Select(e => new { e.questionTypeID, e.questionType1 });
TempData["Creation"] = "unsuccess";
return View(osurveyQuestion);
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.SP_Models
{
public class SurveyResponse
{
public long SurveyId { get; set; }
public long SurveyQuestionId { get; set; }
public string QuestionText { get; set; }
public List<QuestionOption> QuestionOptions { get; set; }
}
public class QuestionOption
{
public long SurveyQuestionOptionId { get; set; }
public string OptionText { get; set; }
public int? Total { get; set; }
public int? TotalResponse { get; set; }
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Data;
using System.Web.Mvc;
using System.Collections.Generic;
namespace electo.Models.Repositories
{
public class AccountServices : Controller, IAccountServices
{
private readonly UnitOfWork uow;
public AccountServices()
{
uow = new UnitOfWork();
}
public sp_LoginUser_Result UserLogin(String userID, string password)
{
var param_userID = new SqlParameter("@userID", userID);
var param_password = new SqlParameter("@password", BaseUtil.encrypt(password));
try
{
return uow.loginVolunteerRepository.SQLQuery<sp_LoginUser_Result>("sp_LoginUser @password,@userID", param_password, param_userID).FirstOrDefault();
}
catch { }
return null;
}
public sp_LoginUser_App_Result UserLoginApp(String userID, string password, int userTypeID)
{
var param_userID = new SqlParameter("@userID", userID);
var param_password = new SqlParameter("@password", <PASSWORD>);
var userTypeID_ = new SqlParameter("@userType", userTypeID);
try
{
return uow.loginVolunteerRepository.SQLQuery<sp_LoginUser_App_Result>("sp_LoginUser_App @password,@userID,@userType", param_password, param_userID,userTypeID_).FirstOrDefault();
}
catch (Exception e)
{
}
return null;
}
public string forgetpassword(string Email)
{
string result = string.Empty;
var emial = Email.ToString();
var emial1 = uow.loginVolunteer_.Find(e => e.userID == emial).Select(e => new { e.userID, e.loginID, e.fullName }).FirstOrDefault();
if (emial1 != null)
{
string newPassword = baseClass.GetRandomPasswordString(6);
int success = 0;
success = ResetPassword(newPassword, emial1.loginID);
if (success == 1)
{
//----------------------------use below code to send emailer------------------------------------------------------------
StreamReader sr = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("/emailers/ForgetPassword.html"));
string HTML_Body = sr.ReadToEnd();
string final_Html_Body = HTML_Body.Replace("#name", emial1.fullName).Replace("#password", newPassword);
sr.Close();
string To = emial1.userID.ToString();
string mail_Subject = "Password Changed";
result = BaseUtil.sendEmailer(To, mail_Subject, final_Html_Body, "");
//----------------------------end to send emailer------------------------------------------------------------
if (result == "ok")//if mail send
{
result = "success";
}
else
{
result = "failure ";
}
}
}
else
{
result = "user not found";
}
return result;
}
public int ResetPassword(string newPassword, long LoginID)
{
int result = 0;
var t = BaseUtil.encrypt(newPassword);
var LoginID_ = new SqlParameter("@loginID", LoginID);
var newPassword_ = new SqlParameter("@password", t);
result = uow.loginVolunteer_.SQLQuery<int>("sp_resetPassword @loginID, @password", LoginID_, newPassword_).FirstOrDefault();
if (result == 1)
{
result = 1;
}
return result;
}
public IEnumerable<politicalParty> getAll()
{
var politicalPartyList = uow.politicalParty_.GetAll().ToList();
return politicalPartyList;
}
public IEnumerable<userType> getAllUserTypes()
{
var userTypeList = uow.userType_.GetAll().ToList();
return userTypeList;
}
public IEnumerable< sp_getVoterDetailsByVoterID_Result> getDet(string voterIDNumber)
{
var voterIDNumber_ = new SqlParameter("@voterIDNumber", voterIDNumber);
try
{
var result = uow.sp_Campaigns_GetByWardId_.SQLQuery<sp_getVoterDetailsByVoterID_Result>("sp_getVoterDetailsByVoterID @voterIDNumber", voterIDNumber_).ToList();
return result;
}
catch { }
return null;
}
public string createUser(string _voterID, string _politicalPartyID, string _dataIsCreated, string _dataIsUpdated, string _createdBy
, string _modifiedBy, string _userID, string _mobile, string _fullName, bool _isActive, bool _isBlocked, string _AadharCardNumber, int userTypeid)
{
string returnResult = string.Empty;// User created and mail has been sent to user, User created, please recover your password,User not created, user already exists
int result = 0;
string _password = baseClass.GetRandomPasswordString(6);
string encriptedPwd = BaseUtil.encrypt(_password);
DateTime dt = Convert.ToDateTime(_dataIsCreated);
DateTime dt2 = Convert.ToDateTime(_dataIsUpdated);
var voterID_ = new SqlParameter("@voterID", _voterID);
var politicalPartyID_ = new SqlParameter("@politicalPartyID", _politicalPartyID);
var dataIsCreated_ = new SqlParameter("@dataIsCreated", dt);
var dataIsUpdated_ = new SqlParameter("@dataIsUpdated", dt2);
var createdBy_ = new SqlParameter("@createdBy", _createdBy);
var modifiedBy_ = new SqlParameter("@modifiedBy", _modifiedBy);
var userID_ = new SqlParameter("@userID", _userID);
var password_ = new SqlParameter("@password", <PASSWORD>);
var mobile_ = new SqlParameter("@mobile", _mobile);
var fullName_ = new SqlParameter("@fullName", _fullName);
var isActive_ = new SqlParameter("@isActive", _isActive);
var isBlocked_ = new SqlParameter("@isBlocked", _isBlocked);
var userPhoto_ = new SqlParameter("@userPhoto", "http://electo.qendidate.com/Logo/Emptyuser.jpg");
var AadharCardNumber_= new SqlParameter("@AadharCardNumber", _AadharCardNumber);
var userTypeid_ = new SqlParameter("@userTypeid", userTypeid);
try
{
result = uow.sp_CreateUser_.SQLQuery<int>("sp_CreateUser @voterID,@politicalPartyID,@dataIsCreated,@dataIsUpdated,@createdBy,@modifiedBy,@userID,@password,@mobile,@fullName,@isActive,@isBlocked, @AadharCardNumber,@userTypeid,@userPhoto",
voterID_, politicalPartyID_, dataIsCreated_, dataIsUpdated_, createdBy_, modifiedBy_, userID_, password_, mobile_, fullName_, isActive_, isBlocked_, AadharCardNumber_, userTypeid_, userPhoto_).FirstOrDefault();
if (result == 0)
{
returnResult = "User not created";
}
else if (result == 2)
{
returnResult = " User already exists";
}
else
{
//----------------------------use below code to send emailer------------------------------------------------------------
StreamReader sr = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("/emailers/NewVolunteerRegistrtion.html"));
string HTML_Body = sr.ReadToEnd();
string final_Html_Body = HTML_Body.Replace("#name", _fullName).Replace("#password", _password).Replace("#userID",_userID.ToString());
sr.Close();
string To = _userID.ToString();
string mail_Subject = "Thank you for registring in mulburry Application ";
returnResult = BaseUtil.sendEmailer(To, mail_Subject, final_Html_Body, "");
//----------------------------end to send emailer------------------------------------------------------------
if (returnResult == "ok")//if mail send
{
returnResult = "User created and mail has been sent to user";
}
else
{
returnResult = "User created, Please ask user to recover password ";
}
}
}
catch (Exception e)
{
}
return returnResult;
}
public int ActivateCreateCompaign(long volunteerID)
{
int result = 0;
var volunteerID_ = new SqlParameter("@volunteerID", volunteerID);
try
{
result = uow.sp_CreateUser_.SQLQuery<int>("sp_update_volunteerList @volunteerID", volunteerID_).FirstOrDefault();
}
catch (Exception e)
{
}
return result;
}
public int saveLogoutDetails(long loginID, DateTime currentDateTime)
{
int result = 0;
long? val = loginID;
var loginID_ = new SqlParameter("@loginID", null);
var currentDateTime_ = new SqlParameter("@loginID", null);
if (val != null)
{
loginID_ = new SqlParameter("@loginID", loginID);
}
if (currentDateTime != null)
{
currentDateTime_ = new SqlParameter("@logoutTime", currentDateTime);
}
try
{
uow.saveLogoutDetails_.SQLQuery<int>("sp_updateLastLoginTime @loginID,@logoutTime", loginID_, currentDateTime_);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
public IEnumerable<sp_getAllParties_NoParams_Result> getAllPoliticalParty()
{
var result = (dynamic)null;
try
{
result = uow.sp_getAllParties_NoParams_Result_.SQLQuery<sp_getAllParties_NoParams_Result>("sp_getAllParties_NoParams").ToList();
}
catch(Exception e)
{
}
return result;
}
public IEnumerable<sp_searchUserLoginStatus_Result> getUserLoginStatus(int userTypeID, string userID)
{
var userTypeID_ = new SqlParameter("@userTypeID", userTypeID);
var userID_ = new SqlParameter("@userID", userID);
var result = (dynamic)null;
try
{
result = uow.sp_getAllParties_NoParams_Result_.SQLQuery<sp_searchUserLoginStatus_Result>("sp_searchUserLoginStatus @userTypeID, @userID", userTypeID_, userID_).ToList();
}
catch (Exception e)
{
}
return result;
}
public loginVolunteer getUserDetails(long loginID)
{
var result = (dynamic)null;
try
{
result = uow.getUserDetails_.GetByID(loginID);
}
catch (Exception e)
{
}
return result;
}
public int saveUserDetails(loginVolunteer _loginVolunteer)
{
int result = 0;
try
{
uow.saveUserDetails_.Update(_loginVolunteer);
result = 1;
}
catch (Exception e)
{
result = 0;
}
return result;
}
public int updateUserLoginStatus(long loginID, long updateBy,bool isActive)
{
var loginID_ = new SqlParameter("@loginID", loginID);
var updateBy_ = new SqlParameter("@updateBy", updateBy);
var isActive_ = new SqlParameter("@isActive", isActive);
var dataIsUpdated_ = new SqlParameter("@dataIsUpdated", BaseUtil.GetCurrentDateTime());
var result = (dynamic)null;
try
{
result = uow.sp_getAllParties_NoParams_Result_.SQLQuery<int>("sp_updateUserLoginStatus @loginID, @updateBy,@isActive,@dataIsUpdated ", loginID_, updateBy_, isActive_, dataIsUpdated_).FirstOrDefault();
}
catch (Exception e)
{
}
return result;
}
}
}<file_sep>using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
[CustomErrorHandling]
public class StateController : BaseClass
{
private readonly IstateService _stateService;
public StateController()
{
_stateService = new stateService();
}
// GET: State
public ActionResult Index()
{
var stateList = _stateService.getAllStates();
return View(stateList);
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection frm)
{
int result = 0;
result= _stateService.create(frm["stateName"].ToString());
ViewBag.result = result;
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Models.BaseClass
{
public class BaseClass : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
String ControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToUpper();
String ActionName = filterContext.ActionDescriptor.ActionName.ToUpper();
String Action = string.Format("{0}Controller{1}", ControllerName, ActionName).ToUpper();
if (BaseUtil.ListControllerExcluded().Contains(ControllerName))
{
if ((ControllerName == "ACCOUNT" && (ActionName == "LOGIN" || ActionName == "LOGOUT" || ActionName == "FORGOTPASSWORD" || ActionName== "RESETPASSWORD"))
|| (ControllerName == "ENQUIRIES" && (ActionName =="CREATE"))
|| (ControllerName == "HOME" && (ActionName == "ACCESSDENIED")))
{
return;
}
if (BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()) == "")
{
filterContext.Result = null;
filterContext.Result = new RedirectResult("/Account/login");
return;
}
if (!BaseUtil.CheckAuthentication(filterContext))
{
filterContext.Result = null;
filterContext.Result = new RedirectResult("/Home/AccessDenied");
return;
}
return;
}
else
{
if (BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()) == "")
{
filterContext.Result = null;
filterContext.Result = new RedirectResult("/Account/login");
return;
}
if (!BaseUtil.CheckAuthentication(filterContext))
{
filterContext.Result = null;
filterContext.Result = new RedirectResult("/Home/AccessDenied");
return;
}
return;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IVSCServices
{
IEnumerable<vidhanSabhaConstituency> getAllvidhanSabhaConstituency();
IEnumerable<vidhanSabhaConstituency> getvidhanSabhaConstituencyByStateID(int stateID);
IEnumerable<sp_getVidhanSabhaLsit_Result> getvidhanSabhaConstituencyByStateIDANDLKSCID(int stateId, int LSCID, string VSC_NAME);
bool CreateVidhanSabha(vidhanSabhaConstituency ovidhanSabhaConstituency);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using electo.Models.IRepositories;
using static electo.Models.SP_Models.StoredProcedureModels;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace electo.Models.Repositories
{
public class NewsServices :INewsServices
{
private readonly UnitOfWork uow;
public NewsServices()
{
uow = new UnitOfWork();
}
public void createNews(news news)
{
uow.createNews_.Add(news);
}
public IEnumerable<sp_GetLatestNews_Result> getNews()
{
var result = uow.getNews_.SQLQuery<sp_GetLatestNews_Result>("sp_GetLatestNews");
return result;
}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class QuestionService: IQuestionService
{
private readonly UnitOfWork uow;
public QuestionService()
{
uow = new UnitOfWork();
}
public IEnumerable<questionType> GetQuestionTypeList() {
var QuestionTypeList_ = uow.questionType_.Find(e => e.isActve).ToList();
return QuestionTypeList_;
}
public bool addNewQuestionType(questionType OquestionType)
{
bool result = false;
try
{
uow.questionType_.Add(OquestionType);
result = true;
}
catch (Exception e)
{
result = false;
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using static electo.Models.SP_Models.StoredProcedureModels;
using electo.Models;
using electo.Models.Repositories;
using electo.Models.IRepositories;
namespace electo.Controllers
{
[CustomErrorHandling]
public class EnquiriesController : Controller
{
private readonly IEnquiryServices _enquiryServices;
// GET: Enquiries
public EnquiriesController()
{
_enquiryServices = new EnquiryServices();
}
public ActionResult Enquiries()
{
ViewBag.EnquiryType = new SelectList((_enquiryServices.getEnquiryTypes().Select(e => new { e.enquiryTypeID, e.enquiryTypeName })), "enquiryTypeID", "enquiryTypeName");
return View();
}
public ActionResult _partialEnquiriesList(string enquirytype, string date, string mobile, bool isTaskCompleted)
{
return PartialView("_partialEnquiriesList",_enquiryServices.GetNewEnquiries_Result(enquirytype, date, mobile, isTaskCompleted));
}
[HttpGet]
public ActionResult _partialEditEnquiry(long eID)
{
//_enquiryServices.get(eID);
return PartialView("_partialEditEnquiry", _enquiryServices.get(eID));
}
[HttpPost]
public ActionResult _partialEditEnquiry(enquiry _enq)
{
_enquiryServices._save(_enq);
TempData["Result"] = "Success";
return RedirectToAction("Enquiries", "Enquiries");
}
[HttpGet]
public ActionResult Create()
{
ViewBag.electionTypeID = _enquiryServices.getEnquiryTypes();
return View();
}
[HttpPost]
public ActionResult Create(enquiry _enq)
{
enquiry _objEnq = new enquiry();
_objEnq.dataIsCreated = BaseUtil.GetCurrentDateTime();
_objEnq.dataIsUpdated = BaseUtil.GetCurrentDateTime();
_objEnq.email = _enq.email;
_objEnq.mobile = _enq.mobile;
_objEnq.enquirerName = _enq.enquirerName;
_objEnq.enquiryDescription = _enq.enquiryDescription;
_objEnq.enquiryTypeID = _enq.enquiryTypeID;
_objEnq.isTaskComplete = false;
_objEnq.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
if (ModelState.IsValid)
{
var result = _enquiryServices.create(_enq);
}
ViewBag.electionTypeID = _enquiryServices.getEnquiryTypes();
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using electo.Models;
using electo.Models.BaseClass;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System.IO;
namespace electo.Controllers
{
[CustomErrorHandling]
public class Biography_sController : BaseClass
{
private readonly IbiographyServices biographyServices_;
public Biography_sController()
{
biographyServices_ = new biographyServices();
}
// GET: Biography_s
public ActionResult Index()
{
return View();
}
public ActionResult _partialBiography(string Variable_)
{
var biographyList = biographyServices_.getListStartWith(Variable_);
return PartialView("_partialBiography", biographyList);
}
// GET: Biography_s/Create
public ActionResult Create()
{
return View();
}
// POST: Biography_s/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
public ActionResult Create(Biography_s biography_s, HttpPostedFileBase files)
{
String fileName = "";
if (files != null)
{
fileName = Guid.NewGuid() + "_" + Path.GetFileName(files.FileName);
var path = Path.Combine(Server.MapPath("~/Logo/"), fileName);
files.SaveAs(path);
biography_s.image = "http://electo.qendidate.com/Logo/" + fileName;
}
else
{
biography_s.image = "http://electo.qendidate.com/Logo/" + "Emptyuser.jpg";
}
int result = biographyServices_.createbiography(biography_s);
if (result == 1)
{
TempData["Result"] = "Success";
}
else {
TempData["Result"] = "Failure";
}
return View();
}
// GET: Biography_s/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var biography_s = biographyServices_.Find((int)id);
if (biography_s == null)
{
return HttpNotFound();
}
return View(biography_s);
}
// POST: Biography_s/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Biography_s biography_s, HttpPostedFileBase files)
{
String fileName = "";
if (files != null)
{
fileName = Guid.NewGuid() + "_" + Path.GetFileName(files.FileName);
var path = Path.Combine(Server.MapPath("~/Logo/"), fileName);
files.SaveAs(path);
biography_s.image = "http://electo.qendidate.com/Logo/" + fileName;
}
int result = biographyServices_.updatebiography(biography_s);
if (result == 1)
{
TempData["Result"] = "Success";
}
else
{
TempData["Result"] = "Failure";
}
return View(biography_s);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
namespace electo.WebServicesController
{
public class CampaignsController : ApiController
{
// private electoEntities db = new electoEntities();
private readonly ICampaignService _campaignService;
public CampaignsController()
{
_campaignService = new CampaignService();
}
/// <summary>
/// Get All Campaigns
/// </summary>
/// <returns></returns>
/// //IEnumerable<sp_Campaigns_GetAll_Result> GetAll();
//public HttpResponseMessage GetCampaigns()
//{
// var objCampaignList = _campaignService.GetAll();
// if (objCampaignList != null)
// {
// var campaignEntities = objCampaignList as List<sp_Campaigns_GetAll_Result> ?? objCampaignList.ToList();
// if (campaignEntities.Any())
// {
// return Request.CreateResponse(HttpStatusCode.OK, campaignEntities);
// }
// }
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Campaign data not found");
//}
public IHttpActionResult GetCampaigns()
{
var objCampaignList = _campaignService.GetAll();
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetAll_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
//return Request.CreateResponse(HttpStatusCode.OK, campaignEntities);
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Campaign data not found");
return Json(new { status = "Error", msg = "Record not found"});
}
/// <summary>
/// Get Campaigns By Id
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
/// //sp_Campaigns_GetById_Result GetById(long Id);
public IHttpActionResult GetCampaigns(long Id)
{
var objCampaign = _campaignService.GetById(Id);
if (objCampaign != null)
{
var campaignEntity = objCampaign as sp_Campaigns_GetById_Result ?? objCampaign;
if (campaignEntity != null)
{
return Json (new { status = "Success", msg = "Record found", data = campaignEntity });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
/// <summary>
/// Get Campaigns By ElectionTypeId
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
/// //IEnumerable<sp_Campaigns_GetByElectionTypeId_Result> GetByElectionTypeId(long Id);
public IHttpActionResult GetByElectionType(long Id)
{
var objCampaignList = _campaignService.GetByElectionTypeId(Id);
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetByElectionTypeId_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any()) {
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Campaigns_GetByElectionId_Result> GetByElectionId(long Id);
public IHttpActionResult GetByElection(long Id)
{
var objCampaignList = _campaignService.GetByElectionId(Id);
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetByElectionId_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Campaigns_GetByLokSabhaConstituencyId_Result> GetByLokSabhaConstituencyId(long Id);
public IHttpActionResult GetByLokSabhaConstituency(long Id)
{
var objCampaignList = _campaignService.GetByLokSabhaConstituencyId(Id);
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetByLokSabhaConstituencyId_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Campaigns_GetByPoliticalPartyId_Result> GetByPoliticalPartyId(long Id);
public IHttpActionResult GetByPoliticalParty(long Id)
{
var objCampaignList = _campaignService.GetByPoliticalPartyId(Id);
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetByPoliticalPartyId_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result> GetByVidhanSabhaConstituencyId(long Id);
public IHttpActionResult GetByVidhanSabhaConstituency(long Id)
{
var objCampaignList = _campaignService.GetByVidhanSabhaConstituencyId(Id);
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Campaigns_GetByVolunteerId_Result> GetByVolunteerId(long Id);
public IHttpActionResult GetByVolunteer(long Id)
{
var objCampaignList = _campaignService.GetByVolunteerId(Id);
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetByVolunteerId_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
//IEnumerable<sp_Campaigns_GetByWardId_Result> GetByWardId(long Id);
public IHttpActionResult GetByWard(long Id)
{
var objCampaignList = _campaignService.GetByWardId(Id);
if (objCampaignList != null)
{
var campaignEntities = objCampaignList as List<sp_Campaigns_GetByWardId_Result> ?? objCampaignList.ToList();
if (campaignEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = campaignEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
public IHttpActionResult GetSectionIncharge(long cmpID)
{
var sectionInchargeList = _campaignService.getAllSectionInchargeByCampaign(cmpID);
if (sectionInchargeList != null)
{
var sectionInchargeEntities = sectionInchargeList as List<sp_GetAllSectionInchargeByCampaign_Result> ?? sectionInchargeList.ToList();
if (sectionInchargeEntities.Any())
{
return Json(new { status = "Success", msg = "Record found", data = sectionInchargeEntities });
}
}
return Json(new { status = "Error", msg = "Record not found" });
}
//// GET: api/Campaigns
//public IQueryable<campaign> Getcampaigns()
//{
// return db.campaigns;
//}
//// GET: api/Campaigns/5
//[ResponseType(typeof(campaign))]
//public IHttpActionResult Getcampaign(long id)
//{
// campaign campaign = db.campaigns.Find(id);
// if (campaign == null)
// {
// return NotFound();
// }
// return Ok(campaign);
//}
//// PUT: api/Campaigns/5
//[ResponseType(typeof(void))]
//public IHttpActionResult Putcampaign(long id, campaign campaign)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// if (id != campaign.campaignID)
// {
// return BadRequest();
// }
// db.Entry(campaign).State = EntityState.Modified;
// try
// {
// db.SaveChanges();
// }
// catch (DbUpdateConcurrencyException)
// {
// if (!campaignExists(id))
// {
// return NotFound();
// }
// else
// {
// throw;
// }
// }
// return StatusCode(HttpStatusCode.NoContent);
//}
//// POST: api/Campaigns
//[ResponseType(typeof(campaign))]
//public IHttpActionResult Postcampaign(campaign campaign)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// db.campaigns.Add(campaign);
// db.SaveChanges();
// return CreatedAtRoute("DefaultApi", new { id = campaign.campaignID }, campaign);
//}
//// DELETE: api/Campaigns/5
//[ResponseType(typeof(campaign))]
//public IHttpActionResult Deletecampaign(long id)
//{
// campaign campaign = db.campaigns.Find(id);
// if (campaign == null)
// {
// return NotFound();
// }
// db.campaigns.Remove(campaign);
// db.SaveChanges();
// return Ok(campaign);
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
//db.Dispose();
}
base.Dispose(disposing);
}
//private bool campaignExists(long id)
//{
// return db.campaigns.Count(e => e.campaignID == id) > 0;
//}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class muncipalCorporationServices: ImuncipalCorporationServices
{
private readonly UnitOfWork uow;
public muncipalCorporationServices()
{
uow = new UnitOfWork();
}
public IEnumerable<municipalCorporationName> getmuncipalCorporationByStateID(int stateID)
{
var _municipalCorporationName = uow.municipalCorporationName_.Find(e => e.stateID == stateID).ToList();
return _municipalCorporationName;
}
public int create(municipalCorporationName omunicipalCorporationName)
{
int result = 0;
omunicipalCorporationName.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
omunicipalCorporationName.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
omunicipalCorporationName.dataIsCreated = BaseUtil.GetCurrentDateTime();
omunicipalCorporationName.datatIsUpdated = BaseUtil.GetCurrentDateTime();
omunicipalCorporationName.isActive = true;
try
{
uow.municipalCorporationName_.Add(omunicipalCorporationName);
result = 1;
}
catch { }
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
namespace electo.WebServicesController
{
public class PageInchargeCommentsController : ApiController
{
//private electoEntities db = new electoEntities();
private readonly IPageInchargeComment _pageInchargeComment;
public PageInchargeCommentsController()
{
_pageInchargeComment = new PageInchargeComment();
}
//20180312
//IEnumerable<sp_PageInchargeComments_ByCampaignId_Result> GetByCampaignId(long Id);
public IHttpActionResult GetByCampaign(long BoothInchargeId, long CampaignId)
{
var objPageInchargeCommentList = _pageInchargeComment.GetByCampaignId(BoothInchargeId, CampaignId);
if (objPageInchargeCommentList != null)
{
var pageInchargeCommentEntities = objPageInchargeCommentList as List<sp_PageInchargeComments_ByCampaignId_Result> ?? objPageInchargeCommentList.ToList();
if (pageInchargeCommentEntities.Any())
{
// return Request.CreateResponse(HttpStatusCode.OK, pageInchargeCommentEntities);
return Json(new { status = "Success", msg = "Record found", data = pageInchargeCommentEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Page Incharge Comment data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//// GET: api/PageInchargeComments
//public IQueryable<pageInchargeComment> GetpageInchargeComments()
//{
// return db.pageInchargeComments;
//}
//// GET: api/PageInchargeComments/5
//[ResponseType(typeof(pageInchargeComment))]
//public IHttpActionResult GetpageInchargeComment(long id)
//{
// pageInchargeComment pageInchargeComment = db.pageInchargeComments.Find(id);
// if (pageInchargeComment == null)
// {
// return NotFound();
// }
// return Ok(pageInchargeComment);
//}
//// PUT: api/PageInchargeComments/5
//[ResponseType(typeof(void))]
//public IHttpActionResult PutpageInchargeComment(long id, pageInchargeComment pageInchargeComment)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// if (id != pageInchargeComment.commentID)
// {
// return BadRequest();
// }
// db.Entry(pageInchargeComment).State = EntityState.Modified;
// try
// {
// db.SaveChanges();
// }
// catch (DbUpdateConcurrencyException)
// {
// if (!pageInchargeCommentExists(id))
// {
// return NotFound();
// }
// else
// {
// throw;
// }
// }
// return StatusCode(HttpStatusCode.NoContent);
//}
//// POST: api/PageInchargeComments
//[ResponseType(typeof(pageInchargeComment))]
//public IHttpActionResult PostpageInchargeComment(pageInchargeComment pageInchargeComment)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// db.pageInchargeComments.Add(pageInchargeComment);
// try
// {
// db.SaveChanges();
// }
// catch (DbUpdateException)
// {
// if (pageInchargeCommentExists(pageInchargeComment.commentID))
// {
// return Conflict();
// }
// else
// {
// throw;
// }
// }
// return CreatedAtRoute("DefaultApi", new { id = pageInchargeComment.commentID }, pageInchargeComment);
//}
//// DELETE: api/PageInchargeComments/5
//[ResponseType(typeof(pageInchargeComment))]
//public IHttpActionResult DeletepageInchargeComment(long id)
//{
// pageInchargeComment pageInchargeComment = db.pageInchargeComments.Find(id);
// if (pageInchargeComment == null)
// {
// return NotFound();
// }
// db.pageInchargeComments.Remove(pageInchargeComment);
// db.SaveChanges();
// return Ok(pageInchargeComment);
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
//db.Dispose();
}
base.Dispose(disposing);
}
//private bool pageInchargeCommentExists(long id)
//{
// return db.pageInchargeComments.Count(e => e.commentID == id) > 0;
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IPollingBooth
{
IEnumerable<sp_pollingBoothList_Result> get_PollingBoothList(int stateId, int LSCID, int VSCID, int wardID);
int createPollingBooth(pollingBooth pollingBooth_);
IEnumerable<sp_getPoolingBoothByCampignID_Result> get_PollingBoothListByCampaignID(Int64 CampaignID);
int AssignPollingBoothToAssignPollingBoothIncharge(AssignPollingBoothToPollingBoothIncharge oAssignPollingBoothToPollingBoothIncharge);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface INewsServices
{
void createNews(news news);
IEnumerable<sp_GetLatestNews_Result> getNews();
}
}
<file_sep>using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace electo.WebServices
{
public class WebServicesController<TEntity>: ApiController where TEntity: class
{
public electoEntities Context= new electoEntities();
protected Models.Repositories.Repositories<TEntity> repo = new Models.Repositories.Repositories<TEntity>();
public electoEntities electoEntities
{
get { return Context as electoEntities; }
}
//[ResponseType(typeof(TEntity))]
public IEnumerable<TEntity> Get()
{
var c = repo.GetAll();
return c;
}
// GET api/values/5
// [ResponseType(typeof(loginVolunteer))]
public IHttpActionResult Get(long id)
{
return Ok("o");
}
//// POST api/values
//[ResponseType(typeof(App_status))]
//public IHttpActionResult Post([FromBody]App_status ochild1)
//{
// return CreatedAtRoute("DefaultApi", new { id = ochild1.App_status_id }, ochild1);
//}
//// PUT api/values/5
//[ResponseType(typeof(void))]
//public IHttpActionResult Put(int id, App_status value)
//{
// return StatusCode(HttpStatusCode.NoContent);
//}
//// DELETE api/values/5
//[ResponseType(typeof(App_status))]
//public IHttpActionResult Delete(int id)
//{
// App_status ochild1 = new App_status();
// return Ok(ochild1);
//}
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class wardServices: IwardServices
{
private readonly UnitOfWork uow;
public wardServices()
{
uow = new UnitOfWork();
}
public IEnumerable<sp_getWardByStateIDAndMUncipalCorporationID_Result> getZoneByStateIDAndMUncipalCorporationID(int stateId, int MPCorporation, int districtID, int vidhanSabhaConstituencyID)
{
var MPCorporation_ = new SqlParameter("@MPCorporation", MPCorporation);
var stateId_ = new SqlParameter("@stateId", stateId);
var districtID_ = new SqlParameter("@distictID", districtID);
var vidhanSabhaConstituencyID_ = new SqlParameter("@vidhanSabhaConstituencyID", vidhanSabhaConstituencyID);
var _wardList = uow.wardConstituency_.SQLQuery<sp_getWardByStateIDAndMUncipalCorporationID_Result>("sp_getWardByStateIDAndMUncipalCorporationID @stateId,@MPCorporation,@distictID, @vidhanSabhaConstituencyID", stateId_, MPCorporation_, districtID_, vidhanSabhaConstituencyID_).ToList();
return _wardList;
}
public bool CreateWardConstituency(wardConstituency owardConstituency)
{
bool result = false;
try
{
uow.wardConstituency_.Add(owardConstituency);
result = true; ;
}
catch (Exception e)
{
result = false;
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
namespace electo.WebServicesController
{
public class SurveyQuestionsController : ApiController
{
//private electoEntities db = new electoEntities();
private readonly ISurveyQuestionServices _surveyQuestionServices;
public SurveyQuestionsController()
{
_surveyQuestionServices = new SurveyQuestionServices();
}
//public IEnumerable<sp_SurveyQuestion_GetBySurveyId_Result> GetBySurveyId(long Id)
public IHttpActionResult GetBySurvey(long Id)
{
var objSurveryQuestionList = _surveyQuestionServices.GetBySurveyId(Id);
if (objSurveryQuestionList != null)
{
var surveyQuestionEntities = objSurveryQuestionList as List<sp_SurveyQuestion_GetBySurveyId_Result> ?? objSurveryQuestionList.ToList();
if (surveyQuestionEntities.Any())
{
// return Request.CreateResponse(HttpStatusCode.OK, surveyQuestionEntities);
return Json(new { status = "Success", msg = "Record found", data = surveyQuestionEntities });
}
}
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Survey Question data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//// GET: api/SurveyQuestions
//public IQueryable<surveyQuestion> GetsurveyQuestions()
//{
// return db.surveyQuestions;
//}
//// GET: api/SurveyQuestions/5
//[ResponseType(typeof(surveyQuestion))]
//public IHttpActionResult GetsurveyQuestion(long id)
//{
// surveyQuestion surveyQuestion = db.surveyQuestions.Find(id);
// if (surveyQuestion == null)
// {
// return NotFound();
// }
// return Ok(surveyQuestion);
//}
//// PUT: api/SurveyQuestions/5
//[ResponseType(typeof(void))]
//public IHttpActionResult PutsurveyQuestion(long id, surveyQuestion surveyQuestion)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// if (id != surveyQuestion.surveyQuesID)
// {
// return BadRequest();
// }
// db.Entry(surveyQuestion).State = EntityState.Modified;
// try
// {
// db.SaveChanges();
// }
// catch (DbUpdateConcurrencyException)
// {
// if (!surveyQuestionExists(id))
// {
// return NotFound();
// }
// else
// {
// throw;
// }
// }
// return StatusCode(HttpStatusCode.NoContent);
//}
//// POST: api/SurveyQuestions
//[ResponseType(typeof(surveyQuestion))]
//public IHttpActionResult PostsurveyQuestion(surveyQuestion surveyQuestion)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// db.surveyQuestions.Add(surveyQuestion);
// db.SaveChanges();
// return CreatedAtRoute("DefaultApi", new { id = surveyQuestion.surveyQuesID }, surveyQuestion);
//}
//// DELETE: api/SurveyQuestions/5
//[ResponseType(typeof(surveyQuestion))]
//public IHttpActionResult DeletesurveyQuestion(long id)
//{
// surveyQuestion surveyQuestion = db.surveyQuestions.Find(id);
// if (surveyQuestion == null)
// {
// return NotFound();
// }
// db.surveyQuestions.Remove(surveyQuestion);
// db.SaveChanges();
// return Ok(surveyQuestion);
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// db.Dispose();
}
base.Dispose(disposing);
}
//private bool surveyQuestionExists(long id)
//{
// return db.surveyQuestions.Count(e => e.surveyQuesID == id) > 0;
//}
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class SurveyServices :ISurveyServices
{
private readonly UnitOfWork uow;
public SurveyServices()
{
uow = new UnitOfWork();
}
#region HR Service Function
public IEnumerable<sp_Survey_GetAll_Result> GetAll()
{
var objSurveyList = uow.sp_Survey_GetAll_Result_.SQLQuery<sp_Survey_GetAll_Result>("sp_Survey_GetAll").ToList();
if (objSurveyList != null)
{
return objSurveyList;
}
return null;
}
public IEnumerable<sp_Survey_GetByCampaignId_Result> GetByCampaignId(long Id)
{
var CampaignId = new SqlParameter("@CampaignId", Id);
var objSurveyList = uow.sp_Survey_GetByCampaignId_Result_.SQLQuery<sp_Survey_GetByCampaignId_Result>("sp_Survey_GetByCampaignId @CampaignId", CampaignId).ToList();
if (objSurveyList != null)
{
return objSurveyList;
}
return null;
}
#endregion
public int create(survey osurvey)
{
int result = 0;
osurvey.createdBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
osurvey.modifiedBy = Convert.ToInt16(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()));
osurvey.dataIsCreated = BaseUtil.GetCurrentDateTime();
osurvey.dataIsUpdated = BaseUtil.GetCurrentDateTime();
osurvey.isDelete = false;
try
{
uow.survey_.Add(osurvey);
result = 1;
}
catch { }
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.IRepositories
{
interface IvoterListService
{
int createNewVoter(voterList ovoterList_Copy);
IEnumerable<sp_GetAllDataEntryOperators_Result> getAllDataEntryOperators();
IEnumerable<sp_GetVoters_List_Result> getVoters(string voterID, string date, string userID);
voterList getVoterByID(long voterID);
int UpdateVoter(voterList ovoterList_Copy);
}
}
<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class VSCServices : IVSCServices
{
private readonly UnitOfWork uow;
public VSCServices()
{
uow = new UnitOfWork();
}
public IEnumerable<vidhanSabhaConstituency> getAllvidhanSabhaConstituency()
{
var _vidhanSabhaConstituencyList = uow.VidhanSabhaConsistuency_.GetAll().ToList();
return _vidhanSabhaConstituencyList;
}
public IEnumerable<vidhanSabhaConstituency> getvidhanSabhaConstituencyByStateID(int stateID)
{
var _vidhanSabhaConstituencyList = uow.VidhanSabhaConsistuency_.Find(e=>e.stateID== stateID).ToList();
return _vidhanSabhaConstituencyList;
}
public IEnumerable<sp_getVidhanSabhaLsit_Result> getvidhanSabhaConstituencyByStateIDANDLKSCID(int stateId, int LSCID, string VSC_NAME)
{
var LSCID_ = new SqlParameter("@lokSabhaId", LSCID);
var stateId_ = new SqlParameter("@stateId", stateId);
var VSC_NAME_ = new SqlParameter("@vidhanSabhaName", VSC_NAME);
var _vidhanSabhaConstituencyList = uow.sp_getVidhanSabhaLsit_Result_.SQLQuery<sp_getVidhanSabhaLsit_Result>("sp_getVidhanSabhaLsit @stateId,@lokSabhaId, @vidhanSabhaName", stateId_, LSCID_, VSC_NAME_).ToList();
return _vidhanSabhaConstituencyList;
}
public bool CreateVidhanSabha(vidhanSabhaConstituency ovidhanSabhaConstituency)
{
bool result= false;
try
{
uow.VidhanSabhaConsistuency_.Add(ovidhanSabhaConstituency);
result = true; ;
}
catch (Exception e)
{
result = false;
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static electo.Models.SP_Models.StoredProcedureModels;
namespace electo.Models.IRepositories
{
interface ISurveyServices
{
#region HR IService Function
IEnumerable<sp_Survey_GetAll_Result> GetAll();
IEnumerable<sp_Survey_GetByCampaignId_Result> GetByCampaignId(long Id);
#endregion
int create(survey osurvey);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Models
{
public class ViewModel
{
}
public class CreatePartyViewModel
{
public politicalParty _politicalParty { get; set; }
public politicalPartyAddress _politicalPartyAddress { get; set; }
}
public class CreateVolunteerLogin
{
[Display(Name = "Political Party")]
[Required(ErrorMessage = "Political party name required ")]
public int politicalPartyID { get; set; }
[StringLength(13, ErrorMessage = "13 digit max")]
[Required(ErrorMessage = "Telephone/Mobile required ")]
[Display(Name = "Telephone/Mobile")]
public string mobile { get; set; }
[Display(Name = "Full Name")]
[Required(ErrorMessage = "Full Name required ")]
public string fullName { get; set; }
[Required(ErrorMessage = "Volunteer email id required")]
[EmailAddress]
[Display(Name = "Email id")]
public string userID { get; set; }
public string voterID { get; set; }
public bool isActive { get; set; }
public bool isBlocked { get; set; }
[StringLength(16, MinimumLength = 16, ErrorMessage = "16 digit max")]
[Required(ErrorMessage = "AAdhar No required")]
[Display(Name = "AAdhar No")]
public string AadharCardNumber { get; set; }
public Int64 createdBy { get; set; }
[Required(ErrorMessage = "User type required")]
[Display(Name = "User type")]
public int userTypeID { get; set; }
}
[MetadataType(typeof(politicalPartyViewModel))]
public partial class politicalParty
{
}
public class politicalPartyViewModel
{
[StringLength(200, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "Party name required")]
[Display(Name = "Party name")]
public string politicalPartyName { get; set; }
[Display(Name = "Party website url")]
[Required(ErrorMessage = "Official website address required")]
public string politicalPartyWebsiteUrl { get; set; }
[Required(ErrorMessage = "Party official email id required")]
[EmailAddress]
[Display(Name = "Email id")]
public string politicalPartyEmail { get; set; }
}
[MetadataType(typeof(loginVolunteerViewModel))]
public partial class loginVolunteer
{
}
public class loginVolunteerViewModel
{
[StringLength(13, MinimumLength = 10, ErrorMessage = "13 digit max")]
[Required(ErrorMessage = "Telephone/Mobile required ")]
[Display(Name = "Telephone/Mobile")]
public string mobile { get; set; }
[StringLength(16, MinimumLength = 16, ErrorMessage = "16 digit max")]
[Required(ErrorMessage = "AAdhar No required")]
[Display(Name = "AAdhar No")]
public string voterAadharNumber { get; set; }
[Display(Name = "Full Name")]
[Required(ErrorMessage = "Full Name required ")]
public string fullName { get; set; }
}
[MetadataType(typeof(politicalPartyAddressViewModel))]
public partial class politicalPartyAddress
{
}
public class politicalPartyAddressViewModel
{
[Required(ErrorMessage = "District is Required ")]
[Display(Name = "District")]
public int districtID { get; set; }
[Required(ErrorMessage = "State is Required ")]
[Display(Name = "State")]
public int stateID { get; set; }
[Display(Name = "Plot number")]
public string plotNo { get; set; }
[Display(Name = "Street number")]
public string streetNo { get; set; }
[Display(Name = "Address1")]
public string address1 { get; set; }
[Display(Name = "Address2")]
public string address2 { get; set; }
[Display(Name = "Pin code")]
[Required(ErrorMessage = "Pin code required ")]
public int pincode { get; set; }
[StringLength(13, ErrorMessage = "13 digit max")]
[Required(ErrorMessage = "Telephone/Mobile required ")]
[Display(Name = "Telephone/Mobile")]
public string telephone { get; set; }
}
[MetadataType(typeof(questionTypeViewModel))]
public partial class questionType
{
}
public class questionTypeViewModel
{
[Display(Name = "Question Type")]
[Required(ErrorMessage = "Question Type required ")]
public string questionType1 { get; set; }
[Display(Name = "Date")]
public System.DateTime dataIsCreated { get; set; }
[Display(Name = "Active")]
public bool isActve { get; set; }
}
[MetadataType(typeof(eventTypeViewModel))]
public partial class eventType
{
}
public class eventTypeViewModel
{
[Display(Name = "Event Type")]
[Required(ErrorMessage = "Event Name required ")]
public string eventName { get; set; }
[Display(Name = "Date")]
public System.DateTime dataIsCreated { get; set; }
[Display(Name = "Active")]
public bool isActive { get; set; }
}
[MetadataType(typeof(areaNameViewModel))]
public partial class areaName
{
}
public class areaNameViewModel
{
[Display(Name = "Area Name")]
[Required(ErrorMessage = "Area Name required ")]
public string areaName1 { get; set; }
[Display(Name = "Vidhan Sabha ")]
[Required(ErrorMessage = "Vidhan Sabha Required")]
public int vidhanSabhaConstituencyID { get; set; }
[Display(Name = "Lok Sabha ")]
[Required(ErrorMessage = "Lok Sabha Required")]
public int lokSabhaConstituencyID { get; set; }
[Display(Name = "Ward")]
[Required(ErrorMessage = "Ward Required")]
public int wardID { get; set; }
[Display(Name = "District")]
[Required(ErrorMessage = "District Required")]
public int districtID { get; set; }
[Display(Name = "State")]
[Required(ErrorMessage = "State Required")]
public int stateID { get; set; }
[Display(Name = "Polling Booth")]
[Required(ErrorMessage = "Polling Booth Required")]
public int pollingBoothID { get; set; }
}
[MetadataType(typeof(pollingBoothViewModel))]
public partial class pollingBooth
{
}
public class pollingBoothViewModel
{
[Display(Name = "Polling Booth Name")]
[Required(ErrorMessage = "Polling Booth Required")]
public string pollingBoothName { get; set; }
[Display(Name = "<NAME> ")]
[Required(ErrorMessage = "Vidhan Sabha Required")]
public int vidhanSabhaConstituencyID { get; set; }
[Display(Name = "Lok Sabha ")]
[Required(ErrorMessage = "Lok Sabha Required")]
public int lokSabhaConstituencyID { get; set; }
[Display(Name = "Ward")]
[Required(ErrorMessage = "Ward Required")]
public int wardID { get; set; }
[Display(Name = "District")]
[Required(ErrorMessage = "District Required")]
public int districtID { get; set; }
[Display(Name = "State")]
[Required(ErrorMessage = "State Required")]
public int stateID { get; set; }
[Display(Name = "Plot No")]
[Required(ErrorMessage = "Plot Number Required")]
public string plotNo { get; set; }
[Display(Name = "Street Number")]
[Required(ErrorMessage = "Street Number Required")]
public string streetNo { get; set; }
[Display(Name = "Address 1 ")]
[Required(ErrorMessage = "Address Line 1 Required")]
public string address1 { get; set; }
[Display(Name = "Address 2 ")]
[Required(ErrorMessage = "Address Line 2 Required")]
public string address2 { get; set; }
[Display(Name = "Pin code ")]
[Required(ErrorMessage = "Pincode Required")]
public int pincode { get; set; }
}
[MetadataType(typeof(campaignPriceViewModel))]
public partial class campaignPrice
{
}
public class campaignPriceViewModel
{
public int campaignPriceID { get; set; }
[Display(Name = "Election Type")]
[Required(ErrorMessage = "Election Type required ")]
public int electionTypeID { get; set; }
[Display(Name = "Year")]
[Required(ErrorMessage = "Election year required ")]
public string year { get; set; }
[Display(Name = "Price")]
[Required(ErrorMessage = "price required ")]
public int price { get; set; }
[Display(Name = "Active")]
public bool isActive { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[System.Web.Mvc.Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginIdViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
[MetadataType(typeof(vidhanSabhaConstituencyViewModel))]
public partial class vidhanSabhaConstituency { }
public class vidhanSabhaConstituencyViewModel
{
[Required(ErrorMessage = "Lock Sabha required")]
[Display(Name = "Lock Sabha")]
public int lokSabhaConstituencyID { get; set; }
[Required(ErrorMessage = "Vidhan Sabha required")]
[Display(Name = "Vidhan Sabha Name")]
public string vidhanSabhaConstituencyName { get; set; }
[Required(ErrorMessage = "State required")]
[Display(Name = "State")]
public int stateID { get; set; }
[Required(ErrorMessage = "District required")]
[Display(Name = "District")]
public int districtID { get; set; }
}
[MetadataType(typeof(stateViewModel))]
public partial class state
{
}
public class stateViewModel
{
[StringLength(120, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "State name required")]
[Display(Name = "State")]
public string stateName { get; set; }
}
[MetadataType(typeof(districtViewModel))]
public partial class district
{
}
public class districtViewModel
{
[Required(ErrorMessage = "State name required")]
[Display(Name = "State")]
public int stateID { get; set; }
[StringLength(120, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "District name required")]
[Display(Name = "District")]
public string districtName { get; set; }
}
[MetadataType(typeof(lokSabhaConstituencyViewModel))]
public partial class lokSabhaConstituency
{
}
public class lokSabhaConstituencyViewModel
{
[Required(ErrorMessage = "state field required")]
[Display(Name = "State")]
public int stateID { get; set; }
[Required(ErrorMessage = "District field required")]
[Display(Name = "District")]
public string districtID { get; set; }
[StringLength(120, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "Loksabha name required")]
[Display(Name = "Lok Sabha Constituency Name")]
public string lokSabhaConstituencyName { get; set; }
}
[MetadataType(typeof(electionNameViewModel))]
public partial class electionName
{
}
public class electionNameViewModel
{
[Required(ErrorMessage = "Election Year required")]
[Display(Name = "Election Year")]
public int electionYear { get; set; }
[Required(ErrorMessage = "Election Type field required")]
[Display(Name = "Election Type")]
public string electionTypeID { get; set; }
[StringLength(120, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "Election name required")]
[Display(Name = "Election Name")]
public string electionName1 { get; set; }
[Required(ErrorMessage = "Election Month required")]
[Display(Name = "Month")]
public int monthId { get; set; }
}
[MetadataType(typeof(municipalCorporationNameViewModel))]
public partial class municipalCorporationName
{ }
public class municipalCorporationNameViewModel
{
[StringLength(120, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "Election required")]
[Display(Name = "Municipal Corp. Name")]
public string municipalCorporationName1 { get; set; }
[Required(ErrorMessage = "District required")]
[Display(Name = "District")]
public int districtID { get; set; }
[Required(ErrorMessage = "State required")]
[Display(Name = "State")]
public int stateID { get; set; }
}
[MetadataType(typeof(zoneMunicipalityViewModel))]
public partial class zoneMunicipality { }
public class zoneMunicipalityViewModel
{
[StringLength(120, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "Zone name required")]
[Display(Name = "Zone Name")]
public string zoneName { get; set; }
[Required(ErrorMessage = "Election name required")]
[Display(Name = "Municipal Corporation")]
public int municipalCorporationID { get; set; }
[Required(ErrorMessage = "State field required")]
[Display(Name = "State")]
public int stateID { get; set; }
[Required(ErrorMessage = "District field required")]
[Display(Name = "District")]
public int districtID { get; set; }
}
[MetadataType(typeof(wardConstituencyViewModel))]
public partial class wardConstituency { }
public class wardConstituencyViewModel
{
[Required(ErrorMessage = "Election name required")]
[Display(Name = "Municipal Corporation")]
public int municipalCorporationID { get; set; }
[Required(ErrorMessage = "State required")]
[Display(Name = "State")]
public int stateID { get; set; }
[Required(ErrorMessage = "District required")]
[Display(Name = "District")]
public int districtID { get; set; }
[Required(ErrorMessage = "Zone required")]
[Display(Name = "Zone")]
public int zoneID { get; set; }
[Required(ErrorMessage = "Ward No required")]
[Display(Name = "Ward No")]
public int wardNo { get; set; }
[StringLength(120, MinimumLength = 3, ErrorMessage = "120 charectar max")]
[Required(ErrorMessage = "Ward name required")]
[Display(Name = "Ward Name")]
public string wardName { get; set; }
[Required(ErrorMessage = "Vidhan Sabha required")]
[Display(Name = "<NAME>")]
public int vidhanSabhaConstituencyID { get; set; }
}
[MetadataType(typeof(languageViewModel))]
public partial class language { }
public class languageViewModel
{
[StringLength(50, MinimumLength = 3, ErrorMessage = "50 charectar max")]
[Required(ErrorMessage = "Language required")]
[Display(Name = "Language Name")]
public string language1 { get; set; }
[StringLength(50, MinimumLength = 3, ErrorMessage = "50 charectar max")]
[Required(ErrorMessage = "Font family required")]
[Display(Name = "Font Family")]
public string fontUsed { get; set; }
}
public class CompaignAdmin
{
[Required(ErrorMessage = "Election Type required")]
[Display(Name = "Election Type")]
public int electionTypeID { get; set; }
[Required(ErrorMessage = "Campaign name required")]
[Display(Name = "Campaign Name")]
public int campaignID { get; set; }
}
[MetadataType(typeof(surveyViewModel))]
public partial class survey { }
public class surveyViewModel
{
[Required(ErrorMessage = "Campaign is required")]
[Display(Name = "Campaign")]
public string campaignID { get; set; }
[StringLength(50, MinimumLength = 3, ErrorMessage = "50 charectar max")]
[Required(ErrorMessage = "Survey title required")]
[Display(Name = "Title")]
public string surveyTitle { get; set; }
[AllowHtml]
[StringLength(50, MinimumLength = 3, ErrorMessage = "50 charectar max")]
[Required(ErrorMessage = "Survey description required")]
[Display(Name = "Description")]
public string surveyDescription { get; set; }
[Required(ErrorMessage = "Survey start date required")]
[Display(Name = "Start Date")]
public System.DateTime startDate { get; set; }
[Required(ErrorMessage = "Survey end date required")]
[Display(Name = "End Date")]
public System.DateTime endDate { get; set; }
}
public class surveyQuestionViewModel {
public long surveyID { get; set; }
[Display(Name = "Serial No")]
[Required(ErrorMessage = "Question serial no. required")]
public int questionSerial { get; set; }
[Display(Name = "Question")]
[Required(ErrorMessage = "Question text required")]
public string question { get; set; }
[Display(Name = "Question Type")]
[Required(ErrorMessage = "Question Type required")]
public int questionTypeID { get; set; }
[Display(Name = "Option 1")]
[Required(ErrorMessage = "Option 1 required")]
public string questionOP1 { get; set; }
[Display(Name = "Option 2")]
[Required(ErrorMessage = "Option 2 required")]
public string questionOP2 { get; set; }
[Display(Name = "Option 3")]
[Required(ErrorMessage = "Option 3 required")]
public string questionOP3 { get; set; }
[Display(Name = "Option 4")]
[Required(ErrorMessage = "Option 4 required")]
public string questionOP4 { get; set; }
}
[MetadataType(typeof(campaignviewmodel))]
public partial class campaign
{
}
public class campaignviewmodel
{
[Display(Name = "Election Type")]
[Required(ErrorMessage = "Election Type required ")]
public int electionTypeID { get; set; }
[Display(Name = "Capaign Name")]
[Required(ErrorMessage = "Campaign name required ")]
public int campaignName { get; set; }
[Display(Name = "Election")]
[Required(ErrorMessage = "Election name required ")]
public int electionID { get; set; }
[Display(Name = "Political Party")]
[Required(ErrorMessage = "Political Party ")]
public int politicalPartyID { get; set; }
[Display(Name = "<NAME>")]
public int lokSabhaConstituencyID { get; set; }
[Display(Name = "<NAME>")]
public int vidhanSabhaConstituencyID { get; set; }
}
[MetadataType(typeof(newsviewmodel))]
public partial class news
{
}
public class newsviewmodel
{
[Display(Name = "Election Type")]
[Required(ErrorMessage = "Election Type required ")]
public int electionTypeID { get; set; }
[Display(Name = "News Title")]
[Required(ErrorMessage = "Title required ")]
public string title { get; set; }
[Display(Name = "News Description")]
[AllowHtml]
[Required(ErrorMessage = "News Description required ")]
public string description { get; set; }
[Display(Name = "Upload Image")]
[Required(ErrorMessage = "Image required ")]
public string imageURL { get; set; }
}
[MetadataType(typeof(Biography_sviewmodel))]
public partial class Biography_s { }
public class Biography_sviewmodel
{
[Display(Name = "Person Name")]
[Required(ErrorMessage = "Person name required ")]
public string personName { get; set; }
[Display(Name = "Biography")]
[Required(ErrorMessage = "Biography required ")]
public string description { get; set; }
}
public class AssignPollingBoothToPollingBoothIncharge
{
public Int64 campaignid { get; set; }
public Int64 voluntearID { get; set; }
[Display(Name = "Polling Booth")]
[Required(ErrorMessage = "Polling Booth required")]
public Int64 PollingBoothID { get; set; }
public string voterName { get; set; }
}
public class PageInchargeAssignAreaviewmodel
{
[Display(Name = "Area")]
[Required(ErrorMessage = "Election Type required ")]
public long areaID { get; set; }
public long volunteerID { get; set; }
public long campaignID { get; set; }
public string voterName { get; set; }
}
[MetadataType(typeof(voterListViewModel))]
public partial class voterList {
}
public class voterListViewModel {
[Required(ErrorMessage = "State required")]
[Display(Name = "State")]
public int stateID { get; set; }
[Required(ErrorMessage = "Lok sabha required")]
[Display(Name = "Lok Sabha ")]
public int lokSabhaConstituencyID { get; set; }
[Required(ErrorMessage = "Vidhan sabha required")]
[Display(Name = "Vidhan Sabha ")]
public int vidhanSabhaConstituencyID { get; set; }
[Required(ErrorMessage = "Ward required")]
[Display(Name = "Ward")]
public int wardID { get; set; }
[Required(ErrorMessage = "Area name required")]
[Display(Name = "Area Name")]
public long areaID { get; set; }
[Required(ErrorMessage = "Pin code required")]
[Display(Name = "Pin Code")]
public int pincode { get; set; }
[Required(ErrorMessage = "Langauge required")]
[Display(Name = "Langauge")]
public Nullable<int> regionalLanguage { get; set; }
[Required(ErrorMessage = "Voter name required")]
[Display(Name = "First Name")]
public string voterName { get; set; }
[Required(ErrorMessage = "Voter name required")]
[Display(Name = "Last Name")]
public string voterLastName { get; set; }
[Required(ErrorMessage = "Father/Husband name required")]
[Display(Name = "F/H Name")]
public string voterFather_HusbandName { get; set; }
[Required(ErrorMessage = "Plot number required")]
[Display(Name = "Plot No")]
public string plotNo { get; set; }
[Display(Name = "Street No")]
public string streetNo { get; set; }
[Required(ErrorMessage = "Gender required")]
[Display(Name = "Gender")]
public int genderID { get; set; }
[Required(ErrorMessage = "Voter id number required")]
[Display(Name = "Voter Id Number")]
public string voterIDNumber { get; set; }
[Display(Name = "Date Of Birth")]
public System.DateTime dateOfBirth { get; set; }
}
}<file_sep>using electo.Models.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace electo.Models.Repositories
{
public class EventTypeService : IEventTypeService
{
private readonly UnitOfWork uow;
public EventTypeService()
{
uow = new UnitOfWork();
}
public IEnumerable<eventType> GetEventTypeList() {
var eventTypeList_ = uow.eventType_.Find(e => e.isActive).ToList();
return eventTypeList_;
}
public IEnumerable<sp_GetAllEventTypes_Result> getEventTypes()
{
var result = uow.getEventTypes_.SQLQuery<sp_GetAllEventTypes_Result>("sp_GetAllEventTypes").ToList();
return result;
}
public bool addNewEventType(eventType OeventType)
{
bool result = false;
try
{
uow.eventType_.Add(OeventType);
result = true;
}
catch (Exception e)
{
result = false;
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IstateService
{
IEnumerable<state> getAllStates();
int create(string stateName);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IDistrictServices
{
IEnumerable<district> getDistrictByStateID(int stateID);
int create(district odistrict);
}
}
<file_sep>
function FIllDistrictDll(stateId) {
debugger
$.ajax({
url: '/zone/getDistrictListByStateID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: +stateId
}),
success: function (result) {
$("#districtID").html("");
$("#districtID").append($('<option></option>').val('').html(' District '));
$.each($.parseJSON(result), function (i, VSC) {
$("#districtID").append($('<option></option>').val(VSC.districtID).html(VSC.districtName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillMuncipartyDll(stateId) {
debugger;
$.ajax({
url: '/zone/getMuncipalCorporationListByStateID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: +stateId
}),
success: function (result) {
$("#ddl_muncipal").html("");
$("#ddl_muncipal").append($('<option></option>').val('').html('Muncipal Corporation'));
$.each($.parseJSON(result), function (i, VSC) {
$("#ddl_muncipal").append($('<option></option>').val(VSC.municipalCorporationID).html(VSC.municipalCorporationName1))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillZoneDll(stateId,MPCorporationID) {
debugger;
$.ajax({
url: '/zone/getZoneListBymuncipalCorpID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: +stateId,
MPCorporation: +MPCorporationID
}),
success: function (result) {
$("#zoneID").html("");
$("#zoneID").append($('<option></option>').val('').html(' Zone '));
$.each($.parseJSON(result), function (i, VSC) {
$("#zoneID").append($('<option></option>').val(VSC.zoneID).html(VSC.zoneName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillLoKSabha(stateId)
{
$.ajax
({
url: '/VidhanSabha/GetLOCKSABHAConstituencyLsit',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: +stateId
}),
success: function (result) {
$("#ddl_LKSC_Constituency").html("");
$("#ddl_LKSC_Constituency").append($('<option></option>').val('').html(' Lock Sabha'));
$.each($.parseJSON(result), function (i, VSC) {
$("#ddl_LKSC_Constituency").append($('<option></option>').val(VSC.lokSabhaConstituencyID).html(VSC.lokSabhaConstituencyName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillVidhanSabha(stateId) {
$.ajax
({
url: '/VidhanSabha/getvidhanSabhaConstituencyByStateID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: +stateId
}),
success: function (result) {
$("#ddl_VKSC_Constituency").html("");
$("#ddl_VKSC_Constituency").append($('<option></option>').val('').html(' Vidhan Sabha'));
$.each($.parseJSON(result), function (i, VSC) {
$("#ddl_VKSC_Constituency").append($('<option></option>').val(VSC.vidhanSabhaConstituencyID).html(VSC.vidhanSabhaConstituencyName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function getvidhanSabhaConstituencyByStateIDANDLKSCID(stateId, loksabhaID) {
$.ajax
({
url: '/VidhanSabha/getvidhanSabhaConstituencyByStateIDANDLKSCID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: +stateId,
LSCID: +loksabhaID
}),
success: function (result) {
$("#ddl_VKSC_Constituency").html("");
$("#ddl_VKSC_Constituency").append($('<option></option>').val('').html(' Vidhan Sabha'));
$.each($.parseJSON(result), function (i, VSC) {
$("#ddl_VKSC_Constituency").append($('<option></option>').val(VSC.vidhanSabhaConstituencyID).html(VSC.vidhanSabhaConstituencyName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillWardByVidhanSabhaConsistuencyID(vidhanSabhaConstituencyID) {
debugger
$.ajax
({
url: '/Ward/getWardByStateIDAndMUncipalCorporationID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: 0,
districtId: 0,
MPCorporation: 0,
vidhanSabhaConstituencyID: +vidhanSabhaConstituencyID
}),
success: function (result) {
$("#ddl_Ward").html("");
$("#ddl_Ward").append($('<option></option>').val('').html(' Ward'));
$.each($.parseJSON(result), function (i, VSC) {
$("#ddl_Ward").append($('<option></option>').val(VSC.wardID).html(VSC.wardName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillWard(stateId, MPCorporation, districtId) {
debugger
var vidhanSabhaConstituencyID = 0;
$.ajax
({
url: '/Ward/getWardByStateIDAndMUncipalCorporationID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId: +stateId,
districtId: +districtId,
MPCorporation: +MPCorporation,
vidhanSabhaConstituencyID:+vidhanSabhaConstituencyID
}),
success: function (result) {
$("#ddl_Ward").html("");
$("#ddl_Ward").append($('<option></option>').val('').html(' Ward'));
$.each($.parseJSON(result), function (i, VSC) {
$("#ddl_Ward").append($('<option></option>').val(VSC.wardID).html(VSC.wardName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillPollingBooth(wardID) {
debugger
$.ajax
({
url: '/PollingBooth/getPollingBoothList',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
wardID: +wardID
}),
success: function (result) {
$("#ddl_PollingBooth").html("");
$("#ddl_PollingBooth").append($('<option></option>').val('').html(' Ward'));
$.each($.parseJSON(result), function (i, VSC) {
$("#ddl_PollingBooth").append($('<option></option>').val(VSC.pollingBoothID).html(VSC.pollingBoothName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}
function FillAreaDDL(wardid) {
debugger
$.ajax
({
url: '/Area/getAll_areaList',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
wardID: +wardid
}),
success: function (result) {
$("#areaID").html("");
$("#areaID").append($('<option></option>').val('').html(' Area Name'));
$.each($.parseJSON(result), function (i, VSC) {
$("#areaID").append($('<option></option>').val(VSC.areaID).html(VSC.areaName))
})
},
error: function () {
bootbox.alert({
title: "Alert !",
message: '<p>Whooaaa! Something went wrong..</p>',
timeOut: 2000
});
},
});
}<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using electo.Models.SP_Models;
namespace electo.Models.IRepositories
{
interface IVotersServices
{
#region HR IService Function
IEnumerable<sp_Voters_GetAll_Result> GetAll ();
sp_Voters_GetById_Result GetById (long Id);
IEnumerable<sp_Voters_GetByPageInchargeId_Result> GetByPageInchargeId(long Id);
//20180228
IEnumerable<sp_Voters_GetByStateId_Result> GetByStateId(long Id);
IEnumerable<sp_Voters_GetByAreaId_Result> GetByAreaId(long Id);
IEnumerable<sp_Voters_GetByVidhanSabhaConstituencyId_Result> GetByVidhanSabhaConstituencyId(long Id);
IEnumerable<sp_Voters_GetByLokSabhaConstituencyId_Result> GetByLokSabhaConstituencyId(long Id);
IEnumerable<sp_Voters_GetByWardId_Result> GetByWardId(long Id);
//20180313
//public Repositories<sp_Voters_DeleteByVoterId> sp_Voters_DeleteByVoterId_
string DeleteVoter(long Id);
//20180314
int UpdateDetail(sp_Voters_UpdateDetail businessObject);
//20180319
int VerifyVoterByPageIncharge(sp_Voters_VerifyByPageIncharge businessObject);
//20180322
//public Repositories<sp_SectionIncharge_GetAllByBoothIncharge_Result> sp_SectionIncharge_GetAllByBoothIncharge_Result_
IEnumerable<sp_SectionIncharge_GetAllByBoothIncharge_Result> GetAllByBoothIncharge(long CampaignId, long BoothInchargeId);
#endregion
IEnumerable<sp_getPageInchargeLocation_Result> getPageInchargeLocation(long CampaignId, long PageInchargeId, DateTime VisitedDate);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface ISurveyQuestionServices
{
#region HR IService Function
IEnumerable<sp_SurveyQuestion_GetBySurveyId_Result> GetBySurveyId(long Id);
#endregion
int CreateSurveyQuestion(surveyQuestionViewModel osurveyQuestionViewModel);
}
}
<file_sep>using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace electo.Controllers
{
public class SurveyController : Controller
{
private readonly ICampaignService _CampaignService;
private readonly ISurveyServices _SurveyServices;
public SurveyController()
{
_CampaignService = new CampaignService();
_SurveyServices = new SurveyServices();
}
// GET: Survey
public ActionResult Index()
{
ViewBag.CampaignList = new SelectList((_CampaignService.getCompaignListByElectionIDandCreatedByID(Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()))).Select(e => new { e.campaignID, e.campaignName })), "campaignID", "campaignName");
return View();
}
public ActionResult _partialsurveyList( int CampaignId)
{
var ActivityListLIst = _SurveyServices.GetByCampaignId(CampaignId);
return PartialView("_partialsurveyList", ActivityListLIst);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.campaignID = _CampaignService.getCompaignListByElectionIDandCreatedByID(Convert.ToInt64(BaseUtil.GetSessionValue(AdminInfo.LoginID.ToString()))).Select(e => new { e.campaignID, e.campaignName });
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(survey osurvey)
{
int result = 0;
result = _SurveyServices.create(osurvey);
if (result == 1)
{
TempData["Result"] = "Success";
return RedirectToAction("Index");
}
else
{
TempData["Result"] = "unsuccess";
return View();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace electo.Models.IRepositories
{
interface IElectionService
{
IEnumerable<electionType> getElectionTypes();
IEnumerable<sp_electionList_Result> getElectionNameList(int ElectionType, int ddl_year, int month);
IEnumerable<monthName> getAllMonthName();
IEnumerable<tblyear> getAllYears();
int create(electionName oelectionName);
IEnumerable<electionName> getAllElections();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static electo.Models.SP_Models.StoredProcedureModels;
using System.Web.Mvc;
namespace electo.Models.IRepositories
{
interface ICampaignService
{
IEnumerable<sp_SearchRunningCampaigns_Result> SearchRunningCampaigns_Result(string electionTypeNAME, string electionYear, string politicalPartyName, string campaignName);
campaign get(long cID);
campaign _save(campaign _campaign);
IEnumerable<sp_SearchCampaignPrices_Result> sp_SearchCampaignPrices_Result(string electionTypeNAME, string year, bool isActive);
campaignPrice getCampaign(int ID);
int createCampaignPrice(campaignPrice newCmpPrice_);
IEnumerable<campaign> getCompaignListByElectionIDandCreatedByID(Int64 createdBy);
IEnumerable<campaignPrice> getAllPrices(int electionTypeID);
void createCampaign(campaign _campaign);
IEnumerable<campaign> getMyCampaigns(int volunteerID);
IEnumerable<sp_GetVolunteers_Result> getVolunteers(string cmpID,string pID, string stateID, string lkID, string vsID);
IEnumerable<userType> get();
int createVolunteerRelationship(string usertype, string vID, string cID);
sp_CheckUserInCampaign_Result checkUser(long volunteerID,long campaignID);
IEnumerable<sp_getAreaListByCampignID_Result> getAreaListByCampignID(long cmpID);
int assignPageInchargeArea(PageInchargeAssignAreaviewmodel _obj);
IEnumerable<sp_GetAllSectionInchargeByCampaign_Result> getAllSectionInchargeByCampaign (long cmpID );
IEnumerable<sp_getAllRelationshipsInCampaignByUserType_Result_> getAllRelationshipsInCampaignByUserType(string cmpID, string userTypeID);
IEnumerable<campaign> getCampaignNames(string prefix);
#region HR IService Function
IEnumerable<sp_Campaigns_GetAll_Result> GetAll();
sp_Campaigns_GetById_Result GetById(long Id);
IEnumerable<sp_Campaigns_GetByElectionTypeId_Result> GetByElectionTypeId(long Id);
IEnumerable<sp_Campaigns_GetByElectionId_Result> GetByElectionId(long Id);
IEnumerable<sp_Campaigns_GetByLokSabhaConstituencyId_Result> GetByLokSabhaConstituencyId(long Id);
IEnumerable<sp_Campaigns_GetByPoliticalPartyId_Result> GetByPoliticalPartyId(long Id);
IEnumerable<sp_Campaigns_GetByVidhanSabhaConstituencyId_Result> GetByVidhanSabhaConstituencyId(long Id);
IEnumerable<sp_Campaigns_GetByVolunteerId_Result> GetByVolunteerId(long Id);
IEnumerable<sp_Campaigns_GetByWardId_Result> GetByWardId(long Id);
#endregion
int DeletecampaignVolunteerRelationShip(Int64 cID, Int64 vID);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using electo.Models;
using electo.Models.IRepositories;
using electo.Models.Repositories;
using electo.Models.SP_Models;
namespace electo.WebServicesController
{
public class SurveyResponsesController : ApiController
{
//private electoEntities db = new electoEntities();
private readonly ISurveyResponseService _surveyResponseService;
public SurveyResponsesController()
{
_surveyResponseService = new SurveyResponseService();
}
//20180313
// public IEnumerable<sp_SurveyAnalysis_BySurveyId_Result> GetBySurveyId(long Id)
public IHttpActionResult GetBySurvey(long Id)
{
var objSurveyReponseList = _surveyResponseService.GetBySurveyId(Id);
if (objSurveyReponseList != null)
{
var surveyResponseEntities = objSurveyReponseList as List<sp_SurveyAnalysis_BySurveyId_Result> ?? objSurveyReponseList.ToList();
if (surveyResponseEntities.Any())
{
/*new code start*/
List<SurveyResponse> objSurveyResponseList = new List<Models.SP_Models.SurveyResponse>();
List<QuestionOption> objQuestionOptionList = new List<Models.SP_Models.QuestionOption>();
for (int i = 0; i < surveyResponseEntities.Count; i++)
{
SurveyResponse objSurveyResponse = new Models.SP_Models.SurveyResponse();
QuestionOption objQuestionOption = new Models.SP_Models.QuestionOption();
if (i == 0)
{
objSurveyResponse.SurveyId = surveyResponseEntities[i].surveyID;
objSurveyResponse.SurveyQuestionId = surveyResponseEntities[i].surveyQuesID;
objSurveyResponse.QuestionText = surveyResponseEntities[i].question;
objQuestionOption.SurveyQuestionOptionId = surveyResponseEntities[i].SurveyQuestionOptionId;
objQuestionOption.OptionText = surveyResponseEntities[i].OptionText;
objQuestionOption.Total = surveyResponseEntities[i].Total;
objQuestionOption.TotalResponse = surveyResponseEntities[i].TotalResponse;
objSurveyResponse.QuestionOptions = new List<QuestionOption>();
objSurveyResponse.QuestionOptions.Add(objQuestionOption);
objSurveyResponseList.Add(objSurveyResponse);
}
if (i > 0)
{
objQuestionOption.SurveyQuestionOptionId = surveyResponseEntities[i].SurveyQuestionOptionId;
objQuestionOption.OptionText = surveyResponseEntities[i].OptionText;
objQuestionOption.Total = surveyResponseEntities[i].Total;
objQuestionOption.TotalResponse = surveyResponseEntities[i].TotalResponse;
if (surveyResponseEntities[i].question == surveyResponseEntities[i - 1].question)
{
//objSurveyResponse.QuestionOptions.Add(objQuestionOption);
objSurveyResponseList.Last().QuestionOptions.Add(objQuestionOption);
}
else
{
objSurveyResponse.SurveyId = surveyResponseEntities[i].surveyID;
objSurveyResponse.SurveyQuestionId = surveyResponseEntities[i].surveyQuesID;
objSurveyResponse.QuestionText = surveyResponseEntities[i].question;
objSurveyResponse.QuestionOptions = new List<QuestionOption>();
objSurveyResponse.QuestionOptions.Add(objQuestionOption);
objSurveyResponseList.Add(objSurveyResponse);
}
}
}
/*new code end*/
// return Request.CreateResponse(HttpStatusCode.OK, surveyResponseEntities);
return Json(new { status = "Success", msg = "Record found", data = objSurveyResponseList });
}
}
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Survey response data not found");
return Json(new { status = "Error", msg = "Record not found" });
}
//20180327
//public IHttpActionResult SurveyResponseGetBySurvey(long Id)
//{
// var objSurveyReponseList = _surveyResponseService.GetBySurveyId(Id);
// if (objSurveyReponseList != null)
// {
// var surveyResponseEntities = objSurveyReponseList as List<sp_SurveyAnalysis_BySurveyId_Result> ?? objSurveyReponseList.ToList();
// if (surveyResponseEntities.Any())
// {
// List<SurveyResponse> objSurveyResponseList = new List<Models.SP_Models.SurveyResponse>();
// List<QuestionOption> objQuestionOptionList = new List<Models.SP_Models.QuestionOption>();
// for (int i= 0; i< surveyResponseEntities.Count; i++)
// {
// SurveyResponse objSurveyResponse = new Models.SP_Models.SurveyResponse();
// QuestionOption objQuestionOption = new Models.SP_Models.QuestionOption();
// if (i==0)
// {
// objSurveyResponse.SurveyId = surveyResponseEntities[i].surveyID;
// objSurveyResponse.SurveyQuestionId = surveyResponseEntities[i].surveyQuesID;
// objSurveyResponse.QuestionText = surveyResponseEntities[i].question;
// objQuestionOption.SurveyQuestionOptionId = surveyResponseEntities[i].SurveyQuestionOptionId;
// objQuestionOption.OptionText = surveyResponseEntities[i].OptionText;
// objQuestionOption.Total = surveyResponseEntities[i].Total;
// objQuestionOption.TotalResponse = surveyResponseEntities[i].TotalResponse;
// objSurveyResponse.QuestionOptions.Add(objQuestionOption);
// objSurveyResponseList.Add(objSurveyResponse);
// }
// if (i>0)
// {
// objQuestionOption.SurveyQuestionOptionId = surveyResponseEntities[i].SurveyQuestionOptionId;
// objQuestionOption.OptionText = surveyResponseEntities[i].OptionText;
// objQuestionOption.Total = surveyResponseEntities[i].Total;
// objQuestionOption.TotalResponse = surveyResponseEntities[i].TotalResponse;
// if (surveyResponseEntities[i].question == surveyResponseEntities[i - 1].question)
// {
// objSurveyResponse.QuestionOptions.Add(objQuestionOption);
// objSurveyResponseList.Last().QuestionOptions.Add(objQuestionOption);
// }
// else
// {
// objSurveyResponse.SurveyId = surveyResponseEntities[i].surveyID;
// objSurveyResponse.SurveyQuestionId = surveyResponseEntities[i].surveyQuesID;
// objSurveyResponse.QuestionText = surveyResponseEntities[i].question;
// objSurveyResponse.QuestionOptions.Add(objQuestionOption);
// objSurveyResponseList.Add(objSurveyResponse);
// }
// }
// }
// //return Json(new { status = "Success", msg = "Record found", data = objSurveyResponseList.ToList() });
// return Json(new { status = "Success", msg = "Record found", data = surveyResponseEntities });
// }
// }
// return Json(new { status = "Error", msg = "Record not found" });
//}
//Post Survey Response
public IHttpActionResult submitResponse([FromBody] IEnumerable< surveyRespons> _surveyResponse )
{
var submitResponse = _surveyResponseService.submitResponse(_surveyResponse);
if (submitResponse == 1)
{
return Json(new { status = "Success", msg = "Success" });
}
// return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Survey response data not found");
return Json(new { status = "Error", msg = "Not Submitted" });
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// db.Dispose();
}
base.Dispose(disposing);
}
}
} | 1543f8021a2bec17aaf8dc62a449b04a3c33c4fd | [
"Markdown",
"C#",
"JavaScript"
] | 103 | C# | abhijeetsap21/electo | f76778a6f58e2177d39c959c1ca52d186b4ac015 | e4b7701d97e6dc3b3cf6b7d80164e9851d5a8d16 |
refs/heads/master | <repo_name>kennyNing/spider<file_sep>/demo.py
# -*- coding: UTF-8 -*-
# 这是单行注释,学习参考链接地址:https://www.w3cschool.cn/python/python-variable-types.html
import random
"""
这是长文本注释,双引号,随便多长,呵呵
"""
'''
这也是长文注释,单引号的
'''
print "世界你好,哈哈"
# 变量
a=b=c=9 #多个变量赋值同为9
print b
e,f,g=9,2.03,"jojo" #为多个对象指定多个变量
print g
# 字符串
strs = 'Hello World!'
print strs[0:5] #输出为:love
print strs * 2 # 输出字符串两次
print strs + "TEST" # 输出连接的字符串
# 列表 List
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个的元素
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表
# 原组 类似于List
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # 输出完整元组
print tuple[0] # 输出元组的第一个元素
print tuple[1:3] # 输出第二个至第三个的元素
print tuple[2:] # 输出从第三个开始至列表末尾的所有元素
print tinytuple * 2 # 输出元组两次
print tuple + tinytuple # 打印组合的元组
# 字典 {}
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # 输出键为'one' 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值
# 数据类型转换
aa=int("123456")
bb=str(2)
print str(aa)+bb
'''
# 算术运算符
+ 加 - 两个对象相加 a + b 输出结果 30
- 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -10
* 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 200
/ 除 - x除以y b / a 输出结果 2
% 取模 - 返回除法的余数 b % a 输出结果 0
** 幂 - 返回x的y次幂 a**b 为10的20次方, 输出结果 100000000000000000000
// 取整除 - 返回商的整数部分 9//2 输出结果 4 , 9.0//2.0 输出结果 4.0
# 比较运算符
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 true.
<> 不等于 - 比较两个对象是否不相等 (a <> b) 返回 true。这个运算符类似 != 。
> 大于 - 返回x是否大于y (a > b) 返回 False。
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 true。
>= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
<= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 true。
# 赋值运算符
= 简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c
+= 加法赋值运算符 c += a 等效于 c = c + a
-= 减法赋值运算符 c -= a 等效于 c = c - a
*= 乘法赋值运算符 c *= a 等效于 c = c * a
/= 除法赋值运算符 c /= a 等效于 c = c / a
%= 取模赋值运算符 c %= a 等效于 c = c % a
**= 幂赋值运算符 c **= a 等效于 c = c ** a
//= 取整除赋值运算符 c //= a 等效于 c = c // a
'''
# 条件语句
num = 5
if num == 3: # 判断num的值
print 'boss'
elif num == 2:
print 'user'
elif num == 1:
print 'worker'
elif num < 0: # 值小于零时输出 print 'error' else: print 'roadman' # 条件均不成立时输出
print 0.00
# for循环
for letter in 'Python': # 第一个实例
print '当前字母 :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print '当前字母 :', fruit
# 随机数
import random #需要引用包
print random.random() #随机生成下一个实数,它在[0,1)范围内。
print random.choice(range(99)) #从0到9中随机挑选一个整数。
# html代码标识符
print r'\n'
print R'\"'
# 时间
import time; # 引入time模块
ticks = time.time()
print "当前时间戳为:", ticks
localtime = time.localtime(time.time())
print "本地时间为 :", localtime
localtime = time.asctime( time.localtime(time.time()) )
print "本地时间为 :", localtime
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 2016-04-07 10:25:09
# 函数
def printme( description="这是给默认值,如果调用函数没传值则用默认值"):
"打印任何传入的字符串"
print description;
return;
printme(description="调用用户自定义函数:printme");
printme();
# 读取键盘输入
str = raw_input("请输入:");
print "你输入的内容是: ", str
#
import os
# 给出当前的目录
os.getcwd()<file_sep>/get_article.py
# -*- coding: UTF-8 -*-
import urllib2
import urllib
import os
hosturl = 'http://www.360doc.com/content/14/0813/17/15477063_401589947.shtml'
#构造header,一般header至少要包含一下两项。这两项是从抓到的包里分析得出的。
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0', 'Referer' : hosturl}
#打开登录主页面(他的目的是从页面下载cookie,这样我们在再送post数据时就有cookie了,否则发送不成功)
request = urllib2.Request(hosturl,None, headers)
response = urllib2.urlopen(request)
htmldata = response.read()
data=htmldata.decode('utf-8')
pre = '<span id="articlecontent" onmousedown="newhighlight = true;" onmouseup="NewHighlight(event)">'
index1 = data.find(pre) + len(pre)
index2 = data.find('<div id="viewerPlaceHolder" style="width: 717px; height: 700px; display: none;">', index1)
content = data[index1 : index2]
pretitle = '<div class="biaoti2 lf360">'
indextitle1 = data.find(pretitle) + len(pretitle)
indextitle2 = data.find('</div>', indextitle1)
title = data[indextitle1 : indextitle2].replace("\r\n","").strip()
print(title)
f = open(title+"_"+hosturl.split("/")[-1],"w")
f.write(content)<file_sep>/README.md
# spider
环境:Python 2.7.13,windows 64
demo.py : python一些demo语法
get_img.py : 实现功能--》抓取网页的图片并且保存到本地
get_article.py : 抓取网页文字
<file_sep>/get_img.py
# -*- coding: UTF-8 -*-
import re
import urllib,urllib2;
# 获取网页内容函数 http://service.wifiha.com/face/get
def getHtml(url):
# 要设置请求头,让服务器知道不是机器人
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
request=urllib2.Request(url,headers=headers);
page = urllib2.urlopen(request);
html = page.read()
return html
#通过正则表达式来获取图片地址,并下载到本地
def getImg(html):
reg = r'src="(.+?\.jpg)"'
imgre = re.compile(reg)
imglist = imgre.findall(html)
x = 0
for imgurl in imglist:
print imgurl;
#通过urlretrieve函数把数据下载到本地的D:\\images,所以你需要创建目录
urllib.urlretrieve(imgurl, 'D:\\images\\%s.jpg' % x)
x = x + 1
htmlContent=getHtml("http://service.wifiha.com/face/get");
getImg(htmlContent) | 25e17fd971b764ee66443448af67029fe2f57473 | [
"Markdown",
"Python"
] | 4 | Python | kennyNing/spider | 0c83ae96900c1d1c4e32451a6f09bcc14381e62a | 9009b62c2fe4b4ef3b2af178aad10faf40c296d2 |
refs/heads/master | <repo_name>isabella232/mruby-simple-random<file_sep>/test/random.rb
##
# Random Test
assert('Kernel#rand') do
r = rand
r.class == Float
end
assert('Kernel#rand(num)') do
r = rand(100)
r.class == Fixnum
end
assert('Kernel#rand entropy check') do
hash = {}
size = 1000
size.times do
hash[rand(size * size)] = 1
end
hash.size > size * 0.9
end
assert('Kernel#srand') do
num = 12345678
seeds = []
ary1 = []
ary2 = []
ary3 = []
srand(num)
ary1 << rand << rand << rand << rand << rand
ary1 << rand(100) << rand(100) << rand(100) << rand(100) << rand(100)
seeds << srand
ary2 << rand << rand << rand << rand << rand
ary2 << rand(100) << rand(100) << rand(100) << rand(100) << rand(100)
seeds << srand(num)
ary3 << rand << rand << rand << rand << rand
ary3 << rand(100) << rand(100) << rand(100) << rand(100) << rand(100)
seeds << srand
ary1 == ary3 and ary1 != ary2 and seeds[0] == seeds[2] and seeds.all?{|i| i > 0 }
end
<file_sep>/src/random.c
/*
** random.c - random
**
** See Copyright Notice in mruby.h
*/
#include "mruby.h"
#include "mruby/variable.h"
#include <stdlib.h>
#include <time.h>
#define RAND_SEED_KEY "$mrb_ext_rand_seed"
mrb_value
mrb_random_srand(mrb_state *mrb, mrb_value seed)
{
if (mrb_nil_p(seed)) {
seed = mrb_fixnum_value(time(NULL) + random());
if (mrb_fixnum(seed) < 0) {
seed = mrb_fixnum_value( 0 - mrb_fixnum(seed));
}
}
srandom((unsigned) mrb_fixnum(seed));
return seed;
}
mrb_value
mrb_random_rand(mrb_state *mrb, mrb_value max)
{
int crand = random();
mrb_value value;
if (mrb_fixnum(max) == 0) {
value = mrb_float_value(mrb, 1.0 * crand / RAND_MAX);
} else {
value = mrb_fixnum_value(crand % mrb_fixnum(max));
}
return value;
}
static mrb_value
mrb_f_rand(mrb_state *mrb, mrb_value self)
{
mrb_value *argv;
mrb_int argc;
mrb_value max, seed;
mrb_get_args(mrb, "*", &argv, &argc);
if (argc == 0) {
max = mrb_fixnum_value(0);
} else if (argc == 1) {
max = argv[0];
if (!mrb_nil_p(max) && !mrb_fixnum_p(max)) {
max = mrb_check_convert_type(mrb, max, MRB_TT_FIXNUM, "Fixnum", "to_int");
}
if (!mrb_nil_p(max) && mrb_fixnum(max) < 0) {
max = mrb_fixnum_value(0 - mrb_fixnum(max));
}
if (!mrb_fixnum_p(max)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument type");
return mrb_nil_value();
}
} else {
mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%d for 0..1)", argc);
return mrb_nil_value();
}
seed = mrb_gv_get(mrb, mrb_intern_lit(mrb, RAND_SEED_KEY));
if (mrb_nil_p(seed)) {
mrb_random_srand(mrb, mrb_nil_value());
}
return mrb_random_rand(mrb, max);
}
static mrb_value
mrb_f_srand(mrb_state *mrb, mrb_value self)
{
mrb_value *argv;
mrb_int argc;
mrb_value old_seed, seed;
mrb_get_args(mrb, "*", &argv, &argc);
if (argc == 0) {
seed = mrb_nil_value();
} else if (argc == 1) {
seed = argv[0];
if (!mrb_nil_p(seed) && !mrb_fixnum_p(seed)) {
seed = mrb_check_convert_type(mrb, seed, MRB_TT_FIXNUM, "Fixnum", "to_int");
}
if (!mrb_nil_p(seed) && mrb_fixnum(seed) < 0) {
seed = mrb_fixnum_value(0 - mrb_fixnum(seed));
}
if (!mrb_fixnum_p(seed)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument type");
return mrb_nil_value();
}
} else {
mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%d for 0..1)", argc);
return mrb_nil_value();
}
seed = mrb_random_srand(mrb, seed);
old_seed = mrb_gv_get(mrb, mrb_intern_lit(mrb, RAND_SEED_KEY));
mrb_gv_set(mrb, mrb_intern_lit(mrb, RAND_SEED_KEY), seed);
return old_seed;
}
void
mrb_mruby_random_gem_init(mrb_state *mrb)
{
struct RClass *krn;
krn = mrb->kernel_module;
mrb_gv_set(mrb, mrb_intern_lit(mrb, RAND_SEED_KEY), mrb_nil_value());
mrb_define_method(mrb, krn, "rand", mrb_f_rand, MRB_ARGS_ANY());
mrb_define_method(mrb, krn, "srand", mrb_f_srand, MRB_ARGS_ANY());
}
void
mrb_mruby_random_gem_final(mrb_state *mrb)
{
}
<file_sep>/run_test.rb
#!/usr/bin/env ruby
#
# mrbgems test runner
#
if __FILE__ == $0
repository, dir = 'https://github.com/mruby/mruby.git', 'tmp/mruby'
build_args = ARGV
Dir.mkdir 'tmp' unless File.exist?('tmp')
unless File.exist?(dir)
system "git clone #{repository} #{dir}"
end
exit system(%Q[cd #{dir}; MRUBY_CONFIG=#{File.expand_path __FILE__} ruby minirake #{build_args.join(' ')}])
end
module MRuby
module Gem
class List
def delete_if(&b)
@ary.delete_if(&b)
end
end
end
end
MRuby::Build.new do |conf|
toolchain :gcc
conf.gembox 'default'
conf.gems.delete_if{|g| g.name == 'mruby-random' }
conf.gem File.expand_path(File.dirname(__FILE__))
end
| 005fcbd09b0aed577fb96aae8014bcc24ffc0ad9 | [
"C",
"Ruby"
] | 3 | Ruby | isabella232/mruby-simple-random | a20cd92d177cfa1dc2b7a6bb1de6069ae5f11656 | 7085b9f2aa7c4a9b813913056e6d3f0d5aaa6e1c |
refs/heads/master | <file_sep>//------------------------- GLOBAL VARIABLE AND CONSTANT -----------------------------------------------
var globalText = "";
var badgetText = "0";
var isSimpleText = true;
var isListWithNumber = false;
var formatFirstLine = false;
var LIST_SYMBOL = "";
const DOT = "•";
const DASH = "-";
const SQUARE = "";
const MULTILINE_REGEX = /\n{2,20}/;
const MULTI_TAB_REGEX = /\t{1,20}/;
const API_URI = "https://v2.convertapi.com/convert/";
const API_SECRET = "";
const API_FILE_STORE_STATE = "&StoreFile=true";
const TAB_RPLC = " : ";
const ACCEPTED_FORMAT = ["jpg", "jpeg", "gif", "png", "tif"];
chrome.commands.onCommand.addListener((command) => {
getListSymbol();
switch (command) {
case "copy_and_format":
isSimpleText = false;
formatText();
formatFirstLine = false;
break;
case "reset_data":
injectScript();
resetData();
clearTextStorage();
break;
case "format_first_line":
isSimpleText = false;
formatText();
formatFirstLine = true;
break;
case "concat_text":
isSimpleText = true;
formatText();
formatFirstLine = false;
break;
}
updateBadgeText({ text: badgetText });
});
//-------------------------- SCRIPT INECTION ------------------------------------------------
function injectScript() {
chrome.tabs.getSelected(null, (tab) => {
chrome.tabs.executeScript(tab.id, { file: 'listnerFile.js' }, () => {
});
})
}
chrome.storage.onChanged.addListener((storedItem, name) => {
if (Object.keys(storedItem)[0] === "all_text") {
let textToC = storedItem['all_text'].newValue;
textToC = textToC.replace(/\t{1,20}/g, ": ");
textToC = textToC.replace(/• •/g, "•");
textToC = textToC.replace(/• ●/g, "•");
textToC = textToC.replace(/• (-+|\.)/g, " - ");
textToC = textToC.replace(/\n{2,50}/g, "\n\n");
//textToC = textToC.replace(/\s{2,80}/g, " ");
copyToClipBoard(textToC);
}
})
//-------------------------- CONTEXT MENU INIT ------------------------------------------------
chrome.contextMenus.create({
"title": "Copy URL",
"contexts": ["image"],
"onclick": onClickImageHandler
});
//----------------------------------------------------------------------------------------------
//---------------------------- IMAGE URL -------------------------------------------------------
//----------------------------------------------------------------------------------------------
function onClickImageHandler(info, tab) {
let url = removeUrlParam(info.srcUrl);
let imageExt = getImageExtentions(url);
/*if (!isAcceptedFormat(imageExt)) {
convertImage(url);
}*/
url = extentionToLowerCase(url);
copyToClipBoard(url);
}
/**
* Convert non-accepted file format
* @Param type String : file url to be converted
*/
function convertImage(url) {
let jpgUrl = "";
let fileArray = [];
let apiUrl = buildApiUrl("web", "jpg", url);
sendRequest(apiUrl);
}
function isAcceptedFormat(imageExtention) {
return (ACCEPTED_FORMAT.find(ext => ext === imageExtention) === undefined) ? false : true;
}
function removeUrlParam(url) {
return (url.indexOf("?") != -1) ? url.substring(0, url.indexOf("?")) : url;
}
function getImageExtentions(url) {
return url.substring(url.lastIndexOf(".") + 1);;
}
function extentionToLowerCase(url) {
let urlExt = getImageExtentions(url);
url = url.substring(0, url.lastIndexOf(".") + 1) + urlExt.toLowerCase();
return url;
}
//----------------------------------------------------------------------------------------------
//---------------------------- TEXT ------------------------------------------------------------
//----------------------------------------------------------------------------------------------
/**
* Main function for the text formatter
**/
function formatText() {
let textFromClipboard = getClipboardData();
if (!isSimpleText) {
let formatedText = buildText(textFromClipboard);
globalText = (globalText != "") ? globalText + "\n\n" + formatedText : formatedText;
}
if (isSimpleText) {
let newText = textFromClipboard;
newText = newText.replace(/\n{3,20}/g, "\n");
newText = newText.replace(/\t{1,20}/g, TAB_RPLC);
globalText = (globalText != "") ? globalText + "\n\n" + newText : newText;
}
copyToClipBoard(globalText);
}
/**
* Format text by adding DASH or DOT
* @Param str : type String ; text to be formated
* @Param formatFirstLineState: type boolean ; parm if first line need to be formated
**/
function buildText(str) {
let formatedText;
if (!isListWithNumber) {
if (MULTILINE_REGEX.test(str))
str = deleteMultiLineBreak(str);
if (formatFirstLine)
str = LIST_SYMBOL + " " + str;
formatedText = str.replace(/\n/g, "\n" + LIST_SYMBOL + " ");
}
if (isListWithNumber) {
str = str.replace(/\n{2,20}/g, "\n");
formatedText = addNumber(splitTextToArray(str));
}
return formatedText;
}
function deleteMultiLineBreak(str) {
return str.replace(/\n{2,20}/g, "\n");
}
/**
* Cut text to 1700<
* @Param str : type String ; text to cut
*/
function cutAllText(textes) {
textes = textes.substr(0, 1699);
return (textes.lastIndexOf(".") < textes.lastIndexOf("\n")) ?
textes.substr(0, textes.lastIndexOf("\n") + 1) :
textes = textes.substr(0, textes.lastIndexOf(".") + 1);
}
/**
* Get the current state of list_symbol from chrome.storage
*/
function getListSymbol() {
chrome.storage.sync.get({
list_symbol: '',
}, function (items) {
let current_choice = items.list_symbol;
switch (current_choice) {
case 'dot':
isListWithNumber = false;
LIST_SYMBOL = DOT;
break;
case 'dash':
isListWithNumber = false;
LIST_SYMBOL = DASH;
break;
case 'square':
isListWithNumber = false;
LIST_SYMBOL = SQUARE;
break;
case 'number':
isListWithNumber = true;
break;
default:
isListWithNumber = false;
LIST_SYMBOL = DOT;
udateListSymbol(DOT);
}
});
}
/**
* Split String with \n as separator
**/
function splitTextToArray(textes) {
let textArray = textes.split("\n");
return textArray;
}
/**
* Add number for list
**/
function addNumber(textArray) {
let newStringText = "";
let j = 1;
for (let i = 0; i < textArray.length; i++) {
if (i === 0 && !formatFirstLine) {
newStringText += textArray[i] + "\n";
continue;
}
newStringText += j + ". " + textArray[i] + "\n";
j++;
}
return newStringText;
}
/**
* Format tab with more than 2 column
**/
function formatMultiDTab(textes) {
let textesArray = splitTextToArray(textes);
let newStringText = "";
for (let i = 0; i < textesArray.length; i++) {
newStringText = newStringText + "\n" + reverseArrayIndex(textesArray[i]);
}
return newStringText;
}
/**
* Revese 1 and 2 index in array
**/
function reverseArrayIndex(textes) {
let textesArray = splitTextTo3DArray(textes);
let unit = (textesArray[1] === "-") ? "" : textesArray[1];
return textesArray[0] + " : " + textesArray[2] + " " + unit;
}
/**
* Split String with \t as separator
**/
function splitTextTo3DArray(textes) {
let textArray = textes.split("\t");
return textArray;
}
//----------------------------------------------------------------------------------------------
//---------------------------- CLIPBOARD FUNCTION ----------------------------------------------
//----------------------------------------------------------------------------------------------
/**
* Get data from clipboard
* @Param formatFirstLineState: type boolean ; parm if first line need to be formated
* @Param simpleText: type boolean ; param if no need to format text
**/
function getClipboardData(str) {
const tempHtmlElement = document.createElement('textarea');
tempHtmlElement.style.position = 'absolute';
tempHtmlElement.style.left = '-9999px';
document.body.appendChild(tempHtmlElement);
tempHtmlElement.select();
document.execCommand('paste');
let textFromClipboard = tempHtmlElement.value
document.body.removeChild(tempHtmlElement);
return textFromClipboard;
}
/**
*
*/
function copyToClipBoard(textes) {
const tempHtmlElement = document.createElement('textarea');
textes = textes.replace(/\n{3,20}/g, "\n\n");
badgetText = textes.length.toString();
if (textes.length > 1699) {
badgetText = "OK";
textes = cutAllText(textes);
}
updateBadgeText({ text: badgetText.toString() });
tempHtmlElement.value = textes;
tempHtmlElement.setAttribute('readonly', '');
tempHtmlElement.style.position = 'absolute';
tempHtmlElement.style.left = '-9999px';
document.body.appendChild(tempHtmlElement);
tempHtmlElement.select();
document.execCommand('copy');
document.body.removeChild(tempHtmlElement);
}
//----------------------------------------------------------------------------------------------
//---------------------------- AJAX REQUEST ----------------------------------------------------
//----------------------------------------------------------------------------------------------
function sendRequest(url) {
let jpgUrl = "";
fetch(url).then((res) => {
return res.json();
}).then((jsRes) => {
jpgUrl = jsRes['Files'][0].Url;
clipboardData(jpgUrl);
})
}
function getJpgUrl(resArray) {
return resArray['Files'][0].Url;
}
function buildApiUrl(sourceFileType, convertTo, fileUrl) {
let urlToRequest = `${API_URI}${sourceFileType}/to/${convertTo}?${API_SECRET}&Url=${fileUrl}${API_FILE_STORE_STATE}`;
return urlToRequest;
}
//----------------------------------------------------------------------------------------------
//---------------------------- OTHER FUNCTION ----------------------------------------------
//----------------------------------------------------------------------------------------------
function sendNotification(message) {
let notifOptions = {
type: "basic",
iconUrl: "copy.png",
title: "",
message: ""
}
notifOptions.message = message;
chrome.notifications.create("text_lenght", notifOptions, () => { });
}
function getAllTabs() {
chrome.tabs.getAllInWindow(null, function (tabs) {
chrome.tabs.sendRequest(tabs[1].id, { test: "test" }, (data) => {
console.log(data);
})
console.log(tabs[1].id);
});
}
function addInfo(str) {
const INFO = "?utm_source=directindustry.com&utm_medium=product-placement&utm_campaign=hq_directindustry.productentry_online-portal&utm_content=C-00031727";
let url = str + INFO;
copyToClipBoard(url);
}
function clearTextStorage() {
chrome.storage.sync.set({ all_text: "" }, () => {
});
}
function resetData() {
globalText = "";
badgetText = "0";
}
function updateBadgeText(textObject) {
chrome.browserAction.setBadgeText(textObject);
}
function udateListSymbol(list_symbol) {
chrome.storage.sync.set({ list_symbol }, () => {
})
}
| ec20d5daab31808f38374189338f22bd21c38986 | [
"JavaScript"
] | 1 | JavaScript | raneric/copy_tools | 5765a5e6a50cc8081fc0b44ff99f0831e53975b7 | 6ad74c6509b1f102a736156bfb9255354288050c |
refs/heads/master | <file_sep>use std::fmt;
use std::mem;
fn reverse(pair: (i32, bool)) -> (bool, i32) {
let (integer, boolean) = pair;
(boolean, integer)
}
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "( {} {} )\n( {} {} )", self.0, self.1, self.2, self.3)
}
}
fn transpose(matrix: Matrix) -> Matrix {
Matrix(matrix.0, matrix.2, matrix.1, matrix.3)
}
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
fn main() {
let _logical: bool = true;
let _a_float: f64 = 1.0;
let _an_integer = 5i32;
let _default_float = 3.0;
let _default_integer = 7;
let mut _inferred_type = 12;
_inferred_type = 4294967296i64;
let mut _mutable = 12;
_mutable = 21;
// mutable = true;
let _mutable = true;
println!("1 + 2 = {}", 1u32 + 2);
println!("1 - 2 = {}", 1i32 - 2);
println!("{} {} {}", true && false, true || false, !true);
println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101);
println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101);
println!("1 << 5 is {}", 1u32 << 5);
println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2);
println!("One million is written as {}", 1_000_000u32);
let long_tuple = (
1u8, 2u16, 3u32, 4u64,
-1i8, -2i16, -3i32, -4i64,
0.1f32, 0.2f64,
'a', true
);
println!("long tuple first and second {} {}", long_tuple.0, long_tuple.1);
let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);
println!("tuple of tuples: {:?}", tuple_of_tuples);
// But long Tuples cannot be printed
// let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
// println!("too long tuple: {:?}", too_long_tuple);
// TODO ^ Uncomment the above 2 lines to see the compiler error
let pair = (1, true);
println!("pair {:?} reverse {:?}", pair, reverse(pair));
println!("tuple {:?} and not {:?}", (5u32,), (5u32));
let tuple = (1, "hello", 4.5, true);
let (a,b,c,d) = tuple;
println!("{:?} {:?} {:?} {:?}", a,b,c,d);
let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
println!("{}", matrix);
println!("{}", transpose(matrix));
let xs: [i32; 5] = [1,2,3,4,5];
let ys: [i32; 500] = [0; 500];
println!("0 {} 1 {}", ys[0], ys[1]);
println!("size {}", xs.len());
// Arrays are stack allocated
println!("array occupies {} bytes", mem::size_of_val(&xs));
println!("array occupies {} bytes", mem::size_of_val(&ys));
// Arrays can be automatically borrows as slices
println!("borrow the whole array as a slice");
analyze_slice(&xs);
analyze_slice(&ys[1 .. 4]);
println!("{} bytes", mem::size_of_val(&ys[1 .. 4]));
// println!("{}", xs[5]);
}
<file_sep># Learning-Rust
A repo where I dump my Rust practice exercises.
Mostly going by [Rust by Example](https://doc.rust-lang.org/stable/rust-by-example/index.html).
The [Rust Book](https://doc.rust-lang.org/book/) and [Rustling](https://github.com/rust-lang/rustlings/) are also useful.
<file_sep>use std::fmt::{self, Formatter, Display};
struct Structure(i32);
impl fmt::Display for Structure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug)]
struct MinMax(i64, i64);
impl fmt::Display for MinMax {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1)
}
}
#[derive(Debug)]
struct Point2D {
x: f64,
y: f64,
}
impl fmt::Display for Point2D {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "x: {}, y: {}", self.x, self.y)
}
}
#[derive(Debug)]
struct Complex {
real: f64,
imag: f64
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} + {}i", self.real, self.imag)
}
}
struct List(Vec<i32>);
impl fmt::Display for List {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let vec = &self.0;
write!(f, "[")?;
for(count, v) in vec.iter().enumerate() {
if count != 0 {
write!(f, ", ")?;
}
write!(f, "{}: {}", count, v)?;
}
write!(f, "]")
}
}
struct City {
name: &'static str,
lat: f32,
lon: f32,
}
impl Display for City {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
write!(f, "{}: {:.3}°{} {:.3}°{}", self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
}
}
#[derive(Debug)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
impl Display for Color {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "RGB ({red}, {green}, {blue}) 0x{red:0>2X}{green:0>2X}{blue:0>2X}", red=self.red, green=self.green, blue=self.blue)
}
}
fn main() {
let minmax = MinMax(0, 14);
println!("Compare structures:");
println!("Display: {}", minmax);
println!("Debug: {:?}", minmax);
let big_range = MinMax(-300, 300);
let small_range = MinMax(-3, 3);
println!("The big range is {big} and the small is {small}",
small = small_range,
big = big_range);
let point = Point2D { x: 3.3, y: 7.2 };
println!("Compare points:");
println!("Display: {}", point);
println!("Debug: {:?}", point);
// Error. Both `Debug` and `Display` were implemented, but `{:b}`
// requires `fmt::Binary` to be implemented. This will not work.
// println!("What does Point2D look like in binary: {:b}?", point);
let complex = Complex { real: 3.3, imag: 7.2 };
println!("Display: {}", complex);
println!("Debug: {:#?}", complex);
let v = List(vec![1,2,3]);
println!("{}", v);
for city in [
City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
City { name: "Oslo", lat: 59.95, lon: 10.75 },
City { name: "Vancouver", lat: 49.25, lon: -123.1 },
].iter() {
println!("{}", *city);
}
for color in [
Color { red: 128, green: 255, blue: 90 },
Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
println!("{}", *color)
}
}
<file_sep>#[derive(Debug)]
struct Person<'a> {
name: &'a str,
age: u8,
}
struct Nil;
struct Pair(i32, f32);
#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
#[allow(dead_code)]
#[derive(Debug)]
struct Rectangle {
top_left: Point,
bottom_right: Point,
}
fn rect_area(rect: Rectangle) -> f32 {
let Rectangle { top_left, bottom_right } = rect;
let Point { x: top_x, y: top_y } = top_left;
let Point { x: bottom_x, y: bottom_y } = bottom_right;
let height = top_y - bottom_y;
let width = bottom_x - top_x;
height * width
}
fn square(p: Point, w: f32) -> Rectangle {
let Point { x: left_edge, y: bottom_edge } = p;
Rectangle { top_left: Point {x: left_edge, y: bottom_edge + w}, bottom_right: Point {x: left_edge + w, y: bottom_edge }}
}
fn main() {
let name = "Peter";
let age = 27;
let peter = Person { name, age };
println!("{:?}", peter);
let point: Point = Point { x: 10.3, y: 0.4 };
println!("({}, {})", point.x, point.y);
let bottom_right = Point { x: 5.2, ..point };
println!("({}, {})", bottom_right.x, bottom_right.y);
let Point { x: top_edge, y: left_edge } = point;
let _rectangle = Rectangle {
top_left: Point { x: left_edge, y: top_edge },
bottom_right: bottom_right,
};
let _nil = Nil;
let pair = Pair(1, 0.1);
println!("pair contains {:?} and {:?}", pair.0, pair.1);
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
println!("{:?}", rect_area(_rectangle));
println!("{:?}", square(point, 1.0));
}<file_sep>fn main() {
let an_integer = 1u32;
let a_boolean = true;
let unit = ();
// copy `an_integer` into `copied_integer`
let copied_integer = an_integer;
println!("An integer: {:?}", copied_integer);
println!("A boolean: {:?}", a_boolean);
println!("Meet the unit value: {:?}", unit);
// The compiler warns about unused variable bindings; these warnings can
// be silenced by prefixing the variable name with an underscore
let _unused_variable = 3u32;
let _noisy_unused_variable = 2u32;
// FIXME ^ Prefix with an underscore to suppress the warning
// =====
let _immutable_binding = 1;
let mut mutable_binding = 1;
println!("Before: {}", mutable_binding);
mutable_binding += 1;
println!("After: {}", mutable_binding);
// _immutable_binding += 1;
// =====
let long_lived_binding = 1;
{
let short_lived_binding = 2;
println!("Inner short: {}", short_lived_binding);
// shadow
let long_lived_binding = 5_f32;
println!("inner long: {}", long_lived_binding);
}
// println!("Outer short: {}", short_lived_binding);
println!("Outer long: {}", long_lived_binding);
// shadow
let long_lived_binding = 'a';
println!("Outer long: {}", long_lived_binding);
// ====
let a_binding;
{
let x = 2;
// init
a_binding = x * x;
}
println!("a binding {}", a_binding);
let another_binding;
// println!("another binding: {}", another_binding);
another_binding = 1;
println!("another binding: {}", another_binding);
}
| 6ad8957ee1499a6d1209afd280daca15a257ba9c | [
"Markdown",
"Rust"
] | 5 | Rust | BrianTheArcane/Learning-Rust | 6cf217dd8eb6a19a2cc9e7131be01c3beddbc9b2 | 576dc086b3ea0165aac360b68fa41850551a383a |
refs/heads/master | <file_sep>//<NAME>
//CppHelpers
//https://github.com/Arthur-Golubev/CppHelpers
//
#pragma once
#ifndef TOSTR_HPP
#define TOSTR_HPP
#include <cstdint>
#include <string>
#include <iomanip>
#include <sstream>
namespace AG{
inline std::string ToStr(const std::string value) {
return value;
}
inline std::string ToStr(const unsigned int value) {
return std::to_string(value);
}
inline std::string ToStr(const int64_t value) {
return std::to_string(value);
}
inline std::string ToStr(const char * value) {
return std::string(value);
}
inline std::string ToStr(char * value) {
return std::string(value);
}
inline std::string ToStr(const char ch) {
return (std::string() += ch);
}
template <typename T>
inline std::string ToStr(const T & value);
template<typename ... Args>
inline std::string ToStr(const unsigned int prefix, const Args&... args);
template<typename ... Args>
inline std::string ToStr(const int64_t prefix, const Args&... args);
template<typename... Args>
inline std::string ToStr(const std::string prefix, const Args&... args);
template<typename ... Args>
inline std::string ToStr(const char * prefix, const Args&... args);
template<typename ... Args>
inline std::string ToStr(char ch, const Args&... args);
template<typename T, typename ... Args>
inline std::string ToStr(const T & prefix, const Args&... args);
template <typename T>
inline std::string ToStr(const T & value) {
return std::to_string(value);
}
template<typename ... Args>
inline std::string ToStr(const unsigned int prefix, const Args&... args) {
return std::to_string(prefix) + ToStr(args...);
}
template<typename ... Args>
inline std::string ToStr(const int64_t prefix, const Args&... args) {
return std::to_string(prefix) + ToStr(args...);
}
template<typename... Args>
inline std::string ToStr(const std::string prefix, const Args&... args) {
return prefix + ToStr(args...);
}
template<typename ... Args>
inline std::string ToStr(const char * prefix, const Args&... args) {
return std::string(prefix) + ToStr(args...);
}
template<typename ... Args>
inline std::string ToStr(char ch, const Args&... args) {
return (std::string() += ch) + ToStr(args...);
}
template<typename T, typename ... Args>
inline std::string ToStr(const T & prefix, const Args&... args) {
return std::to_string(prefix) + ToStr(args...);
}
}//namespace AG
#endif //TOSTR_HPP
<file_sep>//<NAME>
//CppHelpers
//https://github.com/Arthur-Golubev/CppHelpers
//
namespace AG{
template<typename DestanationType, typename SourceType>
DestanationType StaticCastWithRangeCheck(SourceType value){
if (value < std::numeric_limits<DestanationType>::min()
|| value > std::numeric_limits<DestanationType>::max())
{
throw std::runtime_error(" out of possible range");
}
return static_cast<DestanationType>(value);
}
} //namespace AG
| a674c002cef4cdda975220e417d30bf3d2a46af1 | [
"C++"
] | 2 | C++ | Arthur-Golubev/CppHelpers | 2b6ac24859049f1de5731eafbbaf508410f0cf07 | 941b1eea4be23517f18214636a54b7c0079b1057 |
refs/heads/master | <repo_name>maiCavalheiro/Temas-Wordpress<file_sep>/template-teste/index.php
<?php get_header(); ?>
<div class="hero-section smaller">
<div class="hero-content-overlay-block w-hidden-small w-hidden-tiny"></div>
<div class="auto-height hero-slider w-slider" data-animation="slide" data-autoplay="1" data-delay="7000" data-duration="600" data-infinite="1" data-ix="show-hero-slider-arrow">
<div class="w-slider-mask">
<div class="_3 hero-slide w-slide">
<div class="hero-slide-overlay padding">
<div class="slide-load-boar">
<div class="slide-load-bar-fill" data-ix="fill-slide-load-bar"></div>
</div>
<div class="container hero-slide-container w-container">
<div class="hero-slide-content-block">
<div class="hero-slide-intro-title" data-ix="slide-title-1">Education & School</div>
<h1 class="hero-slide-title" data-ix="slide-title-2">Showcase courses, events and more!</h1>
<p class="slide-intro-paragraph" data-ix="slide-title-3">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. </p>
<a class="button slider-button w-button" data-ix="slide-title-4" href="/blog">Learn more</a>
</div>
</div>
</div>
</div>
<div class="hero-slide w-slide">
<div class="hero-slide-overlay padding">
<div class="slide-load-boar">
<div class="slide-load-bar-fill" data-ix="fill-slide-load-bar"></div>
</div>
<div class="container hero-slide-container w-container">
<div class="hero-slide-content-block"><div class="hero-slide-intro-title" data-ix="slide-title-1">Education & School</div>
<h1 class="hero-slide-title" data-ix="slide-title-2">School & Education Webflow Template</h1>
<p class="slide-intro-paragraph" data-ix="slide-title-3">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. </p>
<a class="button slider-button w-button" data-ix="slide-title-4" href="/about-us">Learn more</a>
</div>
</div>
</div>
</div>
<div class="_2 hero-slide w-slide">
<div class="hero-slide-overlay padding">
<div class="slide-load-boar">
<div class="slide-load-bar-fill" data-ix="fill-slide-load-bar"></div>
</div>
<div class="container hero-slide-container w-container">
<div class="hero-slide-content-block">
<div class="hero-slide-intro-title" data-ix="slide-title-1">Education & School</div>
<h1 class="hero-slide-title" data-ix="slide-title-2">Easily customize to fit your company</h1>
<p class="slide-intro-paragraph" data-ix="slide-title-3">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. </p>
<a class="button slider-button w-button" data-ix="slide-title-4" href="/pricing">Learn more</a>
</div>
</div>
</div>
</div>
</div>
<div class="hero-slider-button w-hidden-small w-hidden-tiny w-slider-arrow-left" data-ix="hide-slider-arrow">
<div class="w-icon-slider-left"></div>
</div>
<div class="hero-slider-button w-hidden-small w-hidden-tiny w-slider-arrow-right" data-ix="hide-slider-arrow">
<div class="w-icon-slider-right"></div>
</div>
<div class="hero-slider-nav w-hidden-main w-hidden-medium w-round w-slider-nav"></div>
</div>
</div>
<div class="section">
<div class="container w-container">
<div class="section-title-wrapper">
<h2 class="section-title">Featured Courses</h2>
<div class="section-title-divider"></div>
</div>
<div class="w-dyn-list">
<div class="w-clearfix w-dyn-items w-row">
<div class="featured-course-item w-col w-col-3 w-dyn-item">
<div class="course-block-wrapper home-featured">
<a class="course-image-link-block home-featured w-inline-block" href="/courses/beginner-study-english-language" style="background-image: url('https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/573ceb0e663360c6485bfa87_Photo-6.jpg');">
<div class="teacher-overlay-block w-clearfix">
<img class="teacher-overlay-photo" sizes="(max-width: 767px) 40px, (max-width: 991px) 35px, 45px" src="https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5725eb90138ce8c852417aaa_Portrait-19.jpg" srcset="https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5725eb90138ce8c852417aaa_Portrait-19-p-500x.jpeg 500w, https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5725eb90138ce8c852417aaa_Portrait-19-p-800x.jpeg 800w, https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5725eb90138ce8c852417aaa_Portrait-19.jpg 1000w">
<div class="teacher-overlay-title"><NAME></div>
</div>
<div class="image-overlay-block">
<div class="image-overlay-block w-clearfix">
<div class="featured-label">Featured</div>
</div>
</div>
</a>
<div class="course-content-block">
<a class="course-title-link" href="/courses/beginner-study-english-language">Beginner study English language</a>
</div>
<div class="_2 course-content-block">
<div class="course-info-icon"></div>
<div class="course-info-title">25</div>
<div class="course-info-icon"></div>
<div class="course-info-title">2 hours</div>
</div>
</div>
</div>
<div class="featured-course-item w-col w-col-3 w-dyn-item">
<div class="course-block-wrapper home-featured">
<a class="course-image-link-block home-featured w-inline-block" href="/courses/computer-science" style="background-image: url('https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/573ceb16f97dd46d4f9e02f1_Photo-5.jpg');">
<div class="teacher-overlay-block w-clearfix">
<img class="teacher-overlay-photo" src="https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5725b9e4c37897e55d01e712_Testimonial-16.jpg">
<div class="teacher-overlay-title"><NAME></div>
</div>
<div class="image-overlay-block">
<div class="image-overlay-block w-clearfix">
<div class="featured-label">Featured</div>
</div>
</div>
</a>
<div class="course-content-block">
<a class="course-title-link" href="/courses/computer-science">Computer science beginner class</a>
</div>
<div class="_2 course-content-block">
<div class="course-info-icon"></div>
<div class="course-info-title">14</div>
<div class="course-info-icon"></div>
<div class="course-info-title">2h, 30 min.</div>
</div>
</div>
</div>
<div class="featured-course-item w-col w-col-3 w-dyn-item">
<div class="course-block-wrapper home-featured">
<a class="course-image-link-block home-featured w-inline-block" href="/courses/architecture-building-and-planning" style="background-image: url('https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/573ceb05f97dd46d4f9e0220_Photo-1.jpg');"><div class="teacher-overlay-block w-clearfix">
<img class="teacher-overlay-photo" src="https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5724c773639cfa231e77824e_Testimonial-5.jpg">
<div class="teacher-overlay-title"><NAME></div>
</div>
<div class="image-overlay-block">
<div class="image-overlay-block w-clearfix">
<div class="featured-label">Featured</div>
</div>
</div>
</a>
<div class="course-content-block">
<a class="course-title-link" href="/courses/architecture-building-and-planning">Architecture, building and planning</a>
</div>
<div class="_2 course-content-block">
<div class="course-info-icon"></div>
<div class="course-info-title">50</div>
<div class="course-info-icon"></div>
<div class="course-info-title">3 hours</div>
</div>
</div>
</div>
<div class="featured-course-item w-col w-col-3 w-dyn-item">
<div class="course-block-wrapper home-featured">
<a class="course-image-link-block home-featured w-inline-block" href="/courses/politics-philosophy-and-theology" style="background-image: url('https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/573ceb2923185ae1484a4d79_Phoot-6.jpg');">
<div class="teacher-overlay-block w-clearfix">
<img class="teacher-overlay-photo" src="https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5725b9dec37897e55d01e711_Testimonial-17.jpg">
<div class="teacher-overlay-title"><NAME></div>
</div>
<div class="image-overlay-block">
<div class="image-overlay-block w-clearfix">
<div class="featured-label">Featured</div>
</div>
</div>
</a>
<div class="course-content-block">
<a class="course-title-link" href="/courses/politics-philosophy-and-theology">Politics, philosophy and theology</a>
</div>
<div class="_2 course-content-block">
<div class="course-info-icon"></div>
<div class="course-info-title">60</div>
<div class="course-info-icon"></div>
<div class="course-info-title">5 hours</div>
</div>
</div>
</div>
</div>
</div>
<div class="bottom-info-text">Want to see the full list of our Courses?
<a href="/our-courses/courses-grid-view">View Full Courses Overview →</a>
</div>
</div>
</div>
<div class="section tint">
<div class="container w-container">
<div class="w-row">
<div class="news-column-left w-col w-col-6">
<div class="section-title-wrapper">
<h2 class="section-title">Latest News</h2>
<div class="section-title-divider"></div>
</div>
<div class="w-dyn-list">
<div class="w-dyn-items">
<div class="blog-post-item w-dyn-item">
<a class="blog-post-title-link" href="/blog/weve-just-added-2-amazing-new-events-and-2-new-courses">We've just added 2 amazing new events and 2 new courses</a>
<div class="blog-post-info-block">
<div class="course-info-icon"></div>
<div class="blog-info-title">May 1, 2016</div>
<div class="course-info-icon"></div>
<div class="blog-info-title"><NAME></div>
</div>
</div>
<div class="blog-post-item w-dyn-item">
<a class="blog-post-title-link" href="/blog/we-are-looking-for-a-teacher-in-the-it-development">We are looking for a teacher in the IT Development</a>
<div class="blog-post-info-block">
<div class="course-info-icon"></div>
<div class="blog-info-title">May 1, 2016</div>
<div class="course-info-icon"></div>
<div class="blog-info-title"><NAME></div>
</div>
</div>
<div class="blog-post-item w-dyn-item">
<a class="blog-post-title-link" href="/blog/are-we-now-finally-really-going-to-mars-in-the-year-2017">Are we now finally, really going to Mars in the year 2017?</a>
<div class="blog-post-info-block">
<div class="course-info-icon"></div>
<div class="blog-info-title">May 1, 2016</div>
<div class="course-info-icon"></div>
<div class="blog-info-title"><NAME></div>
</div>
</div>
<div class="blog-post-item w-dyn-item">
<a class="blog-post-title-link" href="/blog/new-horizons-team-proposes-new-world-to-explore">New Horizons team proposes new world to explore</a>
<div class="blog-post-info-block">
<div class="course-info-icon"></div>
<div class="blog-info-title">May 1, 2016</div>
<div class="course-info-icon"></div>
<div class="blog-info-title"><NAME></div>
</div>
</div>
</div>
</div>
<div class="bottom-info-text">Want to read more? <a href="/blog">View Full Blog Archive →</a></div>
</div>
<div class="about-column-right w-col w-col-6">
<div class="section-title-wrapper">
<h2 class="section-title">About our School</h2>
<div class="section-title-divider"></div>
</div>
<a class="video-lightbox w-inline-block w-lightbox" href="#">
<div class="about-image-block"><div class="lightbox-overlay-block">
<div class="overlay-lightbox-icon"></div>
</div>
</div>
<script class="w-json" type="application/json">{ "items": [{
"type": "video",
"html": "<iframe class=\"embedly-embed\" src=\"https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAYAHkql75qM%3Fautoplay%3D1%26feature%3Doembed&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAYAHkql75qM&image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAYAHkql75qM%2Fhqdefault.jpg&key=c4e54deccf4d4ec997a64902e9a30300&autoplay=1&type=text%2Fhtml&schema=youtube\" width=\"940\" height=\"528\" scrolling=\"no\" frameborder=\"0\" allowfullscreen></iframe>",
"thumbnailUrl": "https://i.embed.ly/1/image?url=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAYAHkql75qM%2Fhqdefault.jpg&key=866738f8f18b4394a18e371517a66ae0",
"width": 940,
"height": 528,
"url": "http://www.youtube.com/watch?v=AYAHkql75qM"
}] }</script>
</a>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. Duis cursus, mi quis viverra ornare, eros dolor interdum nulla, ut commodo diam libero.</p>
<a class="link-below-paragraph" href="/about-us">Learn more →</a>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container w-container">
<div class="section-title-wrapper">
<h2 class="section-title">Upcoming Events</h2>
<h2 class="section-title subtitle">Morbi accumsan ipsum velit. Nam nec tellus</h2>
<div class="section-title-divider"></div>
</div>
<div class="upcoming-events-list-wrapper w-dyn-list">
<div class="w-dyn-items">
<div class="event-item w-dyn-item">
<a class="event-image-block w-inline-block" style="background-image: url('https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/573ceb3ff97dd46d4f9e02f9_Photo-3.jpg');" href="/events/how-to-become-a-freelancer">
<div class="event-date-block w-clearfix">
<div class="event-date-title">30</div>
<div class="event-date-title month">April</div>
<div class="event-date-title month">2016</div>
</div>
</a>
<div class="event-info-block">
<a class="event-title-link" href="/events/how-to-become-a-freelancer">How to become a Freelancer</a>
<div class="event-info-wrapper"><div class="course-info-icon"></div>
<div class="event-info-title">April 30, 2016</div>
<div class="course-info-icon"></div>
<div class="event-info-title">4:00 AM</div>
<div class="event-info-title">-</div>
<div class="event-info-title">7:00 PM</div>
</div>
<div class="event-info-wrapper">
<div class="course-info-icon"></div>
<div class="event-info-title">Berlin</div>
</div>
<a class="button events-learn-more w-button" href="/events/how-to-become-a-freelancer">Learn more</a>
</div>
</div>
<div class="event-item w-dyn-item">
<a class="event-image-block w-inline-block" style="background-image: url('https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/573ceb0e663360c6485bfa87_Photo-6.jpg');" href="/events/emmanuel-nunes-viola-music">
<div class="event-date-block w-clearfix">
<div class="event-date-title">19</div>
<div class="event-date-title month">May</div>
<div class="event-date-title month">2016</div>
</div>
</a>
<div class="event-info-block">
<a class="event-title-link" href="/events/emmanuel-nunes-viola-music"><NAME>: Viola Music</a>
<div class="event-info-wrapper">
<div class="course-info-icon"></div>
<div class="event-info-title">May 19, 2016</div>
<div class="course-info-icon"></div>
<div class="event-info-title">4:00 AM</div>
<div class="event-info-title">-</div>
<div class="event-info-title">7:00 PM</div>
</div>
<div class="event-info-wrapper">
<div class="course-info-icon"></div>
<div class="event-info-title">Amsterdam</div>
</div>
<a class="button events-learn-more w-button" href="/events/emmanuel-nunes-viola-music">Learn more</a></div></div><div class="event-item w-dyn-item">
<a class="event-image-block w-inline-block" style="background-image: url('https://daks2k3a4ib2z.cloudfront.net/5724c55c9134bc281e3f6a7c/5724ca282f3e6fea5d007221_City-4.jpg');" href="/events/2016-polar-prediction-workshop">
<div class="event-date-block w-clearfix">
<div class="event-date-title">16</div>
<div class="event-date-title month">June</div>
<div class="event-date-title month">2016</div>
</div></a>
<div class="event-info-block">
<a class="event-title-link" href="/events/2016-polar-prediction-workshop">2016 Polar Prediction Workshop</a>
<div class="event-info-wrapper">
<div class="course-info-icon"></div>
<div class="event-info-title">June 16, 2016</div>
<div class="course-info-icon"></div>
<div class="event-info-title">4:00 AM</div>
<div class="event-info-title">-</div>
<div class="event-info-title">7:00 PM</div>
</div>
<div class="event-info-wrapper">
<div class="course-info-icon"></div>
<div class="event-info-title">Chicago</div>
</div>
<a class="button events-learn-more w-button" href="/events/2016-polar-prediction-workshop">Learn more</a>
</div>
</div>
</div>
</div>
<div class="bottom-info-text">Want to see the full list of upcoming Events? <a href="/events">View Full Events Overview →</a></div>
</div>
</div>
<?php get_sidebar(); ?>
</div>
<?php get_footer(); ?><file_sep>/template-teste/header.php
<!DOCTYPE html><!-- This site was created in Webflow. http://www.webflow.com--><!-- Last Published: Mon Sep 12 2016 06:31:38 GMT+0000 (UTC) --><html data-wf-domain="template-university.webflow.io" data-wf-page="57278920639cfa231e7a9578" data-wf-site="571cab5c86c1049c4c0e7047">
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>>
<title><?php wp_title(''); ?></title>
<meta content="Template University - Webflow Responsive Website Template" name="description">
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta content="Webflow" name="generator">
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script>
<script type="text/javascript">WebFont.load({
google: {
families: ["Source Sans Pro:200,300,regular,italic,600,700,900"]
}
});</script>
<script src="https://daks2k3a4ib2z.cloudfront.net/0globals/modernizr-2.7.1.js" type="text/javascript"></script>
<link href="https://daks2k3a4ib2z.cloudfront.net/571cab5c86c1049c4c0e7047/572660eb138ce8c8524203a9_Favicon.png" rel="shortcut icon" type="image/x-icon">
<link href="https://daks2k3a4ib2z.cloudfront.net/571cab5c86c1049c4c0e7047/572660ed9134bc281e40be6a_Webclip.png" rel="apple-touch-icon">
</head>
<body>
<div class="header-wrapper">
<div class="top-navbar w-nav" data-animation="default" data-collapse="none" data-contain="1" data-duration="400">
<div class="w-container">
<nav class="top-nav-menu w-nav-menu" role="navigation">
<a class="top-nav-link w-inline-block" href="#">
<div class="icon top-nav-title"></div>
<div class="top-nav-title">+1 303 4020 43</div></a>
<a class="top-nav-link w-inline-block" href="#">
<div class="icon top-nav-title"></div>
<div class="top-nav-title"><EMAIL></div></a></nav>
<div class="top-bar-text w-hidden-small w-hidden-tiny">Weekly new courses!</div>
<a class="top-bar-link w-hidden-small w-hidden-tiny" href="/our-courses/courses-featured">View Featured Courses →</a>
<div class="w-nav-button">
<div class="w-icon-nav-menu"></div>
</div>
</div>
</div>
<div class="navbar w-nav" data-animation="over-right" data-collapse="medium" data-contain="1" data-doc-height="1" data-duration="400">
<div class="w-container">
<a class="logo-block w-nav-brand" href="/"><img class="image-logo" sizes="(max-width: 479px) 93vw, (max-width: 767px) 171.109375px, (max-width: 991px) 192.5px, 235.28125px" src="http://uploads.webflow.com/571cab5c86c1049c4c0e7047/5725f0639134bc281e403428_Logo.jpg" srcset="http://uploads.webflow.com/571cab5c86c1049c4c0e7047/5725f0639134bc281e403428_Logo-p-500x117.jpeg 500w, http://uploads.webflow.com/571cab5c86c1049c4c0e7047/5725f0639134bc281e403428_Logo.jpg 800w"></a>
<nav class="nav-menu w-nav-menu" role="navigation">
<div class="dropdown w-dropdown" data-delay="0" data-hover="1">
<div class="dropdown-toggle nav-link w-dropdown-toggle">
<div>Homepage</div>
<div class="dropdown-icon w-icon-dropdown-toggle"></div>
</div>
<nav class="dropdown-list w-dropdown-list">
<a class="dropdown-link w-dropdown-link" href="/">Homepage #1</a>
<a class="dropdown-link w-dropdown-link" href="/home-2">Homepage #2</a>
<a class="dropdown-link w-dropdown-link" href="/home-3">Homepage #3</a>
</nav>
</div>
<div class="dropdown w-dropdown" data-delay="0" data-hover="1">
<div class="dropdown-toggle nav-link w-dropdown-toggle">
<div>Courses</div>
<div class="dropdown-icon w-icon-dropdown-toggle"></div>
</div><nav class="dropdown-list w-dropdown-list">
<a class="dropdown-link w-dropdown-link" href="/our-courses/categories">Categories</a>
<a class="dropdown-link w-dropdown-link" href="/our-courses/courses-listview">Courses (List View)</a>
<a class="dropdown-link w-dropdown-link" href="/our-courses/courses-grid-view">Courses (Grid View)</a>
<a class="dropdown-link w-dropdown-link" href="/our-courses/courses-featured">Featured Courses</a>
</nav>
</div>
<div class="dropdown w-dropdown" data-delay="0" data-hover="1">
<div class="dropdown-toggle nav-link w-dropdown-toggle">
<div>Information</div>
<div class="dropdown-icon w-icon-dropdown-toggle"></div>
</div>
<nav class="dropdown-list w-dropdown-list">
<a class="dropdown-link w-dropdown-link" href="/about-us">About us</a>
<a class="dropdown-link w-dropdown-link" href="/teachers">Our Teachers</a>
<a class="dropdown-link w-dropdown-link" href="/pricing">Pricing Information</a>
</nav>
</div>
<a class="nav-link w-nav-link" href="/events">Events</a>
<a class="nav-link w-nav-link" href="/blog">Blog</a>
<a class="nav-link w-nav-link" href="/faqs">FAQs</a>
<a class="nav-link w-nav-link" href="/contact-us">Contact us</a>
</nav>
<div class="menu-button w-nav-button">
<div class="w-icon-nav-menu"></div>
</div>
</div>
</div>
</div> | 29a28af6c41eee5f398e0b76852503ae56e52f5f | [
"PHP"
] | 2 | PHP | maiCavalheiro/Temas-Wordpress | 8ce51cc12eae399f470a5f982d42c187b19cd41a | d3658a7f5cbdcf9668b1822fe8e13c501173e552 |
refs/heads/master | <repo_name>no111u3/stm32f7x7-hal<file_sep>/Cargo.toml
[package]
name = "stm32f7x7-hal"
version = "0.2.1"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
categories = ["embedded", "hardware-support", "no-std"]
description = "HAL for the STM32F7x7 familiy of microcontrollers"
keywords = ["arm", "cortex-m", "stm32", "stm32f767", "hal"]
license = "Apache-2.0"
repository = "https://github.com/no111u3/stm32f7x7-hal"
documentation = "https://docs.rs/stm32f7x7-hal"
readme = "README.md"
[dependencies]
cortex-m-rt = "0.6.7"
nb = "0.1.1"
[dependencies.cortex-m]
features = ["const-fn"]
version = "0.6.0"
[dependencies.stm32f7]
features = ["stm32f7x7"]
version = "0.7.0"
[dependencies.void]
default-features = false
version = "1.0.2"
[dependencies.cast]
default-features = false
version = "0.2.2"
[dependencies.embedded-hal]
features = ["unproven"]
version = "0.2.2"
[features]
rt = ["stm32f7/rt"]
<file_sep>/src/lib.rs
#![no_std]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(deprecated)]
pub use embedded_hal as hal;
pub use stm32f7::stm32f7x7 as stm32;
pub use nb;
pub use nb::block;
#[cfg(feature = "rt")]
pub use crate::stm32::interrupt;
pub mod adc;
pub mod delay;
pub mod gpio;
pub mod i2c;
pub mod prelude;
pub mod qei;
pub mod rcc;
pub mod serial;
pub mod signature;
pub mod spi;
pub mod time;
pub mod timer;
pub mod watchdog;
| 21b7e9cf0519fbdfabf8dd6370d06cde34b4bdee | [
"TOML",
"Rust"
] | 2 | TOML | no111u3/stm32f7x7-hal | 85bdab12e8f2a7d543c91cdab41754ba0b27cab0 | 06cd5dcb6bfa6d904963573504003bd572a6f29e |
refs/heads/main | <file_sep>const express = require('express');
const router = express.Router();
const Post = require('../models/post');
const blogDb = require('../data/blogDb');
// home page
router.get('/', function (req, res) {
// paimti index.ejs faila is views direktorijos
res.render('index', {
title: 'Home',
page: 'home',
});
});
// about page
router.get('/about', function (req, res) {
res.render('about', {
title: 'About us',
page: 'about',
});
});
// blog page
router.get('/blog', function (req, res) {
// parsisiusti duomenis is db
Post.find()
.then((posts) => {
res.render('blog/blog', {
title: 'Our blog',
page: 'blog',
posts,
});
})
.catch((err) => console.error(err.message));
});
// contact page
router.get('/contact', function (req, res) {
res.render('contact', {
title: 'Contact us',
page: 'contact',
});
});
// create blog page /blog/create
// contact page
router.get('/blog/create', function (req, res) {
res.render('blog/createBlog', {
title: 'Create new Post',
page: 'createB',
});
});
// Single page route
router.get('/single/:id', (req, res) => {
const blogId = req.params.id;
Post.findById(blogId)
.then((foundPost) => {
res.render('blog/singlePage', {
title: 'Post about ...',
page: 'single',
post: foundPost,
});
})
// redirect if not found
.catch((err) => res.redirect('/blog'));
});
// GET /single/edit/:id renderina singlePageEdit.ejs
router.get('/single/edit/:id', (req, res) => {
const blogId = req.params.id;
Post.findById(blogId)
.then((foundPost) => {
console.log(' foundPost', foundPost);
res.render('blog/singlePageEdit', {
title: 'Post about ...',
page: 'single_edit',
post: foundPost,
});
})
// redirect if not found
.catch((err) => res.redirect('/blog'));
});
// singlePageEdit.ejs kuris yra kopija singlePage.ejs
// tik su ivesties laukais
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const Owner = require('../models/owner');
router.get('/', (req, res) => {
// was there a delete
console.log(' req.query', req.query);
const feedback = req.query;
// get all owners from db
Owner.find()
.sort({ createdAt: -1 })
.then((found) => {
// generate list items with owners name and email
res.render('owners/index', {
title: 'Owners',
page: 'owners',
owners: found,
feedback,
});
})
.catch((err) => console.error(err));
// pass owners to view
});
// get single owner
router.get('/single/:id', (req, res) => {
// find by id
Owner.findById(req.params.id)
.then((found) => {
res.render('owners/single', {
title: 'Single',
page: 'single_owner',
found,
});
})
.catch((err) => console.error(err));
});
// formos parodymo route
router.get('/new', (req, res) => {
res.render('owners/new', {
title: 'Add owner',
page: 'owners_new',
});
});
// formos apdorojimo routas
router.post('/new', (req, res) => {
console.log(' req.body', req.body);
const newOwner = new Owner(req.body);
newOwner
.save()
.then((result) => {
res.redirect('/owners?msg=created&name=' + result.name);
})
.catch((err) => res.send('Opps did not save', err));
});
// delete form
router.post('/delete/:id', (req, res) => {
Owner.findByIdAndDelete(req.params.id)
.then((result) => res.redirect('/owners?msg=deleted&name=' + result.name))
.catch((err) => res.send(`delete failed ${err}`));
});
module.exports = router;
| 4ed20e5489ac887af4ac873741fdbc1863d57cc2 | [
"JavaScript"
] | 2 | JavaScript | andriusdulevicius/fullstack-crud-app-oficiali | 0912c1165b5f844d0e9264c7523828230895ae2d | 26deda92f611816c4fb8bc72494e3e5b7964eaa9 |
refs/heads/master | <repo_name>zyedManai/blockchainjs<file_sep>/jsBlockchain.ts
import SHA256 from "crypto-js/sha256"
class Block {
index:number
timestamp:string
data:any
previousHash:string
hash:string
constructor(index:number,timestamp:string,data:any,previousHash=''){
this.index = index
this.timestamp = timestamp
this.data = data
this.previousHash = previousHash
this.hash = this.calculateHash()
}
calculateHash (){
return SHA256(this.index.toString()+this.timestamp+this.previousHash+JSON.stringify(this.data)).toString();
}
}
class BlockChain{
chain : Block[]
constructor(){
this.chain = [this.createGenesisBlock()]
}
createGenesisBlock(){
return new Block (0,"01/01/2020","this is the genesis block","0")
}
getLatestBlock(){
return this.chain[this.chain.length-1]
}
addBlock(newBlock:Block){
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash()
this.chain.push(newBlock)
}
}
//creating 2 blocks
let block1 = new Block(1,"01/01/2020",{myBalance : 100})
let block2 = new Block(1,"02/01/2020",{myBalance : 200})
//creating a new chaine
let myBlockChaine = new BlockChain()
myBlockChaine.addBlock(block1)
myBlockChaine.addBlock(block2)
console.log(JSON.stringify(myBlockChaine,null,4))<file_sep>/jsBlockchain.js
const SHA256 = require ("crypto-js/sha256");
class Block {
constructor(index,timestamp,data,previousHash=''){
this.index = index
this.timestamp = timestamp
this.data = data
this.previousHash = previousHash
this.hash = this.calculateHash()
this.nonce = 0
}
calculateHash (){
return SHA256(this.index.toString()+this.timestamp+this.previousHash+JSON.stringify(this.data)+this.nonce).toString();
}
mineNewBlock (difficulty){
while(this.hash.substring(0,difficulty)!==Array(difficulty+1).join("0")){
this.nonce++
this.hash = this.calculateHash()
}
console.log("a new blog was mined with hash", this.hash)
}
}
class BlockChain{
constructor(){
this.chain = [this.createGenesisBlock()]
this.difficulty=7
}
createGenesisBlock(){
return new Block (0,"01/01/2020","this is the genesis block","0")
}
getLatestBlock(){
return this.chain[this.chain.length-1]
}
addBlock(newBlock){
newBlock.previousHash = this.getLatestBlock().hash;
//newBlock.hash = newBlock.calculateHash()
newBlock.mineNewBlock(this.difficulty)
this.chain.push(newBlock)
}
checkBlockValid(){
for (var i=1; i<this.chain.length; i++){
var currentBlock = this.chain[i]
var previousBlock = this.chain[i-1]
if(currentBlock.previousHash!=previousBlock.calculateHash()){
return false
}
}
return true
}
}
//creating 2 blocks
let block1 = new Block(1,"01/01/2020",{myBalance : 100})
let block2 = new Block(1,"02/01/2020",{myBalance : 200})
//creating a new chaine
let myBlockChaine = new BlockChain()
myBlockChaine.addBlock(block1)
myBlockChaine.addBlock(block2)
/*console.log(JSON.stringify(myBlockChaine,null,4))
console.log("Validity ",myBlockChaine.checkBlockValid())
myBlockChaine.chain[1].data = {myBalance : 1000}
console.log("Validity ",myBlockChaine.checkBlockValid())*/ | 84c3bc21ede9f9533da2b1c8ef74fbe96d1270f5 | [
"JavaScript",
"TypeScript"
] | 2 | TypeScript | zyedManai/blockchainjs | 4d29e4d01fe22952db27da755a0720d7ef40f87c | 61e9e9758c12be69377af1ed3e0d927751e7d34c |
refs/heads/master | <file_sep>require 'open-uri'
require 'json'
class ForecastsController < ApplicationController
def location
the_address = params[:address]
# Address to Coords
url_safe_address = URI.encode(the_address)
url_of_data_we_want = "http://maps.googleapis.com/maps/api/geocode/json?address="
url = url_of_data_we_want + url_safe_address
raw_data = open(url).read
parsed_data = JSON.parse(raw_data)
the_latitude = parsed_data["results"][0]["geometry"]["location"]["lat"]
the_longitude = parsed_data["results"][0]["geometry"]["location"]["lng"]
# Coords to Weather
url_of_weather_we_want = "https://api.forecast.io/forecast/a432dda20e513555718f2527e386944c/#{the_latitude},#{the_longitude}"
raw_weather = open(url_of_weather_we_want).read
parsed_weather = JSON.parse(raw_weather)
the_temperature = parsed_weather["currently"]["temperature"]
the_hour_outlook = parsed_weather["hourly"]["data"][1]["summary"]
the_day_outlook = parsed_weather["daily"]["data"][1]["summary"]
@address = the_address
@temperature = the_temperature
@hourly = the_hour_outlook
@day = the_day_outlook
end
end
| 7bdbbacccd2b9f83dede9fe12dd361e286073c52 | [
"Ruby"
] | 1 | Ruby | jaywlee/rails_api_project | 6869f69169707e82917c2f9040b648012f09bfcd | 44d8dcec1f481b7652963200ee778a9da06004d9 |
refs/heads/master | <repo_name>carloschfa/SwiftMongoDBApollo<file_sep>/Database/app/AppDelegate.swift
//
// Copyright (c) 2018 Related Code - http://relatedcode.com
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Apollo
#warning("Change the endpoint before running the project.")
let graphQLEndpoint = "http://172.16.58.3:3000/graphql"
let apollo: ApolloClient = {
let configuration = URLSessionConfiguration.default
let wsEndpointURL = URL(string: "ws://172.16.58.3:3000/graphql")!
let endpointURL = URL(string: graphQLEndpoint)!
let websocket = WebSocketTransport(request: URLRequest(url: wsEndpointURL), connectingPayload: nil)
let splitNetworkTransport = SplitNetworkTransport(
httpNetworkTransport: HTTPNetworkTransport(
url: endpointURL
),
webSocketNetworkTransport: websocket
)
return ApolloClient(networkTransport: splitNetworkTransport)
}()
//-------------------------------------------------------------------------------------------------------------------------------------------------
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var testView: TestView!
//---------------------------------------------------------------------------------------------------------------------------------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
//-----------------------------------------------------------------------------------------------------------------------------------------
// UI initialization
//-----------------------------------------------------------------------------------------------------------------------------------------
window = UIWindow(frame: UIScreen.main.bounds)
testView = TestView(nibName: "TestView", bundle: nil)
let navController = UINavigationController(rootViewController: testView)
window?.rootViewController = navController
window?.makeKeyAndVisible()
return true
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func applicationDidEnterBackground(_ application: UIApplication) {
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func applicationWillEnterForeground(_ application: UIApplication) {
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func applicationDidBecomeActive(_ application: UIApplication) {
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func applicationWillTerminate(_ application: UIApplication) {
}
}
<file_sep>/Database/Podfile
platform :ios, '12.4'
use_frameworks!
target 'app' do
pod 'Apollo'
pod "Apollo/WebSocket"
end
<file_sep>/README.md
# DemoDatabase
DemoDatabase
| 6b9fcc7f4a9bbe2cba77a75781a34aca0ea26c4a | [
"Swift",
"Ruby",
"Markdown"
] | 3 | Swift | carloschfa/SwiftMongoDBApollo | 33fee59947036073cd9f378dc986f6cde4d41500 | 260c7c3f2639500899d5cce85d7d003426efa53c |
refs/heads/master | <file_sep>package it.unibo.buttonLed.interfaces;
public interface IShow {
public void print(boolean on);
}
<file_sep>/**
*
*/
Observable =function(){
this.k = 0;
this.observerFunc = [ ];
this.observer = [ ];
this.register = function(obs){
//println(" Observable register " + this.k + " " + func);
this.observerFunc[this.k++] = func;
}
this.notify = function(){
for (var i=0;i< this.observer.length;i++){
//println("Observable update" + this.observer[i]);
this.observer[i].update();
}
for (var i=0;i< this.observerFunc.length;i++){
//println("Observable calls" + this.observerFunc[i]);
this.observerFunc[i]();
}
}
}
}<file_sep>package it.unibo.buttonLed.interfaces;
public interface IButtonListener {
public void onButtonPressed();
}
<file_sep>package it.unibo.buttonLed.impl;
import it.unibo.buttonLed.interfaces.IButton;
import it.unibo.buttonLed.interfaces.IButtonListener;
public class ButtonImpl implements IButton{
private IButtonListener listener;
public ButtonImpl(IButtonListener listener){
this.listener = listener;
}
@Override
public void pressed(){
listener.onButtonPressed();
}
}
<file_sep>/**
*
*/
function Button ( name ){
this.name = name;
}
Button.prototype = new Observable();
//Button.prototype.constructor = Button
Button.prototype.press = function(){
this.notify // va a richiamare la funzione di observable sopra
}
//EXPORTS
if (typeof document == "undefined")
module.exports.Button = Button;<file_sep>var Led = function(name, guiId){
//Led constructor: instance data
this.name = name;
this.guiId = guiId;
this.ledState = false;
}
//Methods (shared)
/*
Led.prototype.turnOn = function(){
this.ledState = true;
}
Led.prototype.turnOff = function(){
this.ledState = false;
}
*/
Led.prototype.switchState = function(){
this.ledState = ! this.ledState;
}
Led.prototype.getState = function(){
return this.ledState;
}
/*
Led.prototype.getName = function(){
return this.name;
}
Led.prototype.getDefaultRep = function(){
return this.name+"||"+ this.ledState;
}
Led.prototype.showGuiRep = function(){
if (typeof document != "undefined"){
if (this.ledState) document.getElementById(this.guiId).style.backgroundColor='#00FF33';
else document.getElementById(this.guiId).style.backgroundColor='#FF0000';
}
else println ( this.getDefaultRep());
}
println = function(){
try{
if ( typeof document != "undefined" ) showMsg('outView', v+"<br/>");
else console.log(v);
}catch(e){
console.log(v);
}
}
*/
//EXPORTS
if (typeof document == "undefined") module.exports.Led = Led;
//To work in (was is) a browser do: browserify Led.js -o LedBro.js<file_sep>/* Generated by AN DISI Unibo */
/*
This code is generated only ONCE
*/
package it.unibo.mycontrol;
import it.unibo.is.interfaces.IOutputEnvView;
import it.unibo.qactors.QActorContext;
public class Mycontrol extends AbstractMycontrol {
private long score;
private long startTime;
public Mycontrol(String actorId, QActorContext myCtx, IOutputEnvView outEnvView ) throws Exception{
super(actorId, myCtx, outEnvView);
}
public void controlLogic(String cmd){
//quando il bottone viene premuto controlla che il led corrispondente sia acceso
}
public void saveStartTime(){
startTime = System.currentTimeMillis();
}
public long updateScore(){
score += 5000 - (System.currentTimeMillis() - startTime);
return score;
}
public long printScore(){
System.out.println(score);
return score;
}
public void resetScore(){
score = 0;
}
}
<file_sep>package it.unibo.buttonLed.impl;
import it.unibo.buttonLed.interfaces.ILed;
public class LedImpl implements ILed {
private boolean state;
//constructor
public LedImpl(){
state = false;
}
public void turnOn(){
state = true;
}
public void turnOff(){
state = true;
}
public boolean isOn(){
return state;
}
}
<file_sep>package it.unibo.buttonLed.impl;
import java.awt.Color;
import javax.swing.JComponent;
import it.unibo.buttonLed.interfaces.IShow;
public class ShowSwing implements IShow {
/*
* Questo e' solo un componente swing da
* colorare che svolge la funzione di led
*/
private JComponent led;
public ShowSwing(JComponent led){
this.led = led;
}
public void print(boolean on) {
if(on) led.setBackground(Color.RED);
else led.setBackground(null);
}
}
<file_sep>package it.unibo.buttonLed.impl;
import it.unibo.buttonLed.interfaces.IShow;
public class ShowConsole implements IShow {
public void print(boolean on){
System.out.println("Led is "+(on?"ON":"OFF"));
}
}
<file_sep>
function Button (name) {
this.name = name;
}
Button.prototype = require("./Observable");
//Button.prototype.constructor = Button;
Button.prototype.press = function(){
this.notify();
}
//Exports
if(typeof document == "undefined") module.exports.Button = Button;
<file_sep>#Wed Jul 26 10:20:57 CEST 2017
org.eclipse.core.runtime=2
org.eclipse.platform=4.6.2.v20161124-1400
| 0f7e15838d8f1d9a6a0d2d2dc31de63f3c576c07 | [
"JavaScript",
"Java",
"INI"
] | 12 | Java | Mikelainz/ISS | a65c18371cfab81d2bfae300134d44fdb599c6fe | 0d1fb7deee1c7e090c5ea8f53727f1033f6808bc |
refs/heads/master | <repo_name>NRDRNR/Lesson2<file_sep>/learn-homework-1/for2.py
def ask_user():
dialog = {'Как дела?': 'Хорошо!', 'Что делаешь?': 'Программирую'}
user_say = input('Введите вопрос ')
if user_say in dialog.keys():
print(dialog.get(user_say))
else:
print('Не знаю')
if __name__ == "__main__":
for _ in range(10):
ask_user()
<file_sep>/learn-homework-1/for.py
"""
Домашнее задание №1
Цикл for: Оценки
* Создать список из словарей с оценками учеников разных классов
школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...]
* Посчитать и вывести средний балл по всей школе.
* Посчитать и вывести средний балл по каждому классу.
"""
def main():
data_storage = [{'school_class': '4a', 'scores': [3, 4, 4, 5, 2, 3, 5]},
{'school_class': '4b', 'scores': [3, 2, 2, 5, 2, 5]},
{'school_class': '5a', 'scores': [3, 4, 5, 5, 2, 2]},
{'school_class': '4b', 'scores': [5, 4, 2, 5, 2]},
{'school_class': '6a', 'scores': [4, 4, 4, 3, 5, 2, 2]},
{'school_class': '6b', 'scores': [3, 3, 5, 5]}]
classes_grade = {item['school_class']:(sum(item['scores'])/len(item['scores'])) for item in data_storage}
school_grade = sum(classes_grade.values()) / len(classes_grade.values())
print("School summary grade is " + '{:.2f}'.format(school_grade))
print("Class summary grade are:")
for name_class, grade_class in classes_grade.items():
print("{}: {:.2f}".format(name_class,grade_class))
if __name__ == "__main__":
main()
<file_sep>/learn-homework-1/if2.py
"""
Домашнее задание №1
Условный оператор: Сравнение строк
* Написать функцию, которая принимает на вход две строки
* Проверить, является ли то, что передано функции, строками.
Если нет - вернуть 0
* Если строки одинаковые, вернуть 1
* Если строки разные и первая длиннее, вернуть 2
* Если строки разные и вторая строка 'learn', возвращает 3
* Вызвать функцию несколько раз, передавая ей разные праметры
и выводя на экран результаты
"""
def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
a = input('Введите первую строку ')
b = input('Введите вторую строку ')
if type(a)==str and type(b)==str :
if len(a)==len(b):
return(1)
elif len(a) > len(b):
return(2)
elif len(a) != len(b) and b == 'learn':
return(3)
else:
return ('Ошибка')
compare = main()
if __name__ == "__main__":
print(compare)
<file_sep>/learn-homework-1/if1.py
"""
Домашнее задание №1
Условный оператор: Возраст
* Попросить пользователя ввести возраст при помощи input и положить
результат в переменную
* Написать функцию, которая по возрасту определит, чем должен заниматься пользователь:
учиться в детском саду, школе, ВУЗе или работать
* Вызвать функцию, передав ей возраст пользователя и положить результат
работы функции в переменную
* Вывести содержимое переменной на экран
"""
age = int(input('Введите Ваш возраст: '))
def main(age):
if 0 < age < 90:
if age >= 65:
return('Не, ну надеюсь они с пенсией больше ничего не придумают...')
elif age >= 23:
return('В офис завтра')
elif age >= 17:
return('Первую пару не проспи')
elif age >= 6:
return('Иди спать, завтра в школу')
elif age >= 2:
return('Детсад')
elif age < 2:
return('Мелкота')
else:
print('Вы мне возраст введите, а не число от балды')
return ('Не введён возраст')
age_test = main(age)
if __name__ == "__main__":
print(age_test)
| 731ecb09f0b52ce8012ebdba5670a5d30e64d612 | [
"Python"
] | 4 | Python | NRDRNR/Lesson2 | 8266a114dd20a314f81c9ed2cf5cd7b0f7e552cb | 60c02a49af3ebfd28d3cd6626454fcdb400dd837 |
refs/heads/master | <file_sep>#Reading all the three (twitter, blogs and news)files
Data_blog <- readLines("en_US.blogs.txt",skipNul = TRUE, warn = TRUE)
#Data_news <- readLines("~/Data Science Capstone/Predict_Next_Word/en_US.news.txt",skipNul = TRUE, warn = TRUE)
Data_twitter <- readLines("en_US.twitter.txt",skipNul = TRUE, warn = TRUE)
library(ggplot2)
library(NLP)
library(tm)
library(RWeka)
library(data.table)
library(dplyr)
#Taking sample from the files
set.seed(1234)
sample_size =800
sample_blog <- Data_blog[sample(1:length(Data_blog),sample_size)]
#sample_news <- Data_news[sample(1:length(Data_news),sample_size)]
sample_twitter <- Data_twitter[sample(1:length(Data_twitter),sample_size)]
sample_data<-rbind(sample_blog,sample_twitter)
rm(Data_blog,Data_twitter)
#Removing unwanted parts from sample data
Corpus_form <- VCorpus(VectorSource(sample_data))
# Converting to lowercase
Corpus_form <- tm_map(Corpus_form, content_transformer(tolower))
# Removing all the punctuation
Corpus_form <- tm_map(Corpus_form, removePunctuation)
# Removing all the numbers
Corpus_form <- tm_map(Corpus_form, removeNumbers)
# Removing all the multiple whitespace
Corpus_form <- tm_map(Corpus_form, stripWhitespace)
# Adjusting the space
Space_form <- content_transformer(function(x, pattern) gsub(pattern, " ", x))
Corpus_form <- tm_map(Corpus_form, Space_form, "/|@|\\|")
#WordCloud
#library(wordcloud)
#wordcloud(Corpus_form, max.words = 100, random.order = FALSE,rot.per=0.45,
#use.r.layout=FALSE,colors=brewer.pal(8, "Dark2"))
# Formation of tokenizer
Unigram_tokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 1, max = 1))
Bigram_tokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 2, max = 2))
Trigram_tokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 3, max = 3))
Fourgram_tokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 4, max = 4))
One_token <- NGramTokenizer(Corpus_form, Weka_control(min = 1, max = 1))
One_gram <- TermDocumentMatrix(Corpus_form, control = list(tokenize = Unigram_tokenizer))
Two_gram <- TermDocumentMatrix(Corpus_form, control = list(tokenize = Bigram_tokenizer))
Three_gram <- TermDocumentMatrix(Corpus_form, control = list(tokenize = Trigram_tokenizer))
Four_gram <- TermDocumentMatrix(Corpus_form, control = list(tokenize = Fourgram_tokenizer))
# Creating Frequency for (uni,bi,tri and fourgram)
Frequency_1 <- findFreqTerms(One_gram, lowfreq = 5)
Frequency_gm1 <- rowSums(as.matrix(One_gram[Frequency_1,]))
Frequency_gm1 <- data.frame(unigram=names(Frequency_gm1), frequency=Frequency_gm1)
Frequency_gm1 <- Frequency_gm1[order(-Frequency_gm1$frequency),]
Unigram_Frequency <- setDT(Frequency_gm1)
save(Unigram_Frequency,file="unigram.Rda")
Frequency_2 <- findFreqTerms(Two_gram, lowfreq = 3)
Frequency_gm2 <- rowSums(as.matrix(Two_gram[Frequency_2,]))
Frequency_gm2 <- data.frame(bigram=names(Frequency_gm2), frequency=Frequency_gm2)
Frequency_gm2 <- Frequency_gm2[order(-Frequency_gm2$frequency),]
Bigram_Frequency <- setDT(Frequency_gm2)
save(Bigram_Frequency,file="bigram.Rda")
Frequency_3 <- findFreqTerms(Three_gram, lowfreq = 2)
Frequency_gm3 <- rowSums(as.matrix(Three_gram[Frequency_3,]))
Frequency_gm3 <- data.frame(trigram=names(Frequency_gm3), frequency=Frequency_gm3)
Trigram_Frequency <- setDT(Frequency_gm3)
save(Trigram_Frequency,file="trigram.Rda")
Frequency_4 <- findFreqTerms(Four_gram, lowfreq = 1)
Frequency_gm4 <- rowSums(as.matrix(Four_gram[Frequency_4,]))
Frequency_gm4 <- data.frame(fourgram=names(Frequency_gm4), frequency=Frequency_gm4)
Fourgram_Frequency <- setDT(Frequency_gm4)
save(Fourgram_Frequency,file="fourgram.Rda")
<file_sep>#
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
shinyUI(fluidPage(titlePanel("Next Word Prediction Application: Data Science Capstone Project"),
hr(),
tags$head(tags$style(
HTML('
#mainpanel {
#background-color: #A6DAF7;
}'))),
#mainPanel(
#plotOutput("Plot", width = "50%",height = "200px")
# ),
fluidPage(
mainPanel(
h3("Introduction:"),
h5("Type your word/phrase and predict the next word"),
h3("Algorithm:"),
h5("Used N-Gram algorithm"),
textInput("Tcir",label=h3("Type your word/phrase here:")),
submitButton('Predict'),
h4('word/phrase you entered : '),
verbatimTextOutput("inputValue"),
h4('next word :'),
verbatimTextOutput("prediction")
)
)))<file_sep>#
# This is the server logic of a Shiny web application. You can run the
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(NLP)
library(tm)
library(RWeka)
#library(rsconnect)
#library(data.table)
#library(dplyr)
#library(wordcloud)
source("NLP_Programe.R")
shinyServer(function(input, output) {
output$inputValue <- renderPrint({input$Tcir})
output$prediction <- renderPrint({Wordform(input$Tcir)})
#output$Plot <- renderPlot({
#wordcloud(Corpus_form, max.words = 100, random.order = FALSE,rot.per=0.45,
# use.r.layout=FALSE,colors=brewer.pal(8, "Dark2"))}
#)
}) | 35f7533aef5f34c2719b45eff67db253fb5c2ff9 | [
"R"
] | 3 | R | rezyananya/Capstone_Project | 4ec6ddb37903e93ecbc09885b7afc7604b01f076 | 5afb753c9a9fcfe3fb0cc9220c5d16ac1d20fc6b |
refs/heads/master | <repo_name>TastyCooler/Game<file_sep>/Jammers/Assets/Scripts/Henry progress/DropOff.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DropOff : MonoBehaviour, IDropHandler {
// Reference to DragAndDrop script
DragAndDrop drop;
<<<<<<< HEAD
<<<<<<< HEAD
// Need to save location to set it back when someone put another object on Table
[HideInInspector] public Transform returnObject;
private bool occupied = false;
=======
// Toggle on to let only one object on parent object(Inventory or Table)
public bool oneObjectOnly = false;
// Toggle on to let more object on parent object(Inventory or Table)
public bool moreThenOneObject = false;
// Parent Object(Inventory or Table) is occupied
private bool accessOnObject = true;
#endregion
>>>>>>> 53914b9ed0336459f2cef0763d9951550df597d7
=======
>>>>>>> parent of 53914b9... DragDrop enhanced
public void OnDrop(PointerEventData eventData)
{
drop = eventData.pointerDrag.GetComponent<DragAndDrop>();
<<<<<<< HEAD
<<<<<<< HEAD
// verify if the ray/pointer hits something
if (drop != null)
{
returnObject = drop.returnToParent;
// Parent canves object to parent position(Table)
drop.returnToParent = transform;
=======
// Look if parent position(Table) is occupied
if (accessOnObject)
{
// Let objects placeable on parent object(Inventory)
if (moreThenOneObject)
{
if (drop != null)
{
// place object on parent position(Inventory)
drop.returnToParent = transform;
}
}
// Look if theres already an child object in the parent object(Table)
if (transform.childCount < 1)
{
oneObjectOnly = true;
}
// Let and object droppable and prohibit to drop anything if theres something
if (oneObjectOnly)
{
// Verify if there is an parent position(Table) to drop it off
if (drop != null)
{
// place object on parent position(Table)
drop.returnToParent = transform;
oneObjectOnly = false;
}
}
>>>>>>> 53914b9ed0336459f2cef0763d9951550df597d7
=======
if(drop != null)
{
drop.returnToParent = this.transform;
>>>>>>> parent of 53914b9... DragDrop enhanced
}
}
}
<file_sep>/Jammers/Assets/Scripts/Henry progress/DragAndDrop.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragAndDrop : MonoBehaviour, IBeginDragHandler, IDragHandler,IEndDragHandler {
#region Fields
// Need to save the parent position(Inventory) of the object to set it back
[HideInInspector] public Transform returnToParent;
// Need to unblock raycast when dragging a canves object
private bool blockRay;
#endregion
/// <summary>
/// Comparable with Start() function, stuff it needs to do before dragging an canves object
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
// Saving parent position(Inventory) where it came from
returnToParent = this.transform.parent;
// Set object out of parent position(Inventory), however, still in canves
this.transform.SetParent(this.transform.parent.parent);
// Stop canves object from blocking the raycast coming from mouse
blockRay = false;
GetComponent<CanvasGroup>().blocksRaycasts = blockRay;
}
/// <summary>
/// Holding mouse 0 on the canves object will parent it to mouse
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
// Set canves object to mouseposition
this.transform.position = eventData.position;
}
/// <summary>
/// Release canves object will parent it back to initially parent position(Inventory)
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
// Set position back to parent position(Inventory)
this.transform.SetParent(returnToParent);
// Enable canves object to block raycast
blockRay = true;
GetComponent<CanvasGroup>().blocksRaycasts = blockRay;
}
}
| c73f985a54f3f66e38f9f2a2eb1cfe41c59803e0 | [
"C#"
] | 2 | C# | TastyCooler/Game | b88d09c13c9699ecf3da2fd11497e5d970ce8e37 | 018e03781d80c25e006677f8cb66d0f797d9b70a |
refs/heads/master | <repo_name>isaaclimdc/mojave-server<file_sep>/app/routes/api.js
// =============================================================================
// MOJAVE API ==================================================================
// =============================================================================
var BUCKET_NAME = 'mojave';
var SERVER_NAME = 'https://s3-us-west-1.amazonaws.com';
var User = require('../models/userModel');
var Album = require('../models/albumModel');
var Asset = require('../models/assetModel');
var fs = require('fs');
var im = require('imagemagick');
var async = require('async');
function apiPath(arg) { return '/api'+arg; }
function albumPath(albumID) { return 'albums/'+albumID; }
function assetPaths(albumID, assetID) {
var pre = 'albums/' + albumID;
var file = assetID + '.jpg'; //TODO: Support other filetypes
return { thumb : pre + '/thumb/' + file,
full : pre + '/full/' + file };
}
function assetURL(remotePath) {
return SERVER_NAME + '/' + BUCKET_NAME + '/' + remotePath;
}
function makeAsset(assetID, thumb, full) {
return { 'assetID' : assetID, 'thumbURL' : thumb, 'fullURL' : full};
}
function getExt(filename) {
return "jpg"; //TODO: Support other filetypes
// var a = filename.split('.');
// if (a.length === 1 || (a[0] === '' && a.length === 2))
// return '';
// return a.pop().toLowerCase();
}
module.exports = function(app, s3) {
// USER ======================================================================
// Get user object with userID
app.get(apiPath('/user/:userID'), function (req, res) {
User.findById(req.params.userID, function (err, user) {
if (err) return sendIntErr('User not found.', err, res);
return res.json(user);
});
});
// ALBUM =====================================================================
// Get album object with albumID
app.get(apiPath('/album/:albumID'), function (req, res) {
var albumID = req.params.albumID;
Album.findById(albumID, function (err, album) {
if (err) return sendIntErr('Album not found', err, res);
async.each(album.assets, function (asset, callback) {
var remotePaths = assetPaths(albumID, asset.assetID);
getSignedURLs(remotePaths, function (urls) {
asset.thumbURL = urls.thumb;
asset.fullURL = urls.full;
callback(); // Means this async call is done.
});
}, function (err) {
if (err) return sendIntErr('Could not update album assets', err, res);
return res.json(album); // All iterators are done, send back album!
});
});
});
// Get album cover URL with albumID
app.get(apiPath('/album/:albumID/cover'), function (req, res) {
var albumID = req.params.albumID;
Album.findById(albumID, function (err, album) {
if (err) return sendIntErr('Album not found', err, res);
var coverIdx = album.coverAsset;
var coverAsset = album.assets[coverIdx];
// If album is empty, send null. Let client handle it
if (!coverAsset) {
return res.json(null);
}
if (coverAsset.thumbURL) {
return res.json(coverAsset.thumbURL);
}
else {
var remotePaths = assetPaths(albumID, coverAsset.assetID);
getSignedURL(remotePaths.thumb, function (thumbURL) {
return res.json(thumbURL);
});
}
});
});
// Create a new album
app.post(apiPath('/album/new'), function (req, res) {
var currentUser = req.user;
var title = req.body.title;
var collabs = req.body.collabs ? req.body.collabs : [];
// Validate fields
if (title.length == 0)
return sendBadReq('Title cannot be empty', res);
collabs.forEach(function (userID) {
if (!currentUser.friends.contains(userID))
return sendBadReq('You must be friends with the colloborators', res);
});
// Add current user to collabs
collabs.unshift(currentUser._id);
// Create database entry so we have the new albumID
var newAlbum = new Album();
newAlbum.users = collabs;
newAlbum.assets = [];
newAlbum.coverAsset = 0; // Default to the first asset (if exists)
newAlbum.title = title;
newAlbum.save(function(err, album) {
if (err) return sendIntErr('Could not save album', err, res);
async.each(collabs, function (userID, callback) {
// Update user's album list with new albumID
User.findById(userID, function (err, user) {
if (err) return sendIntErr('User not found', err, res);
user.albums.push(album._id); // Add to the back
user.save(function (err, user) {
if (err) return sendIntErr('Could not save user', err, res);
callback(); // Means this async call is done.
});
});
}, function (err) {
if (err) return sendIntErr('Could not update collabs', err, res);
return res.send(200); // All iterators are done, send "OK"!
});
});
});
// Upload photo
app.post(apiPath('/album/:albumID/upload'), function (req, res, next) {
// Prepare file upload
var fileName = req.files.newImage.name;
var localPath = req.files.newImage.path;
var albumID = req.params.albumID;
var fileType = getExt(fileName);
// Validate fields
// Protect against empty form submission.
if (!fileName) return sendBadReq('No image selected for upload', res);
// Create database entry so we have the assetID
var newAsset = new Asset();
newAsset.fileType = fileType;
newAsset.owner = req.user._id;
// Find album we're uploading to
Album.findById(albumID, function (err, album) {
if (err) return sendIntErr('Album not found', err, res);
if (!album.collabs.contains(req.user._id))
return sendBadReq('You must be a colloborator to upload photos', res);
newAsset.save(function (err, asset) {
if (err) return sendIntErr('Could not save asset', err, res);
// Append to the album's list of assets
var assetID = asset._id;
album.assets.push(makeAsset(assetID, null, null));
album.save(function (err, album) {
if (err) return sendIntErr('Could not save album', err, res);
// Prepare upload
var remotePaths = assetPaths(albumID, assetID);
var params = {
Bucket: BUCKET_NAME,
ContentType: 'image/jpeg',
};
// Upload thumbnail and full image to S3 __in parallel__
async.parallel([
// THUMBNAIL
function (callback) {
// Resize image into thumbnail, save locally
var tmpLocalPath = localPath+'thumb';
im.resize({ srcPath: localPath, dstPath: tmpLocalPath, width: 200 },
function (err) {
if (err) return sendIntErr('Could not create image thumbnail', err, res);
console.log('Resized image to width of 200px!');
// Read in local thumbnail image
fs.readFile(tmpLocalPath, function (err, data) {
if (err) return sendIntErr('Could not read file', err, res);
// Send thumbnail to S3
params.Body = data;
params.Key = remotePaths.thumb;
s3.client.putObject(params, function (err, ETag) {
if (err) return sendIntErr('Could not upload thumbnail', err, res);
console.log('Successfully uploaded thumbnail!');
callback();
});
});
});
},
// FULL IMAGE
function (callback) {
// In the background, upload full image to S3, don't respond.
fs.readFile(localPath, function (err, data) {
if (err) return sendIntErr('Could not read file', err, res);
params.Body = data;
params.Key = remotePaths.full;
s3.client.putObject(params, function (err, ETag) {
if (err) return sendIntErr('Could not upload image', err, res);
console.log('Successfully uploaded full image!');
callback();
});
});
}
],
// BOTH DONE!
function (err, results) {
console.log('Uploaded both thumbnail and full image!');
return res.send(200);
});
});
});
});
});
// // Get photo
// app.get(apiPath('/album/:albumID/:assetID'), function (req, res) {
// var albumID = req.params.albumID;
// var assetID = req.params.assetID;
// // Get signed URLs from S3
// var remotePaths = assetPaths(albumID, assetID);
// getSignedURLs(remotePaths, function (urls) {
// console.log("Image URLs are:", urls);
// return res.json(urls);
// });
// });
// HELPERS ===================================================================
// Send an internal server error (500)
function sendIntErr(responseText, err, res) {
return res.send(400, responseText+'. '+err);
}
function sendBadReq(responseText, res) {
return res.send(500, responseText);
}
// TODO: Optimize by not calling .getSignedUrl every time.
function getSignedURL(remotePath, success) {
var params = { Bucket: BUCKET_NAME, Key: remotePath };
s3.getSignedUrl('getObject', params, function (err, signedURL) {
if (err) throw err;
success(signedURL);
});
}
function getSignedURLs(remotePaths, success) {
getSignedURL(remotePaths.thumb, function (thumbURL) {
getSignedURL(remotePaths.full, function (fullURL) {
success({ thumb : thumbURL, full : fullURL });
});
});
}
Array.prototype.contains = function(obj) {
return this.indexOf(obj) != -1;
}
};
<file_sep>/app/routes/pages.js
// =============================================================================
// PAGES =======================================================================
// =============================================================================
module.exports = function(app, passport) {
// Home (with login)
app.get('/', function(req, res) {
if (req.isAuthenticated()) {
res.redirect('/albums');
}
else {
res.render('index.ejs');
}
});
// Authentication: Facebook login
app.get('/auth', passport.authenticate('facebook', { scope : 'email' }));
app.get('/auth/callback',
passport.authenticate('facebook', {
successRedirect : '/albums',
failureRedirect : '/'
}));
// Albums
app.get('/albums', isLoggedIn, function(req, res) {
res.render('albums.ejs', {
user : req.user
});
});
// Single Album
app.get('/albums/:albumID', isLoggedIn, function(req, res) {
res.render('singleAlbum.ejs', {
albumID : req.params.albumID
});
});
// Profile - login access only
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user
});
});
// Logout
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
};
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't, redirect them to home
res.redirect('/');
}
<file_sep>/public/js/singleAlbum.js
$(document).ready(function() {
$('input[type=file]').bootstrapFileInput();
$('.file-inputs').bootstrapFileInput();
$('.fancybox').fancybox();
$('#newImageForm').submit(submitNewImg);
loadAlbum();
});
function submitNewImg(e) {
e.preventDefault();
var table = $('.albumTable');
var albumID = table.attr('id');
$.ajax({
url: '/api/album/'+albumID+'/upload',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
location.reload();
},
error: function(err) {
console.error("Error:", err.responseText);
}
});
}
function loadAlbum() {
var table = $('.albumTable');
var albumID = table.attr('id');
console.log("Loading album:", albumID);
// Fetch album
$.ajax({
url: '/api/album/'+albumID,
type: 'GET',
success: function(album) {
// Load title
$('#singleAlbumTitle').text(album.title);
// Load assets
album.assets.forEach(function (asset) {
var div = $('<div>');
div.attr('class', 'col-md-4 albumCell');
var a = $('<a>');
a.attr('class', 'fancybox');
a.attr('rel', 'group');
a.attr('href', asset.fullURL);
var img = $('<img>');
img.attr('src', asset.thumbURL);
a.append(img);
div.append(a);
table.prepend(div);
});
},
error: function(err) {
console.error("Error:", err.responseText);
}
});
}<file_sep>/app/models/userModel.js
// =============================================================================
// USER MODEL ==================================================================
// =============================================================================
var mongoose = require('mongoose');
var UserSchema = mongoose.Schema({
fbID : Number, // Facebook ID (!= _id)
email : String,
firstName : String,
lastName : String,
picture : String, // URL of picture from Facebook
fbToken : String,
friends : [mongoose.Schema.Types.ObjectId], // Array of userID
albums : [mongoose.Schema.Types.ObjectId], // Array of albumID
currentAlbum : mongoose.Schema.Types.ObjectId, // albumID
appPrefs : {
syncOnData : Boolean,
syncOnBattery : Boolean
}
});
module.exports = mongoose.model('User', UserSchema);
<file_sep>/config/aws.js
module.exports = function(AWS) {
AWS.config.update({region: 'us-west-1'});
};
<file_sep>/config/database.js
module.exports = {
'url' : 'mongodb://admin:mojaveAdmin@kahana.mongohq.com:10006/app26022801'
};<file_sep>/app/models/albumModel.js
// =============================================================================
// ALBUM MODEL =================================================================
// =============================================================================
var mongoose = require('mongoose');
var AlbumSchema = mongoose.Schema({
collabs : [mongoose.Schema.Types.ObjectId], // Array of userIDs
assets : [{ // TODO: Make this and AssetSchema the same thing
assetID : mongoose.Schema.Types.ObjectId,
thumbURL : String,
fullURL : String
}],
coverAsset : Number, // Index into assets array
title : String // Album title
});
module.exports = mongoose.model('Album', AlbumSchema);
| 136e6e42e91684fb1a94168b2c1fc6d9502892fc | [
"JavaScript"
] | 7 | JavaScript | isaaclimdc/mojave-server | 52da77304ac5e856a62f5f4f4ff9589e49dd05bd | d3ba42b3651f9890864abcb5f0534dfca7c5249e |
refs/heads/master | <file_sep>var PEEP_METADATA = {
tft: {frame:0, color:"#4089DD"},
all_d: {frame:1, color:"#52537F"},
all_c: {frame:2, color:"#FF75FF"},
grudge: {frame:3, color:"#efc701"},
prober: {frame:4, color:"#f6b24c"},
tf2t: {frame:5, color:"#88A8CE"},
pavlov: {frame:6, color:"#86C448"},
random: {frame:7, color:"#FF5E5E"}
};
var PD = {};
PD.COOPERATE = "COOPERATE";
PD.CHEAT = "CHEAT";
PD.PAYOFFS_DEFAULT = {
P: 0, // punishment: neither of you get anything
S: -1, // sucker: you put in coin, other didn't.
R: 2, // reward: you both put 1 coin in, both got 3 back
T: 3 // temptation: you put no coin, got 3 coins anyway
};
PD.PAYOFFS = JSON.parse(JSON.stringify(PD.PAYOFFS_DEFAULT));
subscribe("pd/editPayoffs", function(payoffs){
PD.PAYOFFS = payoffs;
});
subscribe("pd/editPayoffs/P", function(value){ PD.PAYOFFS.P = value; });
subscribe("pd/editPayoffs/S", function(value){ PD.PAYOFFS.S = value; });
subscribe("pd/editPayoffs/R", function(value){ PD.PAYOFFS.R = value; });
subscribe("pd/editPayoffs/T", function(value){ PD.PAYOFFS.T = value; });
subscribe("pd/defaultPayoffs", function(){
PD.PAYOFFS = JSON.parse(JSON.stringify(PD.PAYOFFS_DEFAULT));
publish("pd/editPayoffs/P", [PD.PAYOFFS.P]);
publish("pd/editPayoffs/S", [PD.PAYOFFS.S]);
publish("pd/editPayoffs/R", [PD.PAYOFFS.R]);
publish("pd/editPayoffs/T", [PD.PAYOFFS.T]);
});
PD.NOISE = 0;
subscribe("rules/noise",function(value){
PD.NOISE = value;
});
PD.getPayoffs = function(move1, move2){
var payoffs = PD.PAYOFFS;
if(move1==PD.CHEAT && move2==PD.CHEAT) return [payoffs.P, payoffs.P]; // both punished
if(move1==PD.COOPERATE && move2==PD.CHEAT) return [payoffs.S, payoffs.T]; // sucker - temptation
if(move1==PD.CHEAT && move2==PD.COOPERATE) return [payoffs.T, payoffs.S]; // temptation - sucker
if(move1==PD.COOPERATE && move2==PD.COOPERATE) return [payoffs.R, payoffs.R]; // both rewarded
};
PD.playOneGame = function(playerA, playerB){
// Make your moves!
var A = playerA.play();
var B = playerB.play();
// Noise: random mistakes, flip around!
if(Math.random()<PD.NOISE) A = ((A==PD.COOPERATE) ? PD.CHEAT : PD.COOPERATE);
if(Math.random()<PD.NOISE) B = ((B==PD.COOPERATE) ? PD.CHEAT : PD.COOPERATE);
// Get payoffs
var payoffs = PD.getPayoffs(A,B);
// Remember own & other's moves (or mistakes)
playerA.remember(A, B);
playerB.remember(B, A);
// Add to scores (only in tournament?)
playerA.addPayoff(payoffs[0]);
playerB.addPayoff(payoffs[1]);
// Return the payoffs...
return payoffs;
};
PD.playRepeatedGame = function(playerA, playerB, turns){
// I've never met you before, let's pretend
playerA.resetLogic();
playerB.resetLogic();
// Play N turns
var scores = {
totalA:0,
totalB:0,
payoffs:[]
};
for(var i=0; i<turns; i++){
var p = PD.playOneGame(playerA, playerB);
scores.payoffs.push(p);
scores.totalA += p[0];
scores.totalB += p[1];
}
// Return the scores...
return scores;
};
PD.playOneTournament = function(agents, turns){
// Reset everyone's coins
for(var i=0; i<agents.length; i++){
agents[i].resetCoins();
}
// Round robin!
for(var i=0; i<agents.length; i++){
var playerA = agents[i];
for(var j=i+1; j<agents.length; j++){
var playerB = agents[j];
PD.playRepeatedGame(playerA, playerB, turns);
}
}
};
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
function Logic_tft(){
var self = this;
var otherMove = PD.COOPERATE;
var roundCounter = 1;
self.play = function(){
if(roundCounter<100){
return otherMove;
}else{
return PD.CHEAT;
}
};
self.remember = function(own, other){
otherMove = other;
roundCounter++;
};
}
function Logic_tf2t(){
var self = this;
var myLastMove = PD.COOPERATE;
self.play = function(){
return myLastMove;
};
self.remember = function(own, other){
myLastMove = own; // remember MISTAKEN move
if(other==PD.COOPERATE) myLastMove = ((myLastMove==PD.COOPERATE) ? PD.CHEAT : PD.COOPERATE); // switch!
};
}
function Logic_grudge(){//Pecl
var self = this;
var othersMoves = [];
var roundCounter = 1;
self.play = function(){
if(roundCounter <=2){
return PD.COOPERATE;
}else if(2 < roundCounter && roundCounter < 6){
if(othersMoves.includes(PD.COOPERATE)){
return PD.COOPERATE;
}else{
return PD.CHEAT;
}
}else if(5 < roundCounter && roundCounter < 11){
othersMovesSecondSeries = [];
for(i=2;i<othersMoves.length;i++){
othersMovesSecondSeries.push(othersMoves[i]);
}
if(othersMovesSecondSeries.includes(PD.COOPERATE)){
return PD.COOPERATE;
}else{
return PD.CHEAT;
}
}else if(10 < roundCounter && roundCounter < 21){
console.log(4);
console.log(roundCounter + 200);
var CooperateWithMe = 0;
for(i=0;i<othersMoves.length;i++){
if(othersMoves[i]==PD.COOPERATE){
CooperateWithMe++;
}}
if(CooperateWithMe>6){
return PD.COOPERATE;
}else{
return othersMoves[othersMoves.length - 1];
}
}else if(20 < roundCounter){
console.log(5);
console.log(roundCounter + 200);
var CooperateWithMe = 0;
for(i=0;i<othersMoves.length;i++){
if(othersMoves[i]==PD.COOPERATE){
CooperateWithMe++;
}}
if(CooperateWithMe>0.7*roundCounter){
if(othersMoves[othersMoves.length - 1] == PD.CHEAT && othersMoves[othersMoves.length - 2] == PD.CHEAT){
return PD.CHEAT;
}else{
return PD.COOPERATE;
}
}else if(0.3*roundCounter < CooperateWithMe <= roundCounter){
return othersMoves[othersMoves.length - 1];
}else{
return PD.CHEAT;
}
}
};
self.remember = function(own, other){
othersMoves.push(other);
roundCounter++;
};
}
function Logic_all_d(){
var self = this;
var otherMove = PD.COOPERATE;
var probability = 0.5;
var step = 0;
self.play = function(){
var rnd = Math.random();
if (rnd < probability){
return PD.COOPERATE;
}else{
return PD.CHEAT;
}
};
self.remember = function(own, other){
if(other == PD.CHEAT){
step--;
}else{
step++;
}
probability += Math.sign(step)*Math.pow(0.5, Math.abs(step))*0.5;
console.log(probability);
};
}
function Logic_all_c(){
var self = this;
var otherMove = PD.COOPERATE;
var roundCounter = 1;
self.play = function(){
if(roundCounter<100){
return otherMove;
}else{
return PD.CHEAT;
}
};
self.remember = function(own, other){
otherMove = other;
roundCounter++;
};
}
function Logic_random(){
var self = this;
var everHeatedMe = 0;
self.play = function(){
if(everHeatedMe==1){
return (Math.random()>0.75 ? PD.COOPERATE : PD.CHEAT);
}else if(everHeatedMe == 0){
return PD.COOPERATE;
}else{
return PD.CHEAT;
}
};
self.remember = function(own, other){
if(other == PD.CHEAT){
everHeatedMe++;
}
};
}
// Start off Cooperating
// Then, if opponent cooperated, repeat past move. otherwise, switch.
function Logic_pavlov(){
var self = this;
self.play = function(){
return PD.COOPERATE;
};
self.remember = function(own, other){
// nah
};
}
// TEST by Cooperate | Cheat | Cooperate | Cooperate
// If EVER retaliates, keep playing TFT
// If NEVER retaliates, switch to ALWAYS DEFECT
function Logic_prober(){
var self = this;
var otherMove = PD.COOPERATE;
var moves = [PD.COOPERATE, PD.COOPERATE, PD.CHEAT, PD.COOPERATE, otherMove, PD.COOPERATE, otherMove, PD.COOPERATE, PD.COOPERATE];
var roundCounter = 1;
var howManyTimesCheated = 0;
self.play = function(){
round15 = roundCounter - 1 % 15;
if(round15 < 9){
return moves[round15];
}else{
if(howManyTimesCheated>=2){
return PD.CHEAT; // retaliate ONLY after two betrayals
}else{
return PD.COOPERATE;
}
}return PD.COOPERATE
};
self.remember = function(own, other){
if(other==PD.CHEAT){
howManyTimesCheated++;
}else{
howManyTimesCheated = 0;
}
otherMove = other;
roundCounter++;
};
}
| b4ada0e8ddf696b90b6c0e598bb7575d783c1715 | [
"JavaScript"
] | 1 | JavaScript | aidam38/aidam38.github.io | f37247e4edf958e9f658357de6ae448b2e1cf4c8 | ea33449965c1eaff8f964871f7f532ad1da8276f |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
var utils = require('../utils/utils');
var firebase = require('../services/firebase');
router.post('/', function (req, res, next) {
var user = firebase.auth().currentUser;
if (user) {
var listBody = req.body;
console.log('Creating list');
var userRef = firebase.database().ref(user.uid).push();
var key = userRef.key;
userRef.set({
name: listBody.name,
due_date: listBody.due
})
.then(function (data) {
res.status(201).json({ 'key': key });
})
.catch(function (error) {
res.status(500).json(utils.createErrorResponse('List could not be saved'));
});
} else {
res.status(500).json(utils.createErrorResponse('No user session available'));
}
});
module.exports = router;
<file_sep>
function createErrorResponse(message) {
var dict = {};
if (message.errmsg) {
dict.error = message.errmsg;
} else if (message.error_message) {
dict.error = message.error_message;
} else if (message.message) {
dict.error = message.message;
} else {
dict.error = message;
}
dict.details = fixErrorStack(new Error().stack);
// return JSON.parse(JSON.stringify(dict));
return dict;
}
function fixErrorStack(stack) {
if (stack) {
var firstIndex = stack.indexOf('\n');
var secondIndex = stack.indexOf('\n', firstIndex + 1);
var fixedStack = stack.substring(secondIndex);
return 'Error\n' + fixedStack.trim();
}
}
module.exports = {
createErrorResponse: createErrorResponse
};
<file_sep>var express = require('express');
var router = express.Router();
var utils = require('../utils/utils');
var firebase = require('../services/firebase');
router.post('/:listId', function (req, res, next) {
var user = firebase.auth().currentUser;
if (user) {
var listId = req.params.listId;
var itemBody = req.body;
var path = user.uid + '/' + listId;
var listRef = firebase.database().ref(path).push();
var key = listRef.key;
listRef.set({
name: itemBody.name,
presentation: itemBody.presentation,
pending: true,
amount: itemBody.amount
})
.then(function (data) {
res.status(201).json({ 'key': key });
})
.catch(function (error) {
res.status(500).json(utils.createErrorResponse('Item could not be saved under ' + path));
});
} else {
res.status(500).json(utils.createErrorResponse('No user session available'));
}
});
module.exports = router;
<file_sep>var gulp = require('gulp');
var getRepoInfo = require('git-repo-info');
var replace = require("gulp-replace");
gulp.task('update-index', function () {
var info = getRepoInfo();
return gulp.src(['templates/layout.pug'])
.pipe(replace('RP_VERSION', info.abbreviatedSha))
.pipe(replace('RP_DATE', info.committerDate))
.pipe(gulp.dest('views/'));
}); | f8cfe000c72745e8f858b2d45dcf6350b87da734 | [
"JavaScript"
] | 4 | JavaScript | cainlara/groshop-fe | 76d7aa00dc2adfd23418aa371fbcce85aefc1874 | 0a4b7f813d7db42a656369d2078b1d1b8d8d80b4 |
refs/heads/master | <repo_name>ducpham2476/IMAGE_CALIBRATION_V2<file_sep>/infoGUI.py
# Import required libraries
import os
import ctypes
import cv2
import io
from PIL import Image, ImageTk
# Get native screen resolution, times the ratio for native compatible resolution, avoid bleeding edges
def get_scr_size(ratio):
user32 = ctypes.windll.user32 # ctypes function
scr_size = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) # ctypes function, returns a list of parameters
scr_width = scr_size[0]
scr_height = scr_size[1]
width = int(scr_width * ratio) # get width*ratio, for later GUI scaling
height = int(scr_height * ratio) # get height*ratio, for later GUI scaling
return width, height
# Draw a grid on to the image, using an overlay image of grid
# Could use an another approach, using PySimpleGUI graphing functions since images are shown on graph-based canvas
def gui_draw(parent_path, file_name):
# Draw a guidance grid onto the image
img = cv2.imread(file_name)
# Avoid using static addresses
# Use this instead, but be cautious :
# grid_img = cv2.imread(os.getcwd() + "\\data_process\\ref_image\\imGrid.png")
# Make sure the working files are in the right positions before use
grid_img = cv2.imread(parent_path + "\\data_process\\grid_img\\imGrid.png")
### Debug: show Grid image
# cv2.imshow("Image", grid_img)
# cv2.waitKey()
rows, cols, channel = grid_img.shape
roi = img[0:rows, 0:cols]
# Add grid to the selected reference image
img2gray = cv2.cvtColor(grid_img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 200, 255, cv2.THRESH_BINARY_INV)
mask_inv = cv2.bitwise_not(mask)
img = cv2.bitwise_and(roi, roi, mask=mask_inv)
grid_img_fg = cv2.bitwise_and(grid_img, grid_img, mask=mask)
img = cv2.add(img, grid_img_fg)
# Get file name, write the image with grid. This will be used in later processing
name = os.path.splitext(file_name)[0]+"_grid.jpg"
# Avoid using static addresses
# Use this instead, but be cautious:
# file_path = os.path.join(os.getcwd()+"\\data_process\\ref_image", name)
file_path = os.path.join(os.getcwd() + "\\data_process\\ref_image", name)
cv2.imwrite(file_path, img)
return file_path
# Convert image data to base64 values, for later drawing on graph canvas
def get_img_data(f, max_size, first=False):
img = Image.open(f)
img.thumbnail(max_size, resample=Image.BICUBIC)
if first:
b_io = io.BytesIO()
img.save(b_io, format="PNG")
del img
return b_io.getvalue()
return ImageTk.PhotoImage(img)
<file_sep>/myTranslation.py
# Import required libraries
import os
import numpy as np
import cv2
import imutils
import datetime
# Define my image calibration algorithm
# Get parent path
parent_path = os.getcwd()
### Debug: get Parent path
# print(parent_path)
# Initiate threshold values, for later image processing (contour recognition based on color)
im_lower = np.array([20, 75, 75], dtype="uint8")
im_upper = np.array([35, 255, 255], dtype="uint8")
kernel = np.ones((3, 3), np.uint8)
# Coordinates corresponding to landmarks
ref_x = [] # Reference landmark coordinates, x axis
ref_y = [] # Reference landmark coordinates, y axis
cur_x = [] # Current landmark coordinates, x axis
cur_y = [] # Current landmark coordinates, y axis
for k in range(0, 5): # Initiate above lists
ref_x.append(0)
ref_y.append(0)
cur_x.append(0)
cur_y.append(0)
# Open parking lot information files - landmark
def info_open_slot(park_lot_name):
file_flag = 0
coord = []
f_slot = open(parent_path + "\\data_process\\{}\\park_lot_info\\slot.txt".format(park_lot_name), 'r')
if os.stat(parent_path + "\\data_process\\{}\\park_lot_info\\slot.txt".format(park_lot_name)).st_size == 0:
# print('Landmark file has no value, please run Define Parking Slot')
file_flag = 1
else:
lis = [line.split() for line in f_slot]
n = len(lis[0])
file_length = len(lis)
for j in range(n):
temp_array = []
for i in range(file_length):
temp_array.append(int(lis[i][j]))
coord.append(temp_array)
return file_flag, coord
def info_open(park_lot_name):
global ref_x, ref_y
file_flag = 0
### Bad coding practice, avoid using static addresses! Try using environment variables instead to prevent machine
### specific errors!
f_landmark = open(parent_path + "\\data_process\\{}\\park_lot_info\\landmark.txt".format(park_lot_name), 'r+')
if os.stat(parent_path + "\\data_process\\{}\\park_lot_info\\landmark.txt".format(park_lot_name)).st_size == 0:
# print('Landmark file has no value, please run Define Parking Slot')
file_flag = 1
else:
# Appending values from file to a list, then add to above ref list
lis = [line.split() for line in f_landmark]
coord = []
n = len(lis[0])
file_length = len(lis)
for j in range(n):
temp_array = []
for i in range(file_length):
temp_array.append(int(lis[i][j]))
coord.append(temp_array)
### Debug:
# print(coord)
ref_x[1] = coord[1][0]
ref_y[1] = coord[2][0]
ref_x[2] = coord[1][1]
ref_y[2] = coord[2][1]
ref_x[3] = coord[1][2]
ref_y[3] = coord[2][2]
ref_x[4] = coord[1][3]
ref_y[4] = coord[2][3]
return file_flag, ref_x, ref_y
# Recognize landmarks available on the input image!
def landmark_recog(filename):
# Value indicates how many contour available at desired landmark positions. Best value = 1
# Initiate values
cur_1 = 0 # Landmark 1
cur_2 = 0 # Landmark 2
cur_3 = 0 # Landmark 3
cur_4 = 0 # Landmark 4
# Input image, create binary mask for contour recognition
img = cv2.imread(filename)
### Debug:
# print(img)
# cv2.imshow("Check image", img)
# cv2.waitKey()
img_copy = img.copy()
im_hsv = cv2.cvtColor(img_copy, cv2.COLOR_BGR2HSV)
im_mask = cv2.inRange(im_hsv, im_lower, im_upper)
im_mask = cv2.morphologyEx(im_mask, cv2.MORPH_OPEN, kernel)
### Debug:
# cv2.imshow("Test landmark_recog", im_mask)
# cv2.waitKey(1000)
# Finding contours available on image
cur_cnt, _ = cv2.findContours(im_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Mapping contours found with desired landmarks, comparing parameters
for c in cur_cnt:
# Define contour bounding box
x, y, w, h = cv2.boundingRect(c)
# Defined range for landmark 1
if (210 < (x + (w // 2)) < 770) and (250 < (y + (h // 2)) < 720) and (15 < w < 70) and (7 < h < 60):
cur_x[1] = x + (w // 2)
cur_y[1] = y + (h // 2)
cur_1 = cur_1 + 1
# Defined range for landmarks 2
elif (880 < (x + (w // 2)) < 1430) and (260 < (y + (h // 2)) < 750) and (15 < w < 70) and (7 < h < 60):
cur_x[2] = x + (w // 2)
cur_y[2] = y + (h // 2)
cur_2 = cur_2 + 1
# Defined range for landmarks 3
elif (30 < (x + (w // 2)) < 580) and (500 < (y + (h // 2)) < 960) and (20 < w < 80) and (10 < h < 60):
cur_x[3] = x + (w // 2)
cur_y[3] = y + (h // 2)
cur_3 = cur_3 + 1
# Defined range for landmarks 4
elif (950 < (x + (w // 2)) < 1510) and (540 < (y + (h // 2)) < 1010) and (20 < w < 90) and (10 < h < 90):
cur_x[4] = x + (w // 2)
cur_y[4] = y + (h // 2)
cur_4 = cur_4 + 1
### Debug:
# print(cur_1, cur_2, cur_3, cur_4)
return cur_1, cur_2, cur_3, cur_4 # Return available contour values
# Translation & Rotation calibration function
def main(park_lot_name, trans_rot_mode, filename, cur_1, cur_2, cur_3, cur_4):
# Switch case for translation/rotation properties, based on the number of landmarks found & check availability
def case_switch_mode():
run_flag = 0 # Initiate run_flag, determine if the program could execute or not
run_mode = 0 # Initiate run_mode, determine if the program run in 4 landmarks mode or 3 landmarks mode
# run_mode = 1: 4 landmarks mode, run_mode = 0: 3 landmark mode
cur_toggle = [] # List, determine which landmark could be used
for i in range(0, 5): # Initiate cur_toggle list, cur_toggle[0]:cur_toggle[5]
cur_toggle.append(0)
# sum_cur variable, quick check if the landmarks could be used or not
sum_cur = cur_1 + cur_2 + cur_3 + cur_4
# Case: 4 landmarks found, usable!
if sum_cur == 4:
if cur_1 == 1 and cur_2 == 1 and cur_3 == 1 and cur_4 == 1:
run_flag = 1
run_mode = 1
else: # sum_cur is not correct, check the individuals
if cur_1 != 1:
print("cur_1 = ", cur_1, ", <> 1, eliminate")
cur_toggle[1] = 1
if cur_2 != 1:
print("cur_2 = ", cur_2, ", <> 1, eliminate")
cur_toggle[2] = 1
if cur_3 != 1:
print("cur_3 = ", cur_3, ", <> 1, eliminate")
cur_toggle[3] = 1
if cur_4 != 1:
print("cur_4 = ", cur_4, ", <> 1, eliminate")
cur_toggle[4] = 1
print("Landmarks mismatch!")
# Case: 3 landmarks found!
elif sum_cur == 3:
sum_toggle = 0 # sum_toggle variable, check if sum_cur actually returns 3 usable landmarks
if cur_1 != 1:
cur_toggle[1] = 1
if cur_2 != 1:
cur_toggle[2] = 1
if cur_3 != 1:
cur_toggle[3] = 1
if cur_4 != 1:
cur_toggle[4] = 1
for i in range(0, 5):
# Taking the sum of cur_toggle, if the value > 1 means there is more than 1 wrong landmark
sum_toggle = sum_toggle + cur_toggle[i]
if sum_toggle > 1:
print("Landmark mismatch")
else:
# 3 valid landmarks, proceed to run!
run_flag = 1
else:
print("Missing required landmarks!")
return run_flag, run_mode, cur_toggle
# Calculate the center (midpoint of ROI), used as a base for later transformation/rotation
def midpoint_cal(run_flag, run_mode, cur_toggle):
global ref_x, ref_y, cur_x, cur_y
ref_midpoint_x = 0
ref_midpoint_y = 0
cur_midpoint_x = 0
cur_midpoint_y = 0
if run_flag == 1 and run_mode == 1: # Calculate using all 4 landmarks
for i in range(1, 5):
ref_midpoint_x = ref_midpoint_x + ref_x[i]
ref_midpoint_y = ref_midpoint_y + ref_y[i]
cur_midpoint_x = cur_midpoint_x + cur_x[i]
cur_midpoint_y = cur_midpoint_y + cur_y[i]
ref_midpoint_x = int(ref_midpoint_x / 4)
ref_midpoint_y = int(ref_midpoint_y / 4)
cur_midpoint_x = int(cur_midpoint_x / 4)
cur_midpoint_y = int(cur_midpoint_y / 4)
elif run_flag == 1 and run_mode == 0: # Calculate using 3 available landmarks only
for i in range(1, 5):
if cur_toggle[i] == 0:
ref_midpoint_x = ref_midpoint_x + ref_x[i]
ref_midpoint_y = ref_midpoint_y + ref_y[i]
cur_midpoint_x = cur_midpoint_x + cur_x[i]
cur_midpoint_y = cur_midpoint_y + cur_y[i]
ref_midpoint_x = int(ref_midpoint_x / 3)
ref_midpoint_y = int(ref_midpoint_y / 3)
cur_midpoint_x = int(cur_midpoint_x / 3)
cur_midpoint_y = int(cur_midpoint_y / 3)
### Debug":
# print("This function has been run")
# print(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y)
# else: # run_flag
# print("Landmark mismatch, program cannot execute!")
return ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y
# Calculate rotation angle using vector-based calculations
def rotate_angle(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y, ref_xx, ref_yy, cur_xx, cur_yy):
# Determine the reference vector & current vector
ref_vector = [ref_midpoint_x - ref_xx, ref_midpoint_y - ref_yy]
cur_vector = [cur_midpoint_x - cur_xx, cur_midpoint_y - cur_yy]
unit_ref_vector = ref_vector / np.linalg.norm(ref_vector)
unit_cur_vector = cur_vector / np.linalg.norm(cur_vector)
dot_prod = np.dot(unit_ref_vector, unit_cur_vector)
angle = np.arccos(dot_prod) * 180 / 3.1415
### Debug:
# print(angle)
return angle
# Define final rotation calibration case, based on the number of landmark available:
def run_case(run_flag, run_mode, cur_toggle):
# case variable for defining cases:
# case = -1: Program error, not enough information for processing
# case = 0: 4 landmarks mode
# case = 1: 3 landmarks mode, landmark 01 eliminated from calculation due to error
# case = 2: 3 landmarks mode, landmark 02 eliminated from calculation due to error
# case = 3: 3 landmarks mode, landmark 03 eliminated from calculation due to error
# case = 4: 3 landmarks mode, landmark 04 eliminated from calculation due to error
case = -1 # Initiate case, default = -1 to prevent unwanted processing
if run_flag == 1 and run_mode == 1:
case = 0
elif run_flag == 1 and run_mode == 0:
if cur_toggle[1] == 1:
case = 1
if cur_toggle[2] == 1:
case = 2
if cur_toggle[3] == 1:
case = 3
if cur_toggle[4] == 1:
case = 4
else: # Cannot process image, return error warning!
case = -1
# print("Not enough landmark information, please check the camera!")
return case
# Zoom image function, process image before translation & rotation
def zoom_image(img):
# Initiate roi list/matrix, we only calculate on 2D plane
roi = np.float32([[1, 0, 0], [0, 1, 0]])
# Zoom out image
# Expand the image to 3000 x 3000 px
zoom = cv2.warpAffine(img, roi, (3000, 3000))
# Matching the center point of the original image to the new center point of 3000 x 3000 px image
shift_image = imutils.translate(zoom, (1500 - 1920 / 2), (1500 - 1080 / 2))
### Debug: Show enlarged & shifted image
# cv2.imshow("Test image", shift_image)
# cv2.waitKey()
return shift_image
# Translation calibration main function
def translation(shift_image, case, ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y):
if case != -1:
# Initiate values
translation_x = ref_midpoint_x - cur_midpoint_x
translation_y = ref_midpoint_y - cur_midpoint_y
# If the shift is around 5 px, the translation is ignored
# Landmark recognition might have small errors in calculating positions
if translation_x in range(-5, 6):
translation_x = 0
if translation_y in range(-5, 6):
translation_y = 0
### Debug: Return value to check
# print(trans_x, trans_y)
# Return the original position
shift_copy = shift_image
shift_revert = imutils.translate(shift_copy, translation_x, translation_y)
else:
translation_x = 0
translation_y = 0
# Zoom out image
shift = zoom_image(image)
# Do nothing, return the original image
shift_revert = shift
return shift_revert, translation_x, translation_y
def rotation(shift_image, case, ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y):
# Initiate the values
angle = [] # Rotation angle properties, angle[1]:angle[4] correspond to angle calculations
# based on landmark01:landmark04
angle_final = 0 # Average rotation angle
for i in range(0, 5): # Initiate angle list
angle.append(0)
### Debug:
# print("Process case = ", case)
# case = 0, 4 landmarks mode, calculation based on angle[1] and angle[4]
if case == 0:
angle[1] = rotate_angle(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y,
ref_x[1], ref_y[1], cur_x[1], cur_y[1])
angle[4] = rotate_angle(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y,
ref_x[4], ref_y[4], cur_x[4], cur_y[4])
angle_final = round((angle[1] + angle[4]) / 2)
# If the current x[1] coordinate > reference x[1] coordinate, image has rotated clockwise, need to revert
# with a negative angle
if cur_x[1] > ref_x[1]:
angle_final = -angle_final
### Debug: Print angle[1], angle[4] & angle_final
# print(angle[1], angle[4])
# print(angle_final)
# case = 2 or case = 3, 3 landmarks mode, calculation based on angle[1] and angle[4]
if case == 2 or case == 3:
angle[1] = rotate_angle(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y,
ref_x[1], ref_y[1], cur_x[1], cur_y[1])
angle[4] = rotate_angle(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y,
ref_x[4], ref_y[4], cur_x[4], cur_y[4])
angle_final = round((angle[1] + angle[4]) / 2)
# If the current x[1] coordinate > reference x[1] coordinate, image has rotated clockwise, need to revert
# with a negative angle
if cur_x[1] > ref_x[1]:
angle_final = -angle_final
### Debug: Print angle[1], angle[4] & angle_final
# print(angle[1], angle[4])
# print(angle_final)
if case == 1 or case == 4:
angle[2] = rotate_angle(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y,
ref_x[2], ref_y[2], cur_x[2], cur_y[2])
angle[3] = rotate_angle(ref_midpoint_x, ref_midpoint_y, cur_midpoint_x, cur_midpoint_y,
ref_x[3], ref_y[3], cur_x[3], cur_y[3])
angle_final = round((angle[2] + angle[3]) / 2)
if cur_x[2] > ref_x[2]:
angle_final = -angle_final
### Debug: Print angle[2], angle[3] & angle_final
# print(angle[2], angle[3])
# print(angle_final)
if case == -1:
# Do nothing, return the original image. Print out a warning to the user
print("Landmarks mismatched or misconstructed, image not processed, please check the camera/input")
rotate_image = shift_image
return rotate_image, 0
### Debug:
# print(angle_final)
# Check if the angle is too large
if angle_final in range(-12, 13):
# Rotate the image
shift_copy = shift_image
### Debug:
# cv2.imwrite(os.path.join("D:\\21_05_08_result\\debug", "debug.jpg"), shift_copy)
rotate_mat = cv2.getRotationMatrix2D((3000 // 2, 3000 // 2), angle_final, 1.0)
### Debug: Print debug value
# cv2.imshow("Image", shift_copy)
# cv2.waitKey()
# print(rotate_mat)
# Rotation calibration
rotate_image = cv2.warpAffine(shift_copy, rotate_mat, (3000, 3000))
else:
print("Image is tilted too much, please check the camera")
print("The image will not be rotated")
rotate_image = shift_image
return rotate_image, angle_final
# Crop out the original image & save image function
def save_image(img, case, translation_x, translation_y, angle):
# Initiate height, width values. Avoid using constant, try using
height = 1080
width = 1920
# Cut the desired image
cut = img[960:960 + height, 540:540 + width]
# Cutting slot images
image_cut(cut, slot_coord)
# Drawing cutting slot
image_out = draw_rectangle(cut, slot_coord)
# Write down the desired image
# Avoid using static addresses, try using environment variable instead!
result_path = parent_path + "\\data_process\\{}\\calib_image".format(park_lot_name) # Image save path
name = os.path.splitext(filename)[0] # Separate filename, remove the extension
cv2.imwrite(os.path.join(result_path, 'recov_{}_({}_{}_{}).jpg'.format(name, translation_x, translation_y,
angle)), image_out)
# Log debug information
f_debug = open(parent_path + "\\data_process\\{}\\debug.txt".format(park_lot_name), 'a+')
f_debug.write("{}\n".format(datetime.datetime.now()))
f_debug.write("Filename: {}\n".format(name))
f_debug.write("Working case: {}\n".format(case))
if case != -1:
print(filename, " recovered")
f_debug.write(filename + " recovered\n")
else:
# cv2.imwrite(os.path.join(result_path, 'not_recov_{}.jpg'.format(name)), cut)
print(filename, " not recovered, please check the camera/input")
f_debug.write(filename + " not recovered, please check the camera/input\n")
f_debug.write("\n")
print("")
# Cut out the slot images after calibration
def image_cut(image_in, cd):
# Define writing path
image_cut_path = parent_path + "\\data_process\\{}\\calib_image_cut".format(park_lot_name)
# Define cutting region
for index in range(0, 20):
if index in range(0, 8):
img = image_in[cd[2][index] - 75:cd[2][index] + 75, cd[1][index] - 75:cd[1][index] + 75]
elif index in range(8, 14):
img = image_in[cd[2][index] - 45:cd[2][index] + 45, cd[1][index] - 45:cd[1][index] + 45]
else:
img = image_in[cd[2][index] - 35:cd[2][index] + 35, cd[1][index] - 35:cd[1][index] + 35]
### Debug: Show cut image
# cv2.imshow("Image", img)
# cv2.waitKey()
# Write cut image
name = '{}_{}.jpg'.format(os.path.splitext(filename)[0], index)
cv2.imwrite(os.path.join(image_cut_path, name), img)
# Draw the rectangular regions that the calibrated image will be cut out
def draw_rectangle(image_in, cd):
image_out = image_in
for i in range(0, 20):
if i in range(0, 8):
cv2.rectangle(image_out, (cd[1][i] - 75, cd[2][i] - 75), (cd[1][i] + 75, cd[2][i] + 75), (0, 255, 0), 2)
elif i in range(8, 14):
cv2.rectangle(image_out, (cd[1][i] - 45, cd[2][i] - 45), (cd[1][i] + 45, cd[2][i] + 45), (0, 255, 0), 2)
else:
cv2.rectangle(image_out, (cd[1][i] - 35, cd[2][i] - 35), (cd[1][i] + 35, cd[2][i] + 35), (0, 255, 0), 2)
return image_out
# Connect functions
image = cv2.imread(filename)
run_fl, run_md, cur_togg = case_switch_mode()
ref_mid_x, ref_mid_y, cur_mid_x, cur_mid_y = midpoint_cal(run_fl, run_md, cur_togg)
r_case = run_case(run_fl, run_md, cur_togg)
slot_fileflag, slot_coord = info_open_slot(park_lot_name)
### Debug:
print("Working case:", r_case)
# print(ref_x)
# print(ref_y)
# print(cur_x)
# print(cur_y)
# Zoom out image
process_image = zoom_image(image)
### Both image translation and rotation calibration
# rot_image, rot_angle = rotation(process_image, r_case, ref_mid_x, ref_mid_y, cur_mid_x, cur_mid_y)
# trans_image, trans_x, trans_y = translation(rot_image, r_case, ref_mid_x, ref_mid_y, cur_mid_x, cur_mid_y)
### In case of running image translation calibration only:
if trans_rot_mode == 1:
trans_image, trans_x, trans_y = translation(process_image, r_case, ref_mid_x, ref_mid_y, cur_mid_x, cur_mid_y)
rot_angle = 0
save_image(trans_image, r_case, trans_x, trans_y, rot_angle)
### In case of running image rotation calibration only:
if trans_rot_mode == 2:
trans_x = 0
trans_y = 0
rot_image, rot_angle = rotation(process_image, r_case, ref_mid_x, ref_mid_y, cur_mid_x, cur_mid_y)
save_image(rot_image, r_case, trans_x, trans_y, rot_angle)
<file_sep>/code_test/mainParkingLotRecog.py
import os
import cv2
# import folderFileManip # Unused
import userDefine as usrDef
import myTranslation as myTrans
# folderFileManip.folderManip()
# folderFileManip.fileManip()
while True:
os.system('cls')
print("_Welcome to Parking Lot recognition_")
print("_To continue, please select one of these functions_")
print("___0. Exit the program___")
print("___1. Define new parking slot___")
print("___2. Run parking lot recognition automatically___")
print("____Select function: ")
path_parent = os.getcwd()
key = input()
if int(key) == 1:
print("_You have selected Define new parking slot_")
os.chdir(path_parent)
image_ref = cv2.imread(".\\data_process\\ref_image\\imageplaceholder.jpg")
usrDef.user_define(image_ref)
print(os.getcwd())
elif int(key) == 2:
os.chdir(path_parent)
f_runTime = open(path_parent+"\\data_process\\runTime.txt", 'r')
checkDef = f_runTime.read()
if checkDef == '0':
print('_Parking lot has not been defined. Please define before running this mode_')
else:
print("_System now supervising parking lot automatically_")
# Main program calls & execution
# Avoid using static address! Use environment variable for this instead!
os.chdir("D:\\IC DESIGN LAB\\[LAB] PRJ.Parking Lot\\IMAGE_CALIBRATION_V2\\data_process\\data")
# Open landmarks information
flag, ref_x, ref_y = myTrans.info_open()
### Debug code:
# print(flag)
# print(ref_x)
# print(ref_y)
if flag == 1:
print("Parking lot is yet to be defined, exit")
else:
trans_rot_mode = 1
### Debug code:
# print(path_parent+"\\data_process\\data")
for filename in os.listdir(os.getcwd()):
image = cv2.imread(filename)
### Debug code:
# print(filename)
# print(os.stat(filename).st_size)
# cv2.imshow("Read image", image)
# cv2.waitKey()
cur1, cur2, cur3, cur4 = myTrans.landmark_recog(filename)
myTrans.main(trans_rot_mode, filename, cur1, cur2, cur3, cur4)
print("")
print("_System has finished monitoring. Now exit_")
break
if int(key) == 0:
print("_Program terminated")
break
print("___Press Enter to continue___")
cont = input()
<file_sep>/userGUI.py
# This is the file containing test layout for ImageCalibration
# The layout is in development
### Import libraries/packages
# ---------------------------------------------------------------------------------------------------------------------
import os
import io
# Import required processing libraries/packages
import PySimpleGUI as sg
import cv2
from PIL import Image, ImageTk
# Import image calibration algorithm file
import myTranslation as mytrans
# Import folder & file manipulation functions
import folderFileManip as ff_manip
# Import GUI additional functions
import infoGUI as inf_gui
# Import camera functions
import cameraFunction as cam_func
# ---------------------------------------------------------------------------------------------------------------------
# Initiate values
# ---------------------------------------------------------------------------------------------------------------------
# Get top working folder directory
parent_path = os.getcwd()
print(parent_path)
# print(parent_path)
index = 0 # index for below lists - Reference landmark position list & Slot position list
ref_pos_x = [] # Reference landmark coordinate, x-axis
ref_pos_y = [] # Reference landmark coordinate, y-axis
slot_pos_x = [] # Slot coordinate, x-axis
slot_pos_y = [] # Slot coordinate, y-axis
# Avoid using static values, try using an input to get this value
number_of_slot = 20 # Define number of slots
# Initiate above lists
for i in range(0, 5):
ref_pos_x.append(0)
ref_pos_y.append(0)
for j in range(0, number_of_slot + 1):
slot_pos_x.append(0)
slot_pos_y.append(0)
# Screen scaling ratio. This value must < 1 to get a fullscreen GUI without bleeding edges
scale = 2 / 3
# Initiate screen size, get max GUI resolution
wid, hght = inf_gui.get_scr_size(scale)
maxsize = (wid, hght)
# Define image files, which should be used in later definitions
file_types = [("JPEG (*.jpg)", ".jpg"),
("All files (*.*)", "*.*")]
# Define a list, emulating reading different parking lot
list_of_parking_lot, avail_flag = ff_manip.file_open_avail_parklot(parent_path)
size_of_list_parklot = len(list_of_parking_lot)
### Define layouts
# ---------------------------------------------------------------------------------------------------------------------
# Layout 1/layout_open: Opening layout of the program
layout_open = [[sg.Text('IMAGE CALIBRATION', font='Arial')],
[sg.Button('Define new parking lot', key='-DEFNEW-')],
[sg.Button('Run automatically', key='-RUNAUTO-')]]
# Layout 2/layout_defnew_1: Define new parking lot name layout
layout_defnew_1 = [[sg.Text('DEFINE NEW PARKING LOT')],
[sg.Text('Please input new parking lot name')],
[sg.InputText(key='-NEW_PARKLOT_NAME-')],
[sg.Button('Enter new name', key='-ENTER_NAME-')],
[sg.Text("This parking lot has been defined, select Redefine or Run auto instead",
key='-RET_MSG_DEFNEW1-', visible=False)],
[sg.Text("Parking lot name is blank, please try again", key='-NAME_BLANK-', visible=False)],
[sg.Button('Back', key='-BACK_2-')],
[sg.Button('Next', key='-DEFINE_01-', visible=False),
sg.Button('Redefine', key='-REDEFINE_DEF-', visible=False),
sg.Button('Run auto', key='-RUN_DEF-', visible=False)]
]
# Layout 3/layout_runauto_1: Select defined parking lot layout
layout_runauto_1 = [[sg.Text("RUN CALIBRATING AUTOMATICALLY")],
[sg.Text("Select one of these defined parking lot")],
[sg.Listbox(values=list_of_parking_lot, select_mode='single', key='-PARKLOT-', size=(30, 6))],
[sg.Button('Back', key='-BACK_3-'),
sg.Button('Redefine', key='-REDEFINE-'), sg.Button('Run auto', key='-RUN-')]]
# Layout 4/layout_defnew_2: Select reference image layout
layout_defnew_2 = [[sg.Text('DEFINE PARKING LOT')],
[sg.Text('Select reference image')],
[sg.Text('Choose a file: '), sg.Input(size=(30, 1), key='-REF_IMG-'),
sg.FileBrowse(file_types=file_types), sg.Button("Load image", key='-LOAD_FROM_BROWSE-')],
[sg.Text('Or load image from camera'), sg.Button("Load from camera", key='-LOAD_FROM_CAM-')],
[sg.Image(key='-REFERENCE_IMAGE-')],
[sg.Button('Back', key='-BACK_4-'), sg.Button('Next', key='-DEFINE_02-', visible=False)]]
# Layout 5/layout_defnew3: Define landmarks & parking slots layout
layout_1 = [[sg.Graph(canvas_size=(wid, hght), # First column
graph_bottom_left=(0, 720),
graph_top_right=(1280, 0),
enable_events=True,
drag_submits=True,
key='-GRAPH-')],
[sg.InputText(size=(10, 1), key='-LM_NUM-'),
sg.Button("Save as Landmark", key='-SAVE_LM-'),
sg.Button("Save LM file", key='-REDEF_LM-'),
sg.InputText(size=(10, 1), key='-SLOT_NUM-'),
sg.Button("Save as ParkSlot", key='-SAVE_SLOT-'),
sg.Button("Save PSlot file", key='-REDEF_SLOT-')],
[sg.Button('Back', key='-BACK_5-'), sg.Button('Finish', key='-FIN-')]]
layout_2 = [[sg.Text(key='-INFO-', size=(50, 1))], # Second column
[sg.Text(key='-LM_1-', size=(30, 1))],
[sg.Text(key='-LM_2-', size=(30, 1))],
[sg.Text(key='-LM_3-', size=(30, 1))],
[sg.Text(key='-LM_4-', size=(30, 1))],
[sg.Text(key='-SLOT_1-', size=(15, 1))],
[sg.Text(key='-SLOT_2-', size=(15, 1))],
[sg.Text(key='-SLOT_3-', size=(15, 1))],
[sg.Text(key='-SLOT_4-', size=(15, 1))],
[sg.Text(key='-SLOT_5-', size=(15, 1))],
[sg.Text(key='-SLOT_6-', size=(15, 1))],
[sg.Text(key='-SLOT_7-', size=(15, 1))],
[sg.Text(key='-SLOT_8-', size=(15, 1))],
[sg.Text(key='-SLOT_9-', size=(15, 1))],
[sg.Text(key='-SLOT_10-', size=(15, 1))],
[sg.Text(key='-SLOT_11-', size=(15, 1))],
[sg.Text(key='-SLOT_12-', size=(15, 1))],
[sg.Text(key='-SLOT_13-', size=(15, 1))],
[sg.Text(key='-SLOT_14-', size=(15, 1))],
[sg.Text(key='-SLOT_15-', size=(15, 1))],
[sg.Text(key='-SLOT_16-', size=(15, 1))],
[sg.Text(key='-SLOT_17-', size=(15, 1))],
[sg.Text(key='-SLOT_18-', size=(15, 1))],
[sg.Text(key='-SLOT_19-', size=(15, 1))],
[sg.Text(key='-SLOT_20-', size=(15, 1))]
]
layout_defnew_3 = [[sg.Text('DEFINE PARKING LOT')], # Master layout of layout 5, combine 1st and 2nd column
[sg.Text('Define landmarks & parking slots')],
[sg.Column(layout_1), sg.Column(layout_2)]]
# Layout 6/layout_select_calib_mode: Select calibration mode
layout_select_calib_mode = [[sg.Text("SELECT DATA FOLDER & CALIBRATION TYPE")],
[sg.Text("Input data folder"), sg.Input(size=(30, 1), key='-DATA_FOL-'),
sg.FolderBrowse()],
[sg.Button('Translation', key='-TRANS-'), sg.Button('Rotation', key='-ROL-')],
[sg.Button('Back', key='-BACK_6-')]]
# Layout 7/layout_wait_error: Wait screen/Error screen layout
layout_wait_error = [[sg.Text("WAIT SCREEN")],
[sg.Text("Parking lot has not been defined, please define before run", key='-NOT_DEF-',
visible=False)],
[sg.Text("Parking lot processing, please wait", key='-WAIT-',
visible=False)],
[sg.Text(key="-PROCESSING_FILE-", size=(60, 1), visible=False)],
[sg.ProgressBar(1, orientation='h', size=(80, 20), key='-PROG_BAR-')],
[sg.Text("Program finished monitoring", key='-FINISHED-', visible=False)],
[sg.Button("Show result", key='-SHOW_RES-', visible=False)]]
# Layout 8/layout_results: Result layout - Image viewer
result_col_1 = [[sg.Text("Before calibration")], # First column
[sg.Graph(canvas_size=(640, 360),
graph_bottom_left=(0, 360),
graph_top_right=(640, 0),
background_color='white',
enable_events=True,
key='-BEFORE_CALIB-')]]
result_col_2 = [[sg.Text("After calibration")], # Second column
[sg.Graph(canvas_size=(640, 360),
graph_bottom_left=(0, 360),
graph_top_right=(640, 0),
background_color='white',
enable_events=True,
key='-AFTER_CALIB-')]]
layout_result = [[sg.Text("RESULTS")], # Master layout of layout 8, combine 1st and 2nd column
[sg.Text("Before and After Calibration")],
[sg.Text("Image", key='-SHOWN_IMG-', size=(30, 1))],
[sg.Column(result_col_1), sg.Column(result_col_2)],
[sg.Button("Prev Image", key='-PREV_IMG-'), sg.Button("Next Image", key='-NEXT_IMG-')],
[sg.Button("Back to define", key='-BACK2DEF-'), sg.Button("Close the program", key='-CLOSE_PROG-')]]
# Master layout of the program: Combining above layouts & navigate buttons
layout = [[sg.Column(layout_open, key='lay_1', element_justification='center'),
sg.Column(layout_defnew_1, visible=False, key='lay_2'),
sg.Column(layout_runauto_1, visible=False, key='lay_3'),
sg.Column(layout_defnew_2, visible=False, key='lay_4'),
sg.Column(layout_defnew_3, visible=False, key='lay_5'),
sg.Column(layout_select_calib_mode, visible=False, key='lay_6'),
sg.Column(layout_wait_error, visible=False, key='lay_7'),
sg.Column(layout_result, visible=False, key='lay_8')]]
# [ sg.Button('Cycle layout'), sg.Button('1'), sg.Button('2'), sg.Button('3'),
# sg.Button('4'), sg.Button('5'), sg.Button('6'), sg.Button('7'), sg.Button('8'),
# sg.Button('Exit')]]
# ---------------------------------------------------------------------------------------------------------------------
# GUI initiate values:
# ---------------------------------------------------------------------------------------------------------------------
# Initiate main window
window = sg.Window('Image Calibration', layout, element_justification='center',
resizable=True, finalize=True)
# Initiate layout
layout = 1
# Initiate additional graph value, for layout 6 & layout 8
graph = window['-GRAPH-']
before_calib = window['-BEFORE_CALIB-']
after_calib = window['-AFTER_CALIB-']
# Initiate variables related to camera functions
camera_runtime_value = 0
# Initiate index for image viewer, layout 8
result_image_index = 0
# Enable/Disable dragging variables, for drawing on graph
dragging = False
start_point = end_point = prior_rect = None
# ---------------------------------------------------------------------------------------------------------------------
# GUI switching functions
# ---------------------------------------------------------------------------------------------------------------------
while True:
# Terminate program
# ----------------------------------------------------------------------
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit' or event == '-CLOSE_PROG-':
break
# ----------------------------------------------------------------------
# Work with Back function
# -----------------------------------------------------------------------------------------------------------------
if event == '-BACK_{}-'.format(layout):
if layout == 2 or layout == 3 or layout == 4:
window[f'lay_{layout}'].update(visible=False) # Toggle current layout off
layout = 1 # Update desired layout value
window[f'lay_{layout}'].update(visible=True) # Toggle new layout on
elif layout == 5:
window[f'lay_{layout}'].update(visible=False)
layout = 4
window[f'lay_{layout}'].update(visible=True)
elif layout == 6:
window[f'lay_{layout}'].update(visible=False)
layout = 5
window[f'lay_{layout}'].update(visible=True)
# -----------------------------------------------------------------------------------------------------------------
# Work with define new parking lot
# -----------------------------------------------------------------------------------------------------------------
if event == '-DEFNEW-': # Change to enter new name layout
window[f'lay_{layout}'].update(visible=False)
layout = 2 # Update define new name layout
window[f'lay_{layout}'].update(visible=True)
if event == '-ENTER_NAME-': # If enter new name button is pressed
match = 0
parklot_name = values['-NEW_PARKLOT_NAME-']
### Debug: Determine input parking lot name
# print(parklot_name)
if parklot_name == "": # Check if new name is blank. Blank name cannot be used
window['-NAME_BLANK-'].update(visible=True) # Blank name message, visible = True
window['-DEFINE_01-'].update(visible=False) # Next button, visible = False
continue # Continue receiving new name
for i in range(0, size_of_list_parklot): # Check if name is used, means parking lot is defined
if parklot_name == list_of_parking_lot[i]:
match = 1 # Found matching result!
temp = list_of_parking_lot[i]
if match == 1: # Display Redefine, RunAuto option. Not append this new name since it's already available
window['-RET_MSG_DEFNEW1-'].update(visible=True) # Matched name message, visible = True
window['-REDEFINE_DEF-'].update(visible=True) # Redefine button, visible = True
window['-RUN_DEF-'].update(visible=True) # RunAuto button, visible = True
window['-DEFINE_01-'].update(visible=False) # Next button, visible = False
window['-NAME_BLANK-'].update(visible=False) # Blank name message, visible = False
else: # No matching name found. This name need to be added
window['-DEFINE_01-'].update(visible=True) # Next button, visible = True
window['-REDEFINE_DEF-'].update(visible=False) # Redefine button, visible = False
window['-RUN_DEF-'].update(visible=False) # RunAuto button , visible = False
window['-RET_MSG_DEFNEW1-'].update(visible=False) # Matched name message, visible = False
window['-NAME_BLANK-'].update(visible=False) # Blank name message, visible = False
ff_manip.file_append_avail_parklot(parent_path, parklot_name)
# Append the new name to available parking lots
# -----------------------------------------------------------------------------------------------------------------
# Work with select reference image
# -------------------------------------------------------------------------------------------------------
if event == '-DEFINE_01-' or event == '-REDEFINE-' or event == '-REDEFINE_DEF-' or event == '-BACK2DEF-' \
or event == '-RUN-':
if event == '-RUN-' or event == '-REDEFINE-':
strx = ""
for v in values['-PARKLOT-']:
strx = v # Extract the string from the list parentheses
parklot_name = strx
### Debug: Determine input parking lot name
# print(parklot_name)
if event == '-REDEFINE-':
window[f'lay_{layout}'].update(visible=False)
layout = 4 # Update select image layout
window[f'lay_{layout}'].update(visible=True)
ff_manip.folder_manip(parent_path, parklot_name)
ff_manip.file_manip(parent_path, parklot_name)
os.chdir(parent_path + "\\data_process\\{}".format(parklot_name))
ff_manip.remove_folder_content(parent_path + "\\data_process\\{}\\image_take_from_camera"
.format(parklot_name))
else:
# If event wish to come/comeback to select reference image
window[f'lay_{layout}'].update(visible=False)
layout = 4 # Update select image layout
window[f'lay_{layout}'].update(visible=True)
# Get the parking lot name
if event == '-DEFINE_01-' or event == '-REDEFINE_DEF-':
### Debug: Print parking lot name string
parklot_name = values['-NEW_PARKLOT_NAME-']
### Debug: Determine input parking lot name
# print(parklot_name)
# Create required folders:
os.chdir(parent_path + "\\data_process")
ff_manip.folder_manip(parent_path, parklot_name)
ff_manip.file_manip(parent_path, parklot_name)
os.chdir(parent_path + "\\data_process\\{}".format(parklot_name))
ff_manip.remove_folder_content(parent_path + "\\data_process\\{}\\image_take_from_camera"
.format(parklot_name))
# If event is load image, after selecting an available image
if event == '-LOAD_FROM_BROWSE-' or event == '-LOAD_FROM_CAM-':
filename = ""
if event == '-LOAD_FROM_BROWSE-':
filename = values['-REF_IMG-'] # Update image value
elif event == '-LOAD_FROM_CAM-':
read_status, filename = cam_func.main_camera_func(parent_path, parklot_name, camera_runtime_value)
camera_runtime_value += 1
# print(filename)
# print(filename)
if os.path.exists(filename): # Open image & show thumbnail before proceed to process
image = Image.open(filename)
image.thumbnail((500, 500))
bio = io.BytesIO()
image.save(bio, format="PNG")
window['-REFERENCE_IMAGE-'].update(data=bio.getvalue()) # Show image
window['-DEFINE_02-'].update(visible=True) # Next button, visible = True
# -----------------------------------------------------------------------------------------------------
# Work with define landmark and parking slot
# --------------------------------------------------------------------------------------
if event == '-DEFINE_02-':
# If event is input image for parking lot defining
### Debug:
# print("Accessing landmark & parking slot mode")
window[f'lay_{layout}'].update(visible=False)
layout = 5 # Update landmark & slot define layout
window[f'lay_{layout}'].update(visible=True)
grid_drawn = inf_gui.gui_draw(parent_path, filename) # Draw grid on selected image
data = inf_gui.get_img_data(grid_drawn, maxsize, first=True) # Convert reference image data to base64
graph.draw_image(data=data, location=(0, 0)) # Draw image to grid, layout 5
# Define actions on graph
if event == '-GRAPH-':
x, y = values['-GRAPH-'] # Get coordinate from mouse on graph
if not dragging: # If drag = False
start_point = (x, y) # Get starting point
dragging = True
else:
end_point = (x, y) # Get ending point
if prior_rect:
graph.delete_figure(prior_rect) # Delete previous selected zone
if None not in (start_point, end_point):
prior_rect = graph.draw_rectangle(start_point, end_point, line_color='blue')
elif event.endswith('+UP'): # If mouse is released
info = window['-INFO-'] # Update information on image (rectangle)
info.update(value=f"Selected rectangle from {start_point} to {end_point}")
dragging = False # Set drag to false, ready for an another action
# Define actions on saving information. Calculate using grabbed coordinates, revert to original scale
if event == '-SAVE_LM-':
if values['-LM_NUM-'] == "": # Save landmark information, but landmark number is not defined
index = 0 # Save in the first slot, as a dummy value
ref_pos_x[index] = int((start_point[0] + end_point[0]) / 2 / scale)
ref_pos_y[index] = int((start_point[1] + end_point[1]) / 2 / scale)
else:
index = int(values['-LM_NUM-']) # Save landmark information, save to the -LM_NUM- position
ref_pos_x[index] = int((start_point[0] + end_point[0]) / 2 / scale)
ref_pos_y[index] = int((start_point[1] + end_point[1]) / 2 / scale)
# Show saved data to the screen
window['-LM_1-'].update(value=f"Landmark 01: {ref_pos_x[1]}, {ref_pos_y[1]}")
window['-LM_2-'].update(value=f"Landmark 02: {ref_pos_x[2]}, {ref_pos_y[2]}")
window['-LM_3-'].update(value=f"Landmark 03: {ref_pos_x[3]}, {ref_pos_y[3]}")
window['-LM_4-'].update(value=f"Landmark 04: {ref_pos_x[4]}, {ref_pos_y[4]}")
# print(ref_pos_x)
# print(ref_pos_y)
# Define actions on saving slots. Calculate using grabbed coordinates, revert to original scale
if event == '-SAVE_SLOT-':
if values['-SLOT_NUM-'] == "": # Save slot information, but slot number is not defined
index = 0 # Save in the first slot, as a dummy value
slot_pos_x[index] = int((start_point[0] + end_point[0]) / 2 / scale)
slot_pos_y[index] = int((start_point[1] + end_point[1]) / 2 / scale)
else:
index = int(values['-SLOT_NUM-']) # Save slot information, save to the -SLOT_NUM- position
slot_pos_x[index] = int((start_point[0] + end_point[0]) / 2 / scale)
slot_pos_y[index] = int((start_point[1] + end_point[1]) / 2 / scale)
window['-SLOT_1-'].update(value=f"Slot 01: {slot_pos_x[1]}, {slot_pos_y[1]}")
window['-SLOT_2-'].update(value=f"Slot 02: {slot_pos_x[2]}, {slot_pos_y[2]}")
window['-SLOT_3-'].update(value=f"Slot 03: {slot_pos_x[3]}, {slot_pos_y[3]}")
window['-SLOT_4-'].update(value=f"Slot 04: {slot_pos_x[4]}, {slot_pos_y[4]}")
window['-SLOT_5-'].update(value=f"Slot 05: {slot_pos_x[5]}, {slot_pos_y[5]}")
window['-SLOT_6-'].update(value=f"Slot 06: {slot_pos_x[6]}, {slot_pos_y[6]}")
window['-SLOT_7-'].update(value=f"Slot 07: {slot_pos_x[7]}, {slot_pos_y[7]}")
window['-SLOT_8-'].update(value=f"Slot 08: {slot_pos_x[8]}, {slot_pos_y[8]}")
window['-SLOT_9-'].update(value=f"Slot 09: {slot_pos_x[9]}, {slot_pos_y[9]}")
window['-SLOT_10-'].update(value=f"Slot 10: {slot_pos_x[10]}, {slot_pos_y[10]}")
window['-SLOT_11-'].update(value=f"Slot 11: {slot_pos_x[11]}, {slot_pos_y[11]}")
window['-SLOT_12-'].update(value=f"Slot 12: {slot_pos_x[12]}, {slot_pos_y[12]}")
window['-SLOT_13-'].update(value=f"Slot 13: {slot_pos_x[13]}, {slot_pos_y[13]}")
window['-SLOT_14-'].update(value=f"Slot 14: {slot_pos_x[14]}, {slot_pos_y[14]}")
window['-SLOT_15-'].update(value=f"Slot 15: {slot_pos_x[15]}, {slot_pos_y[15]}")
window['-SLOT_16-'].update(value=f"Slot 16: {slot_pos_x[16]}, {slot_pos_y[16]}")
window['-SLOT_17-'].update(value=f"Slot 17: {slot_pos_x[17]}, {slot_pos_y[17]}")
window['-SLOT_18-'].update(value=f"Slot 18: {slot_pos_x[18]}, {slot_pos_y[18]}")
window['-SLOT_19-'].update(value=f"Slot 19: {slot_pos_x[19]}, {slot_pos_y[19]}")
window['-SLOT_20-'].update(value=f"Slot 20: {slot_pos_x[20]}, {slot_pos_y[20]}")
# print("{} {} {}\n".format(index, slot_pos_x[index], slot_pos_y[index]))
# Save changes to landmark file, if redefine landmark file is pressed
if event == '-REDEF_LM-':
ff_manip.file_landmark_write(parent_path, ref_pos_x, ref_pos_y, parklot_name)
# Save changes to slot file, if redefine slot button is pressed
if event == '-REDEF_SLOT-':
ff_manip.file_slot_write(parent_path, parklot_name, slot_pos_x, slot_pos_y, number_of_slot)
# ---------------------------------------------------------------------------------------
# Work with run automatically
# -----------------------------------------------
if event == '-RUNAUTO-':
window[f'lay_{layout}'].update(visible=False)
layout = 3 # Update select defined parking lot layout
window[f'lay_{layout}'].update(visible=True)
# -----------------------------------------------
# Work with select calibration mode
# ---------------------------------------------------------------------------------------------
if event == '-RUN-' or event == '-RUN_DEF-' or event == '-FIN-':
# print("Accessing running mode, return the results")
window[f'lay_{layout}'].update(visible=False)
layout = 6 # Update select calibration mode layout
window[f'lay_{layout}'].update(visible=True)
# Check if all required folders are created or not. If not, create new ones
ff_manip.folder_manip(parent_path, parklot_name)
ff_manip.file_manip(parent_path, parklot_name)
# Update the destination folders after working with folder name
folder_calibrated = parent_path + "\\data_process\\{}\\calib_image".format(parklot_name)
# Move into the required folder
cur_cwd = parent_path + "\\data_process\\{}".format(parklot_name)
os.chdir(cur_cwd)
# print(os.getcwd())
# Switch between 2 types of calibration: Translation & Rotation
if event == '-TRANS-' or event == '-ROL-':
window[f'lay_{layout}'].update(visible=False)
layout = 7 # Update waiting layout
window[f'lay_{layout}'].update(visible=True)
# Avoid using static addresses
# Remove all files in the previous run. This function should be removed in future updates or refurbished for a
# better experience
folder_original = values['-DATA_FOL-']
write_address_full = cur_cwd + "\\calib_image"
write_address_small = cur_cwd + "\\calib_image_cut"
ff_manip.remove_folder_content(write_address_full)
ff_manip.remove_folder_content(write_address_small)
# Open runtime file, check if the parking lot is actually defined
f_runtime = open(cur_cwd + "\\runTime.txt", 'r+')
# Actual image calibrating
landmark_flag, ref_x, ref_y = mytrans.info_open(parklot_name)
checkdef = f_runtime.read()
progress_bar = window.FindElement('-PROG_BAR-') # Define loading bar
if checkdef == '0' or landmark_flag == 1: # The parking lot is not defined. Redefine required!
window['-NOT_DEF-'].update(visible=True) # Not defined message, visible = True
window['-WAIT-'].update(visible=False) # Wait for processing message, visible = False
else:
window['-NOT_DEF-'].update(visible=False) # Not defined message, visible = False
window['-WAIT-'].update(visible=True) # Wait for processing message, visible = True
# Change to data need calibration folder
os.chdir(folder_original)
number_of_file = 0 # Initiate the number of data files need calibration
run_var = 0 # Running variable for loading bar
for base, dirs, files in os.walk(os.getcwd()):
for Files in files:
number_of_file = number_of_file + 1 # Get the number of data files need calibration
if event == '-TRANS-':
trans_rot_mode = 1 # Use Translation only
for filename in os.listdir(os.getcwd()):
image = cv2.imread(filename)
# Update which file is being processed
window['-PROCESSING_FILE-'].update(value=f"{filename} processing")
window['-PROCESSING_FILE-'].update(visible=True)
# Image calibration
cur1, cur2, cur3, cur4 = mytrans.landmark_recog(filename)
### Debug: Print recognized landmarks values
# print(cur1, cur2, cur3, cur4)
# print("")
mytrans.main(parklot_name, trans_rot_mode, filename, cur1, cur2, cur3, cur4)
run_var = run_var + 1
progress_bar.UpdateBar(run_var, number_of_file) # Update loading bar
window['-FINISHED-'].update(visible=True) # Finished message, visible = True
window['-SHOW_RES-'].update(visible=True) # Show result button, visible = True
elif event == '-ROL-':
trans_rot_mode = 2 # Use Rotation only
for filename in os.listdir(os.getcwd()):
image = cv2.imread(filename)
window['-PROCESSING_FILE-'].update(value=f"{filename} processing")
window['-PROCESSING_FILE-'].update(visible=True)
cur1, cur2, cur3, cur4 = mytrans.landmark_recog(filename)
mytrans.main(parklot_name, trans_rot_mode, filename, cur1, cur2, cur3, cur4)
run_var = run_var + 1
progress_bar.UpdateBar(run_var, number_of_file) # Update loading bar
window['-FINISHED-'].update(visible=True) # Finished message, visible = True
window['-SHOW_RES-'].update(visible=True) # Show result button, visible = True
# ---------------------------------------------------------------------------------------------
# Work with showing results
# ---------------------------------------------------------------------------------------------
if event == '-SHOW_RES-':
result_image_index = 0 # Reset image index to 0
window[f'lay_{layout}'].update(visible=False)
layout = 8 # Update image viewer layout
window[f'lay_{layout}'].update(visible=True)
# Get a list of file names available
# Define image viewer function
flist_o = os.listdir(folder_original) # Get list of original images
flist_c = os.listdir(folder_calibrated) # Get list of calibrated images
# Get list of names, original images
fnames_o = [f for f in flist_o if os.path.isfile(os.path.join(folder_original, f))]
numfiles_o = len(fnames_o) # Get number of original images
# Get list of names, calibration images
fnames_c = [g for g in flist_c if os.path.isfile(os.path.join(folder_calibrated, g))]
numfiles_c = len(fnames_c) # Get number of calibrated images
del flist_o, flist_c # Remove lists of names, since it's unused
# End of getting list
# Grab the first image
filename_og = os.path.join(folder_original, fnames_o[result_image_index])
filename_cab = os.path.join(folder_calibrated, fnames_c[result_image_index])
# print(os.path.isfile(filename_og), os.path.isfile(filename_cab))
# Print the image name:
window['-SHOWN_IMG-'].update(value=f"{fnames_o[result_image_index]}")
# Show the first images:
data_og = inf_gui.get_img_data(filename_og, (640, 360), first=True)
before_calib.draw_image(data=data_og, location=(0, 0)) # Draw image to left graph, image viewer
data_cab = inf_gui.get_img_data(filename_cab, (640, 360), first=True)
after_calib.draw_image(data=data_cab, location=(0, 0)) # Draw image to right graph, image viewer
# Image scrolling
if event in ('-PREV_IMG-', '-NEXT_IMG-'):
if event == '-PREV_IMG-': # Previous function in image viewer
result_image_index = result_image_index - 1
if result_image_index < 0:
result_image_index = numfiles_o + result_image_index
window['-SHOWN_IMG-'].update(value=f"{fnames_o[result_image_index]}")
elif event == '-NEXT_IMG-': # Next function in image viewer
result_image_index = result_image_index + 1
if result_image_index >= numfiles_o:
result_image_index = result_image_index - numfiles_o
window['-SHOWN_IMG-'].update(value=f"{fnames_o[result_image_index]}")
# Grab the image
filename_og = os.path.join(folder_original, fnames_o[result_image_index])
filename_cab = os.path.join(folder_calibrated, fnames_c[result_image_index])
# print(os.path.isfile(filename_og), os.path.isfile(filename_cab))
# Show the images:
data_og = inf_gui.get_img_data(filename_og, (640, 360), first=True)
before_calib.draw_image(data=data_og, location=(0, 0)) # Draw image to left graph, image viewer
data_cab = inf_gui.get_img_data(filename_cab, (640, 360), first=True)
after_calib.draw_image(data=data_cab, location=(0, 0)) # Draw image to right graph, image viewer
# ---------------------------------------------------------------------------------------------
"""
# Test layout change & access directly to available layouts
# ----------------------------------------------------------
if event == 'Cycle layout':
window[f'lay_{layout}'].update(visible=False)
layout = layout + 1 if layout < 8 else 1
window[f'lay_{layout}'].update(visible=True)
elif event in '12345678':
window[f'lay_{layout}'].update(visible=False)
layout = int(event)
window[f'lay_{layout}'].update(visible=True)
# -----------------------------------------------------------
"""
window.close()
<file_sep>/cameraFunction.py
# Import required libraries
import cv2
import os
# Initiate camera's default values
### This could be changed in future updates
rtsp_user = "admin"
rtsp_pass = "<PASSWORD>"
ip = "192.168.1.115"
port = "554"
device_number = "1"
# Define functions
def create_camera(rtsp_username, rtsp_password, ip_val, port_val, device_no):
# Set up camera rtsp hyperlink
rtsp = "rtsp://" + rtsp_username + ":" + rtsp_password + "@" + ip_val + ":" + port_val + "/Streaming/channels/" \
+ device_no
# Capture video frames
cap = cv2.VideoCapture()
cap.open(rtsp)
# Define additional values
# cap.set(10, 1920)
# cap.set(10, 1080)
# cap.set(10, 100)
return cap
def main_camera_func(parent_path, parking_lot_name, runtime_value):
# Define image save path
image_save_path = "{}\\data_process\\{}\\image_take_from_camera".format(parent_path, parking_lot_name)
### Debug:
# print(image_save_path)
# Define image dimensions
width = 1920
height = 1080
image_dimension = (width, height)
# Capture image
camera_capture = create_camera(rtsp_user, rtsp_pass, ip, port, device_number)
read_status, image_from_camera = camera_capture.read()
# Save image data, if capture succeed
if read_status:
# Resize the image to the desired dimensions
image_data = cv2.resize(image_from_camera, image_dimension)
# Get image path & save captured image data
image_name = "{}_{}_ref.jpg".format(parking_lot_name, runtime_value)
image_path = os.path.join(image_save_path, image_name)
# Write the image
cv2.imwrite(image_path, image_data)
### Debug:
# print(image_path)
# cv2.imshow("Captured image", image_data)
else:
print("Get image data failed, check the camera & connection to the camera")
image_path = image_save_path
return read_status, image_path
<file_sep>/Sort_contour.py
from sys import path
import numpy as np
import cv2
im_lower = np.array([20, 75, 75], dtype="uint8")
im_upper = np.array([35, 255, 255], dtype="uint8")
kernel = np.ones((3, 3), np.uint8)
def Print(a):
print(a)
exit(0)
#smaller image
def resize_img(img):
size = 1000
dim = (size, int(1080 * size / 1920))
resized = cv2.resize(img, dim)
cv2.imshow('a', resized)
cv2.waitKey()
# exit(0)
return resized
def angle(v1, v2):
unit_vector_1 = v1 / np.linalg.norm(v1)
unit_vector_2 = v2 / np.linalg.norm(v2)
dot_product = np.dot(unit_vector_1, unit_vector_2)
angle= np.arccos(dot_product) * 180 / 3.14
return angle
def landmark_recog(img):
img_copy = img.copy()
im_hsv = cv2.cvtColor(img_copy, cv2.COLOR_BGR2HSV)
im_mask = cv2.inRange(im_hsv, im_lower, im_upper)
im_mask = cv2.morphologyEx(im_mask, cv2.MORPH_OPEN, kernel)
# resize_img(im_mask)
# Finding contours available on image
cur_cnt, _ = cv2.findContours(im_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return cur_cnt, im_mask
path_4 = "D:\\CodeGit\\IMAGE_CALIBRATION_V2\\data_process\\C9\\ref_image\\imageplaceholder.jpg"
path_3 = "D:\\CodeGit\\IMAGE_CALIBRATION_V2\\data_process\\C9\\ref_image\\imageplaceholder_3.jpg"
# cur_1, cur_2, cur_3, cur_4 = landmark_recog(path_4)
def lm_3(image):
Pos = []
left = []
right = []
i = 0
mid_X = mid_Y = 0
#angle_3_1_2 : angle between vector(1, 3) and vector (1, 2) (defined by user)
angle_3_1_2_ref = 124
angle_3_1_4_ref = 105
angle_4_2_3_ref = 91
angle_4_2_1_ref = 72
(h, w, d) = image.shape
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, 0, 1.0)
image = cv2.warpAffine(image, M, (w, h))
cnts, im_mask = landmark_recog(image)
# 3 largest landmarks
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:3]
#Pos = [[,][,][,][,]] #coordinates of 4 landmarks
for c in cnts:
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
Pos.append([cX, cY])
mid_X = mid_X + Pos[i][0]
mid_Y = mid_Y + Pos[i][1]
i = i + 1
#left[]: coordinates of landmarks on the left
#right[]: coordinates of landmarks on the right
mid = [int(mid_X / 3), int(mid_Y / 3)]
for i in range(3):
if Pos[i][0] < mid[0]:
left.append(Pos[i])
else:
right.append(Pos[i])
#sort left = [[lm1], [lm3]]
#right = [[lm2], [lm4]]
if len(left) == 2:
if left[0][1] > left[1][1]:
left[0], left[1] = left[1], left[0]
if len(right) == 2:
if right[0][1] > right[1][1]:
right[0], right[1] = right[1],right[0]
#put text
if len(left) == 2:
#if there are 2 landmarks on the left => landmark_1 and landmark_3 => puttext
cv2.putText(image, "#1", (int(left[0][0]), int(left[0][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
cv2.putText(image, "#3", (int(left[1][0]), int(left[1][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
#vector_ll : vector go through 2 landmarks on the left
#vector_lr: vector go through landmark 1 and landmark on the right
vector_ll = [left[1][0] - left[0][0], left[1][1] - left[0][1]]
vector_lr = [right[0][0] - left[0][0], right[0][1] - left[0][1]]
#angle between ll and lr ~ angle_3_1_4 or angle_3_1_2
if angle_3_1_4_ref - 10 < angle(vector_ll, vector_lr) < angle_3_1_4_ref + 10:
cv2.putText(image, "#4", (int(right[0][0]), int(right[0][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
else: #~angle_3_1_2
cv2.putText(image, "#2", (int(right[0][0]), int(right[0][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
else: #if len(right) == 2
cv2.putText(image, "#2", (int(right[0][0]), int(right[0][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
cv2.putText(image, "#4", (int(right[1][0]), int(right[1][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
#same
vector_rr = [right[1][0] - right[0][0], right[1][1] - right[0][1]]
vector_rl = [left[0][0] - right[0][0], left[0][1] - right[0][1]]
if angle_4_2_1_ref - 10 < angle(vector_rr, vector_rl) < angle_4_2_1_ref + 10:
cv2.putText(image, "#1", (int(left[0][0]), left(right[0][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
else:
print(angle(vector_rr, vector_rl))
cv2.putText(image, "#3", (int(left[0][0]), int(left[0][1])), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 2)
return image
for i in range(150):
filename = "C:\\Users\\phamt\\Downloads\\DATA.2020_12_30\\lmTst_{}.jpg".format(i)
image = cv2.imread(filename)
image = lm_3(image)
resize_img(image)
exit()
<file_sep>/folderFileManip.py
# Import required libraries
import os.path
from os import path
# This comment was added for fun
# os.getcwd()
# print(os.listdir())
# Test name functions
# input_name = input("Write your input name here: ")
# Create required working directory if needed
def folder_manip(parent_path, input_name):
print(parent_path)
os.chdir(parent_path + '//data_process')
### Debug: Print the parent folder name
# print(path_parent)
# Define folder_make command:
def folder_make(folder_name):
if not path.exists(folder_name):
os.mkdir(folder_name)
print(folder_name + ' created!')
else:
print(folder_name + ' existed!')
return
# Create folder with name
folder_make(input_name)
os.chdir("./{}".format(input_name))
# Create sub-directories
folder_make("calib_image")
folder_make("data")
folder_make("park_lot_info")
folder_make("ref_image")
folder_make("calib_image_cut")
folder_make("image_take_from_camera")
# Return the folder pointer to main folder
os.chdir(parent_path)
### Debug: Print current working directory
# print(os.getcwd())
# print(os.listdir)
# Create required working files
def file_manip(parent_path, input_name): # Making log files for future access
os.chdir(parent_path + '//data_process//{}'.format(input_name))
### Debug: Print working directory
# print(parent_path)
def file_make(filename):
if not path.isfile(filename):
f = open(filename, "w")
f.close()
print(filename + ' created!')
else:
print(filename + ' existed!')
# Create files to store debug data
file_make("debug.txt")
file_make("runTime.txt")
# Create files to store parking lot data
os.chdir(".\\park_lot_info")
file_make("slot.txt")
file_make("landmark.txt")
os.chdir(parent_path)
# Open available parking lot file, append positions to a list
def file_open_avail_parklot(parent_path):
# Initiate values
file_flag = 0
avail_parklot = []
# Open file contains defined parking lot name
# Avoid using static addresses
f_avail_parklot = open(parent_path + "\\data_process\\avail_parklot.txt", 'r+')
if os.stat(parent_path + "\\data_process\\avail_parklot.txt").st_size == 0:
# Indicates if the parking lot is defined or not. If not, halt the processing program
file_flag = 1 # Not defined value
avail_parklot = None
return avail_parklot, file_flag
else:
string_x = ""
# Initiate new list, get the value from the list
lis = [line.split() for line in f_avail_parklot]
file_length = len(lis)
for ii in range(file_length):
for val in lis[ii]:
string_x = val
avail_parklot.append(string_x)
f_avail_parklot.close()
return avail_parklot, file_flag
# Add new parking lot to the monitoring file
def file_append_avail_parklot(parent_path, new_parklot_name):
# Initiate values:
# Avoid using static addresses
f_avail_parklot = open(parent_path + "\\data_process\\avail_parklot.txt", 'a+')
f_avail_parklot.write("\n")
f_avail_parklot.write(new_parklot_name)
f_avail_parklot.close()
return 0
# Rewrite the parking lot's parking slots' positions
def file_slot_write(parent_path, park_lot_name, slot_x, slot_y, num_of_slot):
# Initiate values:
f_slot = open(parent_path + "\\data_process\\{}\\park_lot_info\\slot.txt".format(park_lot_name), 'w+')
# Write slot coordinates to the file
for slot_index in range(1, num_of_slot+1):
f_slot.write('%d ' % slot_index)
f_slot.write('%d ' % slot_x[slot_index])
f_slot.write('%d\n' % slot_y[slot_index])
f_slot.close()
return 0
# Rewrite the landmarks' positions
def file_landmark_write(parent_path, ref_xx, ref_yy, park_lot_name):
# Initiate values:
# Avoid using static addresses
f_landmark = open(parent_path + "\\data_process\\{}\\park_lot_info\\landmark.txt".format(park_lot_name), 'w+')
f_runt = open(parent_path + "\\data_process\\{}\\runTime.txt".format(park_lot_name), 'w+')
# Write value to the file
f_runt.write('1')
# Write landmark coordinates to the file
for landmark_index in range(1, 5):
f_landmark.write('%d ' % landmark_index)
f_landmark.write('%d ' % ref_xx[landmark_index])
f_landmark.write('%d\n' % ref_yy[landmark_index])
f_landmark.close()
f_runt.close()
return 0
# Remove all folder content before an another run, to avoid image show errors
# A better approach to file management is recommended. Deleting files is not recommended.
def remove_folder_content(address):
for file_name in os.listdir(address):
if os.path.exists(os.path.join(address, file_name)):
os.remove(os.path.join(address, file_name))<file_sep>/code_test/progressBar.py
import PySimpleGUI as sg
def CustomMeter():
# layout the form
layout = [[sg.Text('A custom progress meter')],
[sg.ProgressBar(1, orientation='h', size=(20,20), key='progress')],
[sg.Cancel()]]
# create the form
window = sg.Window('Custom Progress Meter').Layout(layout)
progress_bar = window.FindElement('progress')
# loop that would normally do something useful
for i in range(10000):
# check to see if the cancel button was clicked and exit loop if clicked
event, values = window.Read(timeout=0)
if event == 'Cancel' or event == None:
break
# update bar with loop value +1 so that bar eventually reaches the maximum
progress_bar.UpdateBar(i+1, 10000)
# done with loop... need to destroy the window as it's still open
window.Close()
CustomMeter()<file_sep>/landmark_tracker/Tracking.py
from numpy.core.numeric import base_repr
import CentroidTracker as ct
import numpy as np
import imutils
import time
import cv2
import datetime
im_lower = np.array([20, 75, 75], dtype="uint8")
im_upper = np.array([35, 255, 255], dtype="uint8")
kernel = np.ones((3, 3), np.uint8)
def landmark_recog(img):
img_copy = img.copy()
im_hsv = cv2.cvtColor(img_copy, cv2.COLOR_BGR2HSV)
im_mask = cv2.inRange(im_hsv, im_lower, im_upper)
im_mask = cv2.morphologyEx(im_mask, cv2.MORPH_OPEN, kernel)
cur_cnt, _ = cv2.findContours(im_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return cur_cnt, im_mask
def angle_dect(v1, v2):
unit_vector_1 = v1 / np.linalg.norm(v1)
unit_vector_2 = v2 / np.linalg.norm(v2)
dot_product = np.dot(unit_vector_1, unit_vector_2)
angle= np.arccos(dot_product) * 180 / 3.14
return angle
(H, W) = (None, None)
#get final result
def Position(objects):
Pos = []
for(x, centroid) in objects.items():
if x in base_cnts:
Pos.insert(base_cnts.index(x), centroid)
return Pos
#check if showed up contour is landmark
def find_4(cur_cnts, objects):
#angle relationship of defined landmarks
angle_1_3_2_ref = 124
angle_1_3_0_ref = 105
angle_0_2_1_ref = 91
angle_0_2_3_ref = 72
Pos = []
#"objects" store all tracked contour (also in the past) by ID (0 -> 1 -> 2 -> ... -> 99999)
#store position of 4 contours in Pos[lm0, lm1, lm2, lm3]
#check angle relationship
for (x, centroid) in objects.items():
if x in cur_cnts:
Pos.insert(cur_cnts.index(x), centroid)
vector_0_2 = [Pos[0][0] - Pos[2][0], Pos[0][1] - Pos[2][1]]
vector_1_2 = [Pos[1][0] - Pos[2][0], Pos[1][1] - Pos[2][1]]
angle = angle_dect(vector_0_2, vector_1_2)
if angle_0_2_1_ref - 10 < angle < angle_0_2_1_ref + 10:
global base_cnts
base_cnts = cur_cnts.copy()
return True
else:
return False
vs = cv2.VideoCapture("D:\\CodeGit\\IMAGE_CALIBRATION_V2\\landmark_tracker\\vid.mp4")
time.sleep(2.0)
count = True
# loop over the frames from the video stream
while True:
# read the next frame from the video stream and resize it
a = datetime.datetime.now()
frame = vs.read()[1]
frame = imutils.resize(frame, width=700)
# if the frame dimensions are None, grab them
if W is None or H is None:
(H, W) = frame.shape[:2]
cnts = landmark_recog(frame)[0]
#keep landmarks that have fixed area
area_sort = [x for x in cnts if (10 < cv2.contourArea(x) < 45)]
rects = []
#get boundingbox of contour
for i in range(len(area_sort)):
cnt = area_sort[i]
x,y,w,h = cv2.boundingRect(cnt)
box = np.array([x, y, x + w, y + h])
rects.append(box.astype("int"))
if (count):
rects = [np.array([435, 274, 445, 281]), np.array([149, 261, 157, 267]),\
np.array([411, 192, 419, 196]), np.array([205, 186, 214, 190])]
base_cnts = [0, 1, 2, 3]
Pos = [np.array([440, 277]), np.array([153, 264]), np.array([415, 194]), np.array([209, 188])]
count = False
#tracking contour
#view Readme.txt to see how this func work
#"objects = [[ID, Position], [ID, Position],...]"
objects = ct.update(rects)
#all contour has their own ID
#if they disappeared and come back, they will have new ID
#base_cnts : ID of being tracked contour that we know are landmarks
#For example: At first we track 4 contours
#so base_cnts = [0, 1, 2, 3]
#if contour 0 disappear and comeback
#base_cnts = [4, 1, 2, 3]
if len(base_cnts) == 4:
#if 1 landmark disappear
if len(objects) == 3:
cur_cnts = []
for (x, _ ) in objects.items():
cur_cnts.append(x)
dis = (list(set(base_cnts) - set(cur_cnts)))[0]
#remember position of missing landmark
dis_index = base_cnts.index(dis)
#remove it from tracking contour list
base_cnts.remove(dis)
#Pos: return position of landmarks that we use to calibrate images (final result)
Pos = Position(objects)
#if we tracking 3 contours
elif len(base_cnts) == 3:
#new contour show up
if len(objects) == 4:
cur_cnts = base_cnts.copy()
for (x, _ ) in objects.items():
#cur_cnts: make a copy of base_cnts
#put new contour in missing landmark's position
#to check if that's new landmark
if x in cur_cnts:
continue
else:
cur_cnts.insert(dis_index, x)
if (find_4(cur_cnts, objects)):
Pos = Position(objects)
Pos = Position(objects)
text = 0
if len(Pos) == 3:
Pos.insert(dis_index, [0,0])
for centroid in Pos:
cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)
cv2.putText(frame, str(text), (centroid[0] - 10, centroid[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
text += 1
# b = datetime.datetime.now()
# print((b - a) * 1000)
#print(Pos)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
rects = []
# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()<file_sep>/code_test/TestReadFile.py
import os
def file_open_avail_parklot():
# Initiate values
file_flag = 0
avail_parklot = []
# Open file contains defined parking lot name
f_avail_parklot = open("D:\\IC DESIGN LAB\\[LAB] PRJ.Parking Lot\\IMAGE_CALIBRATION_V2\\data_process"
"\\avail_parklot.txt", 'r+')
if os.stat("D:\\IC DESIGN LAB\\[LAB] PRJ.Parking Lot\\IMAGE_CALIBRATION_V2"
"\\data_process\\avail_parklot.txt").st_size == 0:
file_flag = 1
avail_parklot = None
return avail_parklot, file_flag
else:
lis = [line.split() for line in f_avail_parklot]
file_length = len(lis)
for i in range (file_length):
for val in lis[i]:
strx = val
avail_parklot.append(strx)
return avail_parklot, file_flag
list_of_parking_lot, avail_flag = file_open_avail_parklot()
size_of_list_parklot = len(list_of_parking_lot)
for i in range(0, size_of_list_parklot):
print(list_of_parking_lot[i])
print(size_of_list_parklot)
| 8a77aad009acac9cbee4da8aec621f755a117096 | [
"Python"
] | 10 | Python | ducpham2476/IMAGE_CALIBRATION_V2 | 6b7089520cf0bc83ec93bfc90a6f3e8f73bafde9 | a6cb0ae20df8d09428bb9a0bb51d024d00c02806 |
refs/heads/master | <file_sep>/**
* Created by PC150430-1 on 2017/4/27.
*/
var video = $(".play-view")[0];
var duration = video.duration;
var vol = video.volume;
var currentSrc = video.currentSrc;
var playerWrapper = $(".main");
var minute = 0;
var second = 0;
var int;
var intProgress;
//准备函数
function play() {
var playBtn = $(".icon-play");
playBtn.addClass("hide");
playBtn.siblings().removeClass("hide");
video.play();
starTime();
starProgress();
$(video).attr("data-state","true");
}
function pause() {
var pauseBtn = $(".icon-pause");
pauseBtn.addClass("hide");
pauseBtn.siblings().removeClass("hide");
video.pause();
pauseTime();
pauseProgress();
$(video).attr("data-state","false");
}
function starTime() {
window.clearInterval(int);
int = setInterval(timer,1000)
}
function timer() {
var currentTime = video.currentTime;
var second = Math.round(currentTime)%60;
var minute = parseInt(Math.floor(currentTime)/60);
var secondStr = second;
var minuteStr = minute;
if(second < 10){
secondStr = "0" + second;
}
if(minute < 10){
minuteStr = "0" + minute;
}
$(".progressTime").text(minuteStr + ":" + secondStr);
}
function pauseTime() {
window.clearInterval(int);
}
function resetTime() {
window.clearInterval(int);
minute = second = 0;
$(".progressTime").text("00:00")
}
function starProgress() {
window.clearInterval(intProgress);
intProgress = setInterval(progress,1000)
}
function starBuffer() {
var intBuffer = setInterval(function () {
var bufferEnd = video.buffered.end(0) || 0;
var duration = video.duration;
var bufferedWidth = (bufferEnd/duration)*100;
$(".buffer-bar").width(bufferedWidth + "%");
if (bufferEnd >= duration){
clearInterval(intBuffer);
}
},1000)
}
function progress() {
var currentTime = video.currentTime;
duration = video.duration;
var width = (currentTime/duration)*100;
$(".progress-bar").css("width",width + "%");
}
function pauseProgress() {
window.clearInterval(intProgress);
}
function showFullscreen(self) {
$(video).css("width",window.screen.Width);
$(video).css("height",window.screen.Height);
$(".index-wrapper").css({
"width":"100%",
"height": "100%",
"margin": "0 auto",
"padding": "0"
});
$(".main").css({
"width":"100%",
"height": "100%"
});
self.addClass("hide");
self.siblings().removeClass("hide");
}
function hideFullscreen(self) {
$(video).css("width","100%");
$(video).css("height","100%");
$(".index-wrapper").removeAttr("style");
$(".main").removeAttr("style");
self.addClass("hide");
self.siblings().removeClass("hide");
}
function launchFullscreen(element) {
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
function exitFullscreen() {
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
//初始化
$(document).ready(function () {
video.autoplay = true;
starTime(); //开始计时
starProgress(); //开启进度条
starBuffer(); //开启缓冲进度条
showVol(); //获取音量并显示
});
//事件
//show--操作面板
playerWrapper.on("mouseover",function () {
setTimeout(function () {
$(playerWrapper).find(".control-wrapper").fadeIn();
},500);
});
//hide--操作面板
playerWrapper.on("mouseout",function () {
setTimeout(function () {
$(playerWrapper).find(".control-wrapper").fadeOut();
},1000);
});
//play--播放
$(".icon-play").on("click",function () {
play();
});
//pause-->暂停按钮点击事件
$(".icon-pause").on("click",function () {
pause();
});
//pause-->点击video暂停事件
$(video).on("click",function () {
var state = $(video).attr("data-state");
if (state == "true"){
pause();
}else if (state == "false"){
play();
}
});
//pause-->空格键暂停事件
//点击进度条
$(".progress").on("click",function (e) {
var changeProgressWidth = e.pageX - $(this).offset().left;
var perPos = changeProgressWidth/($(this).width());
video.currentTime = (video.duration)*perPos;
starTime();
starProgress();
});
//音量显示
function showVol() {
var volBarHeight = video.volume*100;
$(".vol-bar").css("height",volBarHeight + "%");
}
$(".icon-vol").on("click",function () {
$(".vol-box").toggle();
});
//控制音量
$(".vol-wrapper").on("click",function (e) {
var changeVolHeight = 80 - (e.pageY - $(this).offset().top);
video.volume = changeVolHeight/80;
showVol();
});
//全屏
$(".icon-fullScreen").on("click",function () {
launchFullscreen(document.documentElement);
showFullscreen($(this))
});
//退出全屏
$(".icon-autoScreen").on("click",function () {
exitFullscreen(); // 判断浏览器种类--浏览器全屏
hideFullscreen($(this));
});
//按下Esc退出全屏
document.onkeydown=function(event){
var e = event || window.event || arguments.callee.caller.arguments[0];
if(e && e.keyCode==27){
exitFullscreen(); // 判断浏览器种类--浏览器全屏
hideFullscreen($(this));
}
};
| 81a14158e37e789e8b4a558af0089c8d1eb5eb40 | [
"JavaScript"
] | 1 | JavaScript | AmyLi1017/cool-videoPlayer | 0a4d0d894f5a7d587313c4324e5b5595711839df | 5743bcd252ae5509b402ed8e35fcbcc3bf4af759 |
refs/heads/master | <file_sep>chalk = require('chalk');
// https://www.npmjs.com/package/chalk
module.exports = {}
RAD = true;
DEG = false;
MODE = RAD;
cos = (i) => {
return MODE ? Math.cos(i) : Math.cos(radToDeg(i));
}
sin = (i) => {
return MODE ? Math.sin(i) : Math.sin(radToDeg(i));
}
tan = (i) => {
return MODE ? Math.tan(i) : Math.tan(radToDeg(i));
}
pow = Math.pow;
sqrt = Math.sqrt;
PI = pi = π = Math.PI;
e = E = Math.E;
º = Math.PI / 180;
radToDeg = (i) => {
return i * Math.PI / 180;
}
abs = Math.abs;
round = (i, p) => {
if (p == 0) {
throw "Precision cannot be 0.";
}
if (p !== undefined) {
p = Math.pow(10, p);
return Math.round(i * p) / p;
}
return Math.round(i);
}
ceil = Math.ceil;
floor = Math.floor;
rand = random = Math.random;
randRange = (min, max) => {
return Math.random() * (max - min) + min;
}
randInt = (min, max) => {
return Math.round(randRange(min, max));
}
out = {
default : function(i) {
console.log(`\t${ (i)}`)
},
black : function(i) {
console.log(`\t${chalk.black (i)}`)
},
red : function(i) {
console.log(`\t${chalk.red (i)}`)
},
green : function(i) {
console.log(`\t${chalk.green (i)}`)
},
yellow : function(i) {
console.log(`\t${chalk.yellow (i)}`)
},
blue : function(i) {
console.log(`\t${chalk.blue (i)}`)
},
magenta : function(i) {
console.log(`\t${chalk.magenta (i)}`)
},
cyan : function(i) {
console.log(`\t${chalk.cyan (i)}`)
},
white : function(i) {
console.log(`\t${chalk.white (i)}`)
},
gray : function(i) {
console.log(`\t${chalk.gray (i)}`)
},
bgBlack : function(i) {
console.log(`\t${chalk.bgBlack (i)}`)
},
bgRed : function(i) {
console.log(`\t${chalk.bgRed (i)}`)
},
bgGreen : function(i) {
console.log(`\t${chalk.bgGreen (i)}`)
},
bgYellow : function(i) {
console.log(`\t${chalk.bgYellow (i)}`)
},
bgBlue : function(i) {
console.log(`\t${chalk.bgBlue (i)}`)
},
bgMagenta : function(i) {
console.log(`\t${chalk.bgMagenta (i)}`)
},
bgCyan : function(i) {
console.log(`\t${chalk.bgCyan (i)}`)
},
bgWhite : function(i) {
console.log(`\t${chalk.bgWhite (i)}`)
},
help: function() {
console.log(`default`);
console.log(chalk.black(`black`));
console.log(chalk.red(`red`));
console.log(chalk.green(`green`));
console.log(chalk.yellow(`yellow`));
console.log(chalk.blue(`blue`));
console.log(chalk.magenta(`magenta`));
console.log(chalk.cyan(`cyan`));
console.log(chalk.white(`white`));
console.log(chalk.gray(`gray`));
console.log(chalk.bgBlack(`bgBlack`));
console.log(chalk.bgRed(`bgRed`));
console.log(chalk.bgGreen(`bgGreen`));
console.log(chalk.bgYellow(`bgYellow`));
console.log(chalk.bgBlue(`bgBlue`));
console.log(chalk.bgMagenta(`bgMagenta`));
console.log(chalk.bgCyan(`bgCyan`));
console.log(chalk.bgWhite(`bgWhite`));
},
reset: function() {
return process.stdout.write('\033c');
},
array2d: function(a, p) {
for (let i = 0; i < a.length; i++) {
let line = ``;
for (let j = 0; j < a[i].length; j++) {
let b = a[i][j];
if (b === undefined) {
b = '';
}
if (p) {
b = b.toFixed(p);
}
line += b + ` `;
}
this.bgMagenta(line);
}
}
}
<file_sep>require('./utils.js');
MODE = DEG;
out.reset();
out.cyan ("Exercises");
out.default(chalk.red("9.1") + ": " + chalk.yellow("4, 13, 20, 25" ));
out.default(chalk.red("9.2") + ": " + chalk.yellow("3, 4, 5, 9, 13" ));
out.default(chalk.red("9.3") + ": " + chalk.yellow("2, 8, 9, 10, 15" ));
out.cyan ("Computer Exercises");
out.default(chalk.green("9.1") + ": " + chalk.yellow("2"));
let t = generate_table(20);
let x = t.x;
let y = t.y;
let m = t.m;
let av = a(x, y, m);
let bv = b(x, y, m);
let φv = φ(av, bv, x, y);
out.cyan("———————————— TABLE ————————————");
out.array2d([x, y]);
out.default("");
out.bgRed(`a: ${av}`);
out.bgRed(`b: ${bv}`);
out.bgBlue(`φ: ${φv}`);
out.green(`y = ${round(av, 3)}x + ${round(bv, 3)}`);
function generate_table(dataset, size) {
let t = {
x: [],
y: [],
m: 0
};
switch (dataset) {
case 0:
t = {
x: [-3, -2, -1, 0, 1, 2, 3],
y: [ 0, 1, 2, 3, 4, 5, 6]
};
break;
case 1: // Example 1
t = {
x: [ 4, 7, 11, 13, 17],
y: [ 2, 0, 2, 6, 7]
};
break;
case 2: // Exercise 1
t = {
x: [ -1, 2, 3],
y: [ 5/4, 4/3, 5/12]
};
break;
case 13: // Exercise 13
t = {
x: [1, 2, 3, 4],
y: [0, 1, 1, 2]
};
break;
case 20: // Exercise 20
t = {
x: [ 0, 1, 2],
y: [ 5, -6, 7]
};
break;
case -1:
out.yellow("test");
for (let i = 0; i <= size; i++) {
t.x[i] = randInt(0, 10);
t.y[i] = randInt(0, 10);
}
}
if (t.x.length != t.y.length) {
throw "x and y need to have the same length";
}
t.m = t.x.length - 1;
return t;
}
// Equation (2) : page 427
function φ(a, b, x, y) {
let sum = 0;
for (let k = 0; k <= m; k++) {
sum += pow(a * x[k] + b - y[k], 2);
}
return sum;
}
/////////////////////////////////////////////////////
////////// Linear least squares : page 428 //////////
/////////////////////////////////////////////////////
function p(x, m) {
let sum = 0;
for (let k = 0; k <= m; k++) {
sum += x[k];
}
return sum;
}
function q(y, m) {
let sum = 0;
for (let k = 0; k <= m; k++) {
sum += y[k];
}
return sum;
}
function r(x, y, m) {
let sum = 0;
for (let k = 0; k <= m; k++) {
sum += x[k] * y[k];
}
return sum;
}
function s(x, m) {
let sum = 0;
for (let k = 0; k <= m; k++) {
sum += pow(x[k], 2);
}
return sum;
}
function d(x, m) {
return (m + 1) * s(x, m) - pow(p(x, m), 2);
}
function a(x, y, m) {
return ((m + 1) * r(x, y, m) - p(x, m) * q(y, m)) / d(x, m);
}
function b(x, y, m) {
return (s(x, m) * q(y, m) - p(x, m) * r(x, y, m)) / d(x, m)
}
/////////////////////////////////////////////////////
//////// END Linear least squares : page 428 ////////
/////////////////////////////////////////////////////
| accc2e52b58f19386fdfe31e8be0781d897198eb | [
"JavaScript"
] | 2 | JavaScript | dudeofawesome/node-workbench | da29d50fe4c9cb1a577840e594139b5d67f58c1e | 3c410f255074353c1269db5940f431c675b7ccfa |
refs/heads/master | <file_sep>export function commentLoad() {
return {
type: 'ALLOW_COMMENT_LOAD',
payload: true,
};
}
export function resetCommentLoad() {
return {
type: 'DISALLOW_COMMENT_LOAD',
payload: false,
};
}
<file_sep>import React from 'react';
import Upload from './upload.js';
import Instructions from './instructions.js';
export default function HomeContainer() {
return (
<div className="home">
<h1>FILENCRYPT</h1>
<Instructions />
<Upload />
</div>
);
}
<file_sep>import React, { Component } from 'react';
import Comment from './comment.js';
import { generateURL } from '../helpers/fileUtilities.js';
export default class CommentList extends Component {
commentsMap = () => this.props.comments[0].comments.map(commentData => (
<Comment key={generateURL()} author={commentData.author} comment={commentData.comment} />
))
render() {
if (this.props.comments && this.props.comments.length > 0) {
return (
<div className="comment-flexbox">
{this.commentsMap()}
</div>
);
}
return (
null
);
}
}
<file_sep>export default function extractMIMEType(base64String) {
if (typeof base64String !== 'string') {
return null;
}
const mime = base64String.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);
const split = mime[1].split('/');
const fileType = split[1];
return fileType;
}
<file_sep>import React from 'react';
export default function EachFile(props) {
return (
<li>
<h3>
File Name:
{props.name}
</h3>
<p>
File Location:
{props.location}
</p>
<p>
File URL:
{props.url}
</p>
<p>
File id (Mongo DB id):
{props.id}
</p>
</li>
);
}
<file_sep>import SimpleSchema from 'simpl-schema';
const commentSchema = new SimpleSchema({
_id: String,
comments: {
type: Array,
},
'comments.$': {
type: Object,
},
'comments.$.author': {
type: String,
optional: true,
},
'comments.$.comment': {
type: String,
},
});
export default commentSchema;
<file_sep>import React from 'react';
export default function Comment(props) {
return (
<div className="comment-container">
{
<div className="comment-author">
{props.author ? props.author : 'Anonymous'}
</div>
}
{props.comment && (
<div className="comment-text">
{props.comment}
</div>
)}
</div>
);
}
<file_sep>import React from 'react';
import { shallow, configure } from 'enzyme';
import { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import Password from '../../imports/components/passwordEncrypt.js';
if (Meteor.isClient) {
configure({ adapter: new Adapter() });
describe('<Password /> (Encrypt)', () => {
it('should have password input placeholder', () => {
const wrapper = shallow(<Password />);
expect(wrapper.find('input[type="password"]').prop('placeholder')).to.equal('Encryption password');
});
});
}
<file_sep>const initialState = {
errors: [],
};
const errorReducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD_ERROR_OBJECT':
return {
...state,
errors: [...state.errors, action.payload],
};
case 'REMOVE_ERROR_OBJECT':
return {
...state,
errors: state.errors.filter(item => item.id !== action.payload.id),
};
case 'REMOVE_ERROR_BY_ID':
return {
...state,
errors: state.errors.filter(item => item.id !== action.payload),
};
default:
return state;
}
};
export default errorReducer;
<file_sep>export function addError(error) {
return {
type: 'ADD_ERROR_OBJECT',
payload: error,
};
}
export function removeError(error) {
return {
type: 'REMOVE_ERROR_OBJECT',
payload: error,
};
}
export function removeErrorById(errorId) {
return {
type: 'REMOVE_ERROR_BY_ID',
payload: errorId,
};
}
<file_sep>import { Meteor } from 'meteor/meteor';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { withTracker } from 'meteor/react-meteor-data';
import MongoFiles from '../api/mongoFiles.js';
import EachFile from './eachFile.js';
import NoFileFound from './noFileFound.js';
import decrypt from '../helpers/decrypt.js';
const password = '<PASSWORD>';
class Folder extends Component {
renderEachFile = () => {
const files = this.props.files;
for (let i = 0; i < files.length; i += 1) {
const salt = files[i].salt;
const iv = files[i].iv;
Meteor.call('fileLoad', files[i].fileLocation, (error, result) => {
if (error) {
// alert(error);
} else {
const encryptedFile = result;
decrypt(encryptedFile, password, salt, iv);
}
});
}
if (files.length <= 0) {
// Nothing found in database
return (
<NoFileFound />
);
}
return files.map(file => (
<EachFile
key={file._id}
id={file._id}
name={file.fileName}
location={file.fileLocation}
url={file.url}
/>
));
}
render() {
return (
<div>
<h2>This is the folder component!</h2>
<ul>
{this.renderEachFile()}
</ul>
<Link to="/">Return to Home</Link>
</div>
);
}
}
export default withTracker(() => {
const urlParam = window.location.pathname.slice(1);
Meteor.subscribe('files', urlParam);
return {
files: MongoFiles.find({}).fetch(),
};
})(Folder);
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { connect } from 'react-redux';
import CommentList from './commentList.js';
import CommentForm from './commentForm.js';
import MongoComments from '../api/mongoComments.js';
import { addError, removeError } from '../redux/actions/errorActions.js';
import addErrorTimer from '../helpers/addErrorTimer.js';
import Loading from './loading.js';
class CommentBox extends Component {
constructor(props) {
super(props);
addErrorTimer = addErrorTimer.bind(this);
}
state = {
fileID: this.props.id,
}
saveComment = (commentData) => {
Meteor.call('saveComments', this.state.fileID, commentData, (error) => {
if (error) {
addErrorTimer(error.error);
}
});
}
render () {
if (!this.props.loading || !this.props.loadComments) {
return <Loading message="Loading comments..." />;
}
return (
<div className="comments-container">
<div className="comment-header">Comments</div>
<CommentList comments={this.props.comments} />
<CommentForm saveComment={this.saveComment} />
</div>
);
}
}
const commentTracker = withTracker(({ id }) => {
const commentSub = Meteor.subscribe('comments', id);
return {
loading: commentSub.ready(),
comments: MongoComments.find({ _id: id }, { comments: 1 }).fetch(),
};
})(CommentBox);
const mapStateToProps = state => ({
loadComments: state.commentReducer.loadComments,
});
const mapDispatchToProps = dispatch => ({
addError: (error) => {
dispatch(addError(error));
},
removeError: (error) => {
dispatch(removeError(error));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(commentTracker);
<file_sep>import React from 'react';
import { Route, Switch } from 'react-router-dom';
import ErrorContainer from './errorContainer.js';
// React Components
import HomeContainer from './homeContainer.js';
import FileListContainer from './fileListContainer.js';
export default function App() {
return (
<ErrorContainer>
<Switch>
<Route exact path="/" component={HomeContainer} />
<Route path="/:folderID" component={FileListContainer} />
</Switch>
</ErrorContainer>
);
}
<file_sep>import React from 'react';
import { shallow, configure } from 'enzyme';
import { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import App from '../../imports/components/app.js';
if (Meteor.isClient) {
configure({ adapter: new Adapter() });
describe('<App />', () => {
it('should have message text within h1', () => {
const wrapper = shallow(<App />);
expect(wrapper.find('h1').text()).to.equal('hello this works');
});
});
}
<file_sep>// Async testing isn't working, utilize promises in future tests
// import { expect } from 'chai';
// import fse from 'fs-extra';
// import { generateURL, generateFileHash, encode64 } from '../../imports/helpers/fileUtilities.js';
//
// const url = generateURL();
// const fileName = generateFileHash('Here is a random string to generate a file hash from');
// const file = encode64('A base64 encoded string used as a file for testing purposes.');
// const fileData = {
// url,
// fileLocation: `${url}/${fileName}`,
// fileName,
// };
// if (Meteor.isClient) {
// describe('File system', function () {
// it('creates and moves a file into tmp/', function () {
// Meteor.call('fileUpload', fileData, file, (error) => {
// if (error) {
// return false;
// }
// return false;
// });
// });
// });
// }
// if (Meteor.isServer) {
// describe('File system', function () {
// it('checks file is located in folder', function () {
// const fullFileLocation = `${process.env.PWD}/tmp/${fileData.fileLocation}`;
// const fileExists = fse.existsSync(fullFileLocation);
// expect(fileExists).to.equal(true);
// });
// });
// }
<file_sep>import { generateURL } from './fileUtilities.js';
export default function addError(message) {
const error = {
message,
id: generateURL(),
};
this.props.addError(error);
const timer = setTimeout(() => {
this.props.removeError(error);
clearTimeout(timer);
}, 5000);
}
<file_sep>/* eslint-disable react/jsx-one-expression-per-line */
import React from 'react';
export default function FileLimitInstructions() {
return (
<ul className="upload-instructions">
<li><span className="asterisk">*</span> Image files only</li>
<li><span className="asterisk">*</span> 5MB maximum</li>
</ul>
);
}
<file_sep>import assert from 'assert';
// import './upload.tests.js'; // Not yet implemented correctly
import './unit/passwordEncrypt.tests.js';
import './unit/passwordDecrypt.tests.js';
import './unit/error.tests.js';
// import './unit/app.tests.js'; // No elements to test in app
import './unit/loading.tests.js';
import './unit/cipher.tests.js';
import './integration/fileMoving.tests.js';
describe('photo-share', function () {
it('package.json has correct name', async function () {
const { name } = await import('../package.json');
assert.strictEqual(name, 'photo-share');
});
if (Meteor.isClient) {
it('client is not server', function () {
assert.strictEqual(Meteor.isServer, false);
});
}
if (Meteor.isServer) {
it('server is not client', function () {
assert.strictEqual(Meteor.isClient, false);
});
}
});
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Error from './error.js';
import { removeErrorById } from '../redux/actions/errorActions.js';
class ErrorContainer extends Component {
constructor(props) {
super(props);
this.removeSelf = this.removeSelf.bind(this);
}
removeSelf = (errorId) => {
this.props.removeErrorById(errorId);
}
renderEachError = (errors) => {
if (errors) {
return errors.map(error => (
<Error
key={error.id}
message={error.message}
id={error.id}
removeSelf={this.removeSelf}
/>
));
}
return null;
}
render() {
return (
<div>
<div className="error-flexbox">
{this.renderEachError(this.props.errors)}
</div>
{this.props.children}
</div>
);
}
}
const mapStateToProps = state => ({
errors: state.errorReducer.errors,
});
const mapDispatchToProps = dispatch => ({
removeErrorById: (errorId) => {
dispatch(removeErrorById(errorId));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(ErrorContainer);
<file_sep>import React from 'react';
import { shallow, configure } from 'enzyme';
import { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import Password from '../../imports/components/passwordDecrypt.js';
if (Meteor.isClient) {
configure({ adapter: new Adapter() });
describe('<Password /> (Decrypt)', () => {
it('should have password input placeholder', () => {
const wrapper = shallow(<Password />);
expect(wrapper.find('input[type="password"]').prop('placeholder')).to.equal('Decryption password');
});
it('should have a submit button', () => {
const wrapper = shallow(<Password />);
expect(wrapper.find('button[type="submit"]').text()).to.equal('Submit');
});
});
}
<file_sep>import React from 'react';
import { shallow, configure } from 'enzyme';
import { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import Loading from '../../imports/components/loading.js';
if (Meteor.isClient) {
configure({ adapter: new Adapter() });
describe('<Loading />', () => {
const message = 'This is a testing loading message.';
it('should have loading message text within div', () => {
const wrapper = shallow(<Loading message={message} />);
expect(wrapper.find('div').first().text()).to.equal(message);
});
});
}
<file_sep>import { Meteor } from 'meteor/meteor';
const callWithPromise = (method, params) => new Promise((resolve) => {
Meteor.call(method, params, (err, result) => {
if (err) {
// console.log(err);
} else {
resolve(result);
}
});
});
export default callWithPromise;
<file_sep>import React, { Component } from 'react';
import blobUtil from 'blob-util';
import { connect } from 'react-redux';
import { commentLoad } from '../redux/actions/commentActions.js';
import callWithPromise from '../helpers/loadFilePromise.js';
import decrypt from '../helpers/decrypt.js';
import Loading from './loading.js';
import Download from './download.js';
class File extends Component {
state = {
fileData: '',
loaded: false,
decrypted: false,
blobCreated: false,
blobURL: '',
};
componentDidMount() {
if (!this.state.loaded) {
this.loadEachFileIntoState();
}
}
componentDidUpdate = () => {
if (this.props.passwordEntered && !this.state.decrypted) {
this.decryptFile();
} else if (!this.state.blobCreated) {
try {
this.createBlob();
} catch (err) {
this.props.imageCouldNotRender();
}
} else if (this.state.blobCreated) {
this.props.loadComments();
}
}
componentWillUnmount() {
window.URL = window.URL || window.webkitURL;
window.URL.revokeObjectURL(this.state.blobURL);
}
loadEachFileFromServ = async () => {
const file = this.props.fileData;
const base64EncodedFile = await callWithPromise('fileLoad', file.fileLocation);
return base64EncodedFile;
}
loadEachFileIntoState = () => {
const self = this;
self.loadEachFileFromServ().then((data) => {
self.setState({ fileData: data, loaded: true });
});
}
decryptFile = () => {
const file = this.props.fileData;
this.setState(prevState => ({
fileData: decrypt(prevState.fileData, this.props.password, file.salt, file.iv),
decrypted: true,
}));
}
createBlob = () => {
window.URL = window.URL || window.webkitURL;
const strippedBase64 = this.state.fileData.split(',')[1].replace(/\s/g, '');
const blob = blobUtil.base64StringToBlob(strippedBase64);
this.setState({
blobURL: window.URL.createObjectURL(blob),
blobCreated: true,
});
}
renderFile = () => {
if (this.state.decrypted) {
return (
<div className="file-container">
<img className="file" src={this.state.blobURL} alt={this.state.fileData.fileName} />
{this.state.blobCreated && (
<Download blob={this.state.blobURL} base64={this.state.fileData} />
)}
</div>
);
}
return (
<Loading message="Decrypting file..." />
);
}
render() {
return this.renderFile();
}
}
const mapDispatchToProps = dispatch => ({
loadComments: () => {
dispatch(commentLoad());
},
});
export default connect(null, mapDispatchToProps)(File);
<file_sep>import React, { Component } from 'react';
export default class CommentForm extends Component {
state = {
author: '',
comment: '',
};
handleFormSubmit = (event) => {
event.preventDefault();
const authorInput = this.state.author;
const commentInput = this.state.comment;
const commentData = Object.freeze({ author: authorInput, comment: commentInput });
this.props.saveComment(commentData);
}
render() {
return (
<form className="comment-form" onSubmit={this.handleFormSubmit}>
<input id="comment-name" type="text" placeholder="Name" onChange={(evt) => { this.setState({ author: evt.target.value }); }} />
<textarea id="comment-text" placeholder="Comment" onChange={(evt) => { this.setState({ comment: evt.target.value }); }} />
<button id="comment-submit" className="button" type="submit">Submit</button>
</form>
);
}
}
<file_sep>import { createStore, combineReducers } from 'redux';
import errorReducer from './reducers/errorReducer.js';
import commentReducer from './reducers/commentReducer.js';
export default createStore(combineReducers({ errorReducer, commentReducer }));
<file_sep>/* eslint-disable jsx-a11y/no-static-element-interactions */
import React from 'react';
export default function Error(props) {
return (
<span
className="error"
onClick={() => props.removeSelf(props.id)}
>
{props.message}
</span>
);
}
<file_sep>// Research loading the Upload component not using enzyme's `shallow` function.
// It does not find html elements because Upload is wrapped by Redux's `connect` function.
// import React from 'react';
// import { shallow, configure } from 'enzyme';
// import { expect, assert } from 'chai';
// import Adapter from 'enzyme-adapter-react-16';
// import Upload from '../../imports/components/upload.js';
// if (Meteor.isClient) {
// configure({ adapter: new Adapter() });
//
// describe('<Upload />', () => {
// it('should have a form', () => {
// const wrapper = shallow(<Upload />).shallow().dive();
// expect(wrapper.find('form')).to.equal(true);
// assert.equal(wrapper.find('form'), '<form>');
// });
//
// it('should have file input', () => {
// const wrapper = shallow(<Upload />);
// expect(wrapper.find('input[type="file"]'));
// });
//
// it('should have a button', () => {
// const wrapper = shallow(<Upload />);
// expect(wrapper.find('button[type="submit"]')).to.exist;
// });
//
// it('button should have text \'Upload\'', () => {
// const wrapper = shallow(<Upload />);
// expect(wrapper.find('button[type="submit"]')).to.have.string('Password');
// expect(wrapper.find('button[type="submit"]').text()).toBe('Upload');
// expect(wrapper.find('button[type="submit"]').children()'Uploadd');
// expect(wrapper.find('input[type="password"]').prop('placeholder'), 'Password');
// });
// });
// }
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { addError, removeError } from '../redux/actions/errorActions';
import { resetCommentLoad } from '../redux/actions/commentActions';
import MongoFiles from '../api/mongoFiles.js';
import encrypt from '../helpers/encrypt.js';
import promise from '../helpers/promise.js';
import {
generateFileHash, randomBytes, generateURL, encode64,
} from '../helpers/fileUtilities.js';
import addErrorTimer from '../helpers/addErrorTimer.js';
import Password from './passwordEncrypt.js';
import Loading from './loading.js';
import FileLimitInstructions from './fileLimitInstructions.js';
class Upload extends Component {
constructor (props) {
super(props);
addErrorTimer = addErrorTimer.bind(this);
this.handlePassword = this.handlePassword.bind(this);
}
state = {
uploaded: false,
loading: false,
statusMessage: '',
url: '',
iv: randomBytes(16),
salt: randomBytes(128),
password: '',
passwordError: '<PASSWORD>.',
passwordValidated: false,
};
uploadEncryptedFiles = (fileInfo, files) => {
const self = this;
for (let i = 0; i < files.length; i += 1) {
const fileName = generateFileHash(files[i]);
const fileData = {
url: `${self.state.url}`,
fileLocation: `${self.state.url}/${fileName}`,
fileName,
};
this.setState(
{ statusMessage: `Encrypting file${files.length === 1 ? '' : 's'}...` },
);
const encryptedFile = encrypt(files[i], this.state.password, this.state.salt, this.state.iv);
Meteor.call('fileUpload', fileData, encryptedFile, (error) => {
if (error) {
addErrorTimer(error.message);
} else {
MongoFiles.insert({
url: fileData.url,
fileLocation: fileData.fileLocation,
fileName: fileData.fileName,
salt: encode64(this.state.salt),
iv: encode64(this.state.iv),
});
if (i === files.length - 1) { // Last file in the array
self.setState({ uploaded: true, loading: false });
}
}
});
}
}
promiseFileLoader = async (fileList) => {
const self = this;
const fileListArr = [];
for (let i = 0; i < fileList.length; i += 1) {
fileListArr.push(promise(fileList[i]));
}
Promise.all(fileListArr).then((values) => {
self.uploadEncryptedFiles(fileList, values);
});
}
fileTypeInvalid = fileType => !fileType.match(/image\/(gif|jpeg|jpg|png|bmp)/i)
fileSizeInvalid = fileSize => fileSize >= 5000000 // 5 MB
filesInvalid = (fileList) => {
const self = this;
return Array.from(fileList).some(function(file) {
const invalidType = self.fileTypeInvalid(file.type);
const invalidSize = self.fileSizeInvalid(file.size);
let errorMessage = '';
if (invalidType && invalidSize) {
errorMessage = `${file.name} is an invalid file type of ${file.type} and is larger than 5 MB.`;
addErrorTimer(errorMessage);
} else if (invalidType) {
errorMessage = `${file.name} has an invalid file type of ${file.type}.`;
addErrorTimer(errorMessage);
} else if (invalidSize) {
errorMessage = `${file.name} is larger than 5MB.`;
addErrorTimer(errorMessage);
}
return invalidType || invalidSize;
});
}
fileSubmitHandler = (event) => {
event.preventDefault();
const fileList = document.querySelector('#files').files;
if (this.state.passwordValidated && fileList.length >= 1) {
this.setState({ url: generateURL() });
this.setState(
{
loading: true,
statusMessage:
`Loading file${fileList.length === 1 ? '' : 's'}...`,
},
);
this.promiseFileLoader(fileList);
} else if (fileList.length < 1) {
addErrorTimer('You must select a file.');
} else if (this.filesInvalid(fileList)) {
// If the files in the list are valid
} else if (!this.state.passwordValidated) {
addErrorTimer(this.state.passwordError);
}
}
handlePassword(passwordObj) {
this.setState({
password: <PASSWORD>,
passwordValidated: passwordObj.passwordValid,
passwordError: passwordObj.message,
});
}
render() {
this.props.resetCommentLoad();
if (this.state.uploaded) return <Redirect to={this.state.url} />;
return (
<form className="upload-grid" onSubmit={this.fileSubmitHandler}>
<div className="file-select-container">
<input type="file" id="files" multiple />
<FileLimitInstructions />
</div>
<Password
handlePassword={<PASSWORD>}
addErrorTimer={addErrorTimer}
/>
<button type="submit" className="button" disabled={this.state.loading}>Upload</button>
{this.state.loading && (
<div className="upload-loading">
<Loading message={this.state.statusMessage} />
</div>
)}
</form>
);
}
}
const mapStateToProps = state => ({
errors: state.errorReducer,
});
const mapDispatchToProps = dispatch => ({
addError: (error) => {
dispatch(addError(error));
},
removeError: (error) => {
dispatch(removeError(error));
},
resetCommentLoad: () => {
dispatch(resetCommentLoad());
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Upload);
<file_sep>import forge from 'node-forge';
import shortid from 'shortid';
export function generateFileHash(file) {
const messageDigest = forge.md.sha256.create();
const fileSHA256 = messageDigest.update(file);
return fileSHA256.digest().toHex().toString();
}
export function randomBytes(bytes) {
return forge.random.getBytesSync(bytes);
}
export function generateURL() {
return shortid.generate();
}
export function encode64(string) {
return forge.util.encode64(string);
}
<file_sep>import React, { Component } from 'react';
export default class Password extends Component {
state = {
password: '',
}
handlePassChange = (pass) => {
this.setState({ password: pass.target.value });
}
handleFormSubmit = (event) => {
event.preventDefault();
this.props.handlePassword(this.handlePasswordValidate(this.state.password));
}
handlePasswordValidate = (pass) => {
const result = {
password: <PASSWORD>,
passwordValid: true,
message: '',
};
if (pass.length === 0) {
result.passwordValid = false;
result.message = 'Password cannot be blank.';
}
return result;
}
render() {
return (
<form className="file-list-form" onSubmit={this.handleFormSubmit}>
<input className="file-list-pass" type="password" id="passDecrypt" placeholder="Decryption password" value={this.state.password} onChange={this.handlePassChange} />
<button className="file-list-button button" type="submit">Submit</button>
</form>
);
}
}
<file_sep>## Photo Share
An encrypted photo sharing service.
### Local Installation
* Install node per your OS specifications
* Install Meteor ([Link](https://guide.meteor.com/code-style.html#eslint-installing))
* `curl https://install.meteor.com | sh` (Mac/Linux command)
* Download Repo to your home folder
* `git clone https://github.com/kmeyerhofer/photo-share.git ~/photo-share`
* Run the server with the command `meteor` within the `photo-share` directory.
<file_sep>import React from 'react';
export default function Instructions() {
return (
<div className="instructions-flexbox">
<div className="instruction">
1. Select files to upload.
</div>
<div className="instruction">
2. Enter a password.
</div>
<div className="instruction">
3. Share link & password to friends and family.
</div>
</div>
);
}
<file_sep># [INSERT TITLE HERE]
## Functionality Description
## Package Changes
## Tests Added
| ee4b93783effa0669e0ef5360221fdd5b8b5f962 | [
"JavaScript",
"Markdown"
] | 33 | JavaScript | kmeyerhofer/photo-share | 99d5922ce066541fe44c1737b9805c2480afca97 | e2f4d43ff3075e43465f67c7665f2cc78821b979 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
/**
*
* @author acer
*/
public class timeMenit {
double result;
double inputValue;
public void setInput(String inputNumber) {
this.inputValue = Double.valueOf(inputNumber);
}
public double menitToJam() {
result = inputValue / 60;
return result;
}
public double menitToDetik() {
result = inputValue * 60;
return result;
}
public double menitToHari() {
result = inputValue / 1440;
return result;
}
public double menitToMinggu() {
result = inputValue / 10080;
return result;
}
public double menitToBulan() {
result = inputValue / 40320;
return result;
}
public double menitToTahun() {
result = inputValue / 483840;
return result;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package design;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import logic.timeBulan;
import logic.timeDetik;
import logic.timeHari;
import logic.timeJam;
import logic.timeMenit;
import logic.timeMinggu;
import logic.timeTahun;
/**
*
* @author <NAME>
*/
public class time extends javax.swing.JInternalFrame {
/**
* @author <NAME>
*/
String number;
double hari, detik, menit, jam, bulan, tahun, minggu;
String outputHari, outputDetik, outputMenit, outputJam, outputBulan, outputMinggu, outputTahun;
public time() {
super("Kalkulator Konversi sederhana");
initComponents();
number = "";
}
public void getNumber(javax.swing.JButton button) {
number += button.getText(); //Mengambil nilai dari button dan diubah ke tipe string dan ditampung divariabel number
txtInput.setText(number); //Merubah nilai data ke string agar dapat ditampilkan di hasil
}
void konversiHari() {
timeHari convertHari = new timeHari();
convertHari.setInput(number);
String getValue = txtInput.getText();
hari = Double.parseDouble(getValue);
jam = convertHari.HariToJam();
menit = convertHari.HariToMenit();
detik = convertHari.HariToDetik();
bulan = convertHari.HariToMinggu1();
minggu = convertHari.HariToBulan();
tahun = convertHari.HariToTahun();
//=========== result hari =================
outputHari = Double.toString(hari);
txtHari.setText(outputHari);
//=========== result jam =================
outputJam = Double.toString(jam);
txtJam.setText(outputJam);
//=========== result menit =================
outputMenit = Double.toString(menit);
txtMenit.setText(outputMenit);
//=========== result detik =================
outputDetik = Double.toString(detik);
txtSecond.setText(outputDetik);
//=========== result tahun =================
outputTahun = Double.toString(tahun);
txtTahun.setText(outputTahun);
//=========== result bulan =================
outputBulan = Double.toString(bulan);
txtBulan.setText(outputBulan);
//=========== result minggu =================
outputMinggu = Double.toString(minggu);
txtMinggu.setText(outputMinggu);
//============readonly===========
txtHari.setEditable(false);
txtJam.setEditable(false);
txtMenit.setEditable(false);
txtSecond.setEditable(false);
txtBulan.setEditable(false);
txtTahun.setEditable(false);
txtMinggu.setEditable(false);
}
void konversiMenit() {
timeMenit convertMenit = new timeMenit();
convertMenit.setInput(number);
String getValue = txtInput.getText();
hari = convertMenit.menitToHari();
jam = convertMenit.menitToJam();
menit = Double.parseDouble(getValue);
detik = convertMenit.menitToDetik();
minggu = convertMenit.menitToMinggu();
bulan = convertMenit.menitToBulan();
tahun = convertMenit.menitToTahun();
//=========== result hari =================
outputHari = Double.toString(hari);
txtHari.setText(outputHari);
//=========== result jam =================
outputJam = Double.toString(jam);
txtJam.setText(outputJam);
//=========== result menit =================
outputMenit = Double.toString(menit);
txtMenit.setText(outputMenit);
//=========== result detik =================
outputDetik = Double.toString(detik);
txtSecond.setText(outputDetik);
//=========== result tahun =================
outputTahun = Double.toString(tahun);
txtTahun.setText(outputTahun);
//=========== result bulan =================
outputBulan = Double.toString(bulan);
txtBulan.setText(outputBulan);
//=========== result minggu =================
outputMinggu = Double.toString(minggu);
txtMinggu.setText(outputMinggu);
//============readonly===========
txtHari.setEditable(false);
txtJam.setEditable(false);
txtMenit.setEditable(false);
txtSecond.setEditable(false);
txtBulan.setEditable(false);
txtTahun.setEditable(false);
txtMinggu.setEditable(false);
}
void konversiDetik() {
timeDetik convertDetik = new timeDetik();
convertDetik.setInput(number);
String getValue = txtInput.getText();
hari = convertDetik.DetikToHari();
jam = convertDetik.DetikToJam();
menit = convertDetik.DetikToMenit();
detik = Double.parseDouble(getValue);
minggu = convertDetik.DetikToMinggu();
bulan = convertDetik.DetikToBulan();
tahun = convertDetik.DetikToTahun();
//=========== result hari =================
outputHari = Double.toString(hari);
txtHari.setText(outputHari);
//=========== result jam =================
outputJam = Double.toString(jam);
txtJam.setText(outputJam);
//=========== result menit =================
outputMenit = Double.toString(menit);
txtMenit.setText(outputMenit);
//=========== result detik =================
outputDetik = Double.toString(detik);
txtSecond.setText(outputDetik);
//=========== result tahun =================
outputTahun = Double.toString(tahun);
txtTahun.setText(outputTahun);
//=========== result bulan =================
outputBulan = Double.toString(bulan);
txtBulan.setText(outputBulan);
//=========== result minggu =================
outputMinggu = Double.toString(minggu);
txtMinggu.setText(outputMinggu);
//============readonly===========
txtHari.setEditable(false);
txtJam.setEditable(false);
txtMenit.setEditable(false);
txtSecond.setEditable(false);
txtBulan.setEditable(false);
txtTahun.setEditable(false);
txtMinggu.setEditable(false);
}
void konversiJam() {
timeJam convertJam = new timeJam();
convertJam.setInput(number);
String getValue = txtInput.getText();
hari = convertJam.JamToHari();
jam = Double.parseDouble(getValue);
menit = convertJam.JamToMenit();
detik = convertJam.JamToDetik();
minggu = convertJam.JamToMinggu();
bulan = convertJam.JamToBulan();
tahun = convertJam.JamToTahun();
//=========== result hari =================
outputHari = Double.toString(hari);
txtHari.setText(outputHari);
//=========== result jam =================
outputJam = Double.toString(jam);
txtJam.setText(outputJam);
//=========== result menit =================
outputMenit = Double.toString(menit);
txtMenit.setText(outputMenit);
//=========== result detik =================
outputDetik = Double.toString(detik);
txtSecond.setText(outputDetik);
//=========== result tahun =================
outputTahun = Double.toString(tahun);
txtTahun.setText(outputTahun);
//=========== result bulan =================
outputBulan = Double.toString(bulan);
txtBulan.setText(outputBulan);
//=========== result minggu =================
outputMinggu = Double.toString(minggu);
txtMinggu.setText(outputMinggu);
//============readonly===========
txtHari.setEditable(false);
txtJam.setEditable(false);
txtMenit.setEditable(false);
txtSecond.setEditable(false);
txtBulan.setEditable(false);
txtTahun.setEditable(false);
txtMinggu.setEditable(false);
}
void konversiTahun() {
timeTahun convertTahun = new timeTahun();
convertTahun.setInput(number);
String getValue = txtInput.getText();
hari = convertTahun.tahunToHari();
jam = convertTahun.tahunToJam();
menit = convertTahun.tahunToMenit();
detik = convertTahun.tahunToDetik();
bulan = convertTahun.tahunTominggu();
minggu = convertTahun.tahunToBulan();
tahun = Double.parseDouble(getValue);
//=========== result hari =================
outputHari = Double.toString(hari);
txtHari.setText(outputHari);
//=========== result jam =================
outputJam = Double.toString(jam);
txtJam.setText(outputJam);
//=========== result menit =================
outputMenit = Double.toString(menit);
txtMenit.setText(outputMenit);
//=========== result detik =================
outputDetik = Double.toString(detik);
txtSecond.setText(outputDetik);
//=========== result tahun =================
outputTahun = Double.toString(tahun);
txtTahun.setText(outputTahun);
//=========== result bulan =================
outputBulan = Double.toString(bulan);
txtBulan.setText(outputBulan);
//=========== result minggu =================
outputMinggu = Double.toString(minggu);
txtMinggu.setText(outputMinggu);
//============readonly===========
txtHari.setEditable(false);
txtJam.setEditable(false);
txtMenit.setEditable(false);
txtSecond.setEditable(false);
txtBulan.setEditable(false);
txtTahun.setEditable(false);
txtMinggu.setEditable(false);
}
void konversiBulan() {
timeBulan convertBulan = new timeBulan();
convertBulan.setInput(number);
String getValue = txtInput.getText();
hari = convertBulan.bulanToHari();
jam = convertBulan.bulanToJam();
menit = convertBulan.bulanToMenit();//celcius*0.8;
detik = convertBulan.bulanToDetik();
minggu = convertBulan.bulanToMingguBln();
bulan = Double.parseDouble(getValue);
tahun = convertBulan.bulanToTahun();
//=========== result hari =================
outputHari = Double.toString(hari);
txtHari.setText(outputHari);
//
//=========== result jam =================
outputJam = Double.toString(jam);
txtJam.setText(outputJam);
//
//=========== result menit =================
outputMenit = Double.toString(menit);
txtMenit.setText(outputMenit);
//
//=========== result detik =================
outputDetik = Double.toString(detik);
txtSecond.setText(outputDetik);
//=========== result tahun =================
outputTahun = Double.toString(tahun);
txtTahun.setText(outputTahun);
//
//=========== result bulan =================
outputBulan = Double.toString(bulan);
txtBulan.setText(outputBulan);
//=========== result minggu =================
outputMinggu = Double.toString(minggu);
txtMinggu.setText(outputMinggu);
//============readonly===========
txtHari.setEditable(false);
txtJam.setEditable(false);
txtMenit.setEditable(false);
txtSecond.setEditable(false);
txtBulan.setEditable(false);
txtTahun.setEditable(false);
txtMinggu.setEditable(false);
}
void konversiMinggu() {
timeMinggu convertMinggu = new timeMinggu();
convertMinggu.setInput(number);
String getValue1 = txtInput.getText();
hari = convertMinggu.mingguToHari();
jam = convertMinggu.mingguToJam();
menit = convertMinggu.mingguToMenit();
detik = convertMinggu.mingguToDetik();
minggu = Double.parseDouble(getValue1);
bulan = convertMinggu.mingguToBulanM();
tahun = convertMinggu.mingguToTahun();
//=========== result hari =================
outputHari = Double.toString(hari);
txtHari.setText(outputHari);
// txtHari.getText().substring(0, 10);
//=========== result jam =================
outputJam = Double.toString(jam);
txtJam.setText(outputJam);
// txtJam.getText().substring(0, 10);
//=========== result menit =================
outputMenit = Double.toString(menit);
txtMenit.setText(outputMenit);
// txtMenit.getText().substring(0, 10);
//=========== result detik =================
outputDetik = Double.toString(detik);
txtSecond.setText(outputDetik);
// txtSecond.getText().substring(0, 10);
//=========== result tahun =================
outputTahun = Double.toString(tahun);
txtTahun.setText(outputTahun);
// txtTahun.getText().substring(0, 10);
//=========== result bulan =================
outputBulan = Double.toString(bulan);
txtBulan.setText(outputBulan);
// txtBulan.getText().substring(0, 10);
//=========== result minggu =================
outputMinggu = Double.toString(minggu);
txtMinggu.setText(outputMinggu);
// txtMinggu.getText().substring(0, 10);
//============readonly===========
txtHari.setEditable(false);
txtJam.setEditable(false);
txtMenit.setEditable(false);
txtSecond.setEditable(false);
txtBulan.setEditable(false);
txtTahun.setEditable(false);
txtMinggu.setEditable(false);
}
void textFieldKeyTyped(java.awt.event.KeyEvent evt) {
if (txtTahun.getText().length() == 15) {
evt.consume();
}
}
void displayInformasi() {
Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, 24);
UIManager.put("OptionPane.font", normalFont);
UIManager.put("OptionPane.messageFont", normalFont);
UIManager.put("OptionPane.minimumSize", new Dimension(400, 300));
UIManager.put("OptionPane.buttonFont", normalFont);
UIManager.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
JOptionPane.showMessageDialog(this,
"Time adalah Kalkulator menghitung Konversi waktu \nterdapat pilihan untuk mengkonversi waktu yakni"
+ "\nDetik, Menit " + "\nJam, Hari,\nMinggu, Bulan,\ndan Tahun\nklik = untuk melihat hasil\nbegitupun sebaliknya."
+ "\n " + "\ncreated by : <NAME>",
"Informasi",
JOptionPane.INFORMATION_MESSAGE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
radioGroup = new javax.swing.ButtonGroup();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
Btnsatu = new javax.swing.JButton();
Btndua = new javax.swing.JButton();
Btntiga = new javax.swing.JButton();
Btn4 = new javax.swing.JButton();
Btn5 = new javax.swing.JButton();
Btn6 = new javax.swing.JButton();
Btn7 = new javax.swing.JButton();
Btn8 = new javax.swing.JButton();
Btn9 = new javax.swing.JButton();
BtnTitik = new javax.swing.JButton();
BtnEqual = new javax.swing.JButton();
BtnClear = new javax.swing.JButton();
Btn0 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtSecond = new javax.swing.JTextField();
txtMenit = new javax.swing.JTextField();
Title = new javax.swing.JLabel();
txtJam = new javax.swing.JTextField();
txtHari = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txtTahun = new javax.swing.JTextField();
txtBulan = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
txtMinggu = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
txtInput = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
rdDetik = new javax.swing.JRadioButton();
rdMenit = new javax.swing.JRadioButton();
rdJam = new javax.swing.JRadioButton();
rdHari = new javax.swing.JRadioButton();
rdBulan = new javax.swing.JRadioButton();
rdTahun = new javax.swing.JRadioButton();
rdMinggu = new javax.swing.JRadioButton();
btnInfo = new javax.swing.JButton();
jPanel4.setBackground(new java.awt.Color(204, 204, 204));
jPanel5.setBackground(new java.awt.Color(240, 149, 221));
jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
Btnsatu.setText("1");
Btnsatu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnsatuActionPerformed(evt);
}
});
Btndua.setText("2");
Btndua.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnduaActionPerformed(evt);
}
});
Btntiga.setText("3");
Btntiga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtntigaActionPerformed(evt);
}
});
Btn4.setText("4");
Btn4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn4ActionPerformed(evt);
}
});
Btn5.setText("5");
Btn5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn5ActionPerformed(evt);
}
});
Btn6.setText("6");
Btn6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn6ActionPerformed(evt);
}
});
Btn7.setText("7");
Btn7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn7ActionPerformed(evt);
}
});
Btn8.setText("8");
Btn8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn8ActionPerformed(evt);
}
});
Btn9.setText("9");
Btn9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn9ActionPerformed(evt);
}
});
BtnTitik.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
BtnTitik.setText(".");
BtnTitik.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BtnTitik.setMargin(new java.awt.Insets(3, 14, 3, 14));
BtnTitik.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnTitikActionPerformed(evt);
}
});
BtnEqual.setText("=");
BtnEqual.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnEqualActionPerformed(evt);
}
});
BtnClear.setText("clear");
BtnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnClearActionPerformed(evt);
}
});
Btn0.setText("0");
Btn0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn0ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(Btnsatu, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Btndua, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(17, 17, 17)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(Btntiga, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BtnTitik, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn0, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(BtnEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btnsatu, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btndua, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btntiga, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn0, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnTitik, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 25, Short.MAX_VALUE))
);
jLabel2.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel2.setText("Input Value");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel3.setText("Pilih Konversi");
txtSecond.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtSecond.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSecondActionPerformed(evt);
}
});
txtMenit.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
Title.setFont(new java.awt.Font("Sitka Heading", 3, 48)); // NOI18N
Title.setForeground(new java.awt.Color(0, 51, 51));
Title.setText("Time");
txtJam.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtJam.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtJamActionPerformed(evt);
}
});
txtHari.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtHari.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtHariActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel4.setText("Second");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel5.setText("Menit");
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel7.setText("Jam");
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel8.setText("Hari");
txtTahun.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtTahun.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtTahunActionPerformed(evt);
}
});
txtBulan.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtBulan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtBulanActionPerformed(evt);
}
});
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel9.setText("Bulan");
txtMinggu.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtMinggu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtMingguActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel1.setText("Minggu");
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/time hijau.png"))); // NOI18N
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel10.setText("Tahun");
txtInput.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
radioGroup.add(rdDetik);
rdDetik.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
rdDetik.setText(" Detik");
radioGroup.add(rdMenit);
rdMenit.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
rdMenit.setText(" Menit");
radioGroup.add(rdJam);
rdJam.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
rdJam.setText(" Jam");
radioGroup.add(rdHari);
rdHari.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
rdHari.setText(" Hari");
radioGroup.add(rdBulan);
rdBulan.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
rdBulan.setText(" Bulan");
radioGroup.add(rdTahun);
rdTahun.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
rdTahun.setText(" Tahun");
radioGroup.add(rdMinggu);
rdMinggu.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
rdMinggu.setText(" Minggu");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(rdDetik)
.addGap(18, 18, 18)
.addComponent(rdTahun))
.addComponent(rdHari)
.addComponent(rdBulan)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rdMenit)
.addComponent(rdJam))
.addGap(18, 18, 18)
.addComponent(rdMinggu)))
.addContainerGap(20, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rdDetik)
.addComponent(rdTahun))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rdMenit)
.addComponent(rdMinggu))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rdJam)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rdHari)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rdBulan)
.addContainerGap(23, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addComponent(jLabel6)
.addComponent(txtInput)))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(270, 270, 270)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtSecond)
.addComponent(txtMenit)
.addComponent(txtJam)
.addComponent(txtHari)
.addComponent(txtTahun, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMinggu)
.addComponent(txtBulan))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel8)
.addComponent(jLabel9)
.addComponent(jLabel1)
.addComponent(jLabel10))
.addGap(85, 85, 85))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Title)
.addGap(247, 247, 247))))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Title)
.addComponent(jLabel3))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(61, 61, 61)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTahun, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addGap(28, 28, 28)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMinggu, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtBulan, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(jLabel1)))
.addGroup(jPanel4Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtSecond, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(18, 18, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMenit, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(28, 28, 28)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtJam, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtHari, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8))))
.addGap(93, 93, 93))
);
btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/circled-i (1).png"))); // NOI18N
btnInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInfoActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 882, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(731, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 12, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void BtnsatuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnsatuActionPerformed
getNumber(Btnsatu);
}//GEN-LAST:event_BtnsatuActionPerformed
private void BtnduaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnduaActionPerformed
getNumber(Btndua);
}//GEN-LAST:event_BtnduaActionPerformed
private void BtntigaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtntigaActionPerformed
getNumber(Btntiga);
}//GEN-LAST:event_BtntigaActionPerformed
private void Btn4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn4ActionPerformed
getNumber(Btn4);
}//GEN-LAST:event_Btn4ActionPerformed
private void Btn5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn5ActionPerformed
getNumber(Btn5);
}//GEN-LAST:event_Btn5ActionPerformed
private void Btn6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn6ActionPerformed
getNumber(Btn6);
}//GEN-LAST:event_Btn6ActionPerformed
private void Btn7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn7ActionPerformed
getNumber(Btn7);
}//GEN-LAST:event_Btn7ActionPerformed
private void Btn8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn8ActionPerformed
getNumber(Btn8);
}//GEN-LAST:event_Btn8ActionPerformed
private void Btn9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn9ActionPerformed
getNumber(Btn9);
}//GEN-LAST:event_Btn9ActionPerformed
private void BtnTitikActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnTitikActionPerformed
getNumber(BtnTitik);
}//GEN-LAST:event_BtnTitikActionPerformed
private void BtnEqualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEqualActionPerformed
if (rdHari.isSelected()) {
konversiHari();
} else if (rdJam.isSelected()) {
konversiJam();
} else if (rdMenit.isSelected()) {
konversiMenit();
} else if (rdBulan.isSelected()) {
konversiBulan();
} else if (rdDetik.isSelected()) {
konversiDetik();
} else if (rdMinggu.isSelected()) {
konversiMinggu();
} else {
konversiTahun();
}
}//GEN-LAST:event_BtnEqualActionPerformed
private void BtnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnClearActionPerformed
//Untuk hapus nilai data
number = "";
txtInput.setText("0");
txtHari.setText("0");
txtJam.setText("0");
txtMenit.setText("0");
txtMinggu.setText("0");
txtTahun.setText("0");
txtBulan.setText("0");
txtSecond.setText("0");
}//GEN-LAST:event_BtnClearActionPerformed
private void Btn0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn0ActionPerformed
getNumber(Btn0); // TODO add your handling code here:
}//GEN-LAST:event_Btn0ActionPerformed
private void txtJamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtJamActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtJamActionPerformed
private void txtHariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHariActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtHariActionPerformed
private void txtSecondActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSecondActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSecondActionPerformed
private void txtBulanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBulanActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtBulanActionPerformed
private void btnInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInfoActionPerformed
displayInformasi();
// JOptionPane.showMessageDialog(null," Program ini dibuat oleh \n Nama: <NAME> \n");
}//GEN-LAST:event_btnInfoActionPerformed
private void txtTahunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTahunActionPerformed
// TODO add your handling code here
}//GEN-LAST:event_txtTahunActionPerformed
private void txtMingguActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMingguActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtMingguActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Btn0;
private javax.swing.JButton Btn4;
private javax.swing.JButton Btn5;
private javax.swing.JButton Btn6;
private javax.swing.JButton Btn7;
private javax.swing.JButton Btn8;
private javax.swing.JButton Btn9;
private javax.swing.JButton BtnClear;
private javax.swing.JButton BtnEqual;
private javax.swing.JButton BtnTitik;
private javax.swing.JButton Btndua;
private javax.swing.JButton Btnsatu;
private javax.swing.JButton Btntiga;
private javax.swing.JLabel Title;
private javax.swing.JButton btnInfo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.ButtonGroup radioGroup;
private javax.swing.JRadioButton rdBulan;
private javax.swing.JRadioButton rdDetik;
private javax.swing.JRadioButton rdHari;
private javax.swing.JRadioButton rdJam;
private javax.swing.JRadioButton rdMenit;
private javax.swing.JRadioButton rdMinggu;
private javax.swing.JRadioButton rdTahun;
private javax.swing.JTextField txtBulan;
private javax.swing.JTextField txtHari;
private javax.swing.JTextField txtInput;
private javax.swing.JTextField txtJam;
private javax.swing.JTextField txtMenit;
private javax.swing.JTextField txtMinggu;
private javax.swing.JTextField txtSecond;
private javax.swing.JTextField txtTahun;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
/**
*
* @author <NAME>
*/
public class kalkulatorKonversi {
public static void main(String[] args) {
new design.awal().setVisible(true); //Memanggil file firstScreen.java
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
/**
*
* @author <NAME>
*/
public class timeMinggu {
double result;
double inputValue;
public void setInput(String inputNumber) {
this.inputValue = Double.valueOf(inputNumber);
}
public double mingguToTahun () {
result = inputValue / 52;
return result;
}
public double mingguToBulanM () {
result = inputValue / 4;
return result;
}
public double mingguToHari () {
result = inputValue * 7;
return result;
}
public double mingguToJam () {
result = inputValue * 168;
return result;
}
//rumus belum bener
public double mingguToMenit () {
result = inputValue * 10080;
return result;
}
public double mingguToDetik () {
result = inputValue * 6004800;
return result;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package design;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import logic.kelilingBangunDatar;
import logic.LuasBangunDatar;
/**
*
* @author <NAME>
*/
public class bangunDatar extends javax.swing.JInternalFrame {
/**
* Creates new form volume
*/
String inputValue, inputValue2, inputValue3, inputValue4;
double value1, value2, value3, value4, hasil;
int finalResult;
public bangunDatar() {
super("Kalkulator Konversi sederhana");
initComponents();
inputValue = "";
}
// volumeKonversi getLogicVolume = new volumeKonversi();
LuasBangunDatar lusBangunDatar = new LuasBangunDatar();
kelilingBangunDatar k = new kelilingBangunDatar();
ImageIcon myIcon = new ImageIcon("aset/apple-calculator.png");
void hitungLuas() {
int selectLuas = selectedLuas.getSelectedIndex();
switch (selectLuas) {
case 0:
txtInput1.setText(" ");
txtInput2.setText(" ");
txtInput3.setText(" ");
txtInput4.setText(" ");
break;
case 1:
//persegi panjang
String getPanjang = String.valueOf(txtInput1.getText());
String getLebar = String.valueOf(txtInput2.getText());
lusBangunDatar.setInput1(getPanjang);
lusBangunDatar.setInput2(getLebar);
hasil = lusBangunDatar.LuasBangunDatar();
String result = Double.toString(hasil);
txtHasil.setText(result);
break;
case 2:
//persegi
String getSisi1 = String.valueOf(txtInput1.getText());
String getSisis2 = String.valueOf(txtInput2.getText());
lusBangunDatar.setInput1(getSisi1);
lusBangunDatar.setInput2(getSisis2);
hasil = lusBangunDatar.LuasBangunDatar();
String resultPersegi = Double.toString(hasil);
txtHasil.setText(resultPersegi);
break;
case 3:
//belah ketupat
String getD1 = String.valueOf(txtInput1.getText());
String getD2 = String.valueOf(txtInput2.getText());
lusBangunDatar.setInput1(getD1);
lusBangunDatar.setInput2(getD2);
hasil = lusBangunDatar.LuasLayangKetupatSegitiga();
String resultKetupat = Double.toString(hasil);
txtHasil.setText(resultKetupat);
break;
case 4:
//jajar genjang
String getSisiMiring = String.valueOf(txtInput1.getText());
String getSisiAlas = String.valueOf(txtInput2.getText());
lusBangunDatar.setInput1(getSisiMiring);
lusBangunDatar.setInput2(getSisiAlas);
hasil = lusBangunDatar.LuasBangunDatar();
String resultJajarGenjang = Double.toString(hasil);
txtHasil.setText(resultJajarGenjang);
break;
case 5:
//Segitiga
String getAlas = String.valueOf(txtInput1.getText());
String getTinggi = String.valueOf(txtInput2.getText());
lusBangunDatar.setInput1(getAlas);
lusBangunDatar.setInput2(getTinggi);
hasil = lusBangunDatar.LuasLayangKetupatSegitiga();
String resultSegitiga = Double.toString(hasil);
txtHasil.setText(resultSegitiga);
break;
case 6:
//Strapesium
String getSisiSejajar1 = String.valueOf(txtInput1.getText());
String getSisiSejajar2 = String.valueOf(txtInput2.getText());
String getTinggiTrapsium = String.valueOf(txtInput3.getText());
lusBangunDatar.setInput1(getSisiSejajar1);
lusBangunDatar.setInput2(getSisiSejajar2);
lusBangunDatar.setInput3(getTinggiTrapsium);
hasil = lusBangunDatar.LuasTrapesium();
String resultTravesium = Double.toString(hasil);
txtHasil.setText(resultTravesium);
break;
case 7:
//layang-layang
String getDiagonal1 = String.valueOf(txtInput1.getText());
String getDiagonal2 = String.valueOf(txtInput2.getText());
lusBangunDatar.setInput1(getDiagonal1);
lusBangunDatar.setInput2(getDiagonal2);
hasil = lusBangunDatar.LuasLayangKetupatSegitiga();
String resultLayangLayang = Double.toString(hasil);
txtHasil.setText(resultLayangLayang);
break;
case 8:
//Lingkaran
String getJariJari = String.valueOf(txtInput1.getText());
lusBangunDatar.setInput1(getJariJari);
hasil = lusBangunDatar.LuasLingkaran();
String resultLingkaran = Double.toString(hasil);
txtHasil.setText(resultLingkaran);
break;
default:
}
}
void hitungKeliling() {
int selectKeliling = selectedKeliling.getSelectedIndex();
switch (selectKeliling) {
case 0:
txtInput1.setText(" ");
txtInput2.setText(" ");
txtInput3.setText(" ");
txtInput4.setText(" ");
break;
case 1:
//peregi panjang
String getPanjangKeliling = String.valueOf(txtInput1.getText());
String getLebarKeliling = String.valueOf(txtInput2.getText());
k.setInput1(getPanjangKeliling);
k.setInput2(getLebarKeliling);
hasil = k.KpersegiPanjangLayang2JajarGenjang();
String resultPP = Double.toString(hasil);
txtHasil.setText(resultPP);
break;
case 2:
//persegi
String getValueSisi = String.valueOf(txtInput1.getText());
k.setInput1(getValueSisi);
hasil = k.KelilingPersegiWithKetupat();
String resultPersegi = Double.toString(hasil);
txtHasil.setText(resultPersegi);
break;
case 3:
//belah ketupat
String getValueSisi1 = String.valueOf(txtInput1.getText());
k.setInput1(getValueSisi1);
hasil = k.KelilingPersegiWithKetupat();
String resultKKetupat = Double.toString(hasil);
txtHasil.setText(resultKKetupat);
break;
case 4:
//jajar genjang
String getSisiMiringK = String.valueOf(txtInput1.getText());
String getSisiAlasK = String.valueOf(txtInput2.getText());
k.setInput1(getSisiMiringK);
k.setInput2(getSisiAlasK);
hasil = k.KpersegiPanjangLayang2JajarGenjang();
String resultKJajarGenjang = Double.toString(hasil);
txtHasil.setText(resultKJajarGenjang);
break;
case 5:
//Segitiga
String getAlasSegitiga = String.valueOf(txtInput1.getText());
String getSisiKiri = String.valueOf(txtInput2.getText());
String getSisiKanan = String.valueOf(txtInput3.getText());
k.setInput1(getAlasSegitiga);
k.setInput2(getSisiKiri);
k.setInput2(getSisiKanan);
hasil = k.KelilingSegitiga();
String resultKSegitiga = Double.toString(hasil);
txtHasil.setText(resultKSegitiga);
break;
case 6:
//Strapesium
String getSisiSejajar1 = String.valueOf(txtInput1.getText());
String getSisiSejajar2 = String.valueOf(txtInput2.getText());
String getSisiSejajar3 = String.valueOf(txtInput3.getText());
String getSisiSejajar4 = String.valueOf(txtInput4.getText());
k.setInput1(getSisiSejajar1);
k.setInput2(getSisiSejajar2);
k.setInput3(getSisiSejajar3);
k.setInput4(getSisiSejajar4);
hasil = k.KelilingTrapesium();
String resultKTravesium = Double.toString(hasil);
txtHasil.setText(resultKTravesium);
break;
case 7:
//layang-layang
String getDiagonalK1 = String.valueOf(txtInput1.getText());
String getDiagonalK2 = String.valueOf(txtInput2.getText());
k.setInput1(getDiagonalK1);
k.setInput2(getDiagonalK2);
hasil = k.KpersegiPanjangLayang2JajarGenjang();
String resultKLayangLayang = Double.toString(hasil);
txtHasil.setText(resultKLayangLayang);
break;
case 8:
//Lingkaran
String getDiameter = String.valueOf(txtInput1.getText());
k.setInput1(getDiameter);
hasil = k.KelilingLingkaran();
String resultKLingkaran = Double.toString(hasil);
txtHasil.setText(resultKLingkaran);
break;
default:
}
}
void displayInformasi() {
Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, 24);
UIManager.put("OptionPane.font", normalFont);
UIManager.put("OptionPane.messageFont", normalFont);
UIManager.put("OptionPane.minimumSize", new Dimension(400, 300));
UIManager.put("OptionPane.buttonFont", normalFont);
UIManager.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
JOptionPane.showMessageDialog(this,
"L & K adalah kalkulator untuk menghitung\nLuas dan keliling dari sebuah Bangun Datar \ndiantaranya:" +
"\nPersegi Panjang, Persegi " + "\nBelah Ketupat, Jajar Genjang,\nSegitiga,Travesium,\nLayang-layang dan Lingkaran\nklik keliling = atau luas = untuk melihat hasil."
+ "\n " + "\ncreated by : <NAME>",
"Informasi",
JOptionPane.INFORMATION_MESSAGE);
}
;
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel4 = new javax.swing.JPanel();
Title = new javax.swing.JLabel();
txtInput1 = new javax.swing.JTextField();
txtHasil = new javax.swing.JTextField();
labelInput1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
selectedLuas = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
selectedKeliling = new javax.swing.JComboBox<>();
txtInput2 = new javax.swing.JTextField();
labelInput3 = new javax.swing.JLabel();
txtInput3 = new javax.swing.JTextField();
labelInput2 = new javax.swing.JLabel();
txtInput4 = new javax.swing.JTextField();
labelInput4 = new javax.swing.JLabel();
rumus = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
BtnClear = new javax.swing.JButton();
btnLuas = new javax.swing.JButton();
btnKeliling = new javax.swing.JButton();
btnInfo = new javax.swing.JButton();
jPanel4.setBackground(new java.awt.Color(204, 204, 204));
Title.setFont(new java.awt.Font("Sitka Heading", 3, 48)); // NOI18N
Title.setForeground(new java.awt.Color(51, 51, 0));
Title.setText("Luas & Keliling");
txtInput1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtInput1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtInput1ActionPerformed(evt);
}
});
txtHasil.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtHasil.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtHasilActionPerformed(evt);
}
});
labelInput1.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
labelInput1.setText("Input");
jLabel2.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel2.setText("Rumus");
selectedLuas.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
selectedLuas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "~ Luas Bangun Datar ~", "Persegi Panjang", "Persegi", "Belah Ketupat", "Jajar Genjang", "Segitiga", "Trapesium", "Layang-layang", "Lingkaran" }));
selectedLuas.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
selectedLuasItemStateChanged(evt);
}
});
selectedLuas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectedLuasActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel3.setText("Jenis Bangun datar");
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/AnyConv.com__vol bulat.png"))); // NOI18N
selectedKeliling.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
selectedKeliling.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "~ Keliling Bangun Datar ~", "Persegi Panjang", "Persegi", "Belah Ketupat", "Jajar Genjang", "Segitiga", "Trapesium", "Layang-layang", "Lingkaran" }));
selectedKeliling.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
selectedKelilingItemStateChanged(evt);
}
});
selectedKeliling.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectedKelilingActionPerformed(evt);
}
});
txtInput2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
labelInput3.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
labelInput3.setText("Input 3");
txtInput3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
txtInput3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtInput3ActionPerformed(evt);
}
});
labelInput2.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
labelInput2.setText("Input 2");
txtInput4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
labelInput4.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
labelInput4.setText("Input 4");
rumus.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
rumus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rumusActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel6.setText("Hasil");
BtnClear.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
BtnClear.setText("clear");
BtnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnClearActionPerformed(evt);
}
});
btnLuas.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
btnLuas.setText("Luas =");
btnLuas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLuasActionPerformed(evt);
}
});
btnKeliling.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
btnKeliling.setText("Keliling =");
btnKeliling.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnKelilingActionPerformed(evt);
}
});
btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/circled-i (1).png"))); // NOI18N
btnInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInfoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel3))
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(selectedLuas, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(selectedKeliling, javax.swing.GroupLayout.Alignment.LEADING, 0, 260, Short.MAX_VALUE)))
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(rumus, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel2))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel4)))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtHasil, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(btnKeliling, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnLuas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtInput3, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
.addComponent(txtInput1)
.addComponent(labelInput1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(labelInput3, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtInput2)
.addComponent(txtInput4)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelInput2, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(labelInput4, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 9, Short.MAX_VALUE)))))))
.addGap(56, 56, 56))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(246, 246, 246)
.addComponent(Title)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(Title))
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(labelInput1))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(labelInput2)))
.addGap(10, 10, 10)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtInput1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(selectedLuas, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtInput2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelInput3)
.addComponent(labelInput4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(selectedKeliling, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtInput3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtInput4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jLabel3)))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
.addComponent(rumus, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(jLabel4)
.addContainerGap(67, Short.MAX_VALUE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtHasil, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnLuas, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnKeliling, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnLuasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuasActionPerformed
hitungLuas();
}//GEN-LAST:event_btnLuasActionPerformed
private void BtnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnClearActionPerformed
//Untuk hapus nilai data
inputValue = "";
txtInput1.setText(" ");
txtInput2.setText(" ");
txtInput3.setText(" ");
txtInput4.setText(" ");
txtHasil.setText("0");
selectedKeliling.setSelectedIndex(0);
selectedLuas.setSelectedIndex(0);
// TODO add your handling code here:
}//GEN-LAST:event_BtnClearActionPerformed
private void txtInput1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtInput1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtInput1ActionPerformed
private void selectedLuasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectedLuasActionPerformed
}//GEN-LAST:event_selectedLuasActionPerformed
private void txtHasilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHasilActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtHasilActionPerformed
private void selectedKelilingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectedKelilingActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_selectedKelilingActionPerformed
private void txtInput3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtInput3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtInput3ActionPerformed
private void rumusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rumusActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_rumusActionPerformed
private void selectedLuasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_selectedLuasItemStateChanged
int pilihLuas = selectedLuas.getSelectedIndex();
switch (pilihLuas) {
case 0:
//change title
labelInput1.setText("value 1");
labelInput2.setText("value 2");
labelInput3.setText("value 3");
labelInput4.setText("value 4");
//disable textfield
txtInput1.setEnabled(false);
txtInput2.setEnabled(false);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" ");
rumus.setEditable(false);
break;
case 1:
//persegiPanjang
labelInput1.setText(" Panjang ");
labelInput2.setText(" Lebar ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" L = P * L");
rumus.setEditable(false);
break;
case 2:
//persegi
labelInput1.setText(" Sisi 1 ");
labelInput2.setText(" Sisi 2 ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" L = s * s");
rumus.setEditable(false);
break;
case 3:
//belah ketupat
labelInput1.setText(" Diagonal 1 ");
labelInput2.setText(" Diagonal 2 ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" L = 1/2 * d1 * d2");
rumus.setEditable(false);
break;
case 4:
//jajar genjang
labelInput1.setText(" Alas ");
labelInput2.setText(" Tinggi ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" L = alas * tinggi");
rumus.setEditable(false);
break;
case 5:
//Segitiga
labelInput1.setText(" Alas ");
labelInput2.setText(" Tinggi ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText("L = 1/2 * alas * tinggi");
rumus.setEditable(false);
break;
case 6:
//trapesium
labelInput1.setText(" Sisi Sejajar a ");
labelInput2.setText(" Sisi Sejajar b ");
labelInput3.setText(" Tinggi ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(true);
txtInput4.setEnabled(false);
rumus.setText(" L = 1/2*(a+b)*t ");
rumus.setEditable(false);
break;
case 7:
//layang layang
labelInput1.setText(" Diagonal 1 ");
labelInput2.setText(" Diagonal2 ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" L = 1/2 * d1 * d2");
rumus.setEditable(false);
break;
case 8:
//lingkaran
labelInput1.setText(" Jari-jari ");
labelInput2.setText(" ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(false);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" L = phi * jari-jari ^ 2");
rumus.setEditable(false);
break;
default:
}
}//GEN-LAST:event_selectedLuasItemStateChanged
private void selectedKelilingItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_selectedKelilingItemStateChanged
int pilihKeliling = selectedKeliling.getSelectedIndex();
switch (pilihKeliling) {
case 0:
//change title
labelInput1.setText("value 1");
labelInput2.setText("value 2");
labelInput3.setText("value 3");
labelInput4.setText("value 4");
//disable textfield
txtInput1.setEnabled(false);
txtInput2.setEnabled(false);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" ");
rumus.setEditable(false);
break;
case 1:
//persegiPanjang
labelInput1.setText(" Panjang ");
labelInput2.setText(" Lebar ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" L = 2 * (P + L)");
rumus.setEditable(false);
break;
case 2:
//persegi
labelInput1.setText(" Sisi ");
labelInput2.setText(" ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(false);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" K = 4 * s");
rumus.setEditable(false);
break;
case 3:
//belah ketupat
labelInput1.setText(" Sisi ");
labelInput2.setText(" ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(false);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" K = 4 * s");
rumus.setEditable(false);
break;
case 4:
//jajar genjang
labelInput1.setText(" Sisi Bawah ");
labelInput2.setText(" Sisi Miring ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" K = 2 * (a + b)");
rumus.setEditable(false);
break;
case 5:
//Segitiga
labelInput1.setText(" Alas ");
labelInput2.setText(" Sisi Kiri ");
labelInput3.setText(" Sisi Kanan ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(true);
txtInput4.setEnabled(false);
rumus.setText("K = a + b + c");
rumus.setEditable(false);
break;
case 6:
//trapesium
labelInput1.setText(" Sisi Sejajar 1 ");
labelInput2.setText(" Sisi Sejajar 2 ");
labelInput3.setText(" Sisi Sejajar 3 ");
labelInput4.setText(" Sisi Sejajar 4 ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(true);
txtInput4.setEnabled(true);
rumus.setText(" K = AB + BC + CD + DA ");
rumus.setEditable(false);
break;
case 7:
//layang layang
labelInput1.setText(" Sisi Miring Atas ");
labelInput2.setText(" Sisi Miring bawah ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(true);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" K = 2 * (AB + AD)");
rumus.setEditable(false);
break;
case 8:
//lingkaran
labelInput1.setText(" Diameter ");
labelInput2.setText(" ");
labelInput3.setText(" ");
labelInput4.setText(" ");
//disable textfield
txtInput1.setEnabled(true);
txtInput2.setEnabled(false);
txtInput3.setEnabled(false);
txtInput4.setEnabled(false);
rumus.setText(" K = phi * diameter");
rumus.setEditable(false);
break;
default:
}
}//GEN-LAST:event_selectedKelilingItemStateChanged
private void btnKelilingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKelilingActionPerformed
// TODO add your handling code here:
hitungKeliling();
}//GEN-LAST:event_btnKelilingActionPerformed
private void btnInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInfoActionPerformed
displayInformasi();
// JOptionPane.showMessageDialog(null," Program ini dibuat oleh \n Nama: <NAME> \n");
}//GEN-LAST:event_btnInfoActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BtnClear;
private javax.swing.JLabel Title;
private javax.swing.JButton btnInfo;
private javax.swing.JButton btnKeliling;
private javax.swing.JButton btnLuas;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel4;
private javax.swing.JLabel labelInput1;
private javax.swing.JLabel labelInput2;
private javax.swing.JLabel labelInput3;
private javax.swing.JLabel labelInput4;
private javax.swing.JTextField rumus;
private javax.swing.JComboBox<String> selectedKeliling;
private javax.swing.JComboBox<String> selectedLuas;
private javax.swing.JTextField txtHasil;
private javax.swing.JTextField txtInput1;
private javax.swing.JTextField txtInput2;
private javax.swing.JTextField txtInput3;
private javax.swing.JTextField txtInput4;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package design;
/**
*
* @author <NAME>
*/
public class Menu extends javax.swing.JFrame {
/**
* Creates new form menu utama
*/
public Menu() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
header = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
panelMenu = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
standar = new javax.swing.JButton();
suhu = new javax.swing.JButton();
time = new javax.swing.JButton();
volume = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
dekstopBody = new javax.swing.JDesktopPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setBackground(new java.awt.Color(252, 196, 196));
setBounds(new java.awt.Rectangle(0, 0, 0, 0));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setResizable(false);
setSize(new java.awt.Dimension(621, 410));
header.setBackground(new java.awt.Color(255, 204, 204));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/apple-calculator.png"))); // NOI18N
jLabel2.setFont(new java.awt.Font("Giddyup Std", 0, 48)); // NOI18N
jLabel2.setText("<NAME>");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 8)); // NOI18N
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/apple-calculator.png"))); // NOI18N
jLabel3.setText("jLabel3");
jLabel3.setMaximumSize(new java.awt.Dimension(30, 35));
javax.swing.GroupLayout headerLayout = new javax.swing.GroupLayout(header);
header.setLayout(headerLayout);
headerLayout.setHorizontalGroup(
headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerLayout.createSequentialGroup()
.addGap(91, 91, 91)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 467, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
headerLayout.setVerticalGroup(
headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headerLayout.createSequentialGroup()
.addGap(0, 23, Short.MAX_VALUE)
.addGroup(headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17))
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
panelMenu.setBackground(new java.awt.Color(255, 204, 204));
jPanel1.setBackground(new java.awt.Color(255, 153, 153));
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/icons8-menu-32.png"))); // NOI18N
jLabel5.setFont(new java.awt.Font("Kozuka Gothic Pro B", 2, 36)); // NOI18N
jLabel5.setText("Menu");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jLabel5)
.addContainerGap(85, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel4))
.addContainerGap())
);
standar.setBackground(new java.awt.Color(255, 153, 204));
standar.setFont(new java.awt.Font("Mongolian Baiti", 1, 24)); // NOI18N
standar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/icons8-calculator-32.png"))); // NOI18N
standar.setText("Standar");
standar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
standar.setIconTextGap(30);
standar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
standarActionPerformed(evt);
}
});
suhu.setBackground(new java.awt.Color(255, 153, 204));
suhu.setFont(new java.awt.Font("Mongolian Baiti", 1, 24)); // NOI18N
suhu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/icons8-temperature-sensitive-30.png"))); // NOI18N
suhu.setText("Suhu");
suhu.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
suhu.setIconTextGap(30);
suhu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
suhuActionPerformed(evt);
}
});
time.setBackground(new java.awt.Color(255, 153, 204));
time.setFont(new java.awt.Font("Mongolian Baiti", 1, 24)); // NOI18N
time.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/icons8-time-machine-32.png"))); // NOI18N
time.setText("Time");
time.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
time.setIconTextGap(30);
time.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
timeActionPerformed(evt);
}
});
volume.setBackground(new java.awt.Color(255, 153, 204));
volume.setFont(new java.awt.Font("Mongolian Baiti", 1, 24)); // NOI18N
volume.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/sugar-cube.png"))); // NOI18N
volume.setText("L & K");
volume.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
volume.setIconTextGap(30);
volume.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
volumeActionPerformed(evt);
}
});
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/ide.png"))); // NOI18N
jLabel7.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel7.setText("\" Be Smart");
jLabel8.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel8.setText("with Mathematics \"");
jLabel9.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel9.setText("Be Creative");
javax.swing.GroupLayout panelMenuLayout = new javax.swing.GroupLayout(panelMenu);
panelMenu.setLayout(panelMenuLayout);
panelMenuLayout.setHorizontalGroup(
panelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(standar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(suhu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(time, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(volume, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(panelMenuLayout.createSequentialGroup()
.addGroup(panelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelMenuLayout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(panelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel7)
.addGroup(panelMenuLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel6))))
.addGroup(panelMenuLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelMenuLayout.setVerticalGroup(
panelMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelMenuLayout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(standar, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(suhu, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(time, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(volume, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 93, Short.MAX_VALUE)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addGap(31, 31, 31)
.addComponent(jLabel6)
.addGap(47, 47, 47))
);
dekstopBody.setBackground(new java.awt.Color(204, 204, 204));
javax.swing.GroupLayout dekstopBodyLayout = new javax.swing.GroupLayout(dekstopBody);
dekstopBody.setLayout(dekstopBodyLayout);
dekstopBodyLayout.setHorizontalGroup(
dekstopBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 876, Short.MAX_VALUE)
);
dekstopBodyLayout.setVerticalGroup(
dekstopBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(header, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(panelMenu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(dekstopBody, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(header, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelMenu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(dekstopBody)))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void standarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_standarActionPerformed
standar standarUi = new standar();
dekstopBody.removeAll();
dekstopBody.add(standarUi);
standarUi.setSize(dekstopBody.getWidth(), dekstopBody.getHeight());
standarUi.setVisible(true);
standarUi.setUI(null);
}//GEN-LAST:event_standarActionPerformed
private void suhuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_suhuActionPerformed
SuhuKalkulator screenSuhu2 =new SuhuKalkulator();
dekstopBody.removeAll();
dekstopBody.add(screenSuhu2);
screenSuhu2.setSize(dekstopBody.getWidth(), dekstopBody.getHeight());
screenSuhu2.setVisible(true);
screenSuhu2.setUI(null);
}//GEN-LAST:event_suhuActionPerformed
private void timeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_timeActionPerformed
time timeUi = new time();
dekstopBody.removeAll();
dekstopBody.add(timeUi);
timeUi.setSize(dekstopBody.getWidth(), dekstopBody.getHeight());
timeUi.setVisible(true);
timeUi.setUI(null);
}//GEN-LAST:event_timeActionPerformed
private void volumeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_volumeActionPerformed
bangunDatar volumeUi = new bangunDatar();
dekstopBody.removeAll();
dekstopBody.add(volumeUi);
volumeUi.setSize(dekstopBody.getWidth(), dekstopBody.getHeight());
volumeUi.setVisible(true);
volumeUi.setUI(null);
}//GEN-LAST:event_volumeActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Menu().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JDesktopPane dekstopBody;
private javax.swing.JPanel header;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel panelMenu;
private javax.swing.JButton standar;
private javax.swing.JButton suhu;
private javax.swing.JButton time;
private javax.swing.JButton volume;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package design;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import logic.CelciusSuhu;
import logic.fahreinheit;
import logic.kelvin;
import logic.reamur;
/**
*
* @author <NAME>
*
*/
public class SuhuKalkulator extends javax.swing.JInternalFrame {
/**
* Creates new form Suhu
*/
String inputNumber;
//new variabel for logic
double celcius;
double fahreinheit;
double reamur;
double kelvin;
String outputConvertCelcius;
String outputConvertFahreinheit;
String outputConvertReamur;
String outputConvertKelvin;
public SuhuKalkulator() {
super("Kalkulator Konversi sederhana");
initComponents();
inputNumber = "";
}
public void getNumber(javax.swing.JButton button) {
inputNumber += button.getText(); //Mengambil nilai dari button dan diubah ke tipe string dan ditampung divariabel number
txtInput.setText(inputNumber);
}
private void hitungCelcius() {
CelciusSuhu celciusText = new CelciusSuhu();
celciusText.setInput(Integer.parseInt(inputNumber));
String getinput = txtInput.getText();
celcius = Double.parseDouble(getinput);
fahreinheit = celciusText.toFahrenheit();//celcius*0.8+32;
reamur = celciusText.toReamur();//celcius*0.8;
kelvin = celciusText.toKelvin();
//=========== result celcius =================
outputConvertCelcius = Double.toString(celcius);
resultCelcius.setText(outputConvertCelcius);
//=========== result fahreinheit =================
outputConvertFahreinheit = Double.toString(fahreinheit);
resultFahreinheit.setText(outputConvertFahreinheit);
//=========== result reamur =================
outputConvertReamur = Double.toString(reamur);
resultReamur.setText(outputConvertReamur);
//=========== result kelvin =================
outputConvertKelvin = Double.toString(kelvin);
resultKelvin.setText(outputConvertKelvin);
//============readonly===========
resultCelcius.setEditable(false);
resultFahreinheit.setEditable(false);
resultKelvin.setEditable(false);
resultReamur.setEditable(false);
}
public void hitungFahreinheit() {
fahreinheit convertFahreinheit = new fahreinheit();
convertFahreinheit.setInput(Integer.parseInt(inputNumber));
String getValueText = txtInput.getText();
celcius = convertFahreinheit.toCelcius();
fahreinheit = Double.parseDouble(getValueText);
reamur = convertFahreinheit.toReamur();
kelvin = convertFahreinheit.toKelvin();
//=========== result celcius =================
outputConvertCelcius = Double.toString(celcius);
resultCelcius.setText(outputConvertCelcius);
//=========== result fahreinheit =================
outputConvertFahreinheit = Double.toString(fahreinheit);
resultFahreinheit.setText(outputConvertFahreinheit);
//=========== result reamur =================
outputConvertReamur = Double.toString(reamur);
resultReamur.setText(outputConvertReamur);
//=========== result kelvin =================
outputConvertKelvin = Double.toString(kelvin);
resultKelvin.setText(outputConvertKelvin);
//============readonly===========
resultCelcius.setEditable(false);
resultFahreinheit.setEditable(false);
resultKelvin.setEditable(false);
resultReamur.setEditable(false);
}
public void hitungReamur() {
reamur convertReamur = new reamur();
convertReamur.setInput(Integer.parseInt(inputNumber));
String getValueText = txtInput.getText();
celcius = convertReamur.toCelcius();
fahreinheit = convertReamur.toFahrenheit();
reamur = Double.parseDouble(getValueText);
kelvin = convertReamur.toKelvin();
//=========== result celcius =================
outputConvertCelcius = Double.toString(celcius);
resultCelcius.setText(outputConvertCelcius);
//=========== result fahreinheit =================
outputConvertFahreinheit = Double.toString(fahreinheit);
resultFahreinheit.setText(outputConvertFahreinheit);
//=========== result reamur =================
outputConvertReamur = Double.toString(reamur);
resultReamur.setText(outputConvertReamur);
//=========== result kelvin =================
outputConvertKelvin = Double.toString(kelvin);
resultKelvin.setText(outputConvertKelvin);
//============readonly===========
resultCelcius.setEditable(false);
resultFahreinheit.setEditable(false);
resultKelvin.setEditable(false);
resultReamur.setEditable(false);
}
public void hitungKelvin() {
kelvin convertKelvin = new kelvin();
convertKelvin.setInput(Integer.parseInt(inputNumber));
String getValueText = txtInput.getText();
celcius = convertKelvin.toCelcius();
fahreinheit = convertKelvin.toFahrenheit();
reamur = convertKelvin.toReamur();
kelvin = Double.parseDouble(getValueText);
//=========== result celcius =================
outputConvertCelcius = Double.toString(celcius);
resultCelcius.setText(outputConvertCelcius);
//=========== result fahreinheit =================
outputConvertFahreinheit = Double.toString(fahreinheit);
resultFahreinheit.setText(outputConvertFahreinheit);
//=========== result reamur =================
outputConvertReamur = Double.toString(reamur);
resultReamur.setText(outputConvertReamur);
//=========== result kelvin =================
outputConvertKelvin = Double.toString(kelvin);
resultKelvin.setText(outputConvertKelvin);
//============readonly===========
resultCelcius.setEditable(false);
resultFahreinheit.setEditable(false);
resultKelvin.setEditable(false);
resultReamur.setEditable(false);
}
void displayInformasi() {
Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, 24);
UIManager.put("OptionPane.font", normalFont);
UIManager.put("OptionPane.messageFont", normalFont);
UIManager.put("OptionPane.minimumSize", new Dimension(400, 300));
UIManager.put("OptionPane.buttonFont", normalFont);
UIManager.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
JOptionPane.showMessageDialog(this,
"Suhu adalah kalkulator untuk menghitung\nkonversi suhu ke suhu yang lain" + "\npilih salah satu suhu diantaranya :" +
"\nCelcius,\nFahreinheit,\nReamur,\nKelvin \nkemudian, klik ( = )untuk melihat hasil"
+ "\n " + "\ncreated by : <NAME>",
"Informasi",
JOptionPane.INFORMATION_MESSAGE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup2 = new javax.swing.ButtonGroup();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
Btnsatu = new javax.swing.JButton();
Btndua = new javax.swing.JButton();
Btntiga = new javax.swing.JButton();
Btn4 = new javax.swing.JButton();
Btn5 = new javax.swing.JButton();
Btn6 = new javax.swing.JButton();
Btn7 = new javax.swing.JButton();
Btn8 = new javax.swing.JButton();
Btn9 = new javax.swing.JButton();
BtnTitik = new javax.swing.JButton();
BtnEqual = new javax.swing.JButton();
BtnClear = new javax.swing.JButton();
Btn0 = new javax.swing.JButton();
txtInput = new javax.swing.JTextField();
resultCelcius = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
btnFahreinheit = new javax.swing.JRadioButton();
btnReamur = new javax.swing.JRadioButton();
btnKelvin = new javax.swing.JRadioButton();
btnCelcius = new javax.swing.JRadioButton();
resultReamur = new javax.swing.JTextField();
resultFahreinheit = new javax.swing.JTextField();
resultKelvin = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
Title = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
btnInfo = new javax.swing.JButton();
jPanel4.setBackground(new java.awt.Color(204, 204, 204));
jPanel5.setBackground(new java.awt.Color(255, 183, 231));
jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
Btnsatu.setText("1");
Btnsatu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnsatuActionPerformed(evt);
}
});
Btndua.setText("2");
Btndua.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnduaActionPerformed(evt);
}
});
Btntiga.setText("3");
Btntiga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtntigaActionPerformed(evt);
}
});
Btn4.setText("4");
Btn4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn4ActionPerformed(evt);
}
});
Btn5.setText("5");
Btn5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn5ActionPerformed(evt);
}
});
Btn6.setText("6");
Btn6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn6ActionPerformed(evt);
}
});
Btn7.setText("7");
Btn7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn7ActionPerformed(evt);
}
});
Btn8.setText("8");
Btn8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn8ActionPerformed(evt);
}
});
Btn9.setText("9");
Btn9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn9ActionPerformed(evt);
}
});
BtnTitik.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
BtnTitik.setText(".");
BtnTitik.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BtnTitik.setMargin(new java.awt.Insets(3, 14, 3, 14));
BtnTitik.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnTitikActionPerformed(evt);
}
});
BtnEqual.setText("=");
BtnEqual.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnEqualActionPerformed(evt);
}
});
BtnClear.setText("clear");
BtnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnClearActionPerformed(evt);
}
});
Btn0.setText("0");
Btn0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn0ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(Btnsatu, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Btndua, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(17, 17, 17)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(Btntiga, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BtnTitik, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn0, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(BtnEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btnsatu, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btndua, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btntiga, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn0, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnTitik, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 25, Short.MAX_VALUE))
);
txtInput.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
txtInput.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtInputActionPerformed(evt);
}
});
resultCelcius.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
resultCelcius.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resultCelciusActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Sitka Heading", 3, 24)); // NOI18N
jLabel1.setText("Input Suhu awal");
jLabel3.setFont(new java.awt.Font("Sitka Heading", 0, 24)); // NOI18N
jLabel3.setText("Pilih Konversi");
jPanel1.setBackground(new java.awt.Color(255, 125, 217));
btnFahreinheit.setBackground(new java.awt.Color(255, 118, 208));
buttonGroup2.add(btnFahreinheit);
btnFahreinheit.setFont(new java.awt.Font("OCR A Std", 0, 18)); // NOI18N
btnFahreinheit.setText("Fahreinheit");
btnReamur.setBackground(new java.awt.Color(255, 118, 225));
buttonGroup2.add(btnReamur);
btnReamur.setFont(new java.awt.Font("OCR A Std", 0, 18)); // NOI18N
btnReamur.setText("Reamur");
btnKelvin.setBackground(new java.awt.Color(255, 111, 223));
buttonGroup2.add(btnKelvin);
btnKelvin.setFont(new java.awt.Font("OCR A Std", 0, 18)); // NOI18N
btnKelvin.setText("Kelvin");
btnCelcius.setBackground(new java.awt.Color(255, 126, 221));
buttonGroup2.add(btnCelcius);
btnCelcius.setFont(new java.awt.Font("OCR A Std", 0, 18)); // NOI18N
btnCelcius.setText("Celcius");
btnCelcius.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCelciusActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnCelcius)
.addComponent(btnKelvin)
.addComponent(btnFahreinheit)
.addComponent(btnReamur))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(btnCelcius)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnFahreinheit)
.addGap(18, 18, 18)
.addComponent(btnReamur)
.addGap(18, 18, 18)
.addComponent(btnKelvin)
.addContainerGap(23, Short.MAX_VALUE))
);
resultReamur.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
resultReamur.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resultReamurActionPerformed(evt);
}
});
resultFahreinheit.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
resultFahreinheit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resultFahreinheitActionPerformed(evt);
}
});
resultKelvin.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
resultKelvin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resultKelvinActionPerformed(evt);
}
});
jPanel2.setBackground(new java.awt.Color(204, 204, 204));
Title.setFont(new java.awt.Font("Sitka Heading", 3, 48)); // NOI18N
Title.setForeground(new java.awt.Color(0, 51, 51));
Title.setText("Suhu");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(Title)
.addContainerGap(95, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(Title)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel4.setBackground(new java.awt.Color(204, 204, 204));
jLabel4.setFont(new java.awt.Font("Sitka Heading", 0, 24)); // NOI18N
jLabel4.setText("Celcius");
jLabel5.setFont(new java.awt.Font("Sitka Heading", 0, 24)); // NOI18N
jLabel5.setText("Fahreinheit");
jLabel6.setFont(new java.awt.Font("Sitka Heading", 0, 24)); // NOI18N
jLabel6.setText("Reamur");
jLabel7.setFont(new java.awt.Font("Sitka Heading", 0, 24)); // NOI18N
jLabel7.setText("Kelvin");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel2.setText("<NAME>");
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/suhuPicture.png"))); // NOI18N
btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/circled-i (1).png"))); // NOI18N
btnInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInfoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtInput)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6)
.addComponent(resultReamur, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
.addComponent(resultCelcius))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel5)
.addComponent(jLabel7)
.addComponent(resultFahreinheit, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
.addComponent(resultKelvin)))
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(168, 168, 168)
.addComponent(jLabel2)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(62, 62, 62))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(289, 289, 289)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(resultCelcius, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(resultFahreinheit, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addGap(6, 6, 6)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(resultReamur, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(resultKelvin, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(36, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addGap(58, 58, 58))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void BtnsatuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnsatuActionPerformed
getNumber(Btnsatu);
}//GEN-LAST:event_BtnsatuActionPerformed
private void BtnduaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnduaActionPerformed
getNumber(Btndua);
}//GEN-LAST:event_BtnduaActionPerformed
private void BtntigaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtntigaActionPerformed
getNumber(Btntiga);
}//GEN-LAST:event_BtntigaActionPerformed
private void Btn4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn4ActionPerformed
getNumber(Btn4);
}//GEN-LAST:event_Btn4ActionPerformed
private void Btn5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn5ActionPerformed
getNumber(Btn5);
}//GEN-LAST:event_Btn5ActionPerformed
private void Btn6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn6ActionPerformed
getNumber(Btn6);
}//GEN-LAST:event_Btn6ActionPerformed
private void Btn7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn7ActionPerformed
getNumber(Btn7);
}//GEN-LAST:event_Btn7ActionPerformed
private void Btn8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn8ActionPerformed
getNumber(Btn8);
}//GEN-LAST:event_Btn8ActionPerformed
private void Btn9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn9ActionPerformed
getNumber(Btn9);
}//GEN-LAST:event_Btn9ActionPerformed
private void BtnTitikActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnTitikActionPerformed
getNumber(BtnTitik);
}//GEN-LAST:event_BtnTitikActionPerformed
private void BtnEqualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEqualActionPerformed
if (btnCelcius.isSelected()) {
hitungCelcius();
} else if (btnFahreinheit.isSelected()) {
hitungFahreinheit();
} else if (btnReamur.isSelected()) {
hitungReamur();
} else {
hitungKelvin();
}
}//GEN-LAST:event_BtnEqualActionPerformed
private void BtnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnClearActionPerformed
//Untuk hapus nilai data
inputNumber = "";
txtInput.setText("0");
resultCelcius.setText("0");
resultFahreinheit.setText("0");
resultKelvin.setText("0");
resultReamur.setText("0");
// TODO add your handling code here:
}//GEN-LAST:event_BtnClearActionPerformed
private void Btn0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn0ActionPerformed
getNumber(Btn0); // TODO add your handling code here:
}//GEN-LAST:event_Btn0ActionPerformed
private void txtInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtInputActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtInputActionPerformed
private void btnCelciusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCelciusActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnCelciusActionPerformed
private void resultReamurActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resultReamurActionPerformed
// TODO add your handling code here:
resultReamur.setEditable(false);
}//GEN-LAST:event_resultReamurActionPerformed
private void resultKelvinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resultKelvinActionPerformed
// TODO add your handling code here:
resultKelvin.setEditable(false);
}//GEN-LAST:event_resultKelvinActionPerformed
private void resultCelciusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resultCelciusActionPerformed
// TODO add your handling code here:
resultCelcius.setEditable(false);
}//GEN-LAST:event_resultCelciusActionPerformed
private void resultFahreinheitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resultFahreinheitActionPerformed
// TODO add your handling code here:
resultFahreinheit.setEditable(false);
}//GEN-LAST:event_resultFahreinheitActionPerformed
private void btnInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInfoActionPerformed
displayInformasi();
// JOptionPane.showMessageDialog(null," Program ini dibuat oleh \n Nama: <NAME> \n");
}//GEN-LAST:event_btnInfoActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Btn0;
private javax.swing.JButton Btn4;
private javax.swing.JButton Btn5;
private javax.swing.JButton Btn6;
private javax.swing.JButton Btn7;
private javax.swing.JButton Btn8;
private javax.swing.JButton Btn9;
private javax.swing.JButton BtnClear;
private javax.swing.JButton BtnEqual;
private javax.swing.JButton BtnTitik;
private javax.swing.JButton Btndua;
private javax.swing.JButton Btnsatu;
private javax.swing.JButton Btntiga;
private javax.swing.JLabel Title;
private javax.swing.JRadioButton btnCelcius;
private javax.swing.JRadioButton btnFahreinheit;
private javax.swing.JButton btnInfo;
private javax.swing.JRadioButton btnKelvin;
private javax.swing.JRadioButton btnReamur;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JTextField resultCelcius;
private javax.swing.JTextField resultFahreinheit;
private javax.swing.JTextField resultKelvin;
private javax.swing.JTextField resultReamur;
private javax.swing.JTextField txtInput;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
/**
*
* @author <NAME>
*/
public class timeHari {
double result;
double inputValue;
public void setInput(String inputNumber) {
this.inputValue = Double.valueOf(inputNumber);
}
public double HariToJam () {
result = inputValue * 24;
return result;
}
public double HariToMenit () {
result = inputValue * 1440;
return result;
}
public double HariToDetik () {
result = inputValue * 86400;
return result;
}
public double HariToBulan () {
result = inputValue / 30;
return result;
}
public double HariToTahun () {
result = inputValue / 365;
return result;
}
public double HariToMinggu1 () {
result = inputValue / 7;
return result;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
/**
*
* @author acer
*/
public class LuasBangunDatar {
double result;
double value1, value2,value3;
public void setInput(String input) {
if (!input.equals("")) {
value1 = Double.valueOf(input);
} else if(!"".equals(input)){
value2 = Double.valueOf(input);
}else if(!"".equals(input)){
value3 = Double.valueOf(input);
}
}
public void setInput1(String inputNumber) {
this.value1 = Double.valueOf(inputNumber);
}
public void setInput2(String inputNumber) {
this.value2 = Double.valueOf(inputNumber);
}
public void setInput3(String inputNumber) {
this.value3 = Double.valueOf(inputNumber);
}
//rumus luas bangun datar
public double LuasBangunDatar() {
result = value1 * value2;
return result;
//untuk persegi = L = s * s
// persegi panjang = = L = p * l
//jajargenjang = = L = s * s
}
public double LuasLayangKetupatSegitiga() {
result = value1 * value2 * 0.5;
return result;
//L = 1/2(d1*d2) layang layang
// L= 1/2(d1*d2) belahketuoat
// L= 1/2(a*t) segitiga
}
public double LuasLingkaran() {
//L = 3.14 * r^2 lingkaran
result = Math.PI * Math.pow(value1, 2);
return result;
}
public double LuasTrapesium() {
//L = 1/2 * (a+b)*t
result = 0.5 * (value1 + value2) * value3;
return result;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
/**
*
*@author <NAME>
*/
public class timeJam {
double result;
double inputValue;
public void setInput(String inputNumber) {
this.inputValue = Double.valueOf(inputNumber);
}
public double JamToHari () {
result = inputValue / 24;
return result;
}
public double JamToDetik () {
result = inputValue * 3600;
return result;
}
public double JamToMenit () {
result = inputValue * 60;
return result;
}
//belum bener
public double JamToMinggu () {
result = inputValue / 168;
return result;
}
public double JamToBulan () {
result = inputValue / 720;
return result;
}
public double JamToTahun () {
result = inputValue / 8640;
return result;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logic;
/**
*
* @author <NAME>
*/
public class timeBulan {
double result;
double inputValue;
public void setInput(String inputNumber) {
this.inputValue = Double.valueOf(inputNumber);
}
public double bulanToTahun() {
result = inputValue / 12;
return result;
}
public double bulanToMingguBln() {
result = inputValue * 4;
return result;
}
public double bulanToHari() {
result = inputValue * 30;
return result;
}
public double bulanToJam() {
result = inputValue * 720 ;
return result;
}
public double bulanToMenit() {
result = inputValue * 403200;
return result;
} public double bulanToDetik() {
result = inputValue * 2419200;
return result;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package design;
import java.awt.Dimension;
import java.awt.Font;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import logic.OperasiKalkulatorStandar;
/**
*
* @author <NAME>
*/
public class standar extends javax.swing.JInternalFrame {
/**
* Creates new form standar
*/
String inputNumber;
public standar() {
super("Kalkulator Konversi sederhana");
initComponents();
inputNumber = "";
}
OperasiKalkulatorStandar calculator = new OperasiKalkulatorStandar();
public void getNumber(javax.swing.JButton button) {
inputNumber += button.getText(); //Mengambil nilai dari button dan diubah ke tipe string dan ditampung divariabel number
calculator.setNumber(inputNumber);//Merubah nilai model int
txtResult.setText(inputNumber ); //Merubah nilai data ke string agar dapat ditampilkan di hasil
labelProses.setText(inputNumber); //Merubah nilai data ke string agar dapat ditampilkan di labelprocess
}
private void getOperator(int operation) {
calculator.setOperator(operation);
inputNumber = "";
}
private void result() {
DecimalFormat df = new DecimalFormat("#,###.########"); //Merubah decimal format
calculator.process();
inputNumber = "";
//Menampilkan hasil perhitungan di hasil
txtResult.setText(df.format(calculator.getResult()) + "");
//Menampilkan process perhitungan yang dibuat pada label process
labelProses.setText(df.format(calculator.angka3) + "" + calculator.cetakProses + "" + (df.format(calculator.angka2) + "=" + (df.format(calculator.result))));
}
void displayInformasi() {
Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, 24);
UIManager.put("OptionPane.font", normalFont);
UIManager.put("OptionPane.messageFont", normalFont);
UIManager.put("OptionPane.minimumSize", new Dimension(400, 300));
UIManager.put("OptionPane.buttonFont", normalFont);
UIManager.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
JOptionPane.showMessageDialog(this,
"Ini adalah Kalkulator standar" + "\ndimana bisa pengoperasian Aritmatika " + "\nKali (*),\nBagi(:),\nTambah(+),\nKurang(-)"
+ "\n " + "\ncreated by : <NAME>",
"Informasi",
JOptionPane.INFORMATION_MESSAGE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
Btnsatu = new javax.swing.JButton();
Btndua = new javax.swing.JButton();
Btntiga = new javax.swing.JButton();
Btn4 = new javax.swing.JButton();
Btn5 = new javax.swing.JButton();
Btn6 = new javax.swing.JButton();
Btn7 = new javax.swing.JButton();
Btn8 = new javax.swing.JButton();
Btn9 = new javax.swing.JButton();
BtnTitik = new javax.swing.JButton();
BtnEqual = new javax.swing.JButton();
BtnClear = new javax.swing.JButton();
Btn0 = new javax.swing.JButton();
BtnPlus = new javax.swing.JButton();
BtnMin = new javax.swing.JButton();
BtnBagi = new javax.swing.JButton();
BtnKali = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
txtResult = new javax.swing.JTextField();
labelProses = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
btnInfo = new javax.swing.JButton();
jPanel1.setBackground(new java.awt.Color(204, 204, 204));
jPanel5.setBackground(new java.awt.Color(255, 153, 204));
jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
Btnsatu.setText("1");
Btnsatu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnsatuActionPerformed(evt);
}
});
Btndua.setText("2");
Btndua.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnduaActionPerformed(evt);
}
});
Btntiga.setText("3");
Btntiga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtntigaActionPerformed(evt);
}
});
Btn4.setText("4");
Btn4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn4ActionPerformed(evt);
}
});
Btn5.setText("5");
Btn5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn5ActionPerformed(evt);
}
});
Btn6.setText("6");
Btn6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn6ActionPerformed(evt);
}
});
Btn7.setText("7");
Btn7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn7ActionPerformed(evt);
}
});
Btn8.setText("8");
Btn8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn8ActionPerformed(evt);
}
});
Btn9.setText("9");
Btn9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn9ActionPerformed(evt);
}
});
BtnTitik.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
BtnTitik.setText(".");
BtnTitik.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BtnTitik.setMargin(new java.awt.Insets(3, 14, 3, 14));
BtnTitik.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnTitikActionPerformed(evt);
}
});
BtnEqual.setText("=");
BtnEqual.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnEqualActionPerformed(evt);
}
});
BtnClear.setText("clear");
BtnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnClearActionPerformed(evt);
}
});
Btn0.setText("0");
Btn0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn0ActionPerformed(evt);
}
});
BtnPlus.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
BtnPlus.setText("+");
BtnPlus.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BtnPlus.setMargin(new java.awt.Insets(3, 14, 3, 14));
BtnPlus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnPlusActionPerformed(evt);
}
});
BtnMin.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
BtnMin.setText("-");
BtnMin.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BtnMin.setMargin(new java.awt.Insets(3, 14, 3, 14));
BtnMin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnMinActionPerformed(evt);
}
});
BtnBagi.setText("/");
BtnBagi.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BtnBagi.setMargin(new java.awt.Insets(3, 14, 3, 14));
BtnBagi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnBagiActionPerformed(evt);
}
});
BtnKali.setText("*");
BtnKali.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
BtnKali.setMargin(new java.awt.Insets(3, 14, 3, 14));
BtnKali.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnKaliActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(Btnsatu, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Btndua, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(Btntiga, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(BtnTitik, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(BtnPlus, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
.addComponent(Btn0, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(BtnKali, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE)
.addComponent(BtnMin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(BtnBagi, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(170, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btnsatu, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btndua, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btntiga, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn0, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnBagi, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnClear, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn5, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn6, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn4, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnKali, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnEqual, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(BtnTitik, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BtnPlus, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Btn7, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn8, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn9, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BtnMin, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(25, 25, 25))
);
txtResult.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N
txtResult.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txtResult.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtResultActionPerformed(evt);
}
});
labelProses.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
labelProses.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelProses.setText("Proses");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtResult, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 674, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelProses, javax.swing.GroupLayout.PREFERRED_SIZE, 602, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(txtResult, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelProses, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE)
.addContainerGap())
);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/kalkulator cek.png"))); // NOI18N
jLabel1.setFont(new java.awt.Font("Serif", 3, 80)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 51, 51));
jLabel1.setText("Standar");
jLabel3.setFont(new java.awt.Font("Sitka Heading", 3, 36)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 51, 51));
jLabel3.setText("Kalkulator");
btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aset/circled-i (1).png"))); // NOI18N
btnInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInfoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(jLabel3)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(95, 95, 95))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 71, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(62, 62, 62))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(jLabel2))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel3))
.addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(49, 49, 49))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 16, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void BtnsatuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnsatuActionPerformed
getNumber(Btnsatu);
}//GEN-LAST:event_BtnsatuActionPerformed
private void BtnduaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnduaActionPerformed
getNumber(Btndua);
}//GEN-LAST:event_BtnduaActionPerformed
private void BtntigaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtntigaActionPerformed
getNumber(Btntiga);
}//GEN-LAST:event_BtntigaActionPerformed
private void Btn4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn4ActionPerformed
getNumber(Btn4);
}//GEN-LAST:event_Btn4ActionPerformed
private void Btn5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn5ActionPerformed
getNumber(Btn5);
}//GEN-LAST:event_Btn5ActionPerformed
private void Btn6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn6ActionPerformed
getNumber(Btn6);
}//GEN-LAST:event_Btn6ActionPerformed
private void Btn7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn7ActionPerformed
getNumber(Btn7);
}//GEN-LAST:event_Btn7ActionPerformed
private void Btn8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn8ActionPerformed
getNumber(Btn8);
}//GEN-LAST:event_Btn8ActionPerformed
private void Btn9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn9ActionPerformed
getNumber(Btn9);
}//GEN-LAST:event_Btn9ActionPerformed
private void BtnTitikActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnTitikActionPerformed
getNumber(BtnTitik);
}//GEN-LAST:event_BtnTitikActionPerformed
private void BtnEqualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEqualActionPerformed
result();
}//GEN-LAST:event_BtnEqualActionPerformed
private void BtnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnClearActionPerformed
//Untuk hapus nilai data
inputNumber = "";
txtResult.setText("0");
labelProses.setText("Process");
calculator.setNumber("0");
calculator.setOperator(0);
calculator.setResult(0);
// TODO add your handling code here:
}//GEN-LAST:event_BtnClearActionPerformed
private void Btn0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn0ActionPerformed
getNumber(Btn0); // TODO add your handling code here:
}//GEN-LAST:event_Btn0ActionPerformed
private void txtResultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtResultActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtResultActionPerformed
private void BtnPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnPlusActionPerformed
getOperator(1);
}//GEN-LAST:event_BtnPlusActionPerformed
private void BtnMinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnMinActionPerformed
getOperator(2);
}//GEN-LAST:event_BtnMinActionPerformed
private void BtnBagiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBagiActionPerformed
getOperator(4);
}//GEN-LAST:event_BtnBagiActionPerformed
private void BtnKaliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnKaliActionPerformed
getOperator(3);
}//GEN-LAST:event_BtnKaliActionPerformed
private void btnInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInfoActionPerformed
displayInformasi();
}//GEN-LAST:event_btnInfoActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Btn0;
private javax.swing.JButton Btn4;
private javax.swing.JButton Btn5;
private javax.swing.JButton Btn6;
private javax.swing.JButton Btn7;
private javax.swing.JButton Btn8;
private javax.swing.JButton Btn9;
private javax.swing.JButton BtnBagi;
private javax.swing.JButton BtnClear;
private javax.swing.JButton BtnEqual;
private javax.swing.JButton BtnKali;
private javax.swing.JButton BtnMin;
private javax.swing.JButton BtnPlus;
private javax.swing.JButton BtnTitik;
private javax.swing.JButton Btndua;
private javax.swing.JButton Btnsatu;
private javax.swing.JButton Btntiga;
private javax.swing.JButton btnInfo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel5;
private javax.swing.JLabel labelProses;
private javax.swing.JTextField txtResult;
// End of variables declaration//GEN-END:variables
}
<file_sep># Kalkulator Konversi Sederhana Basis OOP
### Editor untuk membuat Kalkulator Sederhana ini adalah
- Netbeans IDE 8.2
## Features
- Kalkulator Standar (*,/,+,-)
- Konversi Waktu (Tahun,bulan,minggu,jam,menit,dan detik)
- Konversi suhu (Celcius,fahreinheit,kelvin,reamur)
- Kalkulator Luas dan keliling bangun datar
## Structure Folder
- Aset (untuk Kumpulan aset gambar atau icon)
- design (khusus untuk design form)
- logic (khusus untuk functionalitas logic)
## Documentation UI
| Name Screen | Keterangan |
| ------------- |------------- |
|  | Ui awal |
|  |Menu Utama |
|  | Ui Kalkulator standar |
| | Ui Kalkulator Konversi Suhu |
|  | Ui Kalkulator Konversi Waktu |
|  | Ui Kalkulator menghitung Luas & Keliling bangun datar |
## created by : <NAME>
| 1b4ec7fce171e3967c9f7f06aa482c6efe6f85cd | [
"Markdown",
"Java"
] | 13 | Java | rinrin26/proyekPBO-Konversi-Sederhana | dacf313d100ee3e0cfc974ba9c597e7bae5620ff | 85696abe29e5da918b2d96c20e5c5a9a64109d2c |
refs/heads/master | <repo_name>faf0/ApproxCircle<file_sep>/README.md
ApproxCircle
============
Monte Carlo simulation written in C which approximates the
quarter area of a circle with a specified radius r.
Additionally, this program approximates Pi using the Monte
Carlo method.
This program picks samples from a uniform distribution over
[0, r] x [0, r] and counts the number of points that
lie within the quarter area of the circle with radius r.
Let `no_inside` denote the number of points that lie within
the quarter area and let `no_samples` denote the number of samples.
The quarter area of the circle is approximately:
qarea := no_inside / no_samples * r^2
Pi is approximately:
Pi ~ 4 * qarea / r^2
How to Run
----------
Go to the directory containing the Makefile in a shell
and run `make`.
Examples
--------
The first parameter specifies the radius, while the second parameter
specifies the number of iterations.
$ ./approx_circle 1 100
-- SIMULATION RESULTS --
points inside circle: 78. outside: 22.
-- AREA --
area approximation: 0.780000. real area: 0.785398.
absolute derivation: 0.005398. relative derivation: 0.687316%.
-- PI --
PI approximation: 3.120000. 'real' PI: 3.141593.
absolute derivation: 0.021593. relative derivation: 0.687316%.
$ ./approx_circle 10 100
-- SIMULATION RESULTS --
points inside circle: 76. outside: 24.
-- AREA --
area approximation: 76.000000. real area: 78.539816.
absolute derivation: 2.539816. relative derivation: 3.233795%.
-- PI --
PI approximation: 3.040000. 'real' PI: 3.141593.
absolute derivation: 0.101593. relative derivation: 3.233795%.
Copyright
---------
Copyright 2013 <NAME>
<file_sep>/src/approx_circle.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <math.h>
#define MAX(a, b) ((a) >= (b) ? (a) : (b))
#define MIN(a, b) ((a) <= (b) ? (a) : (b))
#define ABS(a) ((a) >= 0 ? (a) : -(a))
#define SQR(a) ((a) * (a))
#define M_PI 3.14159265358979323846264338327
/*
* Data structure that stores simulations
* results and settings.
*/
typedef struct _simulation_t {
double radius;
int iterations;
int no_inside;
double area;
double pi;
} simulation_t;
/*
* Print the usage syntax of this program.
*
* @param arg the command-line name of this program.
*/
static void usage(const char *arg)
{
printf("Syntax: %s R N.\n\n"
"R is a floating point number representing the radius.\n"
"N is an integer representing the number of iterations.\n", arg);
}
/*
* Runs the simulation with the given parameters.
* Remember to call srand before!
*
* @param radius the radius of the circle
* @param iterations the number of iterations of the simulation
* @param result structure where the results and settings of the simulation
* are to be stored
*/
static void simulate(double radius, int iterations, simulation_t *result)
{
int no_inside = 0;
assert(radius > 0.0);
assert(iterations >= 1);
for (int i = 0; i < iterations; i++) {
/* assert: 0 <= x,y <= radius */
double x = radius * ((double) rand() / (double) RAND_MAX);
double y = radius * ((double) rand() / (double) RAND_MAX);
if (sqrt(SQR(x) + SQR(y)) <= radius) {
no_inside++;
}
}
result->radius = radius;
result->iterations = iterations;
result->no_inside = no_inside;
/*
* Approximate the area of a quarter of a circle with radius r using
* numbers sampled uniformly at random from the square [0, r^2] x [0, r^2].
* When the number of iterations is large, the area approximation value is
* likely near the actual area value: r^2 * PI / 4.
* We use the approximation formula:
* area ~ no_inside / (no_inside + no_outside) * r^2
*/
result->area = (double) no_inside / (double) iterations * SQR(radius);
/*
* We approximate PI using the following formula:
* PI ~ 4 * quarter area / r^2 = 4 * no_inside / (no_inside + no_outside)
*/
result->pi = (double) 4.0 * ((double) no_inside / (double) iterations);
}
/*
* Print the simulation data and comparison to accurate values on
* standard output.
*
* @param sim the simulation values to show
*/
static void show(simulation_t *sim)
{
/* realArea = r^2 * PI / 4 */
double realArea = (double) SQR(sim->radius) * M_PI / 4.0;
printf("\t-- SIMULATION RESULTS --\n"
"points inside circle: %d. outside: %d.\n"
"\t-- AREA --\n"
"area approximation: %f. real area: %f.\n"
"absolute derivation: %f. relative derivation: %f%%.\n"
"\t-- PI --\n"
"PI approximation: %f. \'real\' PI: %f.\n"
"absolute derivation: %f. relative derivation: %f%%.\n",
sim->no_inside, sim->iterations - sim->no_inside,
sim->area, realArea,
ABS(sim->area - realArea), (1.0 - MIN(sim->area, realArea) / MAX(sim->area, realArea)) * 100.0,
sim->pi, M_PI,
ABS(sim->pi - M_PI), (1.0 - MIN(sim->pi, M_PI) / MAX(sim->pi, M_PI)) * 100.0);
}
/*
* Runs the simulation and prints the result.
*
* @param argv radius of the circle to approximate
* number of iterations
*/
int main(int argc, char *argv[])
{
if (argc != 3) {
usage(argv[0]);
exit(EXIT_FAILURE);
} else {
double radius = atof(argv[1]);
int iterations = atoi(argv[2]);
simulation_t result;
/* Check inputs */
if (radius <= 0.0) {
printf("Radius R must not be negative or zero.\n");
return EXIT_FAILURE;
}
if (iterations < 1) {
printf("Iterations N must be an integer greater or equal to one.\n");
return EXIT_FAILURE;
}
/*
* Initialize the PRNG with the current time as the seed, run
* the simulation, and print the results.
*/
srand(time(NULL));
simulate(radius, iterations, &result);
show(&result);
return EXIT_SUCCESS;
}
}
<file_sep>/src/Makefile
CC = gcc
CPP = g++
CPPFLAGS += -I./ -Wall -Wsign-compare -Wchar-subscripts -Werror -pedantic
CFLAGS += -std=c99
#CXXFLAGS += -O2
LDFLAGS += -L./
LOADLIBES = -lm
.PHONY: all, clean
PROGNAME := approx_circle
all: approx_circle
approx_circle: approx_circle.o
clean:
rm *.o approx_circle
| 2a89a95e2da20bb3c1f62dea586e313c3eb2942a | [
"Markdown",
"C",
"Makefile"
] | 3 | Markdown | faf0/ApproxCircle | a8f881fc59c71c68f616867d7971d7801803b776 | 30137f87a1f1d78790e20275312f339dc734e38e |
refs/heads/master | <file_sep>package calculator.objectDefinitions;
import calculator.operations.UnitMeasures;
import calculator.operations.ValidationException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
public class Calculator implements ICalculator {
private String expression;
private UnitMeasures resultUnitMeasure;
private Distance distance;
private Duration duration;
public Calculator(String expression, UnitMeasures resultUnitMeasure) {
this.expression = expression;
this.resultUnitMeasure = resultUnitMeasure;
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
public UnitMeasures getResultUnitMeasure() {
return resultUnitMeasure;
}
public void setResultUnitMeasure(UnitMeasures resultUnitMeasure) {
this.resultUnitMeasure = resultUnitMeasure;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
CalculationDurationRepository<Calculator> calculationDuration;
public double calculateDistance() throws ValidationException {
CalculationDurationRepository calculationDuration=new CalculationDurationRepository<>();
Instant start=Instant.now();
double calculatedDistance = 0;
List<Distance> listOfDistances = new ArrayList<>();
listOfDistances = breakUpExpressionInDistanceData(listOfDistances);
calculatedDistance += listOfDistances.get(0).getDistanceValue();
List<String> stringOperators = getOperators(expression);
for (int i = 0; i < stringOperators.size(); i++) {
switch (stringOperators.get(i)) {
case "+":
calculatedDistance += listOfDistances.get(i + 1).getDistanceValue();
break;
case "-":
calculatedDistance -= listOfDistances.get(i + 1).getDistanceValue();
break;
}
}
if (calculatedDistance < 0) {
throw new ValidationException("Resulting distance negative!");
}
Instant stop=Instant.now();
Duration durationOfCalculation= Duration.between(start,stop);
setDuration(durationOfCalculation);
calculationDuration.addDuration(getDuration());
return calculatedDistance;
}
private double transformDistancesToResultUM(String unitMeasureToBeTransformed, double doubleDistance) throws ValidationException {
switch (resultUnitMeasure) {
case MM:
doubleDistance = transformIntoMm(unitMeasureToBeTransformed, doubleDistance);
break;
case CM:
doubleDistance = transformIntoCm(unitMeasureToBeTransformed, doubleDistance);
break;
case DM:
doubleDistance = transformIntoDm(unitMeasureToBeTransformed, doubleDistance);
break;
case M:
doubleDistance = transformIntoM(unitMeasureToBeTransformed, doubleDistance);
break;
case KM:
doubleDistance = transformIntoKM(unitMeasureToBeTransformed, doubleDistance);
break;
default:
throw new ValidationException("UnitMeasure not valid!");
}
return doubleDistance;
}
private double transformIntoKM(String unitMeasureToBeTransformed, double doubleDistance) throws ValidationException {
switch (unitMeasureToBeTransformed) {
case "mm":
doubleDistance /= 1000000;
break;
case "cm":
doubleDistance /= 100000;
break;
case "dm":
doubleDistance /= 10000;
break;
case "m":
doubleDistance /= 1000;
break;
case "km":
break;
default:
throw new ValidationException("Unit measure not valid format (mm,cm,dm,m,km");
}
return doubleDistance;
}
private double transformIntoM(String unitMeasureToBeTransformed, double doubleDistance) throws ValidationException {
switch (unitMeasureToBeTransformed) {
case "mm":
doubleDistance /= 1000;
break;
case "cm":
doubleDistance /= 100;
break;
case "dm":
doubleDistance /= 10;
break;
case "m":
break;
case "km":
doubleDistance *= 1000;
break;
default:
throw new ValidationException("Unit measure not valid format (mm,cm,dm,m,km");
}
return doubleDistance;
}
private double transformIntoDm(String unitMeasureToBeTransformed, double doubleDistance) throws ValidationException {
switch (unitMeasureToBeTransformed) {
case "mm":
doubleDistance /= 100;
break;
case "cm":
doubleDistance /= 10;
break;
case "dm":
break;
case "m":
doubleDistance *= 10;
break;
case "km":
doubleDistance *= 10000;
break;
default:
throw new ValidationException("Unit measure not valid format (mm,cm,dm,m,km");
}
return doubleDistance;
}
private double transformIntoCm(String unitMeasureToBeTransformed, double doubleDistance) throws ValidationException {
switch (unitMeasureToBeTransformed) {
case "mm":
doubleDistance /= 10;
break;
case "cm":
break;
case "dm":
doubleDistance *= 10;
break;
case "m":
doubleDistance *= 100;
break;
case "km":
doubleDistance *= 1000000;
break;
default:
throw new ValidationException("Unit measure not valid format (mm,cm,dm,m,km");
}
return doubleDistance;
}
private double transformIntoMm(String unitMeasureToBeTransformed, double doubleDistance) throws ValidationException {
switch (unitMeasureToBeTransformed) {
case "mm":
break;
case "cm":
doubleDistance *= 10;
break;
case "dm":
doubleDistance *= 100;
break;
case "m":
doubleDistance *= 1000;
break;
case "km":
doubleDistance *= 1000000;
break;
default:
throw new ValidationException("Unit measure not valid format (mm,cm,dm,m,km");
}
return doubleDistance;
}
private List<Distance> breakUpExpressionInDistanceData(List<Distance> listOfDistances) throws ValidationException {
List<Double> doubleDistance = getDistances(expression);
List<String> stringUnitMeasure = getUnitMeasures(expression);
System.out.println("-----------------------------------------------------------");
System.out.println("The introduced distances are: ");
for (int i = 0; i < doubleDistance.size(); i++) {
System.out.print(doubleDistance.get(i) + " ");
System.out.println(stringUnitMeasure.get(i));
}
System.out.println("-----------------------------------------------------------");
for (int i = 0; i < doubleDistance.size(); i++) {
distance = new Distance(transformDistancesToResultUM(stringUnitMeasure.get(i), doubleDistance.get(i)), resultUnitMeasure);
listOfDistances.add(distance);
}
return listOfDistances;
}
private List<Double> getDistances(String expression) throws ValidationException {
List<Double> doubleDistance = new ArrayList<>();
String separator = "[cmk+\\-]+";
String[] stringDistances = expression.split(separator);
for (int i = 0; i < stringDistances.length; i++) {
if (!stringDistances[i].equals("")) {
doubleDistance.add(Double.parseDouble(stringDistances[i]));
}
}
return doubleDistance;
}
private List<String> getUnitMeasures(String expression) {
List<String> stringUnitMeasures = new ArrayList<>();
String separator = "[1234567890+\\-]+";
String[] string = expression.split(separator);
for (int i = 0; i < string.length; i++) {
if (!string[i].equals("")) {
stringUnitMeasures.add(string[i]);
}
;
}
return stringUnitMeasures;
}
private List<String> getOperators(String expression) {
List<String> stringOperators = new ArrayList<>();
String separator = "[1234567890mcdk]+";
String[] string = expression.split(separator);
for (int i = 0; i < string.length; i++) {
if (!string[i].equals("")) {
stringOperators.add(string[i]);
}
;
}
return stringOperators;
}
}
<file_sep># Homework-9_JUnit2_parameterized_test
For the previous implemented calculator, make sure you have the following tests:
one parameterized test
one suite of tests which contains all existing ones
Create a statistics repository where each computing time will be hold. Add extra methods for analysing data and create unit tests for the
repo using TDD.
<file_sep>package calculator;
import calculator.objectDefinitions.Calculator;
import calculator.operations.UnitMeasures;
import calculator.operations.ValidationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.List;
import static junit.framework.Assert.assertEquals;
@RunWith(Parameterized.class)
public class parameterizedTestCalculator {
private static Calculator calculator /* = new Calculator()*/;
private String expression;
private UnitMeasures unitMeasures;
private double expected;
@Parameterized.Parameters
public static List<Object> data() {
return Arrays.asList(new Object[][]{
{"33m-12cm", UnitMeasures.M, 32.88},
{"10m+30dm-20cm+1km", UnitMeasures.M, 1012.8},
{"2m-20cm+10dm", UnitMeasures.CM, 280}
});
}
public parameterizedTestCalculator(String expression, UnitMeasures unitMeasures, double expected) {
this.expression = expression;
this.unitMeasures = unitMeasures;
this.expected = expected;
}
@Test
public void testDistanceCalculator() throws ValidationException {
calculator = new Calculator(expression, unitMeasures);
assertEquals(calculator.calculateDistance(), expected);
}
}
<file_sep>package calculator.objectDefinitions;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
public class CalculationDurationRepository <T extends Calculator>{
List<Duration> calculationDuration=new ArrayList<>();
public void addDuration(Duration duration){
calculationDuration.add(duration);
for(Duration member:calculationDuration){
System.out.println("Calculation duration: "+member);
}
}
}
| 38750658c40ffca4f1a608e3e239ae6488021808 | [
"Markdown",
"Java"
] | 4 | Java | gergelyla/Homework-9_JUnit2_parameterized_test | 05725ff6a18f024ea419098290e200d1305ea038 | e547a7daf9be0bc5e166e1d1f31a887c2c127e28 |
refs/heads/master | <repo_name>Adoc7/Fonctions_php<file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FONCTIONS</title>
</head>
<body>
<!-- Exercice 1 -->
<?php
// Fonction qui retourne "true"
function vrai() {
return true;
}
echo vrai();
?>
</br>
<!-- Exercice 2 -->
<?php
// Faire une fonction qui prend en paramètre une chaine de caractères et qui retourne cette même chaine.
function car() {
return "Bonjour, ceci est une chaîne de caractères.";
}
echo car();
?>
</br>
<!-- Exercice 3 -->
<?php
// Faire une fonction qui prend en paramètre deux chaines de caractères et qui revoit la concaténation de ces deux chaines
function bar() {
return "Bonjour"." "."un café?";
}
echo bar();
?>
</br>
<!-- Exercice 4 -->
<?php
// Faire une fonction qui prend en paramètre deux nombres. La fonction doit retourner :
//
// Le premier nombre est plus grand si le premier nombre est plus grand que le deuxième
// Le premier nombre est plus petit si le premier nombre est plus petit que le deuxième
// Les deux nombres sont identiques si les deux nombres sont égaux
function comparer($a=10,$b=20) {
if ($a>$b) {
echo "Le premier nombre est plus grand.";
} elseif ($a<$b) {
echo "Le premier nombre est plus petit.";
}else {
echo "Le premier nombre est plus petit.";
}
}
echo comparer();
?>
</br>
<!-- Exercice 5 -->
<?php
// Faire une fonction qui prend en paramètre un nombre et une chaine de caractères et qui renvoit la concaténation de ces deux paramètres.
function mel_nbr_car($car="chiffre",$chif=10) {
return $car.$chif;
}
echo mel_nbr_car();
?>
</br>
<!-- Exercice 6 -->
<?php
// Faire une fonction qui prend en paramètre deux chaines de caractères et qui revoit la concaténation de ces deux chaines
function chaine_caract($name="Adoc7",$surname="captain",$age=70) {
return "Bonjour "."".$name." ".$surname." ,tu as ".$age." ans.";
}
echo chaine_caract();
?>
</br>
<!-- Exercice 7 -->
<?php
// Faire une fonction qui prend deux paramètres : age et genre. Le paramètre genre peut prendre comme valeur :
//
// Homme
// Femme
//
// La fonction doit renvoyer en fonction des paramètres :
//
// Vous êtes un homme et vous êtes majeur
// Vous êtes un homme et vous êtes mineur
// Vous êtes une femme et vous êtes majeur
// Vous êtes une femme et vous êtes mineur
// Gérer tous les cas.
function genre_age($genre,$age) {
if ($genre=="homme" && $age>=18) {
return " Vous êtes un homme et vous êtes majeur.";
} elseif ($genre=="homme" && $age<18) {
return " Vous êtes un homme et vous êtes mineur.";
} elseif ($genre=="femme" && $age>=18) {
return " Vous êtes une femme et vous êtes majeur.";
}else {
return "Vous êtes une femme et vous êtes mineur.";
}
}
echo genre_age("homme",24);
?>
</br>
<!-- Exercice 8 -->
<?php
// Faire une fonction qui prend en paramètre trois nombres et qui renvoit la somme de ces nombres.
//Tous les paramètres doivent avoir une valeur par défaut.
$a=42;
$b=33;
$c=5;
function nombres($a,$b,$c) {
return $a+$b+$c;
}
echo nombres($a,$b,$c);
?>
| 7688c442a5f55e1ed72e5eb02868816e56ac5b73 | [
"PHP"
] | 1 | PHP | Adoc7/Fonctions_php | 0e103cf754445e16290a1f3c17eedf8d00222fe2 | deb14ef002d5f3542279b4c7ceee8e9a810c74f6 |
refs/heads/master | <file_sep>import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/HomeComponent';
import { LoginComponent } from './components/LoginComponent';
import { AuthGuard } from './services/AuthGuard';
import { PublicComponent } from './components/PublicComponent';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: '', component: PublicComponent},
{ path: '**', redirectTo: '' }
]
export const Routing = RouterModule.forRoot(appRoutes);
<file_sep>import * as chai from 'chai';
import * as sinon from 'sinon';
import { Book } from '../interfaces/Book';
import { Observable } from 'rxjs/Observable';
describe('PublicComponent', () => {
let mockService: any = {};
let mockBook: Book = { isbn: 1, title: 'TestTitle', authorFirst: 'First', authorLast: 'Last', price: 1.25 };
let mockBook2: Book = { isbn: 2, title: 'TestTitle2', authorFirst: 'First', authorLast: 'Last', price: 1.35 };
let collection: Book[] = [mockBook, mockBook2];
beforeEach(() => {
mockService = {
getAllBooks: sinon.stub().returns(Observable.of(collection))
}
});
function createComponent() {
let Component = require('../components/PublicComponent').PublicComponent
return new Component(mockService)
}
describe('#ngOnit', () => {
it('should retrieve all books', () => {
let comp = createComponent();
comp.ngOnInit();
chai.expect(comp.books).not.to.be.null;
});
});
describe('#getBooks', () => {
it('should retrieve all books from the db', () => {
let comp = createComponent();
let actual: Book[] = comp.getBooks();
chai.expect(comp.books).to.equal(collection);
});
})
});
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './components/AppComponent';
import { NavbarComponent } from './components/NavbarComponent';
import { LoginComponent } from './components/LoginComponent';
import { LocalStorageService } from './services/LocalStorageService';
import { LoginService } from './services/LoginService';
import { TransactionService } from './services/TransactionService';
import { HomeComponent } from './components/HomeComponent';
import { PublicComponent } from './components/PublicComponent';
import { CustomerService } from './services/CustomerService';
import { AuthGuard } from './services/AuthGuard';
import { Routing } from './Routing';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
NavbarComponent,
PublicComponent
],
imports: [
BrowserModule,
HttpModule,
FormsModule,
Routing
],
providers: [CustomerService, LocalStorageService, LoginService, AuthGuard, TransactionService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import * as chai from 'chai';
import * as sinon from 'sinon';
import { LoginService } from '../services/LoginService';
import { Observable } from 'rxjs/Observable';
import { Customer } from '../interfaces/Customer';
import 'rxjs/add/observable/of';
let assert = chai.assert;
describe('LoginService', () => {
let mockCustomerService: any = {};
let mockLocalStorageService: any = {};
let mockCustomer: Customer = { customerId: 1,
firstName: 'Testy',
lastName: 'McTestface',
emailAddress: '<EMAIL>',
password: '<PASSWORD>'
};
beforeEach( () => {
mockCustomerService = {
getCustomerDetailsByEmail: sinon.stub().returns(Observable.of(mockCustomer))
}
mockLocalStorageService = {
setLocalStorage: sinon.stub(),
getLocalStorage: sinon.stub(),
removeItem: sinon.stub()
}
});
function createService() {
let Service = require('../services/LoginService').LoginService;
let service = new Service(mockCustomerService, mockLocalStorageService);
return service;
}
describe('#checkDetails', () => {
it ('should return true if the details are correct', () => {
let service = createService();
let actual = service.checkDetails('password', '<PASSWORD>');
assert.equal(true, actual);
});
});
describe('#login', () => {
it ('should return true if details are correct', () => {
let service = createService();
service.login('<EMAIL>', '<PASSWORD>')
.subscribe((res) => {
expect(res).toBe(true);
})
});
it ('should return false if details are incorrect', () => {
let service = createService();
service.login('<EMAIL>', '<PASSWORD>PW')
.subscribe((res) => {
expect(res).toBe(false);
}, (error) => {
expect(error).not.toBeNull();
})
});
});
});
<file_sep>import { Transaction } from '../interfaces/Transaction';
import { Observable } from 'rxjs/Observable';
import { TransactionService } from '../services/TransactionService';
import { ReflectiveInjector } from '@angular/core';
import { async, fakeAsync, tick } from '@angular/core/testing';
import { BaseRequestOptions, ConnectionBackend, Http, RequestOptions } from '@angular/http';
import { Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import * as chai from 'chai';
let mockTransaction: Transaction = { transactionId: 1, isbn: 1, customerId: 1, transactionDate: null};
let mockTransaction2: Transaction = { transactionId: 2, isbn: 3, customerId: 1, transactionDate: null};
let collection: Transaction[] = [mockTransaction, mockTransaction2];
beforeEach(() => {
this.injector = ReflectiveInjector.resolveAndCreate([
{ provide: ConnectionBackend, useClass: MockBackend },
{ provide: RequestOptions, useClass: BaseRequestOptions },
Http,
TransactionService
]);
this.service = this.injector.get(TransactionService);
this.backend = this.injector.get(ConnectionBackend) as MockBackend;
this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
});
describe('#TransactionService', () => {
describe('getTransaction', () => {
it('should make the get call to the correct url', () => {
this.service.getTransaction(1);
expect(this.lastConnection).toBeDefined();
expect(this.lastConnection.request.url).toMatch('/transactions/1');
});
it('should retrieve the correct transaction given a transactionId', () => {
this.service.getTransaction(1)
.subscribe( (Transaction) => {
expect(Transaction).toEqual(mockTransaction);
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: mockTransaction
})));
});
it('should throw an error if the transactionId does not exist', () => {
this.service.getTransaction(2)
.subscribe( (transaction) => {
expect(transaction).toBeNull();
}, (error) => {
expect(error).toBeDefined();
expect(error.message).toEqual('TransactionId unknown');
});
this.lastConnection.mockError(new Error('TransactionId unknown'));
});
});
describe('getAllTransactions', () => {
let customerId = 1;
it('should return all transactions given a customerId', fakeAsync(() => {
this.service.getAllTransactions(customerId)
.subscribe((transactions) => {
chai.expect(transactions).to.equal(collection);
});
this.lastConnection.mockRespond(new Response( new ResponseOptions({
body: collection
})))
}));
});
describe('addTransaction', () => {
it('should make the request to the correct url', () => {
this.service.addTransaction(mockTransaction);
expect(this.lastConnection.request.url).toMatch('/transactions');
chai.expect(JSON.parse(this.lastConnection.request.getBody())).to.deep.equal(mockTransaction);
});
it('should return the transaction if created successfully', fakeAsync(() => {
this.service.addTransaction(mockTransaction)
.subscribe( (res) => {
chai.expect(res).to.deep.equal(mockTransaction);
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: mockTransaction
})));
}));
it('should indicate if the book could not be added', fakeAsync(() => {
this.service.addTransaction(mockTransaction)
.subscribe( (res) => {
chai.expect(res).to.be.null;
}, (error) => {
chai.expect(error).not.to.be.null;
chai.expect(error.message).to.equal('Transaction could not be added');
})
this.lastConnection.mockError(new Error('Transaction could not be added'));
}));
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { Book } from '../interfaces/Book';
import { BookService } from '../services/BookService';
@Component({
selector: 'public-component',
templateUrl: '../templates/PublicComponent.html',
providers: [BookService],
styleUrls: ['../styles/PublicComponent.scss'],
})
export class PublicComponent implements OnInit {
public books: Book[]
public constructor(private bookService: BookService) {}
public ngOnInit(): void {
this.getBooks();
}
public getBooks(): void {
this.bookService.getAllBooks()
.subscribe((books: Book[]) => {
this.books = books;
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Customer } from '../interfaces/Customer';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
var config = require('../../config');
@Injectable()
export class CustomerService {
baseUrl = `http://${config.domainIP}:${config.domainPort}`;
constructor(private http: Http) {}
public getCustomerDetails(customerID: number): Observable<Customer> {
let url = `${this.baseUrl}/customers/${customerID}`;
return this.http.get(url, this.getOptions())
.map(res => res.json())
.catch( error => Observable.throw(error));
}
public getCustomerDetailsByEmail(customerEmail: string): Observable<Customer> {
let url = `${this.baseUrl}/customers/accounts/${customerEmail}`;
return this.http.get(url, this.getOptions())
.map(res => res.json())
.catch( error => Observable.throw(error));
}
public addCustomer(customer: Customer): Observable<Response> {
let url = `${this.baseUrl}/customers/add`;
return this.http.put(url, customer)
.map(res => res.json())
.catch( error => Observable.throw('User could not be added'));
}
public deleteCustomer(customer: Customer): Observable<Response> {
let url = `${this.baseUrl}/customers/${customer.customerId}`;
return this.http.delete(url)
.map(res => res.json())
.catch( error => Observable.throw('Could not delete user'));
}
private getOptions(): RequestOptions {
let requestHeaders = new Headers();
requestHeaders.append('Content-Type', 'application/json');
requestHeaders.append('Accept', 'application/json');
return new RequestOptions({ headers: requestHeaders });
}
}
<file_sep>export interface Book {
isbn: number;
title: string;
authorFirst: string;
authorLast: string;
price: number;
}
<file_sep>import { Customer } from '../interfaces/Customer';
import { Observable } from 'rxjs/Observable';
import { CustomerService } from '../services/CustomerService'
import { ReflectiveInjector } from '@angular/core';
import { async, fakeAsync, tick } from '@angular/core/testing';
import { BaseRequestOptions, ConnectionBackend, Http, RequestOptions } from '@angular/http';
import { Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
let mockCustomer: Customer = { customerId: 1,
firstName: 'Testy',
lastName: 'McTestface',
emailAddress: '<EMAIL>',
password: '<PASSWORD>'
};
beforeEach(() => {
this.injector = ReflectiveInjector.resolveAndCreate([
{ provide: ConnectionBackend, useClass: MockBackend },
{ provide: RequestOptions, useClass: BaseRequestOptions },
Http,
CustomerService,
]);
this.service = this.injector.get(CustomerService);
this.backend = this.injector.get(ConnectionBackend) as MockBackend;
this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
});
describe('#CustomerService', () => {
describe('#getCustomerDetails', () => {
it('should make the get call to the correct url', () => {
this.service.getCustomerDetails(1).subscribe();
expect(this.lastConnection).toBeDefined();
expect(this.lastConnection.request.url).toMatch('/customers/1', 'url invalid');
});
it('should retrieve the customer details given an id', fakeAsync(() => {
this.service.getCustomerDetails(1)
.subscribe( (customer) => {
expect(customer.customerId).toEqual(1);
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: mockCustomer
})));
}));
it('should throw an error if the customerid does not exist', fakeAsync(() => {
this.service.getCustomerDetails(3)
.subscribe((customer) => {
expect(customer).toBeNull();
}, (error) => {
expect(error).toBeDefined();
expect(error.message).toEqual('Customer not found');
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
status: 404,
statusText: 'Customer not found'
})));
}));
});
describe('#addCustomer', () => {
it('should throw an error if user could not be added', () => {
this.service.addCustomer(mockCustomer)
.subscribe((response) => {
expect(response).toBeNull();
}, (error) => {
expect(error.message).toEqual('User could not be added')
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
status: 505,
statusText: 'User could not be added'
})));
});
it('should create the user on success', () => {
this.service.addCustomer(mockCustomer)
.subscribe((res) => {
expect(res.status).toEqual(200);
}, (error) => {
expect(error).toBeNull();
});
});
});
describe('#deleteCustomer', () => {
it('should delete the user on success', () => {
this.service.deleteCustomer(1)
.subscribe((res) => {
expect(res.status).toEqual(200);
});
});
it('should throw an error if the user could not be removed', () => {
this.service.deleteCustomer(1)
.subscribe((res) => {
expect(res).toBeNull();
}, (error) => {
expect(error.message).toEqual('Could not delete user');
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
status: 505,
statusText: 'Server Error'
})));
});
});
describe('#getCustomerByEmail', () => {
it('should retrieve the customer details given an email', () => {
this.service.getCustomerDetailsByEmail('<EMAIL>')
.subscribe( (customer) => {
expect(customer).toEqual(mockCustomer);
});
});
it('should make the get call to the correct url', () => {
this.service.getCustomerDetailsByEmail('<EMAIL>').subscribe();
expect(this.lastConnection.request.url).toMatch('/customers/accounts/<EMAIL>', 'url invalid');
});
it('should throw an error if the customerid does not exist', () => {
this.service.getCustomerDetailsByEmail('<EMAIL>')
.subscribe((res) => {
expect(res).toBeNull();
}, (error) => {
expect(error.message).toEqual('Could not find user');
});
this.lastConnection.mockError(new Error('Could not find user'));
});
});
});
<file_sep>import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Book } from '../interfaces/Book';
var config = require('../../config');
@Injectable()
export class BookService {
baseUrl = `http://${config.domainIP}:${config.domainPort}`;
constructor(private http: Http) { }
public getBook(isbn: number): Observable<Book> {
let url = `${this.baseUrl}/books/${isbn}`;
return this.http.get(url, this.getOptions())
.map(res => res.json())
.catch(error => Observable.throw(error));
}
public getAllBooks(): Observable<Book[]> {
let url = `${this.baseUrl}/books/collection`;
return this.http.get(url, this.getOptions())
.map(res => res.json())
.catch(error => Observable.throw(error))
}
public addBook(book: Book): Observable<Response> {
let url = `${this.baseUrl}/books`
return this.http.put(url, book, this.getOptions())
.map(res => res.json())
.catch(error => Observable.throw(error.message))
}
public removeBook(isbn: number): Observable<Response> {
let url = `${this.baseUrl}/books/${isbn}`;
return this.http.delete(url, this.getOptions())
.map(res => {
if (res.status < 200 || res.status > 300) {
Observable.throw('Could not delete book');
}
})
.catch(error => Observable.throw(error.message))
}
private getOptions(): RequestOptions {
let requestHeaders = new Headers();
requestHeaders.append('Content-Type', 'application/json');
requestHeaders.append('Accept', 'application/json');
return new RequestOptions({ headers: requestHeaders });
}
}
<file_sep>import * as chai from 'chai';
import * as sinon from 'sinon';
import { LoginService } from '../services/LoginService';
import { Observable } from 'rxjs/Observable';
import { Customer } from '../interfaces/Customer';
import 'rxjs/add/observable/of';
let assert = chai.assert;
describe('LocalStorageService', () => {
let mockLocalStorage: any = {};
let store = {};
beforeEach(() => {
mockLocalStorage = {
getItem: (key: string): string => {
return key in store ? store[key] : null;
},
setItem: (key: string, value: string) => {
store[key] = `${value}`;
},
removeItem: (key: string) => {
delete store[key];
},
clear: () => {
store = {};
}
};
spyOn(localStorage, 'getItem')
.and.callFake(mockLocalStorage.getItem);
spyOn(localStorage, 'setItem')
.and.callFake(mockLocalStorage.setItem);
spyOn(localStorage, 'removeItem')
.and.callFake(mockLocalStorage.removeItem);
spyOn(localStorage, 'clear')
.and.callFake(mockLocalStorage.clear);
});
function createService() {
let Service = require('../services/LocalStorageService').LocalStorageService;
let service = new Service();
return service;
}
describe('#setLocalStorage', () => {
it('should set the appropriate key and value set', () => {
let service = createService();
service.setLocalStorage('key', 'value');
assert.equal(store['key'], 'value');
});
});
describe('#getLocalStorage', () => {
store = {testKey: 'testValue'};
it('should get the correct value given a key', () => {
let service = createService();
let actual = service.getLocalStorage('testKey');
assert.equal('testValue', actual);
})
});
describe('#removeItem', () => {
it('should remove the correct pair from the local Storage', () => {
let service = createService();
service.removeItem('testKey');
expect(store['testKey']).toBeUndefined();
});
});
});
<file_sep>import * as chai from 'chai';
import * as sinon from 'sinon';
import { Injectable, EventEmitter } from '@angular/core';
import { CustomerService } from '../services/CustomerService';
@Injectable()
export class LocalStorageService {
loggedIn: EventEmitter<boolean> = new EventEmitter();
constructor() { }
public setLocalStorage<T>(key: string, value: T) {
if (key === 'currentUser') {
this.loggedIn.emit(true);
}
localStorage.setItem(key, value.toString());
}
public getLocalStorage(key: string): string {
return localStorage.getItem(key);
}
public removeItem(key: string): void {
if (key === 'currentUser') {
this.loggedIn.emit(false);
}
localStorage.removeItem(key);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Transaction } from '../interfaces/Transaction';
import { TransactionService } from '../services/TransactionService';
import { LocalStorageService } from '../services/LocalStorageService';
@Component({
selector: 'home-component',
templateUrl: '../templates/HomeComponent.html',
styleUrls: ['../styles/HomeComponent.scss'],
})
export class HomeComponent implements OnInit {
public transactions: Transaction[];
constructor(private transactionService: TransactionService,
private localStorageSerice: LocalStorageService) {}
public ngOnInit(): void {
this.getCustomerTransactions();
}
private getCustomerTransactions() {
let customerId: number = parseInt(this.localStorageSerice.getLocalStorage('currentUser'));
this.transactionService.getAllTransactions(customerId)
.subscribe(transactions => {
this.transactions = transactions;
})
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: '../templates/AppComponent.html'
})
export class AppComponent {
public constructor() {}
}
<file_sep>import * as chai from 'chai';
import * as sinon from 'sinon';
import { Injectable } from '@angular/core';
import { CustomerService } from '../services/CustomerService';
import { LocalStorageService } from '../services/LocalStorageService';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class LoginService {
constructor(private customerService: CustomerService, private localStorageService: LocalStorageService) {}
public login(email: string, password: string): Observable<boolean> {
return this.customerService.getCustomerDetailsByEmail(email)
.map( customer => {
if (this.checkDetails(customer.password, password)) {
this.localStorageService.setLocalStorage('currentUser', customer.customerId);
return true;
} else {
return false;
}
});
}
public logout() {
this.localStorageService.removeItem('currentUser');
}
private checkDetails(expected: String, given: String) {
return expected === given;
}
}
<file_sep>import { ReflectiveInjector } from '@angular/core';
import { async, fakeAsync, tick } from '@angular/core/testing';
import { BaseRequestOptions, ConnectionBackend, Http, RequestOptions } from '@angular/http';
import { Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { Book } from '../interfaces/Book';
import { BookService } from '../services/BookService';
import * as chai from 'chai';
let mockBook: Book = { isbn: 1, title: 'TestTitle', authorFirst: 'First', authorLast: 'Last', price: 1.25 };
let mockBook2: Book = { isbn: 2, title: 'TestTitle2', authorFirst: 'First', authorLast: 'Last', price: 1.35 };
let collection: Book[] = [mockBook, mockBook2];
beforeEach( () => {
this.injector = ReflectiveInjector.resolveAndCreate([
{ provide: ConnectionBackend, useClass: MockBackend },
{ provide: RequestOptions, useClass: BaseRequestOptions },
Http,
BookService,
]);
this.service = this.injector.get(BookService);
this.backend = this.injector.get(ConnectionBackend) as MockBackend;
this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
});
describe('BookService', () => {
describe('#getBook', () => {
it('should make the get call to the correct url', () => {
this.service.getBook(1);
expect(this.lastConnection).toBeDefined();
expect(this.lastConnection.request.url).toMatch('/books/1');
});
it('should retrieve the correct book given an isbn', () => {
this.service.getBook(1)
.subscribe( (book) => {
expect(book).toEqual(mockBook);
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: mockBook
})));
});
it('should throw an error if the isbn does not exist', () => {
this.service.getBook(2)
.subscribe( (book) => {
expect(book).toBeNull();
}, (error) => {
expect(error).toBeDefined();
expect(error.message).toEqual('ISBN unknown');
});
this.lastConnection.mockError(new Error('ISBN unknown'));
});
});
describe('#getAllBooks', () => {
it('should return all books from the database', fakeAsync(() => {
this.service.getAllBooks()
.subscribe( (books) => {
chai.expect(books).to.equal(collection);
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: collection
})));
}));
});
describe('#addBook', () => {
it('should make the request to the correct url', () => {
this.service.addBook(mockBook);
expect(this.lastConnection.request.url).toMatch('/books');
chai.expect(JSON.parse(this.lastConnection.request.getBody())).to.deep.equal(mockBook);
});
it('should return the book if created successfully', fakeAsync(() => {
this.service.addBook(mockBook)
.subscribe( (res) => {
chai.expect(res).to.deep.equal(mockBook);
});
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: mockBook
})));
}));
it('should indicate if the book could not be added', fakeAsync(() => {
this.service.addBook(mockBook)
.subscribe( (res) => {
chai.expect(res).to.be.null;
}, (error) => {
chai.expect(error).not.to.be.null;
chai.expect(error).to.equal('Book could not be added');
})
this.lastConnection.mockError(new Error('Book could not be added'));
}));
});
describe('#removeBook', () => {
it('should make the request to the correct url', () => {
this.service.removeBook(1)
chai.expect(this.lastConnection.request.url).to.have.string('/books/1')
});
it('should thrown an error if book could not be deleted', fakeAsync(() => {
this.service.removeBook(1)
.subscribe(res => {
chai.expect(res).to.be.null;
}, (error) => {
chai.expect(error).not.to.be.null;
chai.expect(error).to.equal('Could not delete book')
});
this.lastConnection.mockError(new Error('Could not delete book'));
}));
});
});
<file_sep>import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Transaction } from '../interfaces/Transaction';
var config = require('../../config');
@Injectable()
export class TransactionService {
baseUrl = `http://${config.domainIP}:${config.domainPort}`;
constructor(private http: Http) {}
public getTransaction(transactionId: number): Observable<Transaction> {
let url = `${this.baseUrl}/transactions/${transactionId}`;
return this.http.get(url, this.getOptions())
.map(res => res.json())
.catch(error => Observable.throw(error));
}
public getAllTransactions(customerId: number): Observable<Transaction[]> {
let url = `${this.baseUrl}/transactions/users/${customerId}`;
return this.http.get(url, this.getOptions())
.map(res => res.json())
.catch(error => Observable.throw(error));
}
public addTransaction(transaction: Transaction): Observable<Transaction> {
let url = `${this.baseUrl}/transactions`;
return this.http.put(url, transaction, this.getOptions())
.map(res => res.json())
.catch(error => Observable.throw(error));
}
private getOptions(): RequestOptions {
let requestHeaders = new Headers();
requestHeaders.append('Content-Type', 'application/json');
requestHeaders.append('Accept', 'application/json');
return new RequestOptions({ headers: requestHeaders });
}
}<file_sep>import { Component, EventEmitter, Output } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { LoginService } from '../services/LoginService';
import { Router } from '@angular/router';
@Component({
selector: 'login-component',
templateUrl: '../templates/LoginComponent.html',
styleUrls: ['../styles/LoginComponent.scss'],
providers: [LoginService]
})
export class LoginComponent {
userName: string;
password: string;
error = false;
errorMessage: string;
constructor(private loginService: LoginService, private router: Router) {}
public login() {
this.loginService.login(this.userName, this.password)
.subscribe((res) => {
if (res) {
this.router.navigate(['/home']);
} else {
this.error = true;
this.errorMessage = 'Wrong password';
}
}, (error) => {
this.error = true;
if (error.status === 404) {
this.errorMessage = 'Unknown user';
} else {
this.errorMessage = 'Server offline';
}
});
}
}
<file_sep>export interface Transaction {
transactionId: number;
isbn: number;
customerId: number;
transactionDate: Date
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { LocalStorageService } from '../services/LocalStorageService';
import { LoginService } from '../services/LoginService';
import { Router } from '@angular/router';
@Component({
selector: 'navbar-component',
templateUrl: '../templates/NavbarComponent.html',
styleUrls: ['../styles/NavbarComponent.scss'],
})
export class NavbarComponent implements OnInit {
loggedIn: boolean;
constructor(private localStorageService: LocalStorageService,
private loginService: LoginService,
private router: Router) { }
ngOnInit() {
this.localStorageService.loggedIn.subscribe(
(loggedIn) => {
this.loggedIn = loggedIn;
}
)
this.loggedIn = this.localStorageService.getLocalStorage('currentUser') !== null;
}
public logout(): void {
this.loginService.logout();
this.router.navigate([''])
}
}
| bdb09f1c7d632ab928ce35a6cee2eb7259a943cb | [
"TypeScript"
] | 20 | TypeScript | kevinDeckerBN/bookstore-ux | d49d9ddfa737753b6c2be4eb8a5b9dcdbcdd1c59 | 23fa94880e39daa910e695d8bb8765d8e5c6f2e5 |
refs/heads/master | <repo_name>vgudzhev/Algo-1<file_sep>/week3/solutions/Trees/src/com/vgudzhev/tree_lecture/BST.java
package com.vgudzhev.tree_lecture;
public class BST {
public static class Node {
public int value;
public Node left;
public Node right;
public void add(Node node) {
if (this.value > node.value) {
left = node;
left.value = value;
} else {
right = node;
right.value = value;
}
}
}
// Checks if a binary tree is a binary search tree.
public static boolean isBST(Node root) {
return isValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private static boolean isValid(Node node, int minValue, int maxValue) {
if (node == null) {
return true;
}
if (node.value <= minValue || node.value > maxValue) {
return false;
}
return isValid(node.left, minValue, node.value)
&& isValid(node.right, node.value, maxValue);
}
} | 274d8412bd258cd75de545d7dbf66f3f96a75058 | [
"Java"
] | 1 | Java | vgudzhev/Algo-1 | d9b542cf9b342ede8c02d16502ae12b55e0cf582 | 3bb936c38da4dabee97608c1694a1ea02ecf863d |
refs/heads/master | <file_sep>from bs4 import BeautifulSoup
import requests as req
import xlrd
import pandas as pd
from omdbapi.movie_search import GetMovie
def parse():
''' Taking information from the website'''
titles, years = [], []
directors, actors, awards, plots, countries = [],[],[],[],[]
html = BeautifulSoup(open("imdb_most_popular_movies_dump.html"), 'lxml')
tds = html.find_all('td', class_ = 'titleColumn')
for td in tds:
a = td.find('a')
titles.append(a.text)
year = td.find('span', class_ = 'secondaryInfo').text
years.append(int(year[1:5]))
''' Taking information from the OMDb'''
for title in titles:
movie = GetMovie(title=title, api_key='767f674e')
mov_data = movie.get_data('Director', 'Actors', 'Awards', 'Plot','Country')
directors.append(mov_data['Director'])
actors.append(mov_data['Actors'])
awards.append(mov_data['Awards'])
plots.append(mov_data['Plot'])
countries.append(mov_data['Country'])
df = pd.DataFrame()
df['Name'] = titles
df['Year'] = years
df['Director'] = directors
df['Actors'] = actors
df['Awards'] = awards
df['Plot'] = plots
df['Country'] = countries
writer = pd.ExcelWriter('./habr.xlsx', engine= 'xlsxwriter')
df.to_excel(writer, sheet_name = 'Лист1', index=False)
writer.sheets['Лист1'].set_column('A:A', 100)
writer.sheets['Лист1'].set_column('B:B', 30)
writer.sheets['Лист1'].set_column('C:C', 100)
writer.sheets['Лист1'].set_column('D:D', 100)
writer.sheets['Лист1'].set_column('E:E', 100)
writer.sheets['Лист1'].set_column('F:F', 100)
writer.sheets['Лист1'].set_column('G:G', 100)
writer.save()
parse() | 812177d61cb48db588c1bc5f8cb8d1815cac9499 | [
"Python"
] | 1 | Python | RomaKorennoy/Roman_Korinnyi_test | c08edefa596fdfb6d2beae898183d29701a8d163 | 28705a6179b566cd1872b13be097f57c99001313 |
refs/heads/master | <file_sep>package com.xebia.spring4_XTR.model;
public interface Person {
}
<file_sep>package com.xebia.spring4_XTR.service;
import java.util.List;
import java.util.Optional;
import com.xebia.spring4_XTR.exception.CustomerException;
import com.xebia.spring4_XTR.exception.OrderException;
import com.xebia.spring4_XTR.model.Customer;
import com.xebia.spring4_XTR.model.Order;
public interface CustomerService {
public Customer getCustomer(String customerId) throws CustomerException;
public Customer saveCustomer(Customer customer) throws CustomerException;
public Customer updateCustomer(String customerId, Customer customer) throws CustomerException ;
public void deleteCustomer(String customerId) throws CustomerException ;
public List<Order> getCustomerOrders(String customerId) throws OrderException, CustomerException;
public Optional<Customer> findByCustomerID(String customerId);
public List<Customer> findByCustomerName(String firstName);
}
<file_sep>package com.xebia.spring4_XTR.business;
import java.util.List;
import com.xebia.spring4_XTR.exception.CityException;
import com.xebia.spring4_XTR.model.City;
public interface CityBusiness {
public City getCity(Long id) throws CityException;
public City saveCity(City city) throws CityException;
public City updateCity(Long id, City city) throws CityException;
public void deleteCity(Long id) throws CityException;
public List<City> getAllCitiesLamda() throws CityException;
public List<City> getAllCitiesInnerClass() throws CityException;
}
<file_sep>package com.xebia.spring4_XTR.controller.core.combining_annotation.old.repository;
public interface OrderDaoWithoutCombinedAnnotation {
}
<file_sep>package com.xebia.spring4_XTR.controller.java8.lamda.new_way;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xebia.spring4_XTR.exception.CityException;
import com.xebia.spring4_XTR.model.City;
import com.xebia.spring4_XTR.service.CityService;
@RestController
@RequestMapping("/api/java8lamdasupportwithfunctionalinterfaces")
public class Java8LamdaSupportWithFunctionalInterfaces {
@Autowired
private CityService cityService;
@RequestMapping("/getallcities")
public List<City> getAllCitiesLamda() throws CityException{
return cityService.getAllCitiesLamda();
}
}
<file_sep>package com.xebia.spring4_XTR.exception;
public class OrderException extends Exception {
private static final long serialVersionUID = 2837536608895057190L;
public OrderException() {
super();
}
public OrderException(String msg) {
super(msg);
}
public OrderException(String msg, Throwable cause) {
super(msg, cause);
}
public OrderException(Throwable cause) {
super(cause);
}
}
<file_sep>package com.xebia.spring4_XTR.model;
public class View {
public interface Summary {}
}
<file_sep>package com.xebia.spring4_XTR.controller.core.order;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.xebia.spring4_XTR.exception.CustomerException;
import com.xebia.spring4_XTR.model.Person;
// call with http://localhost:9090/api/OrderCoreAnnotation
@RestController
@RequestMapping("/api/OrderCoreAnnotation")
public class OrderCoreAnnotation{
@Autowired
List<Person> list;
/**
* @param customerId
* @return
* @throws CustomerException
*/
@RequestMapping(method = RequestMethod.GET)
public List<Person> getCustomer() throws CustomerException {
return list;
}
}
<file_sep>package com.xebia.spring4_XTR.controller.web.rest_controller_annotation.new_way;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.xebia.spring4_XTR.exception.CustomerException;
import com.xebia.spring4_XTR.exception.OrderException;
import com.xebia.spring4_XTR.model.Customer;
import com.xebia.spring4_XTR.model.Order;
import com.xebia.spring4_XTR.service.CustomerService;
// call with http://localhost:9090/api/webrestcontrollerannotation?customerId=5<PASSWORD>
@RestController
@RequestMapping("/api/webrestcontrollerannotation")
public class WebRestControllerAnnotation{
@Autowired
private CustomerService customerService;
/**
* @param customerId
* @return
* @throws CustomerException
*/
@RequestMapping(method = RequestMethod.GET)
public Customer getCustomer(String customerId) throws CustomerException {
return customerService.getCustomer(customerId);
}
/**
* @param customer
* @return
* @throws CustomerException
*/
@RequestMapping(method=RequestMethod.POST)
public Customer saveCustomer(@RequestBody Customer customer) throws CustomerException {
return customerService.saveCustomer(customer);
}
/**
* @param customerId
* @param customer
* @return
* @throws CustomerException
*/
@RequestMapping(method = RequestMethod.PUT)
public Customer updateCustomer(String customerId, @RequestBody Customer customer) throws CustomerException {
return customerService.updateCustomer(customerId, customer);
}
/**
* @param customerId
* @throws CustomerException
*/
@RequestMapping(method = RequestMethod.DELETE)
public void deleteCustomer(String customerId) throws CustomerException {
customerService.deleteCustomer(customerId);
}
/**
* @param customerId
* @return
* @throws OrderException
* @throws CustomerException
*/
@RequestMapping(value="/orders", method = RequestMethod.GET)
public List<Order> getCustomerOrders(String customerId) throws OrderException, CustomerException{
return customerService.getCustomerOrders(customerId);
}
}
<file_sep>package com.xebia.spring4_XTR.controller.java8.repeating_annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.xebia.spring4_XTR.exception.OrderException;
@RestController
@RequestMapping("/api/java8mutipleannotation")
@PropertySource("classpath:/repeating_annotations/property_file1.properties")
@PropertySource("classpath:/repeating_annotations/property_file2.properties")
@PropertySource("classpath:/repeating_annotations/property_file3.properties")
@PropertySource("classpath:/repeating_annotations/property_file4.properties")
public class Java8RepeatedAnnotation {
@Autowired
private Environment env;
/**
* @param orderId
* @return
* @throws OrderException
*/
@RequestMapping(value= "/getproperty/{property}", method = RequestMethod.GET)
public String getProperty(@PathVariable String property){
return env.getProperty(property);
}
}
<file_sep>package com.xebia.spring4_XTR.exception;
public class CustomerException extends Exception {
private static final long serialVersionUID = 3440506627961894681L;
public CustomerException() {
super();
}
public CustomerException(String msg) {
super(msg);
}
public CustomerException(String msg, Throwable cause) {
super(msg, cause);
}
public CustomerException(Throwable cause) {
super(cause);
}
}
<file_sep>package com.xebia.spring4_XTR;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CustomerInfomataApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerInfomataApplication.class, args);
System.out.println("######################## Started Customer InfoMata ##########################");
System.out.println("######################## Get Cutomer Data and order data ##########################");
}
}
<file_sep>package com.xebia.spring4_XTR.controller.java8.optional.new_way;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xebia.spring4_XTR.exception.CustomerException;
import com.xebia.spring4_XTR.model.Customer;
import com.xebia.spring4_XTR.service.CustomerService;
@RestController
@RequestMapping("/api/java8optionalsupportfornullsafety")
public class Java8OptionalSupportForNullSafety {
@Autowired
private Optional<CustomerService> customerServiceOptional;
@RequestMapping("/accounts/{customerId}")
public String getCustomer(@PathVariable String customerId) throws CustomerException{
if(customerServiceOptional.isPresent()){
CustomerService customerService = customerServiceOptional.get();
Optional<Customer> optional = customerService.findByCustomerID(customerId);
if(optional.isPresent()) {
Customer customer = optional.get();
return customer.getFirstName() + " " + customer.getLastName();
} else{
return "No Customer with ID";
}
} else{
return "Service not present";
}
}
}
<file_sep>package com.xebia.spring4_XTR.business.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xebia.spring4_XTR.business.CityBusiness;
import com.xebia.spring4_XTR.exception.CityException;
import com.xebia.spring4_XTR.model.City;
import com.xebia.spring4_XTR.repository.CityRepositoryService;
@Service("cityBusiness")
public class CityBusinessImpl implements CityBusiness {
@Autowired
private CityRepositoryService cityRepositoryService;
@Override
public City getCity(Long cityId) {
City city=cityRepositoryService.findOne(cityId);
return city;
}
@Override
public City saveCity(City city) {
return cityRepositoryService.save(city);
}
@Override
public City updateCity(Long cityId, City city) {
City updateCity = cityRepositoryService.findOne(cityId);
return cityRepositoryService.save(updateCity);
}
@Override
public void deleteCity(Long cityId) {
cityRepositoryService.delete(cityId);
}
@Override
public List<City> getAllCitiesLamda() throws CityException {
return cityRepositoryService.getAllCitiesLamda();
}
@Override
public List<City> getAllCitiesInnerClass() throws CityException {
return cityRepositoryService.getAllCitiesInnerClass();
}
}
<file_sep>package com.xebia.spring4_XTR.exception;
public class CityException extends Exception {
private static final long serialVersionUID = 6175021560585444761L;
public CityException() {
super();
}
public CityException(String msg) {
super(msg);
}
public CityException(String msg, Throwable cause) {
super(msg, cause);
}
public CityException(Throwable cause) {
super(cause);
}
}
<file_sep>package org.pantha.infomata.controller;
import java.util.Date;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.jayway.restassured.RestAssured;
import com.xebia.spring4_XTR.CustomerInfomataApplication;
import com.xebia.spring4_XTR.exception.CustomerException;
import com.xebia.spring4_XTR.exception.OrderException;
import com.xebia.spring4_XTR.model.Customer;
import com.xebia.spring4_XTR.model.Order;
import com.xebia.spring4_XTR.service.CustomerService;
import com.xebia.spring4_XTR.service.OrderService;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CustomerInfomataApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class OrderControllerTest extends RestAssured {
@Autowired
CustomerService customerService;
@Autowired
OrderService orderService;
Customer customer;
Order order;
@Value("${local.server.port}")
int port;
String mockedCustomerId="<KEY>";
String mockedOrderId="558fdca<KEY>5356789";
double amount=24.56;
Date currentDate = new Date();
@Before
public void setUp() throws OrderException, CustomerException {
customer = new Customer("firstName","lastName", currentDate, currentDate, null);
customer.setCustomerId(mockedCustomerId);
order = new Order("SKUNAME", mockedCustomerId ,"PRODUCTNAME", currentDate, currentDate, amount);
order.setOrderId(mockedOrderId);
customerService.saveCustomer(customer);
orderService.saveOrder(order);
RestAssured.port = port;
}
@Test
public void getOrderTest() {
String orderId = order.getOrderId();
when().get("/api/order?orderId={orderId}", orderId).
then().
statusCode(HttpStatus.OK.value()).
body("sku", Matchers.is("SKUNAME"))
.body("orderId", Matchers.is(orderId))
.body("productName", Matchers.is("PRODUCTNAME"));
}
@Test
public void updateOrderWithoutBodyTest() {
String orderId = order.getOrderId();
when().put("/api/order?orderId={orderId}", orderId).then().statusCode(HttpStatus.BAD_REQUEST.value());
}
}
<file_sep>package com.xebia.spring4_XTR.service.impl;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xebia.spring4_XTR.business.OrderBusiness;
import com.xebia.spring4_XTR.exception.CustomerException;
import com.xebia.spring4_XTR.exception.OrderException;
import com.xebia.spring4_XTR.model.Customer;
import com.xebia.spring4_XTR.model.Order;
import com.xebia.spring4_XTR.service.CustomerService;
import com.xebia.spring4_XTR.service.OrderService;
@Service("orderService")
public class OrderServiceImpl implements OrderService{
@Autowired
private OrderBusiness orderBusiness;
@Autowired
private CustomerService customerService;
public Order getOrder(String orderId) throws OrderException {
try{
return orderBusiness.getOrder(orderId);
}catch(Exception e){
throw new OrderException("Unable to get order with orderId = "+orderId);
}
}
public Order saveOrder(Order order) throws OrderException, CustomerException {
Order customerOrder=null;
try{
customerOrder = orderBusiness.saveOrder(order);
} catch(Exception e){
throw new OrderException("Unable to create order!");
}
Customer customer = customerService.getCustomer(order.getCustomerId());
if(customer==null){
throw new CustomerException("Customer Not Found!");
}
List<String> orders= customer.getOrders();
orders.add(customerOrder.getOrderId());
customer.setOrders(orders);
customerService.updateCustomer(order.getCustomerId(), customer);
return customerOrder;
}
public Order updateOrder(String orderId, Order order) throws OrderException {
try{
if(order.getCustomerId()!=null || StringUtils.isNotEmpty(order.getCustomerId())){
throw new OrderException("Change of customerId not permitted!");
}
return orderBusiness.updateOrder(orderId, order);
}catch(Exception e){
throw new OrderException("Fail to update order!");
}
}
public void deleteOrder(String orderId) throws OrderException, CustomerException {
Order order = orderBusiness.getOrder(orderId);
if(order==null){
throw new OrderException("Order Not Found!");
}
orderBusiness.deleteOrder(orderId);
Customer customer = customerService.getCustomer(order.getCustomerId());
if(customer==null){
throw new CustomerException("Customer Not Found!");
}
List<String> orders = customer.getOrders();
orders.remove(orderId);
customer.setOrders(orders);
try{
customerService.updateCustomer(order.getCustomerId(), customer);
}catch(Exception e){
throw new CustomerException("Failed to update customer with order!");
}
}
}
<file_sep>package com.xebia.spring4_XTR.business;
import java.util.List;
import java.util.Optional;
import com.xebia.spring4_XTR.model.Customer;
public interface CustomerBusiness {
public Customer getCustomer(String customerId);
public Customer saveCustomer(Customer customer);
public Customer updateCustomer(String customerId, Customer customer) ;
public void deleteCustomer(String customerId) ;
public Optional<Customer> findByCustomerID(String customerId);
public List<Customer> findByCustomerName(String firstName);
}
| 28a5562eaa47fbb9bf538d8883c7a9836d23ed0d | [
"Java"
] | 18 | Java | SOURABHAGGARWAL/spring4_xtr | 947bc5c3441e949ad52ccca5886606d141a8b8f5 | 17e14b33e001f6e48ec7cc3838d639740aa4c019 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.