
Dmitri Konradi
Ardent math oriented full stack web developer extended his Computer Science knowledge at Kennesaw State University.
Code examples created in Java, C#, C, Python, JavaScript
Languages
- C#
- Java
- Python
- Client/Server in Python - Server module
- Client/Server in Python - Client module
- Client/Server in Python - Function module
- Python and SQLite databases - DB access module
- Python and SQLite databases - DB utility module
- Python and SQLite databases - Print result module
- Python and SQLite databases - DB Util module
- C
- JavaScript
Problem 28.7 | Graphs and Applications using JAVA
The method returns a List that contains all the vertices in a cycle starting from u. If the graph doesn’t have any cycles, the method returns null.
/** (Find a cycle) Add a new method in AbstractGraph to find a cycle in the graph
* Problem 28.7 | Intro to Java Programming, Comprehensive Version (10th Edition) Liang
* The method returns a List that contains all the vertices in a cycle starting from u.
* If the graph doesn’t have any cycles, the method returns null.
*/
@Override
public List getACycle(int v) {
List cyclePath = new ArrayList<>();
boolean cycleFound = false;
int startIndex = -1;
int endIndex = -1;
List searchOrder = new ArrayList<>();
int[] parent = new int[vertices.size()];
for (int i = 0; i < parent.length; i++)
parent[i] = -1; // Initialize parent[i] to -1
java.util.LinkedList queue = new java.util.LinkedList<>();
boolean[] isVisited = new boolean[vertices.size()];
for(int i = 0; i < isVisited.length; i++)
isVisited[i] = false;
queue.offer(v); // Enqueue v
isVisited[v] = true; // Mark it visited
while (!queue.isEmpty() && !cycleFound)
{
int u = queue.poll(); // Dequeue to u
searchOrder.add(u); // u searched
for (Edge e : neighbors.get(u))
{
if (!isVisited[e.v])
{
queue.offer(e.v); // Enqueue w
parent[e.v] = u; // The parent of w is u
isVisited[e.v] = true; // Mark it visited
}
else if(isVisited[e.v] && parent[v] != e.v) {
cycleFound = true;
startIndex = v;
endIndex = e.v;
cyclePath = searchOrder;
}
}
}
cyclePath.add(endIndex);
if (cyclePath.isEmpty())
return null;
else
return cyclePath;
}
Problem 28.5 | Graphs and Applications using JAVA
The method returns a List
/** Created by Dmitri Konradi on 7/16/15.
* Problem 28.5 | Intro to Java Programming, Comprehensive Version (10th Edition) Liang
* The method returns a List that contains all the vertices in a shortest path from v to u1
*/
@Override
public List getPath(int v, int u) {
List path = new ArrayList<>();
int start = v;
int end = u;
AbstractGraph.Tree t = bfs(v);
path.add(u);
while (t.getParent(u) != -1) {
path.add(t.getParent(u));
u = t.getParent(u);
}
if(path.get(0).equals(end) && path.get(path.size() - 1).equals(start))
return path;
else
return null;
}
/** Created by Dmitri Konradi on 7/16/15.
* Problem 28.5
* The method returns a List that contains all the vertices in a shortest path from v to u1
* This method is more efficient because it doesn't create full tree,
* it terminates when it gets to the final vertex u1.
*/
@Override
public List getPathE(int v, int u1) {
List path = new ArrayList<>();
int start = v;
int end = u1;
List searchOrder = new ArrayList<>();
int[] parent = new int[vertices.size()];
for (int i = 0; i < parent.length; i++)
parent[i] = -1; // Initialize parent[i] to -1
java.util.LinkedList queue = new java.util.LinkedList<>();
boolean[] isVisited = new boolean[vertices.size()];
for(int i = 0; i < isVisited.length; i++)
isVisited[i] = false;
queue.offer(v); // Enqueue v
isVisited[v] = true; // Mark it visited
int u = -1;
while (!queue.isEmpty() && u1 != u)
{
u = queue.poll(); // Dequeue to u
searchOrder.add(u); // u searched
for (Edge e : neighbors.get(u))
{
if (!isVisited[e.v])
{
queue.offer(e.v); // Enqueue w
parent[e.v] = u; // The parent of w is u
isVisited[e.v] = true; // Mark it visited
}
}
}
AbstractGraph.Tree t = new Tree(v, parent, searchOrder);
path.add(u1);
while (t.getParent(u1) != -1) {
path.add(t.getParent(u1));
u1 = t.getParent(u1);
}
if(path.get(0).equals(end) && path.get(path.size() - 1).equals(start))
return path;
else
return null;
}
Reflection in JAVA
This programm prints all fields and methods of a class by providing the class name.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Scanner;
/**
* Created by Dmitri Konradi on 8/24/15.
* This programm prints all fields and methods of a class by providing the class name.
*/
public class ReflectionActivity {
public static void main(String[] args){
System.out.print("Please enter fully specified name of a class: ");
Scanner input = new Scanner(System.in);
String cls = input.next();
input.close();
try {
Class> enteredClass = Class.forName(cls);
Field[] fld = enteredClass.getFields();
Method[] mtd = enteredClass.getMethods();
printAllFields(fld);
printAllMethods(mtd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
/**
* Prints all non-static class fields first, then all static class fields
* @param fld - array of all class fields
* @throws IllegalArgumentException if fld is null
*/
private static void printAllFields(Field[] fld) {
if(fld == null)
throw new IllegalArgumentException ("currentClass.getFields() is equal to null");
for(Field elements: fld)
if(!Modifier.isStatic((elements.getModifiers())))
System.out.println(elements.getName() + " : " + elements.getGenericType().getTypeName() + " - " + elements.getDeclaringClass().getName());
for(Field elements: fld)
if(Modifier.isStatic((elements.getModifiers())))
System.out.println("S:" + elements.getName() + " : " + elements.getGenericType().getTypeName() + " - " + elements.getDeclaringClass().getName());
}
/**
* Prints all non-static class methods first, then all static class methods
* @param mtd - array of all class methods
* @throws IllegalArgumentException if mtd is null
*/
private static void printAllMethods(Method[] mtd) {
if(mtd == null)
throw new IllegalArgumentException ("currentClass.getMethods() is equal to null");
for(Method elements: mtd)
if(!Modifier.isStatic((elements.getModifiers()))) {
System.out.print(elements.getName() + "(");
Class>[] ts = elements.getParameterTypes();
printParameterList(ts);
System.out.print(")" + " : " + elements.getGenericReturnType().getTypeName() + " - " + elements.getDeclaringClass().getName() + "\n");
}
for (Method elements: mtd)
if(Modifier.isStatic((elements.getModifiers()))) {
System.out.print("S:" + elements.getName() + "(");
Class>[] ts = elements.getParameterTypes();
printParameterList(ts);
System.out.print(")" + " : " + elements.getGenericReturnType().getTypeName() + " - " + elements.getDeclaringClass().getName() + "\n");
}
}
/**
* Prints all methods parameters
* @param ts
*/
private static void printParameterList(Class>[] ts) {
for(Class> types: ts)
System.out.print(types + ",");
}
}
Reflection in JAVA
Several methods from Interpreter
/*
* TODO: convertNameToInstance
* Given a name (identifier or literal) return the object.
* If the name is in the symbol table, you can just return the object it is
* associated with. If it's not in the symbol table, then it is either
* a String literal or it is an integer literal. Check to see if the
* first character is quotation marks. If so, create a new String object to
* return that has the same characters as the name, just without the quotes.
* If there aren't quotation marks, then it is an integer literal. Use Integer.parseInt
* to turn the String into an int.
*
* Dmitri Konradi
* Assignment #1
*/
public Object convertNameToInstance(String name){
if(name == null)
throw new IllegalArgumentException ("name is null");
Object obj = null;
if(mySymbolTable.containsKey(name))
return mySymbolTable.get(name);
else {
if(name.charAt(0) == '"')
return name.substring(1, name.length() - 1);
else
try {
obj = Integer.parseInt(name);
} catch (NumberFormatException e) {
System.out.println("parameter should be integer literal or string in quotation marks");
}
}
return obj;
}
/*TODO: convertNameToInstance.
* Takes an array of Strings and converts all of them to their associated objects.
* Simply call the other helper method of the same name on each item in the array.
*
* Dmitri Konradi
* Assignment #1
*/
public Object[] convertNameToInstance(String[] names){
if(names == null)
throw new IllegalArgumentException ("names array is null");
if(names.length == 0) {
}
Object[] obj = new Object[names.length];
for(int i = 0; i < names.length; i++) {
obj[i] = convertNameToInstance(names[i]);
}
return obj;
}
/* TODO: makeObject
* This method does the "process" job for making objects.
* Don't forget to add the new object to the symbol table.
* The String that is returned should be a basic message telling what happened.
* input String example: java.lang.String word = new java.lang.String("Interpreter");
* output example: ok. I have a new java.lang.String called word
*
* Dmitri Konradi
* Assignment #1
*/
public String makeObject(ParseResults parse){
if(parse == null)
throw new IllegalArgumentException ("parse is null");
String result = null;
try {
Object[] args = convertNameToInstance(parse.arguments);
Object obj = ReflectionUtilities.createInstance(parse.className, args);
mySymbolTable.put(parse.objectName, obj);
result = "ok. I have a new " + obj.getClass().getName() + " called '" + parse.objectName;
} catch (Exception e) {
System.out.println(e);
}
return result;
}
/*
* TODO: callMethod
* This method does the "process" job for calling methods.
* You MUST use the ReflectionUtilities to call the method for
* this to work, because ints can't be directly transformed into Objects.
* When you call a method, if it has an output, be sure to
* either create a new object for that output or change the
* existing object. This will require either adding a new
* thing to the symbol table or removing what is currently there
* and replacing it with something else.
* input: java.lang.String nextWord = word.substring(0,4);
*
* Dmitri Konradi
* Assignment #1
*/
public String callMethod(ParseResults parse){
if(parse == null)
throw new IllegalArgumentException ("parse is null");
Object obj;
Object new_obj = null;
String result = "Error";
// if object exists call the method
if(mySymbolTable.containsKey(parse.objectName)) {
Object[] args = convertNameToInstance(parse.arguments);
// get the object associated with the objectName
obj = mySymbolTable.get(parse.objectName);
// invoke the method
try {
new_obj = ReflectionUtilities.callMethod(obj, parse.methodName, args);
if(new_obj != null) {
mySymbolTable.put(parse.answerName, new_obj);
result = "ok. I made a new object. " + new_obj.getClass().getName() + " called '" + parse.answerName + "'" +
"\nResult: " + new_obj.toString();
}
else {
result = "I performed the operation. My answer is: null";
}
} catch (Exception e) {
System.out.println(e);
}
}
else {
// if object doesn't exist, we can't call any method on it
result = "Error: Object '" + parse.objectName + "' doesn't exist";
}
// add new object + key to the Symbol table
mySymbolTable.put(parse.answerName, new_obj);
return result;
}
Client/Server Using Sockets in Python
Server module
__author__ = 'Dmitri Konradi'
"""
CS 4720
Dmitri Konradi
09/06/2015
"""
from polynomial import eval, bisection
from socket import socket
# exportable resources
port = 12321
encoding = "utf-8"
if __name__ == "__main__":
# server script
# setting up a listener socket
listener = socket()
listener.bind(('', port))
# 0 backlog of connections - if listener is busy connection is denied
listener.listen(0)
while True:
try:
(conn, address) = listener.accept() # the system makes the connection
print("connction socket", conn)
print("connection address", address)
data_string = ""
bytes = conn.recv(2048)
while len(bytes) > 0:
str1 = bytes.decode(encoding)
data_string += str1
bytes = conn.recv(2048)
print("received: |{}|".format(data_string))
if len(data_string) == 0:
message = "XInvalid request syntax: empty request"
elif data_string[0] == "E":
# Evaluate Request
e_data = data_string[1:]
#print(e_data)
e_parts = e_data.split(' ')
#print(e_parts)
if len(e_parts) == 0:
message = "XInvalid request syntax: wrong number of fields in request"
else:
poly = []
try:
x = float(e_parts[0])
for i in range(1,len(e_parts)):
poly.append(float(e_parts[i]))
#print(x)
#print(poly)
result = eval(x, poly)
message = "E" + str(result)
except Exception as e:
message = "XInvalid format numeric data: " + str(e)
elif data_string[0] == "S":
# Bisection Request
s_data = data_string[1:]
#print(s_data)
s_parts = s_data.split(' ')
#print(s_parts)
if len(s_parts) < 3:
message = "XInvalid request syntax: wrong number of fields in request"
else:
try:
a = float(s_parts[0])
b = float(s_parts[1])
poly = []
for i in range(2, len(s_parts)-1):
poly.append(float(s_parts[i]))
tolerance = float(s_parts[-1])
#print(a)
#print(b)
#print(poly)
#print(tolerance)
result = bisection(a, b, poly, tolerance)
message = "S" + str(result)
except Exception as e:
message = "XInvalid format numeric data: " + str(e)
else:
message = "XInvalid input! First letter shoulb be 'E' or 'S'"
#print(message)
# send result to client (response)
conn.sendall(message.encode(encoding))
print("data sent")
conn.shutdown(1) ## shutdown the sending side
finally:
conn.close()
print("connection closed")
print("=" * 30)
print("\n")
Client/Server Using Sockets in Python
Client module
__author__ = 'Dmitri Konradi'
"""
CS 4720
Dmitri Konradi
09/06/2015
"""
from socket import socket
from server import encoding, port
def send_receive(message):
"""
Function to send message to the server and receive respond from the server
:param message: to be send
:return: string message from the server
"""
sock = socket()
sock.connect(('127.0.0.1', port))
# print("connection made")
print("request: " + message)
bytes = message.encode(encoding)
sock.sendall(bytes) # we can send only bytes through the socket
# print("data send")
sock.shutdown(1) # shutdown the sending side of the socket
data_string = ""
bytes = sock.recv(2048)
while len(bytes) > 0:
data_string += bytes.decode(encoding)
bytes = sock.recv(2048)
# print(data_string)
sock.close()
# print("connection closed\n")
return data_string
# initial data
a = "8"
b = "10"
poly = "-945 1689 -950 230 -25 1"
tolerance = "1e-13"
message1 = "S" + a + " " + b + " " + poly + " " + tolerance
# print(message1)
resp1 = send_receive(message1)
if resp1[0] == "S":
print("Value returned from bisection: " + resp1[1:])
x = resp1[1:]
message2 = "E" + x + " " + poly
# print(message2)
resp2 = send_receive(message2)
if resp2[0] == "E":
print("Value returned from eval: " + resp2[1:])
else:
print("Error in evaluation call: " + resp2[1:])
else:
print("Error in bisection call: " + resp1[1:])
Client/Server Using Sockets in Python
Polynomial function module
__author__ = 'Dmitri Konradi'
"""
CS 4720
Dmitri Konradi
09/06/2015
"""
def eval(x, poly):
"""
Evaluate the polynomial at the value x.
poly is a list of coefficients from lowest to highest.
:param x: Argument at which to evaluate
:param poly: The polynomial coefficients, lowest order to highest
:return: The result of evaluating the polynomial at x
"""
result = 0
for i in range(len(poly)):
result += poly[i] * x ** i
return result
def bisection(a, b, poly, tolerance):
"""
Assume that poly(a) <= 0 and poly(b) >= 0.
:param a: poly(a) <= 0 Raises an exception if not true
:param b: poly(b) >= 0 Raises an exception if not true
:param poly: polynomial coefficiens, low order first
:param tolerance: greater than 0
:return: a value between a and b that is within tolerance of a root of the polynomial
"""
if eval(a, poly) > 0:
raise Exception("polynomial at the value", a, "should be <= 0")
if eval(b, poly) < 0:
raise Exception("polynomial at the value", b, "should be >= 0")
if tolerance <= 0:
raise Exception("tolerance should be greater than 0")
while abs(a - b) > tolerance:
mid = (a + b) / 2
if eval(mid, poly) < 0:
a = mid
else:
b = mid
return (a + b) / 2
Python and SQLite databases
DB Util module
__author__ = 'zhuk7'
"""
Assignment 3
CS 4720
Dmitri Konradi
09/19/2015
"""
import sqlite3
from os.path import split, join
def dictionary_factory(cursor, row):
"""
Create a dictionary from rows in a cursor result.
The keys will be the column names.
:param cursor: A cursor from which a query row has just been fetched
:param row: The query row that was fetched
:return: A dictionary associating column names to values
"""
# desc = cursor.description
# map1 = {} # create an empty map
# for i in range(len(row)):
# key = desc[i][0].lower()
# value = row[i]
# map1[key] = value
# return map1
col_names = [d[0].lower() for d in cursor.description]
return dict(zip(col_names, row)) # zip makes list of pairs (key/value), dict - creates map from it
def get_connection():
this_dir = split(__file__)[0]
fname = join(this_dir, 'measures.sqlite')
conn = sqlite3.connect(fname)
conn.row_factory = dictionary_factory
return conn
def default_process(crs):
return crs.fetchall()
def do_command(cmd, args=[], process=default_process):
try:
conn = get_connection()
crs = conn.cursor()
crs.execute(cmd, args)
return process(crs)
finally:
conn.close()
Python and SQLite databases
DB access module
__author__ = 'Dmitri Konradi'
"""
CS 4720
Dmitri Konradi
09/19/2015
"""
from util.db import do_command
def get_all_areas():
"""
Returns a list of dictionaries representing all the rows in the
area table.
"""
return do_command("select * from area")
def get_locations_for_area(area_id):
"""
Return a list of dictionaries giving the locations for the given area.
"""
return do_command("select * from location where location_area = ?", [area_id])
def get_measurements_for_location(location_id):
"""
Return a list of dictionaries giving the measurement rows for the given location.
"""
return do_command("select * from measurement where measurement_location = ?", [location_id])
def get_categories_for_area(area_id):
"""
Return a list of rows from the category table that all contain the given area.
"""
return do_command("select * from category where category_id IN (select category_id from category_area where area_id = ?)", [area_id])
Python and SQLite databases
DB utility module
__author__ = 'Dmitri Konradi'
"""
CS 4720
Dmitri Konradi
09/19/2015
"""
import db_access
def get_average_measurements_for_area(area_id):
"""
Returns the average value of all measurements for all locations in the given area.
Returns None if there are no measurements.
"""
if area_id == '':
raise Exception("area ID could not be ''")
locations = db_access.get_locations_for_area(area_id)
total_val = 0
counter = 0
for i in range(len(locations)):
location_id = locations[i]['location_id']
measurements = db_access.get_measurements_for_location(str(location_id))
for j in range(len(measurements)):
total_val = total_val + (measurements[j]['value'])
counter += 1
if total_val == 0:
return None
else:
avr_val = total_val / counter
return avr_val
def number_of_locations_by_area(area_id):
"""
Returns the number of locations for the given area.
"""
if area_id == '':
raise Exception("area ID could not be ''")
locations = db_access.get_locations_for_area(area_id)
return len(locations)
Python and SQLite databases
Print result module
__author__ = 'Dmitri Konradi'
"""
Assignment 3
CS 4720
Dmitri Konradi
09/19/2015
"""
import db_access
import db_utility
template = "{:>3} {:20} {:>10} {:>10} {:15}"
row = template.format("ID", "Name", "Num Loc", "Avg Value", "Categories")
print(row)
areas = db_access.get_all_areas()
for area in areas:
area_id = area['area_id']
num_loc = db_utility.number_of_locations_by_area(area_id)
avg_value = db_utility.get_average_measurements_for_area(area_id)
if avg_value is None:
avg_value = '-----'
else:
avg_value = round(avg_value, 2)
cat_s = db_access.get_categories_for_area(str(area_id))
c = ''
for e in cat_s:
c += e['name'] + ', '
c = c[:-2]
row = template.format(area_id, area['name'], num_loc, avg_value, c)
print(row)
Parent–child synchronization in C
/* Dmitri Konradi
* CS 3540-02
* Assignment 9
* April 14, 2015
*/
#include ...
void TELL_WAIT(void); /* parent/child from {Sec race_conditions} */
void TELL_PARENT(pid_t);
void TELL_CHILD(pid_t);
void WAIT_PARENT(void);
void WAIT_CHILD(void);
static volatile sig_atomic_t sigflag; /* set nonzero by sig handler */
static sigset_t newmask, oldmask, zeromask;
void increment_f();
static void sig_usr(int signo) /* one signal handler for SIGUSR1 and SIGUSR2 */
{
sigflag = 1;
}
void err_sys (const char* message);
/* global variables */
int counter;
//char buf2[10];
pid_t pid;
FILE* fp = NULL;
int main (int argc, char* argv[])
{
char buf1[] = "1";
memset(buf2, 0, sizeof(buf2));
/* print out size of buf1 */
printf("strlen of buf1 is : %d\n", strlen(buf1));
printf("sizeof of buf2 is : %d\n", sizeof(buf2));
/* opent the stream to read and write */
fp = fopen("counter_file_1.txt", "w+");
if(fp == NULL)
err_sys("fopen failed");
else
printf("File opened successfully using fopen()\n");
/* write to file "counter_file_1.txt" from buf1 */
if(fwrite(buf1, sizeof(char), strlen(buf1), fp) != strlen(buf1))
err_sys("fwrite failed.");
else
{
printf("initial fwrite worked, ");
printf("%s bytes written\n\n", buf1);
}
if(fclose(fp) != 0)
err_sys("fclose failed");
TELL_WAIT();
/*create a child process by calling fork function */
if((pid = fork()) < 0)
err_sys("fork error\n");
else if(pid == 0) //child
{
int i;
for(i = 0; i < 5; i++)
{
WAIT_PARENT(); /* wait fot parent */
printf("================================================================\n");
printf("i am a child process\n");
increment_f();
TELL_PARENT(getppid()); /* tell parent we're done*/
}
}
else //parent
{
int j;
for(j = 0; j < 5; j++)
{
printf("================================================================\n");
printf("i am a parent process\n");
increment_f();
TELL_CHILD(pid); /* tell child we're done */
WAIT_CHILD(); /* and wait fot child */
}
}
return 0;
} // end of main
void increment_f() {
/* opent the stream/file to read and write */
fp = fopen("counter_file_1.txt", "r+");
if(fp == NULL)
err_sys("fopen failed");
else
printf("file opened successfully using fopen | pid = %ld\n", (long)getpid());
if(fseek(fp, 0, SEEK_SET) != 0)
err_sys("fseek failed");
else
printf("fseek worked\n");
/* read from the file "counter_file_1.txt" to buf2 */
if(fread(buf2, sizeof(char), strlen(buf2), fp) != strlen(buf2))
err_sys("failed to fread\n");
else
{
printf("%d bytes read from file using fread() to buffer \n", strlen(buf2));
printf("pid = %ld | ", (long)getpid());
printf("buffer = ");
printf("%s\n\n", buf2);
/* cast from char[] to integer*/
counter = atoi(buf2);
printf("counter before increment = %d\n", counter);
counter++;
/* cast from integer to char[] */
int n;
n = snprintf(buf2, sizeof(buf2), "%d", counter);
printf("buffer after increment = ");
printf("%s\n", buf2);
}
/* set file counter_file_1.txt offset */
if(fseek(fp, 0, SEEK_SET) != 0)
err_sys("fseek failed");
else
{
printf("fseek worked\n");
printf("counter = %d | ", counter);
printf("pid = %ld\n", (long)getpid());
printf("\n");
}
/* write to file counter_file_1.txt from buf2 */
if(fwrite(buf2, sizeof(char), strlen(buf2), fp) != strlen(buf2))
err_sys("fwrite failed.");
else
{
printf("fwrite worked | pid = %ld\n", (long)getpid());
printf("counter = %d\n", counter);
printf("info written to file from buffer = ");
printf("%s\n", buf2);
}
if(fclose(fp) != 0)
err_sys("fclose failed");
else
printf("file closed succsessfully using fclose | pid = %ld\n", (long)getpid());
printf("================================================================\n\n");
//exit(1);
} // end of increment_f
void err_sys (const char* message)
{
printf ("%s\n", message);
exit(1);
}
void TELL_WAIT(void)
{
if (signal(SIGUSR1, sig_usr) == SIG_ERR)
err_sys("signal(SIGUSR1) error");
if (signal(SIGUSR2, sig_usr) == SIG_ERR)
err_sys("signal(SIGUSR2) error");
sigemptyset(&zeromask);
sigemptyset(&newmask);
sigaddset(&newmask, SIGUSR1);
sigaddset(&newmask, SIGUSR2);
/* Block SIGUSR1 and SIGUSR2, and save current signal mask */
if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
err_sys("SIG_BLOCK error");
}
void TELL_PARENT(pid_t pid)
{
kill(pid, SIGUSR2); /* tell parent we're done */
}
void WAIT_PARENT(void)
{
while (sigflag == 0)
sigsuspend(&zeromask); /* and wait for parent */
sigflag = 0;
/* Reset signal mask to original value */
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
err_sys("SIG_SETMASK error");
}
void TELL_CHILD(pid_t pid)
{
kill(pid, SIGUSR1); /* tell child we're done */
}
void WAIT_CHILD(void)
{
while (sigflag == 0)
sigsuspend(&zeromask); /* and wait for child */
sigflag = 0;
/* Reset signal mask to original value */
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
err_sys("SIG_SETMASK error");
}
Link list in C
/* Dmitri Konradi
* CS 3540-02
* Assignment 5
* Feb 11, 2015
*/
#include "linked_list.h"
#include ...
//
// This is updated as of 2/10/15. There was an error in the Get function
// This has been corrected.
//
//create and return empty list;
list create_list()
{
list l;
l.front = NULL;
l.rear = NULL;
l.size = 0;
return l;
}
int is_empty(list l)
{
return l.front == NULL;
}
int size(list l)
{
return l.size;
}
void delete (list* l)
{
if(l != NULL)
{
node* temp = l -> front;
while(temp != NULL)
{
node* temp1 = temp->next;
free(temp);
temp = temp1;
}
}
}
int prepend(list* l, void* item)
{
int result = 0;
if(l != NULL)
{
node* temp = malloc (sizeof(node));
if(temp != NULL)
{
result = 1;
temp -> item = item;
if(l -> front == NULL)
{
temp -> next = NULL;
temp -> previous = NULL;
l -> front = temp;
l -> rear = temp;
}
else
{
temp -> next = l -> front;
temp -> previous = NULL;
l -> front -> previous = temp; // point 'l->front node' to 'temp node'
l -> front = temp;
}
l -> size++;
}
}
return result;
}
int append(list* l, void* item)
{
int result = 0;
if(l != NULL)
{
node* temp = malloc (sizeof(node));
if(temp != NULL)
{
result = 1;
temp -> item = item;
temp -> next = NULL;
if(l -> front == NULL)
{
temp -> previous = NULL;
l -> front = temp;
l -> rear = temp;
}
else
{
l -> rear -> next = temp;
temp -> previous = l -> rear; // point 'temp node' to privious (in this case to 'l->rear node')
l -> rear = temp;
}
l -> size++;
}
}
return result;
}
int insert_in_list(list* l, int location, void* item)
{
int result = 0;
if(l == NULL)
return result;
if(location < 1 || location > size(*l) + 1)
return result;
if(l -> size == 0 || location == 1)
{
if(prepend(l, item))
result = 1;
}
else
{
node* temp = malloc (sizeof(node));
if(temp == NULL)
result = 0;
else
{
result = 1;
temp -> item = item;
int i;
node* temp1 = l -> front;
for(i = 1; i < location -1; i++)
temp1 = temp1 -> next;
temp -> next = temp1 -> next;
temp -> previous = temp1; //
temp1 -> next = temp;
if(location == l -> size +1)
l -> rear = temp;
l -> size++;
}
}
return result;
}
int delete_from_list(list* l, int location)
{
int result = 0;
if(l == NULL)
return result;
if(location < 1 || location > size(*l))
return result;
if(l -> size == 0)
return result;
if(location == 1)
{
node* temp = l -> front;
l -> front = l -> front -> next;
l -> front -> previous = NULL; //
if(size(*l) == 1)
l -> rear = NULL;
free(temp);
l -> size--;
result = 1;
}
else
{
node* temp = l -> front;
int i;
for(i = 1; i < location - 1; i++)
temp = temp -> next;
node* temp1 = temp -> next;
temp -> next = temp1 -> next;
temp -> previous = temp1; //
free(temp1);
if(location == l -> size)
l -> rear = temp;
l -> size--;
result = 1;
}
return result;
}
void* get(list l, int location)
{
void* item = NULL;
if(1 <= location && location <= size(l))
{
node* temp = l.front;
int i;
for(i = 1; i < location; i++)
temp = temp -> next;
item = temp -> item;
}
return item;
}
int set(list l, int location, void* item)
{
int result = 0;
if(1 <= location && location <= size(l))
{
node* temp = l.front;
int i;
for(i = 1; i< location; i++)
temp = temp -> next;
temp->item = item;
result = 1;
}
return result;
}
Compute statistics using JavaScript
/**
* Created by Dmitri Konradi on 11/7/15.
* Assignment #6
* CS 4720
*/
function setup() {
//alert("setting up");
var addElementButton = document.getElementById("addElement");
addElementButton.addEventListener("click", addValue, false);
var computeButton = document.getElementById("compute");
computeButton.addEventListener("click", computeStatistics, false);
var removeElementButton = document.getElementById("removeElement");
removeElementButton.addEventListener("click", removeValue, false);
}
function addValue() {
//alert("Add element");
//var eltab = document.getElementById("elementTable");
var tbody = document.getElementById("values");
var lastNum = tbody.lastElementChild.firstElementChild.textContent;
//alert("Last number: " + lastNum);
var nextNum = +lastNum+1;
//alert("Next number: " + nextNum);
var newRow = document.createElement("tr");
var numCell = document.createElement("td");
var valCellX = document.createElement("td");
var valCellY = document.createElement("td");
var numText = document.createTextNode(nextNum+"");
numCell.appendChild(numText);
var inputX = document.createElement("input");
inputX.setAttribute("name", "xvalue");
inputX.setAttribute("type", "text");
valCellX.appendChild(inputX);
var inputY = document.createElement("input");
inputY.setAttribute("name", "yvalue");
inputY.setAttribute("type", "text");
valCellY.appendChild(inputY);
newRow.appendChild(numCell);
newRow.appendChild(valCellX);
newRow.appendChild(valCellY);
tbody.appendChild(newRow);
}
function removeValue() {
//var eltab = document.getElementById("elementTable");
var tbody = document.getElementById("values");
//alert("child count: " + tbody.childElementCount)
if(tbody.childElementCount > 1) {
// leave at least one value row
//alert("removing");
tbody.removeChild(tbody.lastElementChild);
}
}
function computeStatistics() {
var valuesX = document.getElementsByName("xvalue");
var valuesY = document.getElementsByName("yvalue");
var countSpan = document.getElementById("countOutput");
if(countSpan.lastChild) {
countSpan.removeChild(countSpan.lastChild);
}
countSpan.appendChild(document.createTextNode(valuesX.length));
// sum for X
var sumX = 0;
for(i = 0; i < valuesX.length; i++ ) {
sumX += +valuesX[i].value;
}
var sumSpanX = document.getElementById("sumOutputX");
if(sumSpanX.lastChild) {
sumSpanX.removeChild(sumSpanX.lastChild);
}
sumSpanX.appendChild(document.createTextNode(sumX));
// average for X
var averageSpanX = document.getElementById("averageOutputX");
if(averageSpanX.lastChild) {
averageSpanX.removeChild(averageSpanX.lastChild);
}
averageSpanX.appendChild(document.createTextNode(sumX/valuesX.length));
// sum for Y
var sumY = 0;
for(i = 0; i < valuesY.length; i++ ) {
sumY += +valuesY[i].value;
}
var sumSpanY = document.getElementById("sumOutputY");
if(sumSpanY.lastChild) {
sumSpanY.removeChild(sumSpanY.lastChild);
}
sumSpanY.appendChild(document.createTextNode(sumY));
// average for Y
var averageSpanY = document.getElementById("averageOutputY");
if(averageSpanY.lastChild) {
averageSpanY.removeChild(averageSpanY.lastChild);
}
averageSpanY.appendChild(document.createTextNode(sumY/valuesY.length));
// compute Correlation
var n = valuesX.length;
var numerator = 0;
var denominator = 0;
var num_1 = 0, num_2 = 0, num_3 = 0;
var den_1 = 0, den_2 = 0;
for(i = 0; i < n; i++){
num_1 += +valuesX[i].value * +valuesY[i].value;
num_2 += +valuesX[i].value;
num_3 += +valuesY[i].value;
den_1 += Math.pow(+valuesX[i].value, 2);
den_2 += Math.pow(+valuesY[i].value, 2);
}
numerator = (n * num_1) - (num_2 * num_3);
denominator = Math.sqrt(n * den_1 - Math.pow(num_2, 2)) * Math.sqrt(n * den_2 - Math.pow(num_3, 2));
//alert(numerator);
var correlation = document.getElementById('corrOutput');
if(correlation.lastChild){
correlation.removeChild(correlation.lastChild)
}
correlation.appendChild(document.createTextNode(numerator/denominator));
}
AngularJS "Content switch"
It is changing content with code when you click links on the left
//AngularJS script
(function () {
var app = angular.module('konradiApp', []);
// Code switch controller
app.controller('CodeController', function () {
this.tab = 1;
this.selectTab = function (newValue) {
this.tab = newValue;
};
this.isSelected = function (tabName) {
return this.tab === tabName;
};
});
})();
// html
Languages
/** code 1 example here */
/** code 2 example here */
/** code 3 example here */
C# | ASP.NET Core
Review APi controller
namespace RMS.Services.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ReviewsController : ControllerBase
{
private readonly IReviewDataProvider _reviewDataProvider;
private readonly IReviewData _reviewData;
public ReviewsController(IReviewDataProvider reviewDataProvider, IReviewData reviewData)
{
_reviewDataProvider = reviewDataProvider;
_reviewData = reviewData;
}
[HttpGet("{feedId}")]
public ActionResult Get(int feedId)
{
try
{
var results = _reviewData.GetReviewsByFeedId(feedId, null).ToArray();
return results;
}
catch (Exception e)
{
return this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure" + e);
}
}
[HttpGet("getActive/{feedId}")]
public ActionResult GetActive(int feedId)
{
try
{
var results = _reviewDataProvider.GetActiveReviewsByFeedId(feedId).ToArray();
return results;
}
catch (Exception e)
{
return this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure" + e);
}
}
}
}
C# | ASP.NET Core
Review DAO
namespace RMS.Data
{
public class SqlReviewData : IReviewData
{
private readonly RMSDbContext _dbContext;
public SqlReviewData(RMSDbContext dbContext)
{
_dbContext = dbContext;
}
public Review Create(Review newReview)
{
_dbContext.Reviews.Add(newReview);
return newReview;
}
public Review[] CreateMany(Review[] newReviews)
{
_dbContext.Reviews.AddRange(newReviews);
return newReviews;
}
public Review Delete(int reviewId)
{
var review = GetById(reviewId);
if (review != null)
{
_dbContext.Reviews.Remove(review);
}
return review;
}
public Review GetById(int reviewId)
{
return _dbContext.Reviews.Find(reviewId);
}
public IEnumerable GetReviewsByReviewSourceIds(IEnumerable reviewSourceIds)
{
var query = from reviewSourceId in reviewSourceIds
join r in _dbContext.Reviews on reviewSourceId equals r.ReviewSourceId
orderby r.CreatedAt descending
select r;
return query;
}
public IEnumerable GetReviewsByFeedId(int feedId, string searchString, bool activeOnly = false)
{
var query = from r in _dbContext.Reviews //.Include(r => r.ReviewSource)
join frsm in _dbContext.FeedReviewSourceMaps on r.ReviewSourceId equals frsm.ReviewSourceId
where frsm.FeedId == feedId
&& (r.IsActive == activeOnly || !activeOnly)
&& (r.AuthorFullName.StartsWith(searchString) || string.IsNullOrEmpty(searchString))
orderby r.CreatedAt descending
select r;
return query;
}
public IEnumerable GetReviewsByUserName(string appUser, string searchString)
{
var query = from r in _dbContext.Reviews
join rs in _dbContext.ReviewSources on r.ReviewSourceId equals rs.Id
where (r.AuthorFullName.StartsWith(searchString) || string.IsNullOrEmpty(searchString))
&& rs.UserId == appUser
orderby r.CreatedAt descending
select r;
return query;
}
public Review Update(Review updatedReview)
{
var entity = _dbContext.Reviews.Attach(updatedReview);
entity.State = EntityState.Modified;
return updatedReview;
}
public int Commit()
{
// returns number of rows affected
return _dbContext.SaveChanges();
}
}
}
C# | ASP.NET Core
Review Data Provider
namespace RMS.Business.Review
{
public class ReviewDataProvider : IReviewDataProvider
{
private readonly IReviewData _reviewData;
private readonly IReviewSourceData _reviewSourceData;
#region { Private properties }
#endregion { Private properties }
#region { Constructors }
public ReviewDataProvider(IReviewData reviewData, IReviewSourceData reviewSourceData)
{
_reviewData = reviewData;
_reviewSourceData = reviewSourceData;
}
#endregion { Constructors }
#region { Public methods }
public IEnumerable GetActiveReviewsByFeedId(int feedId)
{
var reviews = _reviewData.GetReviewsByFeedId(feedId, null, true).ToList();
var reviewSourceIds = reviews.Select(r => r.ReviewSourceId).Distinct().ToList();
var reviewSources = _reviewSourceData.GetReviewSourcesByIds(reviewSourceIds).ToList();
var reviewModels = GetReviewModels(reviews, reviewSources);
return reviewModels;
}
public IEnumerable GetReviewsWithReviewSourceByFeedId(int feedId, string searchTerm)
{
var reviews = _reviewData.GetReviewsByFeedId(feedId, searchTerm).ToArray();
var reviewsWithReviewSource = AddReviewSourceToReview(reviews);
return reviewsWithReviewSource;
}
public IEnumerable GetReviewsWithReviewSourceByReviewSourceIds(List reviewSourceIds)
{
var reviews = _reviewData.GetReviewsByReviewSourceIds(reviewSourceIds).ToArray();
var reviewsWithReviewSource = AddReviewSourceToReview(reviews);
return reviewsWithReviewSource;
}
public IEnumerable GetReviewsWithReviewSourceByUserName(string appUser, string searchString)
{
var reviews = _reviewData.GetReviewsByUserName(appUser, searchString).ToArray();
var reviewsWithReviewSource = AddReviewSourceToReview(reviews);
return reviewsWithReviewSource;
}
public IEnumerable SaveNewGoogleReviews(int reviewSourceId, IEnumerable reviews, short totalReviews)
{
// map google reviews to RMS reviews
var mappedReviews = MapGoogleReviewsToRmsReviews(reviewSourceId, reviews).ToArray();
// get existing RMS reviews
// get new only
// call DB save new only
var savedReviews = _reviewData.CreateMany(mappedReviews);
_reviewData.Commit();
return savedReviews;
}
#endregion { Public methods }
#region { Private methods }
private IEnumerable AddReviewSourceToReview(Core.Models.Review[] reviews)
{
var reviewSourceIds = reviews.Select(r => r.ReviewSourceId).Distinct().ToList();
var reviewSources = _reviewSourceData.GetReviewSourcesByIds(reviewSourceIds).ToList();
for (int i = 0; i < reviews.Length; i++)
{
var reviewSourceId = reviews[i].ReviewSourceId;
var reviewSource = reviewSources.FirstOrDefault(rs => rs.Id == reviewSourceId);
reviews[i].ReviewSource = reviewSource;
}
return reviews;
}
private IEnumerable GetReviewModels(List reviews,
List reviewSources)
{
var reviewModels = new List();
foreach (var review in reviews)
{
var reviewSourceId = review.ReviewSourceId;
var reviewSource = reviewSources.FirstOrDefault(rs => rs.Id == reviewSourceId);
var reviewModel = new ReviewViewModel
{
AuthorFullName = review.AuthorFullName,
AuthorUrl = review.AuthorUrl,
CreatedAt = review.CreatedAt,
Id = review.Id,
ProfilePhotoUrl = review.ProfilePhotoUrl,
Rating = review.Rating,
Source = reviewSource?.Source.ToString() ?? SourceEnum.Google.ToString(), // change to new enum = website
Text = review.Text,
SocialComments = review.SocialComments,
SocialLikes = review.SocialLikes
};
reviewModels.Add(reviewModel);
}
return reviewModels;
}
private IEnumerable MapGoogleReviewsToRmsReviews(int reviewSourceId, IEnumerable reviews)
{
var rmsReviews = new List();
foreach (var review in reviews)
{
var rmsReview = new Core.Models.Review
{
AuthorFullName = review.AuthorName,
AuthorUrl = review.AuthorUrl,
CreatedAt = DateTimeOffset.FromUnixTimeSeconds(review.Time).UtcDateTime,
IsActive = true,
ProfilePhotoUrl = review.ProfilePhotoUrl,
Rating = review.Rating,
ReviewSourceId = reviewSourceId,
Text = review.Text,
Time = review.Time
};
rmsReviews.Add(rmsReview);
}
return rmsReviews;
}
#endregion { Private methods }
}
}
C# | ASP.NET Core
Google Place Client
namespace RMS.Client.Clients
{
public class GooglePlaceClient
{
#region { private fields }
private readonly HttpClient _client;
#endregion { private fields }
#region { constructor }
public GooglePlaceClient(HttpClient httpClient)
{
_client = httpClient;
_client.BaseAddress = new Uri("https://maps.googleapis.com/maps/");
_client.Timeout = new TimeSpan(0, 0, 30);
_client.DefaultRequestHeaders.Clear();
}
#endregion { constructor }
#region { public methods }
public async Task GetGooglePlaceCandidatesFromText(string searchText, string[] fields, CancellationToken cancellationToken)
{
// API setup
// key required to call Place Details API
const string key = "xxx";
var pathAndQuery = GetGoogleFindPlaceFromTextPathAndQuery(key, searchText, fields);
var request = new HttpRequestMessage(HttpMethod.Get, pathAndQuery);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
if (!response.IsSuccessStatusCode)
{
// in case we have to inspect a lot of status codes a SWITCH is better option here
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
//TODO write to log table
Console.WriteLine($"The requested movie cannot be found {response.StatusCode}.");
return null;
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// trigger a login flow
return null;
}
response.EnsureSuccessStatusCode();
}
var stream = await response.Content.ReadAsStreamAsync();
return stream.ReadAndDeserializeFromJson();
}
}
public async Task GetGooglePlaceDetailsByPlaceId(string placeId, string[] fields,
CancellationToken cancellationToken)
{
// key required to call Place Details API
const string key = "xxx";
var pathAndQuery = GetGooglePlaceDetailsPathAndQuery(placeId, key, fields);
var request = new HttpRequestMessage(HttpMethod.Get, pathAndQuery);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
if (!response.IsSuccessStatusCode)
{
// in case we have to inspect a lot of status codes a SWITCH is better option here
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
//TODO write to log table
Console.WriteLine($"The requested movie cannot be found {response.StatusCode}.");
return null;
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// trigger a login flow
return null;
}
response.EnsureSuccessStatusCode();
}
var stream = await response.Content.ReadAsStreamAsync();
return stream.ReadAndDeserializeFromJson();
}
}
#endregion { public methods }
#region { private methods }
private string GetGooglePlaceDetailsPathAndQuery(string placeId, string key, string[] fields)
{
var fieldsParameter = string.Join(",", fields);
const string path = "api/place/details/json";
var query = $"?place_id={placeId}&fields={fieldsParameter}&key={key}";
var pathAndQuery = $"{path}{query}";
return pathAndQuery;
}
private string GetGoogleFindPlaceFromTextPathAndQuery(string key, string inputText, string[] fields)
{
var fieldsParameter = string.Join(",", fields);
const string path = "api/place/findplacefromtext/json";
var query = $"?input={inputText}&inputtype=textquery&fields={fieldsParameter}&key={key}";
var pathAndQuery = $"{path}{query}";
return pathAndQuery;
}
#endregion { private methods }
}
}