branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>alden-p/Orpheus<file_sep>/Code/A_Orpheus_Functions.py
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 14:13:10 2018
@author: <NAME>
This program contains the necessacary functions for the Orpheus Program
"""
# =============================================================================
# Import Libraries
# =============================================================================
import winsound
import time
import random
import pandas as pd
import re
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import LogisticRegressionCV
# =============================================================================
# Class Definitions
# =============================================================================
class Note:
"""
The Note Class, a pitch and note to be assigned to a beat
"""
def __init__(self, pitch, octave):
"""
pitch: A string, corresponds to the pitch of the chromatic scale.
octave: The octave of the note
hertz: The hertz of the note
"""
hertz_base = 440
octave_base = 4
numerical_base = 2**(1/12)
pitch_dict = {"A": 0, "A#": 1, "Bb": 1, "B": 2, "C": 3, "C#": 4,
"Dd": 4, "D": 5, "D#": 6, "Eb": 6, "E": 7, "F": 8, "F#": 9,
"Gb": 9, "G": 10, "G#": 11, "Ab": 11}
self.pitch = pitch
self.octave = octave
self.hertz = hertz_base*(numerical_base)**(12*(octave-octave_base) + pitch_dict[pitch])
def win_play(self, duration):
"""
Play the note through the windows system sound library for a specified duration
"""
winsound.Beep(int(self.hertz), int(duration))
class Measure:
"""
The Measure Class, the building block of more complex musical structures
"""
def __init__(self, bpm, measure, nbeat):
"""
measure: A list that is the actual measure of the object
nbeat: how many "beats" are in the measure (say, 32 for 4/4 time with 16th notes)
"""
self.bpm = bpm
self.measure = measure # A list of notes
self.nbeat = nbeat
self.nnotes= len(measure)
self.note_duration = (60000/self.bpm) * (self.nbeat/self.nnotes)
def win_play(self):
"""
Play the measure as a series of system beeps
"""
for i in range(0,self.nnotes):
#starttime = time.time() #display note time
note = self.measure[i]
if note == "rest":
#"rest" types in the list are interpreted as rests
#Rest for a duration given by the number of proceeding continuations
continuations = 1
next_note_i = i + 1
while next_note_i <= self.nnotes - 1 and self.measure[next_note_i] == "cont":
continuations += 1
next_note_i +=1
#print("hi")
time.sleep(self.note_duration/1000 * continuations)
#print("rest: " + str(time.time() - starttime)) #Display Rest Time
elif note == "cont":
continue
else:
#Play the note for a duration given by the number of proceeding continuations
continuations = 1
next_note_i = i + 1
while next_note_i <= self.nnotes - 1 and self.measure[next_note_i] == "cont":
continuations += 1
next_note_i +=1
#print("hi")
note.win_play(self.note_duration*continuations)
#print("note: " + str(time.time() - starttime)) #Display Note Time
# =============================================================================
# Functions
# =============================================================================
def convert_notes(note_string_list):
"""
Convert a list of strings to the note class of a specified octave.
"""
note_list = []
for i in range(len(note_string_list)):
if note_string_list[i] != "rest" and note_string_list[i] != "cont":
note_list.append(Note(note_string_list[i].split('-')[0], int(note_string_list[i].split('-')[1]))) #Construct a list of note objects
else:
note_list.append(note_string_list[i])
return note_list
def random_select(p_list):
"""
Randomly select an index from an iterable list of probabilities
Inputs:
p_list, a list of probabilities that sums to 1
Outputs:
An index from p_list
"""
target_num = random.uniform(0,1)
cum_prob = 0
#Add up probability until the first index that passes cum_prob
# and return that index, if the probabilities do not sum to one, and the
# target number is greater, we simply return the last index
for i in range(0,len(p_list)):
cum_prob += p_list[i]
if cum_prob >= target_num:
return i
return len(p_list)-1
def next_note_lin(notes, p_notes):
"""
This function runs through the decision tree with specified probabilities
Inputs:
notes, a list of notes must have [..., cont, rest] at the end
p_notes, a vector of probabilities correspond to each note
Outputs:
A note from key
"""
#Randomly returns the next beat in the sequence based on prespecified probabilities
#According to the decision tree
return notes[random_select(p_notes)]
def selection_prob(prob_list):
"""
Given a list of probabilities "prob_list" that denotes the probability someone likes a given piece,
compute the probabilities of selection
"""
S = sum(prob_list)
selection_probs = []
for i in range(0, len(prob_list)):
selection_probs.append(prob_list[i]/S)
return selection_probs
def like_dislike(outfilename, music_function):
"""
Plays a piece, asks the user if they like or dislike it, then appends the piece and
respose to a .csv file.
inputs:
outfilename, the name of the csv file a string
music_function, a function handle that plays music and returns the measure of music being played
outputs:
none, writes to a file
"""
measure = music_function().measure
critical_review = input("Did you like it <y/n>? ")
if critical_review.lower() == "y":
response = 1
elif critical_review.lower() == "n":
response = 0
else:
print("Can you read? Answer y or n.")
raise ValueError
with open(outfilename, mode = 'a', encoding = "utf_8") as outfile:
outfile.write(str(response) + ",")
for index, beat in enumerate(measure):
if index < len(measure)-1:
if isinstance(beat, Note):
outfile.write(beat.pitch + "-" + str(beat.octave) + ",")
elif type(beat) == str:
outfile.write(beat + ",")
else:
print("Unknown beat value")
raise ValueError
elif index == len(measure)-1:
if isinstance(beat, Note):
outfile.write(beat.pitch + "-" + str(beat.octave))
elif type(beat) == str:
outfile.write(beat)
else:
print("Unknown beat value")
raise ValueError
outfile.write("\n")
def initialize_datafile(outfilename, num_beats):
"""
Intialize the datafile to store training data on a particular measure
inputs:
outfilename, a string
outputs:
none, writes to a file
"""
with open(outfilename, mode = 'w', encoding = "utf_8") as outfile:
outfile.write("listener_response" + ",")
for i in range(0,num_beats):
outfile.write("beat" + str(i) + ",")
outfile.write("\n")
def expand_datafile(infilename, outfilename, mes_len):
"""
Expand the csv file of the listener_respond, note1, note2,...
into all measures of length 'mes_len'
inputs:
infilename, a string the input filename
outfilename, a string the output filename
mes_len, and integer how far back we are looking
outputs:
None
"""
#Loop over every line in the input file
with open(infilename, mode = "r", encoding = "utf_8") as infile:
for count, line in enumerate(infile):
num_notes = len(line.strip().split(",")) - 1 #The number of notes in the measure
data = line.strip().split(",")
#If it is the first line, write the first mes_len + 1 entries
if count == 0:
with open(outfilename, mode = "w", encoding = "utf_8") as outfile:
for i in range(0,mes_len + 1):
outfile.write(data[i])
if i < mes_len:
outfile.write(",")
else:
outfile.write("\n")
#The actual data
else:
with open(outfilename, mode = "a", encoding = "utf_8") as outfile:
for j in range(1, num_notes-mes_len + 2):
#If we have empty data, continue
if data[j] == "cont":
continue
outfile.write(data[0] + ",")
for i in range(j, mes_len + j):
outfile.write(data[i])
if i < mes_len + j-1:
outfile.write(",")
outfile.write("\n")
def powerset(s):
"""
This function takes a set object S and returns its powerset Ps.
Inputs:
s, a set
Outputs:
Ps, a set, the powerset of s
"""
result = [[]]
for elem in s:
result.extend([x + [elem] for x in result])
return result
def create_interactions(infilename, outfilename, order):
"""
This function creates a series of interaction variables
inputs:
infilename, a string, the name of the file containing the variables to be interacted
outfilename, a stirng, the name of the file to output interactions to
order, an integer, the maximum allowed order of interactions
outputs:
none, writes to a csv file
"""
with open(infilename, mode = 'r', encoding = 'utf_8') as infile:
with open(outfilename, mode = 'w', encoding = 'utf_8') as outfile:
for index, row in enumerate(infile):
row_data = row.strip().split(',')
if index == 0:
header = row_data
interaction_orders = set(range(1, len(header))) # The different desired orders of interacitons
interactions = powerset(interaction_orders)
outfile.write(row_data[0] + ',')
for sub_num, subset in enumerate(interactions):
if subset == []:
continue
if len(subset) > order:
continue
for elem in subset:
outfile.write(row_data[elem])
if sub_num < len(interactions) - 1:
outfile.write(',')
outfile.write('\n')
def create_indicators(infilename, outfilename):
"""
This function creates a series of indicator variables for each column beat value,
outputs a high dimensional csv file.
inputs:
filename, a string the filename to read in
outfilename, a string, the file to output to
outputs:
none, constructs a csv file under outfilename
"""
input_df = pd.read_csv(infilename) # read the data input
input_col_names = list(input_df.columns.values)
output_df = pd.get_dummies(input_df, columns = input_col_names[1:])
output_df.to_csv(outfilename, index = False)
def logit_lasso(infilename, reg_par = 1):
"""
This function takes in a file containing csv data with dep var in the first column
and potential covariates in the others, fits a logistic regression with a L1
penalty to it, and returns that model.
inputs:
infilename, a string the name of the file containing the data
reg_par, a float, the regularization penalty parameter for the logit. Defaults to 1
outputs:
A trained logit model
"""
input_df = pd.read_csv(infilename)
y = input_df.iloc[:,0]
X = input_df.iloc[:,1:]
model = LogisticRegression(penalty = "l1", solver = "liblinear", C = reg_par, multi_class = "ovr")
# model = LogisticRegressionCV(penalty = "l1", solver = "liblinear", multi_class = "ovr", Cs = reg_par)
fitted_model = model.fit(X,y)
return fitted_model
def create_X(note_string_list, datafilename):
"""
This function takes a sequence of notes and returns a vector (list) of covariate
indicators for that list.
inputs:
note_string_list, A list of strings indicating the sequence of notes to be played
datafilename, a string, the name of the file containing the information on the covariates
outputs:
a list of indicators (1,0)s
"""
X = []
#Read in the header of the datafile and take everything but listerner respose into a list
with open(datafilename, mode = 'r', encoding = 'utf_8') as infile:
columnnames = infile.readline().strip().split(',')[1:]
#Loop over columnnames, they should be of the form beat0beat2_A#-4C-5
for col in columnnames:
noteseq = '' #Intialize empty sequence of notes
#Split the format into the beatorder we care about, and what the corresponding
#Note order should be for indicator = 1
collist = col.split('_')
beatorder = re.sub('[^0-9]','', collist[0]) #Construct a string defining the order
noteorder = collist[1]
#Check if the note order in the list equals the note order we care about.
for i in beatorder:
noteseq += note_string_list[int(i)]
if noteorder == noteseq:
X.append(1)
else:
X.append(0)
return np.array(X).reshape(1,-1)
def construc_prob(history, window, note_set, model, datafilename):
"""
This function constructs the proabilities of seeing each next note
Inputs:
history, A list of strings, the note history in chronological order
window, and integer how far back we are looking
note_set, the set of notes to be considered
model, the model used to construct probabilities
datafilename, a string, the name of the file containing the information to convert strings of notes to interaction dummies
Outputs:
A list of probabilities of len(note_set)
"""
recent_history = history[len(history)-window + 1:len(history)]
like_prob = [] # Initialize a empty list of probabilities of liking a certain sequence
for note in note_set:
potential_hist = recent_history + [note]
X = create_X(potential_hist, datafilename)
# print(potential_hist)
# print(model(X))
like_prob.append(model(X))
return selection_prob(like_prob)
def Amajor_8beat():
"""
This function plays an 8 beat A major scale.
Inputs:
None
Outputs:
A instance of the measure class
"""
#Intialize teh scale and probability list for the first 3 notes
A_major = ["A-4", "B-4", "C#-4", "D-4", "E-4", "F#-4", "G#-4", "A-5"]
note_set = A_major + ["cont", "rest"]
p_list = [.08, .08, .08, .08, .08, .08, .08, .08]
scale = convert_notes(note_set)
#Generate the first note, add it to the history and random measure
first_note = A_major[random_select(p_list)] #Initialize the first note
history = [first_note]
random_measure_list = [Note(first_note.split("-")[0], int(first_note.split("-")[1]))]
#Allow for the possibility of rests and continues now that the first note has been added
p_list.append(.18)
p_list.append(.18)
#Generate the next 2 notes
for i in range(1, 3):
#randomly select the index, using that index add a new note to the scale
index = random_select(p_list)
new_note = scale[index]
new_note_str = note_set[index]
#Add the new note to the random measure and the history
random_measure_list.append(new_note)
history.append(new_note_str)
#Fit a logit model to predict probabilities
datafilename = "../input/A_Amajor-8beat-winsound_indicators.csv"
fitted_model = logit_lasso(datafilename,3)
model = lambda X: fitted_model.predict_proba(X)[0,1]
window = 4
#Intelligently generate the remainder of the measure
for i in range(3, 8):
#randomly select the index, using that index add a new note to the scale, where the probabilities are updated accodring to model
p_list = construc_prob(history, window, note_set, model, datafilename)
index = random_select(p_list)
new_note = scale[index]
new_note_str = note_set[index]
#Add the new note to the random measure and the history
random_measure_list.append(new_note)
history.append(new_note_str)
print(history)
random_measure = Measure(145, random_measure_list, len(random_measure_list))
starttime = time.time()
random_measure.win_play()
print("Measure Duration: " + str(time.time() - starttime))
return random_measure
def Amajor_8beat_adddata():
"""
Add a datapoint to the Amajor_8beat file.
"""
like_dislike("../input/A_Amajor-8beat-winsound.csv", Amajor_8beat)
expand_datafile("../input/A_Amajor-8beat-winsound.csv", "../input/A_Amajor-8beat-winsound_expanded.csv", 4)
create_interactions("../input/A_Amajor-8beat-winsound_expanded.csv", "../input/A_Amajor-8beat-winsound-interactions.csv", 3)
create_indicators("../input/A_Amajor-8beat-winsound-interactions.csv", "../input/A_Amajor-8beat-winsound_indicators.csv")
# =============================================================================
# Testing
# =============================================================================
#Amajor_8beat()
Amajor_8beat_adddata()
| affb9497a75635bb40257ca0918004f428751b15 | [
"Python"
] | 1 | Python | alden-p/Orpheus | 6cf692cb79634901e3947e69c6ca3615e9760afc | 13f15201ad2a252a47538d1e47841f763e0d7637 |
refs/heads/master | <repo_name>i-toge-nta/md-editor<file_sep>/src/modules/menusModule.ts
import { createSlice, PayloadAction } from "redux-starter-kit";
// 型定義
interface Menu {
id: number;
title: string;
text: string;
}
// MainMenu1
export interface MainMenu1 extends Menu {
list: MainMenu2[];
}
// MainMenu2
interface MainMenu2 extends Menu {
list: Menu[];
}
// state
export interface MenusState {
nextMenuId: number;
menuList: MainMenu1[];
}
// state の初期値
const menuInitialState: MenusState = {
nextMenuId: 1,
menuList: [
{
id: 0,
title: "MainMenu",
text: "",
list: []
}
]
};
// actions と reducers の定義
const menusModules = createSlice({
slice: "menus",
initialState: menuInitialState,
reducers: {
// todo を追加
addMainMenu1: (state, action: PayloadAction<string>) => {
const menu = {
id: state.nextMenuId++,
title: "",
text: "",
list: []
};
// Pushしてしまっている
state.menuList.push(menu);
}
}
});
export default menusModules;
| 14b58ef219fcb118fc5fcce657feacb627facf3a | [
"TypeScript"
] | 1 | TypeScript | i-toge-nta/md-editor | 482af9144bdfaf68ddde6f103f894edb17e2222b | 3e56d92096e6f6003f44976e872c7705f9fdad58 |
refs/heads/master | <repo_name>solegaonkar/Reminders<file_sep>/src/vikas/solegaonkar/reminders/Flash.java
package vikas.solegaonkar.reminders;
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JDialog;
public class Flash extends JDialog {
private static final long serialVersionUID = 6379800513625947640L;
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
new Flash();
} catch (InterruptedException e) {
}
System.gc();
}
}, 1000 * 60 * 5, 1000 * 60 * 15);
}
public Flash() throws InterruptedException {
super();
this.setAlwaysOnTop(true);
this.setModal(false);
this.setUndecorated(true);
this.add(new MyTextArea());
this.setResizable(false);
this.pack();
this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width / 2 - this.getSize().width / 2, Toolkit.getDefaultToolkit()
.getScreenSize().height / 2 - this.getSize().height / 2);
this.setVisible(true);
flash();
this.dispose();
}
private void flash(int i) {
this.setOpacity(((float) i) / 10.0f);
}
private void flash() throws InterruptedException {
for (int i = 0; i <= 10; i++) {
flash(i);
Thread.sleep(200);
}
Thread.sleep(1000);
for (int i = 10; i > 0; i--) {
Thread.sleep(200);
flash(i);
}
}
}
| 1d65d5031b815f99e6964af0252f59191e5a3b89 | [
"Java"
] | 1 | Java | solegaonkar/Reminders | ab5661aa8c65b3a286d781df71def2270a670b5b | b581d18d6c41ebff4d879f22ecbb00523bacc5c7 |
refs/heads/master | <repo_name>androidok/DownloadManager-1<file_sep>/app/src/main/java/com/example/administrator/downloadmanager/Download/Downloader.java
package com.example.administrator.downloadmanager.Download;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import java.io.File;
import static com.example.administrator.downloadmanager.Download.DownloadTask.*;
/**
* Created by huangweiliang on 2018/5/7.
*/
public class Downloader {
private Context mContext;
private DownloadListener mDownloadListener;
private FileInfo mFileInfo;
private boolean mIsDownloading = true;
public static final String UPDATE = "UPDATE";
public Downloader(Context context, DownloadListener downloadListener, FileInfo fileInfo) {
mContext = context;
mDownloadListener = downloadListener;
mFileInfo = fileInfo;
// 注册广播接收者
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UPDATE);
mContext.registerReceiver(broadcastReceiver, intentFilter);
}
public void unregisterReceiver() {
mContext.unregisterReceiver(broadcastReceiver);
}
public void download() {
Intent intent = new Intent(mContext, DownloadService.class);
intent.setAction(DownloadService.START);
intent.putExtra(mFileInfo.getClass().getName(), mFileInfo);
mContext.startService(intent);
mIsDownloading = true;
}
public void pause() {
Intent intent = new Intent(mContext, DownloadService.class);
intent.setAction(DownloadService.PAUSE);
intent.putExtra(mFileInfo.getClass().getName(), mFileInfo);
mContext.startService(intent);
mIsDownloading = false;
}
public void cancle() {
Intent intent = new Intent(mContext, DownloadService.class);
intent.setAction(DownloadService.CANCLE);
intent.putExtra(mFileInfo.getClass().getName(), mFileInfo);
mContext.startService(intent);
mIsDownloading = false;
}
public boolean isDownloading() {
return mIsDownloading;
}
// 广播接收者
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(UPDATE)) {
int progress = intent.getIntExtra(PROGRESS, 0);
final long downloaded = intent.getLongExtra(DOWNLOADED, 0);
final long totallength = intent.getLongExtra(TOTALLENGTH, 0);
final String url = intent.getStringExtra(URL);
final int state = intent.getByteExtra(STATE, (byte) -1);
if (progress != 100)
progress = (int) (downloaded * 100 / totallength);
Log.i("BaseDownloadListener", state + " " + progress);
if (!url.equals(mFileInfo.getUrl()))
return;
switch (state) {
case DOWNLOADSTART:
mDownloadListener.onDownloadStart(progress);
break;
case DOWNLOADING:
mDownloadListener.onDownloading(progress);
break;
case DOWNLOADFINISH:
mDownloadListener.onDownloadFinish(url);
break;
case DOWNLOADPAUSE:
mDownloadListener.onDownloadPause(url);
break;
case DOWNLOADFAIL:
mDownloadListener.onDownloadFail(url);
break;
case DOWNLOADCANCLE:
mDownloadListener.onDownloadCancle(url);
break;
default:
break;
}
}
}
};
}
<file_sep>/app/src/main/java/com/example/administrator/downloadmanager/Download/BaseDownloadListener.java
package com.example.administrator.downloadmanager.Download;
import android.util.Log;
/**
* Created by huangweiliang on 2018/5/8.
*/
public abstract class BaseDownloadListener implements DownloadListener {
private static final String TAG = "BaseDownloadListener";
@Override
public void onDownloading(int progress) {
Log.i(TAG,"downloading");
}
@Override
public void onDownloadStart(int progress) {
Log.i(TAG,"download start");
}
@Override
public void onDownloadPause(String url) {
Log.i(TAG,"download pause");
}
@Override
public void onDownloadFinish(String url) {
Log.i(TAG,"download finish");
dissolveRelations(url);
}
@Override
public void onDownloadFail(String url) {
Log.i(TAG,"download fail");
dissolveRelations(url);
}
@Override
public void onDownloadCancle(String url) {
Log.i(TAG,"download cancle");
dissolveRelations(url);
}
private void dissolveRelations(String url){
DownloadManager.INSTANCE().unregisterReceiver(url);
DownloadManager.INSTANCE().removeDownloader(url);
}
}
<file_sep>/app/src/main/java/com/example/administrator/downloadmanager/Download/ThreadInfo.java
package com.example.administrator.downloadmanager.Download;
import java.io.Serializable;
/**
* Created by huangweiliang on 2018/5/3.
*/
public class ThreadInfo implements Serializable {
private int thread_id;
private String url;
private long start;
private long end;
private long downloaded;
public ThreadInfo() {
}
public ThreadInfo(int thread_id, String url, long start, long end, long downloaded) {
this.thread_id = thread_id;
this.url = url;
this.start = start;
this.end = end;
this.downloaded = downloaded;
}
public int getThread_id() {
return thread_id;
}
public void setThread_id(int thread_id) {
this.thread_id = thread_id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
public long getDownloaded() {
return downloaded;
}
public void setDownloaded(long downloaded) {
this.downloaded = downloaded;
}
@Override
public String toString() {
return "ThreadInfo [thread_id=" + thread_id + ", url=" + url + ", start=" + start + ", end=" + end + ", downloaded=" + downloaded + "]";
}
}<file_sep>/app/src/main/java/com/example/administrator/downloadmanager/Download/DownloadTask.java
package com.example.administrator.downloadmanager.Download;
import android.content.Context;
import android.content.Intent;
import org.apache.http.HttpStatus;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.util.List;
import static com.example.administrator.downloadmanager.Download.Downloader.UPDATE;
/**
* Created by huangweiliang on 2018/5/7.
*/
public class DownloadTask {
public static final byte DOWNLOADSTART = 0;
public static final byte DOWNLOADING = 1;
public static final byte DOWNLOADPAUSE = 2;
public static final byte DOWNLOADFINISH = 3;
public static final byte DOWNLOADFAIL = 4;
public static final byte DOWNLOADCANCLE = 5;
public static final String STATE = "STATE";
public static final String PROGRESS = "PROGRESS";
public static final String DOWNLOADED = "DOWNLOADED";
public static final String TOTALLENGTH = "TOTALLENGTH";
public static final String URL = "URL";
private Context mContext;
private DownloadDAO mDownloadDAO;
private FileInfo mFileInfo;
public boolean mIsPause = false;
public boolean mIsCancle = false;
public DownloadTask(Context context, FileInfo fileInfo) {
mContext = context;
mFileInfo = fileInfo;
mDownloadDAO = new DownloadDAOImpl(context);
}
public void download() {
//寻找数据库中的数据,看是否存在缓存数据
List<ThreadInfo> threadInfos = mDownloadDAO.getThreadInfo(mFileInfo.getUrl());
ThreadInfo threadInfo;
//没有缓存数据
if (threadInfos.size() == 0)
threadInfo = new ThreadInfo(0, mFileInfo.getUrl(), 0, mFileInfo.getLength(), 0);
//有缓存数据,获取第一个数据。
else threadInfo = threadInfos.get(0);
new Thread(new DownloadThread(threadInfo)).start();
}
private class DownloadThread implements Runnable {
private ThreadInfo mThreadInfo;
public DownloadThread(ThreadInfo threadInfo) {
mThreadInfo = threadInfo;
}
@Override
public void run() {
/**
* 添加该下载任务到数据库中。
* 计算出该从哪个位置进行下载。
* 生成临时文件。
* 生成随机访问文件流,并设置文件数据的位置。
* 开始下载。
* 广播下载进度,改变UI。
* 暂停下载。
* 下载完毕,在数据库中删除数据。
* 将文件的名字由临时下载文件名称改为正式名称。
*/
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
RandomAccessFile randomAccessFile = null;
long mDownloaded = 0;//下载进度
//数据库中没有该数据,就在数据库中添加该数据
if (!mDownloadDAO.isExists(mThreadInfo.getUrl(), mThreadInfo.getThread_id()))
mDownloadDAO.insertThread(mThreadInfo);
Intent intent = new Intent(UPDATE);
try {
java.net.URL url = new URL(mThreadInfo.getUrl());
httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setRequestMethod("GET");
//计算出下载的数据的开始位置
long start = mThreadInfo.getStart() + mThreadInfo.getDownloaded();
// 设置请求属性
// 参数一:Range头域可以请求实体的一个或者多个子范围(一半用于断点续传),如果用户的请求中含有range
// ,则服务器的相应代码为206。
// 参数二:表示请求的范围:比如头500个字节:bytes=0-499
httpURLConnection.setRequestProperty("range", "bytes=" + start + "-" + mThreadInfo.getEnd());
//生成临时文件
File file = new File(mFileInfo.getDownloadPath(), mFileInfo.getTmpFileName());
//生成随机访问文件流
randomAccessFile = new RandomAccessFile(file, "rwd");
// 设置从哪里开始写入,如参数为100,那就从101开始写入
randomAccessFile.seek(start);
mDownloaded = mThreadInfo.getDownloaded();
if (httpURLConnection.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT) {
inputStream = httpURLConnection.getInputStream();
// 设置字节数组缓冲区
byte[] data = new byte[1024 * 10];
int len = -1;
long time = System.currentTimeMillis();
noticBroadcast(intent, mDownloaded , mFileInfo.getLength(), DOWNLOADSTART);
while ((len = inputStream.read(data)) != -1) {
// 读取成功,写入文件
randomAccessFile.write(data, 0, len);
//更新下载进度
mDownloaded += len;
if (System.currentTimeMillis() - time > 2000) {
time = System.currentTimeMillis();
// 把当前进度通过广播传递给UI
noticBroadcast(intent, mDownloaded, mFileInfo.getLength(), DOWNLOADING);
}
mDownloadDAO.updateThread(mThreadInfo.getUrl(), mThreadInfo.getThread_id(), mDownloaded);
if (mIsPause) {
// 暂停下载,更新进度到数据库
mDownloadDAO.updateThread(mThreadInfo.getUrl(), mThreadInfo.getThread_id(), mDownloaded);
noticBroadcast(intent, mDownloaded , mFileInfo.getLength(), DOWNLOADPAUSE);
return;
}
if (mIsCancle) {
// 暂停下载,更新进度到数据库
mDownloadDAO.deleteThread(mThreadInfo.getUrl(), mThreadInfo.getThread_id());
if (file.exists())
file.delete();
mDownloaded = 0 ;
noticBroadcast(intent, mDownloaded , mFileInfo.getLength(), DOWNLOADCANCLE);
return;
}
}
//将文件的名字由临时下载文件名称改为正式名称。
file.renameTo(new File(mFileInfo.getDownloadPath(), mFileInfo.getFileName()));
noticBroadcast(intent, mDownloaded , mFileInfo.getLength(), DOWNLOADFINISH);
// 当下载执行完毕时,删除数据库线程信息
mDownloadDAO.deleteThread(mThreadInfo.getUrl(), mThreadInfo.getThread_id());
}
} catch (SocketException e) {
// 暂停下载,更新进度到数据库
mDownloadDAO.updateThread(mThreadInfo.getUrl(), mThreadInfo.getThread_id(), mDownloaded);
noticBroadcast(intent, mDownloaded , mFileInfo.getLength(), DOWNLOADFAIL);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (randomAccessFile != null)
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void noticBroadcast(Intent intent, long downloaded,long totalLength ,byte state) {
intent.putExtra(DOWNLOADED, downloaded);
intent.putExtra(TOTALLENGTH, totalLength);
intent.putExtra(STATE, state);
intent.putExtra(URL, mFileInfo.getUrl());
mContext.sendBroadcast(intent);
}
}
<file_sep>/app/src/main/java/com/example/administrator/downloadmanager/Download/DownloadDAO.java
package com.example.administrator.downloadmanager.Download;
import java.util.List;
/**
* Created by huangweiliang on 2018/5/3.
*/
public interface DownloadDAO {
// 新增一条线程信息
public void insertThread(ThreadInfo threadInfo);
// 删除一条线程信息(多线程下载,可能一个url对应多个线程,所以需要2个条件)
public void deleteThread(String url, int thread_id);
// 修改一条线程信息
public void updateThread(String url, int thread_id, long finished);
// 查询线程有关信息(根据url查询下载该url的所有线程信息)
public List<ThreadInfo> getThreadInfo(String url);
// 判断线程是否已经存在
public boolean isExists(String url, int thread_id);
} | 48cbc62bb93e77b4a04e554dea6f226d589faf54 | [
"Java"
] | 5 | Java | androidok/DownloadManager-1 | 1f3c8da3e9a9a600a8b5894aa9010ae991de18b5 | 6bfd65c3dd1aa8bff5bb9b1c0fe0641b49fe1680 |
refs/heads/master | <file_sep># Modul2
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
.png)
<file_sep>
package hellotelkom;
import java.util.Scanner;
public class KonversiSuhu {
public static void main (String []args){
Scanner baca = new Scanner(System.in);
double r, c, f, k;
System.out.println("Masukkan Suhu (celsius) : ");
c = baca.nextDouble();
r = 0.8*c;
f = (1.8*c)+32;
k = 273 + c;
System.out.println("78 derajat celsius = " + r + " derajat reamur");
System.out.println("78 derajat celsius = " + f +" derajat farenheit");
System.out.println("78 derajat celsius = " + k + "kelvin");
}}
| 0cf95bee2114f037883a1d5dfe5adc986a48a0b4 | [
"Markdown",
"Java"
] | 2 | Markdown | Risqyta/Modul2 | 820fa0755733caa8ba0df469ad69ab9d0d3a7981 | 6e83b28f4c1635916ab1936d41173e31e7e75d9f |
refs/heads/master | <repo_name>chrismintan/pollplay<file_sep>/client/src/components/Nav-legacy.jsx
import React from 'react';
import styles from './style.scss';
import axios from 'axios';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
const styling = {
appBar: {
height: 60,
background: '#323232FF',
},
contain: {
height: 60,
position: 'relative',
}
}
class NavBar extends React.Component {
constructor() {
super();
this.state = {
active: false,
profilePic: '',
displayName: '',
userId: null,
};
this.toggleActive = this.toggleActive.bind(this);
this.handleToggle = this.handleToggle.bind(this);
}
toggleActive() {
this.setState({
active: !this.state.active,
});
}
componentDidMount() {
axios.get('/auth/isLoggedIn')
.then(({data}) => {
this.setState({
profilePic: data.image_url,
displayName: data.display_name,
userId: data.userId,
});
})
.catch(err => {
console.log(err);
});
}
handleToggle() {
document.getElementById("body").classList.toggle('nav-open');
}
render() {
const { classes } = this.props;
let profile;
if ( this.state.profilePic != '' && this.state.displayName != '' ) {
profile = (
<div>
<img src={this.state.profilePic} alt='Profile Pic'/>
<div>{this.state.displayName}</div>
</div>
)
} else {
profile = <div></div>
}
return (
<div className="navbar">
<CssBaseline />
<div className={classes.contain}>
<AppBar position="fixed" className={classes.appBar}>
<div className="body" id="body">
<div className="wrapper">
<div className="nav-toggle" id="icon" onClick={this.handleToggle}>
<div className="icon"></div>
</div>
</div>
</div>
</AppBar>
</div>
<div className={this.state.active ? "side-nav active" : "side-nav hidden"}>
<div className="nav-logo">
<div>Logo Goes Here</div>
</div>
<div className="nav-links">
{profile}
<a className="nav-link" href="/">Home</a>
{this.state.userId ?
<a className="nav-link" href="/auth/logout">Logout</a>
:
<a className="nav-link" href="/auth/login">Login</a>
}
</div>
</div>
</div>
)
}
}
export default withStyles(styling)(NavBar);<file_sep>/client/src/components/Main/Search/SearchResults.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
const styles = {
card: {
display: 'flex',
height: 'auto',
alignItems: 'center',
border: '1px solid transparent',
borderRadius: 0,
background: 'transparent',
'&:hover': {
background: 'rgb(33, 33, 33)',
cursor: 'pointer',
},
},
details: {
display: 'flex',
flexDirection: 'column',
},
content: {
flex: '1 0 auto',
},
cover: {
width: 75,
height: 75,
borderRadius: 50,
},
artist: {
fontSize: 12,
color: '#FEFEFEFF',
},
title: {
fontSize: 17,
color: 'white',
}
};
class SearchResults extends React.Component {
constructor(props) {
super(props);
this.state = {
disabled: false,
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
let reactThis = this
// Disabling multiple instances of song in the song queue
if ( reactThis.props.songBank.some(e => e.trackURI === reactThis.props.trackURI ) == true ) {
this.setState({
disabled: true,
})
} else {
// Sending song data from SearchResults -> DropDownList -> SearchBar -> Main
let songData = {
trackName: reactThis.props.title,
artistName: reactThis.props.artist,
albumImageURL: reactThis.props.image,
trackURI: reactThis.props.trackURI,
addSong: true,
likes: 0,
}
reactThis.props.addSong(songData);
// Host will then add song to SongList
reactThis.setState({
disabled: true,
})
}
}
render() {
const { classes, theme } = this.props;
return (
<div onClick={this.handleClick}>
<Card className={classes.card}>
<CardMedia id="card-image"
className={classes.cover}
image={this.props.image}
/>
<div className={classes.details}>
<CardContent className={classes.content}>
<Typography className={classes.title} id="card-title">
{this.props.title}
</Typography>
<Typography className={classes.artist} id="card-artist">
{this.props.artist}
</Typography>
</CardContent>
</div>
</Card>
</div>
);
}
}
export default withStyles(styles, { withTheme: true })(SearchResults);<file_sep>/server/routes/config/passport-setup.js
const passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
const db = require('../../../database/index');
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((id, done) => {
db.getUserById({ userId: id }, (err, user) => {
if (err) {
console.log(err);
} else {
done(null, user);
}
});
});
passport.use(
new SpotifyStrategy({
clientID: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
callbackURL: '/auth/spotify/redirect'
}, (accessToken, refreshToken, expires_in, profile, done) => {
const tokenExpiresAt = new Date(Date.now() + 60*60*1000).toISOString().slice(0, 19).replace('T', ' ');
db.addUser({spotify_id: profile.id, spotify_display_name: profile.displayName, access_token: accessToken, refresh_token: refreshToken, token_expires_at: tokenExpiresAt, image_url: profile.photos[0]}, (err, user) => {
if (err) {
console.log(err);
} else {
db.getUserBySpotifyId({spotify_id: profile.id}, (err, user) => {
if (err) {
console.log(err);
} else {
done(null, user);
}
});
}
});
})
);<file_sep>/client/src/components/Main/NowPlaying/Chat.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListSubheader from '@material-ui/core/ListSubheader';
const styles = theme => ({
root: {
background: 'white',
padding: 0,
},
listSection: {
backgroundColor: 'inherit',
},
ul: {
backgroundColor: 'inherit',
padding: 0,
},
zero: {
padding: 0,
margin: 0,
},
});
function PinnedSubheaderList(props) {
const { classes } = props;
return (
<List className={classes.root}>
<ListSubheader className={classes.zero}>
Name
</ListSubheader>
<ListItem className={classes.ul}>
<ListItemText className={classes.zero}>
Hello
</ListItemText>
</ListItem>
</List>
);
}
export default withStyles(styles)(PinnedSubheaderList);<file_sep>/client/src/components/Main/Search/DropDownSongList.jsx
import React from 'react';
import SearchResults from './SearchResults.jsx';
class DropDownSongList extends React.Component {
constructor() {
super();
}
render() {
let songSelection = this.props.spotifyResults.map( (spotifyResults, index) => {
return (
<SearchResults key={index} title={spotifyResults.name} artist={spotifyResults.artists[0].name} image={spotifyResults.album.images[1].url} addSong={this.props.addSong} trackURI={spotifyResults.uri} songBank={this.props.songBank} />
)
})
return (
<div>
{songSelection}
</div>
)
}
}
export default DropDownSongList;<file_sep>/client/src/components/NavBar.jsx
import React from 'react';
import styles from './style.scss';
import axios from 'axios';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Tooltip from '@material-ui/core/Tooltip';
import IconButton from '@material-ui/core/IconButton';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
const styling = {
appBar: {
height: 60,
background: '#323232FF',
},
contain: {
height: 60,
position: 'relative',
},
toolTip: {
background: 'white',
color: 'black',
// boxShadow: theme.shadows[1],
fontSize: 11,
},
icon: {
color: 'white',
padding: 0,
margin: 0,
}
}
class NavBar extends React.Component {
constructor() {
super();
this.state = {
active: false,
profilePic: '',
displayName: '',
userId: null,
expanded: false,
};
this.toggleActive = this.toggleActive.bind(this);
this.handleToggle = this.handleToggle.bind(this);
this.social = this.social.bind(this);
}
toggleActive() {
this.setState({
active: !this.state.active,
});
}
componentDidMount() {
axios.get('/auth/isLoggedIn')
.then(({data}) => {
this.setState({
profilePic: data.image_url,
displayName: data.display_name,
userId: data.userId,
});
})
.catch(err => {
console.log(err);
});
}
social() {
this.setState({
expanded: !this.state.expanded,
})
}
handleToggle() {
this.toggleActive()
document.getElementById("body").classList.toggle('nav-open');
}
render() {
const { classes } = this.props;
let social;
if ( this.state.expanded == true ) {
social = (
<span>
<IconButton onClick={this.social}>
<KeyboardArrowRight className={classes.icon} />
</IconButton>
<span className='name' style={{display: 'inline-block'}}>An app made by: <strong id="copy">©</strong>hristopher Tan </span>
</span>
)
} else {
social = (
<IconButton onClick={this.social}>
<KeyboardArrowLeft className={classes.icon} />
</IconButton>
)
}
let profile;
if ( this.state.profilePic != '' && this.state.displayName != '' ) {
profile = (
<div className="nav-link">
<img className="profile-image" src={this.state.profilePic} alt='Profile Pic'/>
<div className="profile-name">{this.state.displayName}</div>
</div>
)
} else {
profile = <div></div>
}
return (
<div className="navbar">
<CssBaseline />
<div className={classes.contain}>
<AppBar position="fixed" className={classes.appBar}>
<div className='inline'>
<div className="body" id="body">
<div className="wrapper">
<div className="nav-toggle" id="icon" onClick={this.handleToggle}>
<div className="icon"></div>
</div>
</div>
</div>
</div>
<div className="head">
<div id="head">
<div style={{display: 'inline-block'}}>PollPlay</div>
<div style={{display: 'inline-block', float: 'right'}}>
<div className="social" >
<Tooltip style={{float: 'right', marginRight: '15px'}} title="Email me!" classes={{ tooltip: classes.toolTip}}>
<a href="mailto:<EMAIL>?Subject=Hello%20there!" ><img src="/email.png" /></a>
</Tooltip>
<Tooltip style={{float: 'right'}} title="Github Profile" classes={{ tooltip: classes.toolTip}}>
<a href="https://github.com/chrismintan" target="_blank" ><img src="/github.png" /></a>
</Tooltip>
<Tooltip style={{float: 'right'}} title="LinkedIn Profile" classes={{ tooltip: classes.toolTip}}>
<a target="_blank" href="https://www.linkedin.com/in/chrismintan/" ><img src="/linkedin.png" /></a>
</Tooltip>
{social}
</div>
</div>
</div>
</div>
</AppBar>
</div>
<div className={this.state.active ? "side-nav active" : "side-nav hidden"}>
<div className="nav-options">
{profile}
<a className="nav-link opts" href="/">Home</a>
{this.state.userId ?
<a className="nav-link opts" href="/auth/logout">Logout</a>
:
<a className="nav-link opts" href="/auth/login">Login</a>
}
</div>
</div>
</div>
)
}
}
export default withStyles(styling)(NavBar);<file_sep>/client/src/components/Main/NowPlaying/ChatBox.jsx
import React from 'react';
import Button from '@material-ui/core/Button';
import ReactDOM from 'react-dom';
import Message from './Message.jsx';
import styles from './chat.scss';
import TextField from '@material-ui/core/TextField';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import { withStyles } from '@material-ui/core/styles';
const styling = theme => ({
button: {
margin: 0,
},
input: {
display: 'none',
},
});
class ChatBox extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
username: false,
open: false,
}
this.handleClickOpen = this.handleClickOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleSelectName = this.handleSelectName.bind(this);
this.handleNameSelectChange = this.handleNameSelectChange.bind(this);
this.submitMessage = this.submitMessage.bind(this);
this.chatInput = this.chatInput.bind(this);
}
componentWillMount() {
this.persistentState()
}
scrollToBottom() {
this.messagesEnd.scrollIntoView();
}
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
handleClickOpen() {
this.setState({
open: true,
})
}
handleClose() {
this.setState({
open: false,
})
}
handleNameSelectChange(e) {
this.setState({
input: e.target.value,
})
}
handleSelectName(e) {
let input = this.state.input
this.setState({
username: '',
input: '',
})
this.setState({
username: input,
})
localStorage.setItem('pollPlayUserName', JSON.stringify(input))
}
chatInput(e) {
if ( this.state.username == false ) {
this.handleClickOpen();
} else {
this.setState({
input: e.target.value,
})
}
}
submitMessage(e) {
e.preventDefault();
if ( this.state.username == false || this.state.input.length == 0 ) {
return
}
let roomId = this.props.roomId
let username = this.state.username;
let message = this.state.input;
let data =
{
roomId: this.props.roomId,
username: this.state.username,
message: this.state.input,
chatBox: true
}
this.props.sendMessage(data)
this.setState({
input: '',
})
}
// scrollToBot() {
// ReactDOM.findDOMNode(this.refs.chats).scrollBot = ReactDOM.findDOMNode(this.refs.chats).scrollHeight;
// }
persistentState() {
let username = this.state.username
for ( username in this.state ) {
if ( localStorage.hasOwnProperty('pollPlayUserName')) {
let value = localStorage.getItem('pollPlayUserName');
value = JSON.parse(value);
this.setState({
username: value,
})
}
}
}
render() {
const { classes } = this.props;
let messages = this.props.msgArr.map( (msgArr, index) => {
return (
<Message key={index} sender={msgArr.username} username={this.state.username} message={msgArr.message} />
)
})
let welcome;
if ( this.state.username != false ) {
welcome = `Welcome ${this.state.username}! `
} else {
welcome = 'PollPlay Chat!'
}
let prompt;
if ( this.state.username == false ) {
prompt =
<div>
<Button style={{zIndex: 9999, marginTop: '175px', color: 'white', position: 'relative'}} onClick={this.handleClickOpen}>Please choose a name to enter chat
</Button>
<Dialog
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">Enter Chat Room
</DialogTitle>
<DialogContent>
<DialogContentText>
Please save a name to enable the chat!
</DialogContentText>
<TextField
onKeyPress={(event) => {
if ( event.key == 'Enter' ) {
this.handleSelectName();
}
}}
value={this.state.usernameInput}
onChange={this.handleNameSelectChange}
autoFocus
margin="dense"
id="name"
label="Display name"
type="text"
fullWidth
autoComplete='off'
/>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Cancel
</Button>
<Button onClick={this.handleSelectName} color="primary">
Enter
</Button>
</DialogActions>
</Dialog>
</div>
} else {
prompt = '';
}
return (
<div>
{prompt}
<div className="chatroom">
<h3 className="chat-title">{welcome}</h3>
<ul className="chats" ref="chats">
<div className="bubbles">
{messages}
</div>
<div style={{ float:"left", clear: "both" }}
ref={(el) => { this.messagesEnd = el; }}>
</div>
</ul>
<div className="bottom">
</div>
</div>
<div>
<form className="form" onSubmit={this.submitMessage}>
<input style={{width: '65%', marginBottom: '20px', lineHeight: '30px', fontSize: '15px'}} type="text" ref="msg" placeholder="Type something to chat!" value={this.state.input} onChange={this.chatInput} />
<Button onClick={this.submitMessage} style={{transform: "translateY(-2px)"}} variant="contained" color="primary" className={classes.button}>Send</Button>
</form>
</div>
</div>
)
}
}
export default withStyles(styling)(ChatBox);<file_sep>/server/index.js
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
// Use routes
const apiRoutes = require('./routes/api/apiRoutes');
const authRoutes = require('./routes/spotify/authRoutes');
const spotifyApiRoutes = require('./routes/spotify/apiRoutes');
// Cookies
const cookieSession = require('cookie-session');
// Use passport modules
const passportSetup = require('./routes/config/passport-setup');
const passport = require('passport');
const session = require('express-session');
const cors = require('cors');
// Link to db queries
const db = require('../database/index');
const app = express();
app.use(cookieSession({
name: 'session',
keys: ['userId', 'spotify_id']
}))
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
secure: false,
httpOnly: false,
maxAge: 1000 * 60 * 60 * 24, //Set for one day
}
}));
app.use(cors());
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Test path can delete later
app.get('/testing', db.getSongsInRoom)
// Spotify api routes
app.use('/api', apiRoutes);
app.use('/auth', authRoutes);
app.use('/spotify', spotifyApiRoutes)
app.use(express.static(__dirname + '/../client/dist'));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/dist/index.html'));
});
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`Tuning into the sweet waves of PORT: ${port}`)
})
const io = require('socket.io')(server);
io.sockets.on('connection', (socket) => {
console.log('Connected!')
// Clunky room implementation but works!
socket.on('room', (room, data) => {
socket.join(room);
socket.on(room, function(data) {
io.in(room).emit('message', data)
})
})
})
<file_sep>/README.md
# PollPlay
[**PollPlay**](https://github.com/chrismintan/pollplay) is a Spotify-based song voting app. Users with Spotify-Premium accounts can create and host rooms. Rooms are accesible through the room code they choose. Upon entering a room, users can add songs and upvote existing songs. Songs will then be played through the host's Spotify account.
### Demo
You can see how the app works below:

[Link to App](https://pollplay.herokuapp.com/)
For more information about how I made the app, read on!
## Setting up
The app is already hosted by me on Heroku. However, if you would like to run it locally / edit and deploy it yourself, please see below for the necessary steps!
### Prerequisites
PollPlay requires [Node.js](https://nodejs.org/) v4+ to run.
### Installation
First, install the dependencies and dev-dependencies and start the server.
```
$ cd pollplay
$ npm install
```
Create your own database by running
```
$ psql -f tables.sql
```
Start the server in its own terminal
```
$ npm run server-dev
```
In a separate terminal run the client
```
$ npm run react-dev
```
### Spotify Setup
* Create a [Spotify Developer Account](https://developer.spotify.com/dashboard/login)
* Create a new app
* Add your SPOTIFY\_CLIENT\_ID and SPOTIFY\_CLIENT\_SECRET to your .env file and deployment environment
* Navigate to 'Edit Settings' in your developer account to whitelist your redirect uri
### Tech
PollPlay utilises a number of open source projects to work properly:
* [React.js](https://reactjs.org/) - Facebook's front-end framework
* [React Router](https://reacttraining.com/react-router/) - Declarative routing for React
* [Material-Ui](https://material-ui.com/) - React components that implement Google's Material Design
* [node.js](https://nodejs.org/en/) - evented I/O for the backend
* [Express](https://expressjs.com/) - node.js framework
* [Passport](http://www.passportjs.org/docs/oauth/) - Handling for Spotify authorization (OAuth)
* [Socket.Io](https://socket.io/) - Handle real-time voting and song addition using sockets and the chatroom
* [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) - To render the music visualiser
For more information on how I made the app read on!
## Application and Development Process
### Spotify OAuth 2.0

Have you visited a site recently, where you are given the option of connecting or signing up using Google, Facebook or Twitter? Sure you have! This is basically what OAuth is all about; granting third-party services permission to do something for you-like you logging in.
OAuth is a framework that gives users the ability to grant access to their information stored in one place, from another place. The idea is that a user is giving Spotify certain permission to access their Facebook details, so that Fadcebook can provide Spotify with enough inbformation to sign them in, enhance their profile details, or display what their friends are listening to.

Why is this important? It is because without an API for exchanging this information, a user would have to give a third party site their Facebook username and password thereby **giving them too much power**. This is where OAuth comes in. I have included it in this project as using Facebook to authenticate the Spotify login is immensely more convenient.
### OAuth Problems
##### Access Tokens
When a user logs in my app via OAuth, Spotify returns us an access token which represents their authorisation to access the user's information (such as playback information). These access tokens have an expiry time so as to limit damage due to malicious use of the token.
##### Refresh Tokens
Refresh tokens are a special type of token that can be help securely with the express purpose of being able to request a new access token once the original access token has expired. These also expire but are generally long lived expiry times as long as they are refreshed in an adequate time frame.
### Spotify's OAuth
Spotify's access tokens last 1hr. Meaning every hour PollPlay would have to either request that the user login again or use the refresh token to attain a new token. Therefore, everytime an API call to Spotify is being made, the access token has to be checked and a request for another token has to be made with the given refresh token.
## Spotify API
### API Rate Limit
For the rendering of the playback meter, API calls have to be made every few seconds to determine the current playback data (such as song title, song playback duration etc). Initially the plan was to have the access token stored in the database and have the users in the room make calls to Spotify's API every 3 seconds to determine the playback data. This evidently became problematic with more users as an API call was being made every 3 seconds per user in the room.
This was initially solved by storing the playback data in the database and having users in the room make AJAX calls to the database every 3 seconds. This however did not work out as well as under heavy load, Heroku's free account did not let that much Postgres queries to go through.
### Enter Sockets!
To counter this problem, [Socket.Io](https://socket.io/) was used instead. The idea was that only one user in the room makes the API requests to Spotify every 3 seconds. The host makes the API requests and sends the playback info via sockets to everyone in the room. This is done via the following code:
```
// Server side
const io = require('socket.io')(server);
io.sockets.on('connection', (socket) => {
socket.on('room', (room, data) => {
socket.join(room);
socket.on(room, function(data) {
io.in(room).emit('message', data)
})
})
})
// Client side
const {roomId} = this.props.match.params;
this.socket.emit('room', roomId)
this.socket.on('message', function(data) {
// Insert emitting code here
})
```
As seen above, when a user enters the room, he emits to the socket server the roomId and on the server side, it joins the room for the user. This segregates different rooms so that what happens in one hosted room does not affect the other.
## Author(s)
- <NAME>
This is a completely open source project! Feel free to submit pull requests or leave comments if you would like to give any feedback or encounter any bugs.
## Acknowledgements
This project is purely educational and expirimental. It would not have been possible without the following sources:
* [Spotify](https://www.spotify.com/) for their fantastic API framework for developers to make use of.
## License
ISC<file_sep>/client/src/components/Main/NowPlaying/Message.jsx
import React from 'react';
class Message extends React.Component {
constructor(props) {
super(props)
}
render() {
const username = this.props.username;
const sender = this.props.sender
let message;
if ( sender == username ) {
message = (
<li className="chat right" style={{float: 'right'}}>
<div style={{float: 'right', fontSize: 15, boxSizing: 'initial'}}>{this.props.sender}:
</div>
<br/>
<span style={{float: 'right'}}>{this.props.message}
</span>
</li>
)
} else {
message = (
<li className="chat left" style={{float: 'left'}}>
<div style={{float: 'left', fontSize: 15, boxSizing: 'initial'}}>{this.props.sender}:
</div>
<br/>
<span style={{float: 'left'}}>{this.props.message}
</span>
</li>
)
}
return (
<div>
{message}
</div>
)
}
}
export default Message;
<file_sep>/database/index.js
const pg = require('pg');
const url = require('url');
require('dotenv').config();
var configs;
if ( process.env.DATABASE_URL ) {
const params = url.parse(process.env.DATABASE_URL);
const auth = params.auth.split(':');
var configs = {
user: auth[0],
password: <PASSWORD>[1],
host: params.hostname,
port: params.port,
database: params.pathname.split('/')[1],
ssl: true,
};
} else {
var configs = {
user: 'chrisssy',
host: '127.0.0.1',
database: 'pollplay',
port: 5432,
}
}
const pool = new pg.Pool(configs);
pool.on('error', function(err) {
console.log('idle client error', err.message, err.stack);
});
const addRoom = (req, res) => {
let text = `INSERT INTO rooms (name, spotify_id) VALUES ($1, $2) RETURNING *`;
let values = [req.roomName, req.spotifyId];
pool.query(text, values, (err, result) => {
if ( err ) {
console.log('error:', err);
res.sendStatus(500);
} else {
res(null, result);
}
})
}
const addSongToRoom = (req, res) => {
let text = `INSERT INTO songs_rooms (track, artist, album_image, track_uri, room_code) VALUES ($1, $2, $3, $4, $5) RETURNING *`;
let values = [req.songObj.trackName, req.songObj.artistName, req.songObj.albumImageURL, req.songObj.trackURI, req.songObj.roomID];
pool.query(text, values, (err, result) => {
if ( err ) {
console.log('error:', err);
res(null, err);
} else {
res(null, result);
}
})
}
const addUser = (req, res) => {
console.log(req.spotify_id)
let text = `SELECT * FROM users WHERE spotify_id = '${req.spotify_id}'`;
pool.query(text, (err, existingUser) => {
if ( err ) {
console.log('error: ', err)
res.sendStatus(500);
} else {
if ( existingUser.rows == 0 ) {
console.log(req)
let text1 = `INSERT INTO users (spotify_id, spotify_display_name, access_token, refresh_token, token_expires_at, image_url) VALUES ($1, $2, $3, $4, $5, $6)`;
let values1 = [req.spotify_id, req.spotify_display_name, req.access_token, req.refresh_token, req.token_expires_at, req.image_url];
pool.query(text1, values1, (err, result) => {
if ( err ) {
console.log('error: ', err)
res.sendStatus(500);
} else {
res(null, result)
}
})
} else {
if ( existingUser.rows != 0 ) {
console.log('UPDATEDDDD!')
let text2 = `UPDATE users SET access_token = '${req.access_token}', token_expires_at = '${req.token_expires_at}', refresh_token = '${req.refresh_token}' WHERE spotify_id = '${req.spotify_id}'`;
pool.query(text2, (err, result) => {
if ( err ) {
console.log('error:', err);
res.sendStatus(500);
} else {
res(null, result)
}
})
} else {
res(null, existingUser)
}
}
}
})
}
const getAccessTokenAndExpiresAt = (req, res) => {
let text = `SELECT * FROM users WHERE spotify_id = '${req.spotify_id}'`
pool.query(text, (err, result) => {
if (err) {
res.sendStatus(500);
} else {
res(null, result)
}
})
}
const getRoomData = (req, res) => {
console.log(req.room)
let text = `SELECT * FROM users INNER JOIN rooms USING (spotify_id) WHERE rooms.name = '${req.room}'`;
pool.query(text, (err, result) => {
if ( err ) {
res.sendStatus(500);
} else {
res(null, result.rows);
}
})
}
const getSongsInRoom = (req, res) => {
let text = `SELECT * FROM songs_rooms WHERE room_code = '${req.roomId}' ORDER BY upvote DESC`;
pool.query(text, (err, result) => {
if (err) {
res.sendStatus(500);
} else {
res(null, result.rows);
}
})
}
const getUserById = (req, res) => {
let text = `SELECT * FROM users WHERE users.id = '${req.userId[0].id}'`;
pool.query(text, (err, result) => {
if ( err ) {
console.log(err);
} else {
// console.log('RESULT.ROWS:', result.rows)
res(null, result.rows);
}
});
};
const getUserBySpotifyId = (req, res) => {
let text = `SELECT * FROM users WHERE spotify_id = '${req.spotify_id}'`;
pool.query(text, (err, result) => {
if ( err ) {
res(err);
} else {
res(null, result.rows);
}
});
};
const removeSongFromRoom = (req, res) => {
let text = `DELETE FROM songs_rooms WHERE room_code = '${req.roomId}' AND track_uri = '${req.trackURI}' RETURNING *`;
pool.query(text, (err, result) => {
if ( err ) {
res(err);
} else {
res(null, result);
}
})
}
const updateAccessTokenAndExpiresAt = (req, res) => {
let text = `UPDATE users SET access_token = '${req.access_token}', token_expires_at = '${req.token_expires_at}' WHERE spotify_id = ${req.spotify_id}`;
pool.query(text, (err, result) => {
if ( err ) {
res(err);
} else {
res(null, result.rows);
}
})
}
const downVoteSong = (req, res) => {
console.log('index.js database REQ:', req)
let text = `UPDATE songs_rooms SET upvote = upvote - 1 WHERE room_code = '${req.roomID}' AND track_uri = '${req.trackURI}' RETURNING *`;
pool.query(text, (err, result) => {
if ( err ) {
console.log(err);
} else {
res(null, result);
}
})
}
const upVoteSong = (req, res) => {
console.log('index.js database REQ:', req)
let text = `UPDATE songs_rooms SET upvote = upvote + 1 WHERE room_code = '${req.roomID}' AND track_uri = '${req.trackURI}' RETURNING *`;
pool.query(text, (err, result) => {
if ( err ) {
console.log(err);
} else {
res(null, result);
}
})
}
module.exports = {
addRoom,
addSongToRoom,
addUser,
downVoteSong,
getAccessTokenAndExpiresAt,
getRoomData,
getSongsInRoom,
getUserById,
getUserBySpotifyId,
removeSongFromRoom,
updateAccessTokenAndExpiresAt,
upVoteSong,
}
<file_sep>/seed.sql
insert into songs (title, artist) values ('Hello', 'Adele');
insert into songs (title, artist) values ('Beat It', '<NAME>');
insert into songs (title, artist) values ('Chicken Fried', 'Random Country Guy');
insert into songs (title, artist) values ('Blinded By The Light', '<NAME>');
insert into rooms (name) values ('TestRoom');
insert into rooms (name) values ('HRATX36 Graduation');
insert into rooms (name) values ('Bathroom Party');
insert into rooms (name) values ('Living Room');
insert into songs_rooms (song_id, room_id) values (1,2);
insert into songs_rooms (song_id, room_id) values (1,3);
insert into songs_rooms (song_id, room_id) values (3,3);
insert into songs_rooms (song_id, room_id) values (3,3);
insert into songs_rooms (song_id, room_id) values (3,3);<file_sep>/client/src/components/Main/NowPlaying/CurrentSongAnimated.jsx
import React from 'react';
import script from './script2.js';
class CurrentSong extends React.Component {
render() {
return (
<div className='current-song'>
<div className='current-song-image'>
<img src={this.props.image} alt='song image' />
</div>
<div className='current-song-title'>
<div>{this.props.title}</div>
</div>
<div className='current-song-artist'>
<div>{this.props.artist}</div>
</div>
<script src={script}></script>
</div>
)
}
}
export default CurrentSong;<file_sep>/client/src/components/Main/Rooms/CreateRoom.jsx
import React from 'react';
import { Link, Route, Redirect, withRouter } from 'react-router-dom';
import axios from 'axios';
import Grid from '@material-ui/core/Grid';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import classNames from 'classnames';
import TouchRipple from '@material-ui/core/ButtonBase/TouchRipple';
import Checkbox from '@material-ui/core/Checkbox';
import Favorite from '@material-ui/icons/Favorite';
import FavoriteBorder from '@material-ui/icons/FavoriteBorder';
import IconButton from '@material-ui/core/IconButton';
import InputAdornment from '@material-ui/core/InputAdornment';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import RedoIcon from '@material-ui/icons/Redo';
import FormControl from '@material-ui/core/FormControl';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Snackbar from '@material-ui/core/Snackbar';
import ErrorIcon from '@material-ui/icons/Error';
const variantIcon = {
error: ErrorIcon,
}
const styles = theme => ({
title: {
marginTop: '60px',
fontSize: '50px',
color: '#CCCCCBFF',
fontStyle: 'italic',
},
root: {
flexGrow: 1,
},
paper: {
textAlign: 'center',
width: '100%',
},
top: {
marginTop: 30,
color: '#FEFEFEFF',
},
bot: {
marginTop: 30,
color: '#FEFEFEFF',
},
textFieldCreate: {
// marginTop: 20,
color: '#FEFEFEFF',
borderBottom: '1px solid #FEFEFEFF',
// marginBottom: 5,
width: '100%',
},
textFieldJoin: {
color: '#FEFEFEFF',
borderBottom: '1px solid #FEFEFEFF',
width: '100%',
},
'input-label': {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
width: '100%',
textAlign: 'center',
},
hidden: {
display: 'none',
},
'input': {
'&::placeholder': {
textOverflow: 'ellipsis !important',
color: 'blue',
backgroundColor: 'white',
}
},
icon: {
color: 'white',
marginTop: '25px',
},
iconTop: {
color: 'white',
marginTop: '17px',
},
margin: {
margin: '10px',
},
error: {
background: 'rgb(186, 38, 26)',
textAlight: 'center',
display: 'block',
},
});
class CreateRoom extends React.Component {
constructor() {
super();
this.state = {
input: '',
roomInput: '',
spotifyId: '',
createError: false,
charError: false,
joinError: false,
vertical: 'top',
horizontal: 'center',
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleRoomCodeChange = this.handleRoomCodeChange.bind(this);
this.joinRoom = this.joinRoom.bind(this);
this.handleClose = this.handleClose.bind(this);
this.throwCreateError = this.throwCreateError.bind(this);
this.throwJoinError = this.throwJoinError.bind(this);
this.charError = this.charError.bind(this);
this.createAndRedirect = this.createAndRedirect.bind(this);
}
componentWillUnmount() {
localStorage.clear();
// Hackerish way to relead script
window.location.reload();
}
componentDidMount() {
let reactThis = this;
axios.get('/auth/isLoggedIn')
.then(({data}) => {
reactThis.props.setUserID(data.userId);
reactThis.setState({
spotifyId: data.spotify_id,
})
})
.catch(err => {
console.log(err);
});
}
handleInputChange(event) {
this.setState({
input: event.target.value.toLowerCase(),
})
}
// Creating a room input - this.state.input function - this.state.handleClick
handleClick(event) {
let reactThis = this;
event.preventDefault();
let roomId = this.state.input;
if ( this.state.input.length < 5 ) {
this.charError();
setTimeout(function() {
reactThis.setState({
createError: false,
joinError: false,
charError: false,
})
}, 5000)
} else if ( this.state.input.length > 4 ) {
axios.get(`/api/rooms/${this.state.input}`, {
params: {
roomId: roomId
}
})
.then(({data}) => {
if ( data.length != 0 ) {
if ( data[0].spotify_id == reactThis.state.spotifyId ) {
reactThis.props.setRoomID(roomId);
reactThis.props.history.push(`/rooms/${roomId}`);
} else {
this.throwCreateError();
setTimeout(function() {
reactThis.setState({
createError: false,
joinError: false,
charErr9r: false,
})
}, 5000)
}
} else if ( data.length == 0 ) {
this.createAndRedirect();
}
})
.catch(err => {
console.error()
})
}
}
createAndRedirect() {
let reactThis = this;
axios.post('/api/createRoom', {
roomName: this.state.input.toLowerCase(),
spotifyId: this.state.spotifyId,
})
.then(({data}) => {
reactThis.props.setRoomID(data);
reactThis.props.history.push(`/rooms/${data}`);
})
.catch(err => {
console.log(err);
});
}
handleRoomCodeChange(event) {
this.setState({
roomInput: event.target.value.toLowerCase(),
});
}
// Joining a room Input - this.state.roomInput function - this.joinRoom
joinRoom(event) {
event.preventDefault()
let reactThis = this;
let roomCode = this.state.roomInput.toLowerCase();
if ( roomCode != 0 ) {
axios.get(`/api/rooms/${roomCode}`, {
params: {
roomId: roomCode,
}
})
.then(({data}) => {
console.log(data.length)
if ( data.length == 0 ) {
reactThis.throwJoinError()
setTimeout(function() {
reactThis.setState({
createError: false,
joinError: false,
})
}, 5000)
} else {
reactThis.props.setRoomID(roomCode);
reactThis.props.history.push(`/rooms/${roomCode}`);
}
})
.catch(err => {
console.log('error!', err)
})
}
}
throwCreateError() {
this.setState({
createError: true,
})
}
throwJoinError() {
this.setState({
joinError: true,
})
}
handleClose() {
this.setState({
open: false,
})
}
charError() {
this.setState({
charError: true,
})
}
render() {
const { classes } = this.props;
const { vertical, horizontal, open } = this.state;
let component;
if (this.props.userID) {
component = (
<div>
<form onSubmit={this.handleClick}>
<FormControl style={{ width: '33%' }} className={classes.textFieldCreate}>
<TextField
value={this.state.input}
onKeyPress={(e) => {
if ( e.which == 32 ) {
e.preventDefault();
}
}}
onChange={this.handleInputChange}
fullWidth
InputProps={{
disableUnderline: true,
classes: {
input: classes.top,
},
endAdornment: (
<InputAdornment variant="filled" position="end">
<IconButton onClick={this.handleClick}>
<AddCircleIcon className={classes.iconTop}/>
</IconButton>
</InputAdornment>
)
}}
label='Type to create a room...'
InputLabelProps={{
style: {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
width: '100%',
color: '#FEFEFEFF',
fontSize: 20,
fontWeight: 'lighter',
marginTop: 25,
fontStyle: 'italic',
}
}}
/>
</FormControl>
</form>
</div>
)
} else {
component = <a style={{ color: "#1db954", fontStyle: 'bold', fontSize: 30, lineHeight: '100px' }} href='/auth/login'>Please Login to Create a Room!</a>
}
return (
<div>
<Grid container spacing={0}>
<div className={classes.paper}>
<h1 className={classes.title}>Welcome to PollPlay!</h1>
{component}
<div>
<div>
<form onSubmit={this.joinRoom}>
<FormControl style={{ width: '33%' }} className={classes.textFieldCreate}>
<TextField
value={this.state.roomInput}
onChange={this.handleRoomCodeChange}
fullWidth
onKeyPress={(e) => {
if ( e.which == 32 ) {
e.preventDefault();
}
}}
InputProps={{
disableUnderline: true,
classes: {
input: classes.top,
},
endAdornment: (
<InputAdornment variant="filled" position="end">
<IconButton onClick={this.joinRoom} >
<RedoIcon className={classes.icon}/>
</IconButton>
</InputAdornment>
)
}}
label='or join a room!'
InputLabelProps={{
style: {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
width: '100%',
color: '#FEFEFEFF',
fontSize: 20,
fontWeight: 'lighter',
marginTop: 25,
fontStyle: 'italic',
}
}}
/>
</FormControl>
</form>
</div>
</div>
</div>
</Grid>
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'middle',
}}
open={this.state.createError}
autoHideDuration={5000}
onClose={this.handleClose}
ContentProps={{
classes: {
root: classes.error,
},
'aria-describedby': 'message-id',
}}
message={<span style={{ textAlign: 'center', fontSize: 17 }} className={classes.error}>Sorry! Room name is already taken. Please choose another!</span>}
/>
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'middle',
}}
open={this.state.joinError}
autoHideDuration={5000}
onClose={this.handleClose}
ContentProps={{
classes: {
root: classes.error,
},
'aria-describedby': 'message-id',
}}
message={<span style={{ textAlign: 'center', fontSize: 17 }} className={classes.error}>No room of such name found. Please try again!</span>}
/>
<Snackbar
anchorOrigin={{
vertical: 'top',
horizontal: 'middle',
}}
open={this.state.charError}
autoHideDuration={5000}
onClose={this.handleClose}
ContentProps={{
classes: {
root: classes.error,
},
'aria-describedby': 'message-id',
}}
message={<span style={{ textAlign: 'center', fontSize: 17 }} className={classes.error}>Room codes must be 5 characters or more!</span>}
/>
</div>
)
}
}
export default withRouter(withStyles(styles)(CreateRoom));
<file_sep>/tables.sql
DROP TABLE IF EXISTS rooms;
CREATE TABLE rooms (
id SERIAL PRIMARY KEY,
name varchar(250) NOT NULL,
isAccessible bit NOT NULL DEFAULT '1',
spotify_id INT NOT NULL DEFAULT 0
);
DROP TABLE IF EXISTS songs;
CREATE TABLE songs (
id SERIAL PRIMARY KEY,
title varchar(250) NOT NULL,
artist varchar(250) NOT NULL,
image varchar(255) DEFAULT NULL,
spotify_id varchar(250) DEFAULT NULL
);
DROP TABLE IF EXISTS songs_rooms;
CREATE TABLE songs_rooms (
id SERIAL PRIMARY KEY,
track varchar(250) NOT NULL,
artist varchar(250) NOT NULL,
album_image varchar(250) NOT NULL,
track_uri TEXT NOT NULL,
room_code varchar(250) NOT NULL,
upvote INT NOT NULL DEFAULT 0
);
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id SERIAL PRIMARY KEY,
spotify_id INT NOT NULL,
spotify_display_name varchar(250) NOT NULL,
access_token varchar(300) NOT NULL,
refresh_token varchar(250) NOT NULL,
token_expires_at varchar(250) NOT NULL,
image_url varchar(250)
);
-- ALTER TABLE songs_rooms ADD CONSTRAINT songs_rooms_fk0 FOREIGN KEY (song_id) REFERENCES songs(id);
-- ALTER TABLE songs_rooms ADD CONSTRAINT songs_rooms_fk1 FOREIGN KEY (room_id) REFERENCES rooms(id);
-- ALTER TABLE rooms ADD CONSTRAINT rooms_fk0 FOREIGN KEY (user_id) REFERENCES users(id);
<file_sep>/server/routes/spotify/authRoutes.js
const router = require('express').Router();
const passport = require('passport');
const cookieSession = require('cookie-session');
const scope = [
'user-read-email',
'streaming',
'user-modify-playback-state',
'user-read-currently-playing',
'user-read-playback-state',
'user-library-read',
'playlist-read-private',
'user-library-modify',
'playlist-modify-public',
'user-read-recently-played',
'user-read-private',
'playlist-modify-private',
'user-top-read',
'user-read-birthdate',
];
// Auth logout
router.get('/logout', (req, res) => {
req.logout();
req.session.userId = null;
res.redirect('/');
});
// Auth with Spotify
router.get('/login', passport.authenticate('spotify', {
scope,
showDialog: true
}));
router.get('/spotify/redirect', passport.authenticate('spotify', {failureRedirect: '/login'}), (req, res) => {
res.redirect('/');
});
router.get('/isLoggedIn', (req, res) => {
if ( typeof req.session.passport != "undefined" ) {
let access_token = req.session.passport.user[0].access_token;
let refresh_token = req.session.passport.user[0].refresh_token;
let spotify_id = req.session.passport.user[0].spotify_id;
let userId = req.session.passport.user[0].id;
let display_name = req.session.passport.user[0].spotify_display_name;
let image_url = req.session.passport.user[0].image_url
res.send( { access_token: access_token, refresh_token: refresh_token, spotify_id: spotify_id, userId: userId, display_name: display_name, image_url: image_url } || null);
} else {
res.send( spotify_id == null )
}
});
module.exports = router;<file_sep>/client/src/components/Main/Main.jsx
import React from 'react';
import axios from 'axios';
import SearchBar from './Search/SearchBar.jsx';
import SongList from './SongList.jsx';
import CurrentSong from './NowPlaying/CurrentSong.jsx';
import io from 'socket.io-client';
import styles from './style.scss';
import Grid from '@material-ui/core/Grid';
import { withStyles } from '@material-ui/core/styles';
import Cookies from 'universal-cookie';
import CssBaseline from '@material-ui/core/CssBaseline';
import ChatBox from './NowPlaying/ChatBox.jsx';
const styling = theme => ({
root: {
flexGrow: 1,
},
paper: {
textAlign: 'center',
margin: 0,
padding: 0,
},
});
class Main extends React.Component {
constructor() {
super();
this.state = {
host: false,
songBank: [],
roomID: null,
access_token: null,
spotify_id: null,
artistName: '',
albumImageURL: '',
albumName: '',
albumURI: '',
visibleAlbumURI: '',
nextVectorData: null,
trackDuration: 180000,
trackURI: '',
trackPosition: 0,
trackPlaying: false,
trackName: '',
voteHandler: [],
nextQueued: false,
messageArray: [],
roomSize: 0,
};
this.socket = io.connect();
// Adding songs to polling pool
this.addSong = this.addSong.bind(this);
this.saveSong = this.saveSong.bind(this);
// Voting functions
this.upVoteSong = this.upVoteSong.bind(this);
this.updateVotes = this.updateVotes.bind(this);
// Remove song from room
this.removeSong = this.removeSong.bind(this);
// Updating state from data received from socket
this.updateSongBank = this.updateSongBank.bind(this);
this.updateStatus = this.updateStatus.bind(this);
// Host emiting updates
this.emitUpdate = this.emitUpdate.bind(this);
this.nextSong = this.nextSong.bind(this);
// Skip to next song (host only
this.skipToNext = this.skipToNext.bind(this);
// Function to send chat msgs
this.sendMessage = this.sendMessage.bind(this);
// Downvotes
this.downVoteSong = this.downVoteSong.bind(this);
this.updateDownVotes = this.updateDownVotes.bind(this);
}
// Setting up player update function (for host)
async componentWillMount() {
var playBackData;
const {roomId} = this.props.match.params;
this.setState({
roomID: roomId,
})
let reactThis = this;
// Get all songs in songBank
await axios.get('/api/getAllSongs', {
params: {
roomId: roomId,
}
})
.then(({data}) => {
let songBank = [];
for ( let i = 0; i < data.length; i++ ) {
let obj = { trackName: data[i].track,
artistName: data[i].artist,
albumImageURL: data[i].album_image,
trackURI: data[i].track_uri,
likes: data[i].upvote }
songBank = songBank.concat(obj)
}
this.setState({
songBank: songBank,
})
})
.catch(err => {
console.log(err)
})
await axios.get(`/api/rooms/${roomId}`, {
params: {
roomId: roomId,
}
})
.then(({data}) => {
this.setState({
spotify_id: data[0].spotify_id,
roomID: data[0].name,
access_token: data[0].access_token,
})
})
.catch(err => {
console.error();
});
await axios.get('/auth/isLoggedIn')
.then(({data}) => {
if ( data.spotify_id == reactThis.state.spotify_id ) {
this.setState({
host: true,
})
console.log('Host is in the building!')
// 1. Setting state for host to be true
setInterval(reactThis.emitUpdate, 3000)
} else {
reactThis.socket.emit(roomId, 'Another voter!');
}
})
.catch(err => {
console.log(err);
});
}
async componentDidMount() {
const {roomId} = this.props.match.params;
let reactThis = this
/* Socket listener listening for
1. updateStatus
- updates seek bar and gets animations for vectors
2. addSong
- listens for people who add songs to the song polling pool
3. upVote
- listens for people who upvote songs in the song pool and updates it accordingly
4. nextSong
- listens for song change and removes the song from the song poll list
*/
this.socket.emit('room', roomId)
this.socket.on('message', function(data) {
if ( data.updateStatus == true ) {
reactThis.updateStatus(data)
} else if ( data.addSong == true ) {
let newArray = reactThis.state.songBank.concat(data);
reactThis.setState({
songBank: newArray,
})
if ( reactThis.state.host == true ) {
reactThis.saveSong(data);
}
} else if ( data.upVote == true ) {
reactThis.updateSongBank(data.trackURI);
if ( reactThis.state.host == true ) {
reactThis.updateVotes(data);
}
} else if ( data.downVote == true ) {
reactThis.downVoteSongBank(data.trackURI);
if( reactThis.state.host == true ) {
reactThis.updateDownVotes(data);
}
} else if ( data.nextSong == true ) {
let newSongBank = reactThis.state.songBank.slice(1);
reactThis.setState({
songBank: [],
})
reactThis.setState({
songBank: newSongBank,
})
} else if ( data.chatBox == true ) {
let newArr = reactThis.state.messageArray;
newArr = reactThis.state.messageArray.concat(data)
reactThis.setState({
messageArray: [],
})
reactThis.setState({
messageArray: newArr,
})
}
})
// Socket listener
}
// 2. Emitting updates once every 3000ms
emitUpdate() {
const {roomId} = this.props.match.params;
let playBackData;
// Socket emitting (only host)
let reactThis = this;
axios.get('/spotify/currentSong')
.then(({data}) => {
playBackData = data;
playBackData.updateStatus = true;
reactThis.socket.emit(roomId, playBackData)
// Checking to see if next song should be played
if ( (playBackData.item.duration_ms - playBackData.progress_ms) <= 10000 && (reactThis.state.nextQueued == false) ) {
let timeLeft = playBackData.item.duration_ms - playBackData.progress_ms - 1500;
reactThis.setState({
nextQueued: true,
})
setTimeout(function() {
reactThis.nextSong(reactThis.state.songBank[0].trackURI)
}, timeLeft)
}
})
.catch(error => {
console.log(error)
})
// Socket emitting (only host)
}
updateStatus(data) {
let reactThis = this;
this.setState({
access_token: data.access_token,
albumURI: data.item.album.uri,
albumImageURL: data.item.album.images[0].url,
trackName: data.item.name,
albumName: data.item.album.name,
artistName: data.item.artists[0].name,
trackPosition: data.progress_ms,
trackDuration: data.item.duration_ms,
trackPlaying: data.is_playing,
trackURI: data.item.uri,
})
}
// Main -> SearchBar -> DropDownList -> SearchResult (User adds song to polling pool)
addSong(songData) {
const {roomId} = this.props.match.params;
// Emiting song added to everyone in room
this.socket.emit(roomId, songData)
}
// After emitting songData to socket, update DB
saveSong(songData) {
let songObj = songData
songObj.roomID = this.state.roomID
axios.post('/api/saveSong', songObj)
.then(() => {
console.log('Song Added!');
})
.catch(function(error) {
console.log('POST failed', error)
});
}
// Update songBank after receiving a vote
updateSongBank(trackURI) {
let songBank = this.state.songBank;
for ( var i in songBank ) {
if ( songBank[i].trackURI == trackURI ) {
songBank[i].likes = parseInt(songBank[i].likes) + 1;
}
}
// Sort songs from most likes to least
function compare(a, b) {
if ( parseInt(a.likes) > parseInt(b.likes) )
return -1;
if ( parseInt(a.likes) < parseInt(b.likes) )
return 1;
return 0;
}
// Sorting songBank by most likes
songBank.sort(compare);
// For some reason setting the state with only 1 change in variable doesnt re render the child component
this.setState({
songBank: [],
})
this.setState({
songBank: songBank,
})
}
// Downvote
downVoteSongBank(trackURI) {
let songBank = this.state.songBank;
for ( var i in songBank ) {
if ( songBank[i].trackURI == trackURI ) {
songBank[i].likes = parseInt(songBank[i].likes) - 1;
}
}
// Sort songs from most likes to least
function compare(a, b) {
if ( parseInt(a.likes) > parseInt(b.likes) )
return -1;
if ( parseInt(a.likes) < parseInt(b.likes) )
return 1;
return 0;
}
// Sorting songBank by most likes
songBank.sort(compare);
// For some reason setting the state with only 1 change in variable doesnt re render the child component
this.setState({
songBank: [],
})
this.setState({
songBank: songBank,
})
}
upVoteSong(songData) {
const {roomId} = this.props.match.params;
songData.roomID = this.state.roomID;
this.socket.emit(roomId, songData);
}
downVoteSong(songData) {
const {roomId} = this.props.match.params;
songData.roomID = this.state.roomID;
this.socket.emit(roomId, songData);
}
updateDownVotes(songData) {
if ( this.state.host == true ) {
axios.put('/api/downVoteSong', songData)
.then((data) => {
console.log('Vote success!', data);
})
.catch(function(error) {
console.log('Vote failed', error);
})
}
}
updateVotes(songData) {
if ( this.state.host == true ) {
axios.put('/api/upVoteSong', songData)
.then((data) => {
console.log('Vote success!', data);
})
.catch(function(error) {
console.log('Vote failed', error);
})
}
}
async getCurrentSong() {
const {data: {songData}} = await axios.get('/spotify/currentSong');
let curSong = Object.values(songData)
this.setState({
currentSong: curSong,
})
}
async nextSong(song) {
// 3. Removing song from the db (host only)
let reactThis = this;
let roomID = this.state.roomID;
let trackURI = this.state.songBank[0].trackURI;
let nextTrackURI = song
this.setState({
nextQueued: false,
})
// Removing played song from the DB pool
if ( this.state.host == true ) {
await axios.put('/spotify/playNext', {nextTrackURI})
.then(({data}) => {
reactThis.removeSong(roomID, trackURI);
reactThis.socket.emit(roomID, { nextSong: true } )
})
.catch(function(error) {
console.log('Play next failed', error);
})
}
}
removeSong(roomID, song) {
axios.delete('/api/removeSong', {
params: {
roomID: roomID,
trackURI: song,
}
})
.then(({data}) => {
console.log('Next!')
})
.catch(function(error) {
console.log('Removal failed.', error)
})
}
skipToNext() {
this.nextSong(this.state.songBank[0].trackURI);
}
sendMessage(data) {
const {roomId} = this.props.match.params;
this.socket.emit(roomId, data)
}
render() {
const { classes } = this.props;
return (
<div className="contain">
<CssBaseline />
<div className='mainbody'>
<div className={classes.roots}>
<Grid container spacing={0} padding={0}>
<Grid item xs={6} spacing={0}>
<div className={classes.paper}>
<div>
<CurrentSong style={{ width: '100%', height: '50%' }} skipToNext={this.skipToNext} {...this.state} />
</div>
<div>
<div style={{ width: '100%', height: '50%' }}>
<ChatBox roomId={this.state.roomID} sendMessage={this.sendMessage} msgArr={this.state.messageArray} />
</div>
</div>
</div>
<div>
</div>
</Grid>
<Grid item xs={3} spacing={0} padding={0}>
<div className={classes.paper}>
<SongList downVoteSong={this.downVoteSong} songBank={this.state.songBank} upVoteSong={this.upVoteSong} />
</div>
</Grid>
<Grid item xs={3} spacing={0} padding={0}>
<div className={classes.paper}>
<SearchBar addSong={this.addSong} songBank={this.state.songBank} access_token={this.state.access_token} />
</div>
</Grid>
</Grid>
</div>
</div>
</div>
)
}
}
export default withStyles(styling)(Main);
| 55f235f4307c34b0c31dca5c155143b425b524fe | [
"JavaScript",
"SQL",
"Markdown"
] | 17 | JavaScript | chrismintan/pollplay | 4418685b4764eac9f07fc22399f63429e9321fef | ac3aa00f15553eff583b358a19fb54968708c181 |
refs/heads/master | <file_sep><?php
class Chapter
{
//Attributs de la classe
private $_id_chapter;
private $_title_chapter;
private $_text_chapter;
private $_date_online_chapter;
//Constructeur de la classe
public function __construct(array $donnees)
{
$this->hydrate($donnees);
}
//Hydratation de l'objet chapter
public function hydrate(array $donnees)
{
foreach ($donnees as $key => $value)
{
$method = 'set'.ucfirst($key);
if (method_exists($this, $method))
{
$this->$method($value);
}
}
}
//Getters
public function id_chapter(){
return $this->_id_chapter;
}
public function title_chapter(){
return $this->_title_chapter;
}
public function text_chapter(){
return $this->_text_chapter;
}
public function date_online_chapter(){
return $this->_date_online_chapter;
}
//Setters
/*public function setId_chapter($id_chapter){
if(!is_int($id_chapter)){
trigger_error('Il faut un nombre entier', E_USER_WARNING);
return;
}
$this->_id_chapter = $id_chapter;
}*/
public function setTitle_chapter($title_chapter){
if(!is_string($title_chapter)){
trigger_error('Il faut du texte', E_USER_WARNING);
return;
}
$this->_title_chapter = $title_chapter;
}
public function setText_chapter($text_chapter){
if(!is_string($text_chapter)){
trigger_error('Il faut du texte', E_USER_WARNING);
return;
}
$this->_text_chapter = $text_chapter;
}
/*public function setDate_cnline_chapter($date_online_chapter){
if(!empty($date_online_chapter)){
if (filter_var($_dateC, FILTER_VALIDATE_REGEXP, array("options" => array("regexp"=>"/^(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))$/"))) !== false )
{
$this->date_online_chapter = $date_online_chapter;
return $this;
} else{
echo "le format " .$date_online_chapter. " est incorrect! <br>";
}
} else {
echo "Veuillez saisir une date! <br>";
}
}
}*/
}<file_sep><?php
class frontendController{
public function __construct($db, $twig)
{
$this->_db = $db;
$this->twig = $twig;
}
public function home() // appel de la page accueil
{
echo $this->twig->render('frontend/home.html.twig', [
'title' => 'variables',
]);
}
public function billetSimple() // appel de la page chapitres
{
$chapterModel = new ChaptersManager($this->_db);
$list_chapitres = $chapterModel->getList();
$numeros_chapitres = $chapterModel->getId($id);
echo $this->twig->render('frontend/billetSimple.html.twig', [
'chapitres' => $list_chapitres
'numeros' => $numeros_chapitres
]);
}
/*public function biographie() // appel de la page biographie
{
require('view/frontend/biographie.php');
}
public function contact() // appel de la page contact
{
require('view/frontend/contact.php');
}
public function login() // appel de la page d'identification
{
require('view/frontend/biographie.php');
}*/
}<file_sep><?php
class Connexion {
protected $db;
public function connect() {
try {
$db = new PDO('mysql:host=localhost;dbname=JeanForteroche;charset=utf8', 'root', 'root');
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
return $db;
}
}<file_sep><?php
class ChaptersManager
{
private $_db; // Instance de PDO
public function __construct($db)
{
$this->setDb($db);
}
//Ajouter un chapitre
public function add(Chapter $chapter)
{
$q = $this->_db->prepare('INSERT INTO chapters(title_chapter, text_chapter, date_online_chapter) VALUES(?, ?, NOW())');
$q->bindValue(':title_chapter', $chapter->title_chapter());
$q->bindValue(':text_chapter', $chapter->text_chapter());
$q->execute();
$chapter->hydrate([
'id_chapter' => $this->_db->lastInsertId(),
]);
}
//Supprimer un chapitre
public function delete(Chapter $chapter)
{
$this->_db->exec('DELETE FROM chapters WHERE id_chapter = '.$chapter->id_chapter());
}
//Récupérer un article par son id
public function get($id)
{
$query = $this->db->prepare('SELECT(*) FROM chapters WHERE id_chapter = ?');
$query->execute([
$id_chapter
]);
$chapter = $query->fetch(PDO::FETCH_ASSOC);
return new Chapter($chapter);
}
//Retourne la liste de tous les chapitres
public function getList()
{
$q = $this->_db->prepare('SELECT id_chapter, title_chapter, text_chapter, date_online_chapter FROM chapters ORDER BY id_chapter ASC');
$q->execute();
$chapters = $q->fetchAll(PDO::FETCH_ASSOC);
return $chapters;
}
public function update(Chapter $chapter)
{
// Prépare une requête de type UPDATE.
// Assignation des valeurs à la requête.
// Exécution de la requête.
}
public function setDb(PDO $db)
{
$this->_db = $db;
}
}
/*class ArticleManager extends Manager
public function exists($id)
{
if (is_numeric($id))
{
$query = $this->db->prepare('SELECT id FROM articles WHERE id = ?');
$query->execute([
$id
]);
return $query->fetch(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}
public function getPosted()
{
// retourne la liste des articles publiés sous forme de tableau d'objets
$articles = [];
$query = $this->db->query("SELECT id, title, content, date_creation, on_line FROM articles WHERE on_line = 1 ORDER BY date_creation");
while ($data = $query->fetch(PDO::FETCH_ASSOC))
{
$articles[] = new Article($data);
}
return $articles;
}
public function update(Article $article)
{
$query = $this->db->prepare("UPDATE articles SET title = :title, content = :content, date_update = NOW(), on_line = :on_line WHERE id = :id") or die(print_r($this->db->errorInfo()));
$query->execute([
':title' => $article->getTitle(),
':content' => $article->getContent(),
':on_line' => $article->getOn_line(),
':id' => $article->getId()
]);
}
}*/
<file_sep><?php
class Twig{
public function run(){
$loader = new \Twig\Loader\FilesystemLoader('view/');
$twig = new \Twig\Environment($loader, []);
return $twig;
}
}
<file_sep><?php
//Auto-chargement de classes
function chargerClasse($classe){
require 'model/' . $classe . '.php';
}
spl_autoload_register('chargerClasse');
//Chargement de la Bdd
require 'model/Connexion.php';
$connexion = new Connexion();
$connect = $connexion->connect();
//Twig
require_once 'vendor/autoload.php';
require 'libraries/Twig.php';
$templateTwig = new Twig();
$twig = $templateTwig->run();
// on ouvre les controllers
require 'controller/frontend.php';
require 'controller/backend.php';
//instancie les class
$frontend = new frontendController($connect, $twig);
$backend = new Backend;
//conditions pour lancement des controllers
try{
if (isset($_GET['action'])) {
// FRONTEND
if ($_GET['action'] == 'home') {
$frontend->home();
}
elseif ($_GET['action'] == 'biographie') {
$frontend->biographie();
}
elseif ($_GET['action'] == 'billetSimple') {
$frontend->billetSimple();
}
elseif ($_GET['action'] == 'contact') {
$frontend->contact();
}
elseif ($_GET['action'] == 'logIn') {
$frontend->logIn();
}
// BACKEND
elseif ($_GET['action'] == 'dashboard') {
dashboard();
}
elseif ($_GET['action'] == 'changeArticle') {
changeArticle();
}
elseif ($_GET['action'] == 'manage') {
manage();
}
elseif ($_GET['action'] == 'newArticle') {
newArticle();
}
}
}
// si il n'y a pas d'action, on affiche la page d'accueil
catch(Exception $e) {
echo 'Erreur : ' . $e->getMessage();
} | 3ec7d684fea0f78e7a8a3b0f379841bfb7fb4ce8 | [
"PHP"
] | 6 | PHP | Chachaton/OpenclassroomProject4 | ce80f7a588c20e0f7188ecccd26689a095a4f918 | 67890de5c8825476cbb7b982b81d4480674ff45e |
refs/heads/master | <file_sep>package ESPressureTest.ch1_ESTypePressureTest;
import junit.framework.TestCase;
/**
* Created by song on 2017/3/3.
*/
public class CreateDateTest extends TestCase {
public void testGetPhoneNum() throws Exception {
System.out.println(new CreateDate().getPhoneNum());
}
public void testGetTime() throws Exception {
}
}<file_sep># ESPressureTest
ESPressureTest 压力测试
<file_sep>package ESPressureTest.ch1_ESTypePressureTest;
import ESPressureTest.ESConnectTool.ESConnectionHandler;
import ESPressureTest.ESConnectTool.ESInsertHandler;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import java.io.IOException;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* Created by song on 2017/3/3.
*/
public class TypePressureRun {
public static void main(String[] args) throws IOException {
System.out.println("TypePressureRun is start ");
int port=8300;
String host1="10.142.78.22";
String host2="10.142.78.23";
String host3="10.142.78.24";
String host4="10.142.78.25";
String host5="10.142.78.26";
String clusterName="my-es";
int insertNum=1000000;
final TransportClient client=new ESConnectionHandler().connection(port,clusterName,host1,host2,host3);
new ESInsertHandler().bulkReq(client,insertNum);
// ExecutorService executorService= Executors.newFixedThreadPool(10);;
// double threadBegin=System.currentTimeMillis();
// for(int i=0;i<10;i++){
// executorService.execute(new Runnable() {
// public void run() {
// try {
// //new ESInsertHandler().bulkReq(client);
// System.out.println("ok");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
// executorService.shutdown();
// double threadEnd=System.currentTimeMillis();
// System.out.println("MultiThread run time is :"+(threadEnd-threadBegin)+"ms");
}
//查找数据
void query(TransportClient client){
GetResponse response = client.prepareGet("testes_analyzer", "userlist_analyzer", "1").get();
System.out.println(response.getSourceAsString());
}
//bulk 插入数据
void bulk(TransportClient client) throws IOException {
BulkRequestBuilder bulkRequest = client.prepareBulk();
// either use client#prepare, or use Requests# to directly build index/delete requests
bulkRequest.add(client.prepareIndex("espressuretest", "13800000002")
.setSource(jsonBuilder()
.startObject()
.field("provinceId", "978")
.field("time", "20170228211345")
.field("longitude","20.30247|")
.field("latitude","110.20054")
.field("NID","460030918137299")
.field("SID","75316024")
.endObject()
)
);
bulkRequest.add(client.prepareIndex("espressuretest", "13800000003")
.setSource(jsonBuilder()
.startObject()
.field("provinceId", "999")
.field("time", "20170228211345")
.field("longitude","20.30247|")
.field("latitude","110.20054")
.field("NID","460030918137299")
.field("SID","75316024")
.endObject()
)
);
BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
// process failures by iterating through each bulk response item
System.out.println("Bulk req is fail");
}
}
}
<file_sep>package ESPressureTest.ESConnectTool;
import ESPressureTest.ch1_ESTypePressureTest.CreateDate;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.transport.TransportClient;
import java.io.IOException;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* Created by song on 2017/3/5.
*/
public class ESInsertHandler {
public void addReqIntoBulk(TransportClient client, BulkRequestBuilder bulkRequest, String index, String phoneNum) throws IOException {
// either use client#prepare, or use Requests# to directly build index/delete requests
bulkRequest.add(client.prepareIndex(index, phoneNum)
.setSource(jsonBuilder()
.startObject()
.field("provinceId", "958")
.field("time", "201702301230")
.field("longitude","20.30247")
.field("latitude","110.20054")
.field("NID","460030918137299")
.field("SID","75316024")
.endObject()
)
);
}
public void bulkReq(TransportClient client,int insertNum) throws IOException {
System.out.println("start load date.");
double loadBeginTime=System.currentTimeMillis();
BulkRequestBuilder bulkRequest = client.prepareBulk();
for(int i=0;i<insertNum;i++){
addReqIntoBulk(client,bulkRequest,"esdocpressuretest","mytype");
}
double loadEndTime=System.currentTimeMillis();
System.out.println("start insert data.");
double insertBeginTime= System.currentTimeMillis();
BulkResponse bulkResponse = bulkRequest.get();
double insertEndTime=System.currentTimeMillis();
if (bulkResponse.hasFailures()) {
// process failures by iterating through each bulk response item
System.out.println("Bulk req is fail");
}
System.out.println("load data is end.");
System.out.println("load data time is :"+(loadEndTime-loadBeginTime) +"ms.");
System.out.println("Insert data time is :"+(insertEndTime-insertBeginTime) +"ms.");
}
}
<file_sep>package ESPressureTest.ch2_ESDocPressureTest;
import ESPressureTest.ESConnectTool.ESConnectionHandler;
import ESPressureTest.ESConnectTool.ESInsertHandler;
import org.elasticsearch.client.transport.TransportClient;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by song on 2017/3/3.
*/
public class DocPressureRun {
public static void main(String[] args) throws IOException {
//args[0] 每个批次插入的数量
//args[1] 线程数量
System.out.println("DocPressureRun is start ");
int port=8300;
String host1="10.142.78.22";
String host2="10.142.78.23";
String host3="10.142.78.24";
String host4="10.142.78.25";
String host5="10.142.78.26";
String clusterName="my-es";
System.out.println("LoadDataNum :"+args[0]+" ThreadNum :"+args[1]);
final int insertNum=Integer.parseInt(args[0]);
int threadNum=Integer.parseInt(args[1]);
final CountDownLatch countDownLatch=new CountDownLatch(threadNum);
final TransportClient client=new ESConnectionHandler().connection(port,clusterName,host1,host2,host3,host4,host5);
ExecutorService executorService = Executors.newFixedThreadPool(10);
double begintime=System.currentTimeMillis();
for(int i=0;i<threadNum;i++){
executorService.execute(new Runnable() {
public void run() {
try {
System.out.println(Thread.currentThread());
new ESInsertHandler().bulkReq(client,insertNum);
countDownLatch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
try {
countDownLatch.await();
executorService.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
double endtime=System.currentTimeMillis();
System.out.println("MultiThread load time is "+(endtime-begintime)+"ms");
}
}
| 57cf2e5995a5159014dd1add4890aeebe8eec73a | [
"Markdown",
"Java"
] | 5 | Java | zhenxing914/ESPressureTest | e85936921bc2810220cabc43a6c19b45f3668347 | 3d013d156b88997376bcb74ee9d1a5f870e0e20a |
refs/heads/master | <repo_name>molocule/basic-transforms<file_sep>/README.md
# basic-transforms
Basic Transformations for 3D slicer app using python
<file_sep>/HelloSharpen/HelloSharpen/HelloSharpen.py
import os
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
import numpy as np
from array import array
#
# HelloSharpen
# Note that the name is misleading. I just used it because it was part of the template I was working on.
#
class HelloSharpen(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
# This part is just setting up the information part of the module.
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "Simple Module Operations" # TODO make this more human readable by adding spaces
self.parent.categories = ["Examples"]
self.parent.dependencies = []
self.parent.contributors = ["<NAME>"] # replace with "Firstname Lastname (Organization)"
self.parent.helpText = """
Select two volumes if the operation calls for two volumes. If not, just select one, but make sure you select Volume
1 for the volume you want to perform operations on. The console may ask you for inputs (scalars, etc.). Then select
the output Volume as the volume you want displayed on the right. Make sure that you have selected that Volume in the
Display so that changes are showing up correctly.
"""
self.parent.helpText += self.getDefaultModuleDocumentationLink()
self.parent.acknowledgementText = """
No grant, knowledge is priceless
""" # replace with organization, grant and thanks.
#
# HelloSharpenWidget
#
# This is the class for the Widget. Defines the Widget
class HelloSharpenWidget(ScriptedLoadableModuleWidget):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Instantiate and connect widgets ...
#
# Parameters Area
#
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton.text = "List of Operators"
self.layout.addWidget(parametersCollapsibleButton)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
#
# VOLUME SELECTION
#
# input volume 1
self.inputSelector = slicer.qMRMLNodeComboBox()
self.inputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode"]
self.inputSelector.selectNodeUponCreation = True
self.inputSelector.addEnabled = False
self.inputSelector.removeEnabled = False
self.inputSelector.noneEnabled = False
self.inputSelector.showHidden = False
self.inputSelector.showChildNodeTypes = False
self.inputSelector.setMRMLScene( slicer.mrmlScene )
self.inputSelector.setToolTip( "Pick the input to the algorithm." )
parametersFormLayout.addRow("Input Volume1: ", self.inputSelector)
# input volume 2
self.inputSelector2 = slicer.qMRMLNodeComboBox()
self.inputSelector2.nodeTypes = ["vtkMRMLScalarVolumeNode"]
self.inputSelector2.selectNodeUponCreation = True
self.inputSelector2.addEnabled = False
self.inputSelector2.removeEnabled = False
self.inputSelector2.noneEnabled = False
self.inputSelector2.showHidden = False
self.inputSelector2.showChildNodeTypes = False
self.inputSelector2.setMRMLScene( slicer.mrmlScene )
self.inputSelector2.setToolTip( "Pick the input to the algorithm." )
parametersFormLayout.addRow("Input Volume2: ", self.inputSelector2)
#
# output volume selector
#
self.outputSelector = slicer.qMRMLNodeComboBox()
self.outputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode"]
self.outputSelector.selectNodeUponCreation = True
self.outputSelector.addEnabled = True
self.outputSelector.removeEnabled = True
self.outputSelector.noneEnabled = True
self.outputSelector.showHidden = False
self.outputSelector.showChildNodeTypes = False
self.outputSelector.setMRMLScene( slicer.mrmlScene )
self.outputSelector.setToolTip( "Pick the output to the algorithm." )
parametersFormLayout.addRow("Output Volume: ", self.outputSelector)
#
# threshold value
#
self.imageThresholdSliderWidget = ctk.ctkSliderWidget()
self.imageThresholdSliderWidget.singleStep = 0.1
self.imageThresholdSliderWidget.minimum = -100
self.imageThresholdSliderWidget.maximum = 100
self.imageThresholdSliderWidget.value = 0.5
self.imageThresholdSliderWidget.setToolTip("Set threshold value for computing the output image. Voxels that have intensities lower than this value will set to zero.")
parametersFormLayout.addRow("Image threshold", self.imageThresholdSliderWidget)
#
# check box to trigger taking screen shots for later use in tutorials
#
self.enableScreenshotsFlagCheckBox = qt.QCheckBox()
self.enableScreenshotsFlagCheckBox.checked = 0
self.enableScreenshotsFlagCheckBox.setToolTip("If checked, take screen shots for tutorials. Use Save Data to write them to disk.")
parametersFormLayout.addRow("Enable Screenshots", self.enableScreenshotsFlagCheckBox)
#
# DIFFERENT OPERATIONS
#
# multiplication
self.applyButton = qt.QPushButton("Multiply")
self.applyButton.toolTip = "Run the operator."
self.applyButton.enabled = False
parametersFormLayout.addRow(self.applyButton)
# connections
self.applyButton.connect('clicked(bool)', self.onApply)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.inputSelector2.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
# division
self.div = qt.QPushButton("Divide")
self.div.toolTip = "Run the operator."
self.div.enabled = False
parametersFormLayout.addRow(self.div)
# connections
self.div.connect('clicked(bool)', self.onDiv)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.inputSelector2.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
# addition
self.add = qt.QPushButton("Add")
self.add.toolTip = "Run the operator."
self.add.enabled = False
parametersFormLayout.addRow(self.add)
# connections
self.add.connect('clicked(bool)', self.onAdd)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.inputSelector2.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
# exp
self.exp = qt.QPushButton("Take Exponent of")
self.exp.toolTip = "Run the operator."
self.exp.enabled = False
parametersFormLayout.addRow(self.exp)
# connections
self.exp.connect('clicked(bool)', self.onExp)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
# pow
self.pow = qt.QPushButton("Raise to the Power of")
self.pow.toolTip = "Run the operator."
self.pow.enabled = False
parametersFormLayout.addRow(self.pow)
# connections
self.pow.connect('clicked(bool)', self.onPow)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
# log
self.logg = qt.QPushButton("Take Natural Log of")
self.logg.toolTip = "Run the operator."
self.logg.enabled = False
parametersFormLayout.addRow(self.logg)
# connections
self.pow.connect('clicked(bool)', self.onLog)
self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
# Add vertical spacer
self.layout.addStretch(1)
# Refresh Apply button state
self.onSelect()
def cleanup(self):
pass
# THE CODE FOR THE ACTUAL OPERATORS
# the addition operator
def onAdd(self):
a, b = (raw_input("Enter two values for scaling Volumes 1, 2 respecitvely: Note that numbers are seperated by a colon ").split(':'))
print("First number is {} and second number is {}".format(a, b))
print()
n1 = int(a)
n2 = int(b)
m1 = self.inputSelector.currentNode()
m2 = self.inputSelector2.currentNode()
vn = self.outputSelector.currentNode()
print(np.array(m1.GetName()))
m1arr = slicer.util.array(m1.GetName())
m2arr = slicer.util.array(m2.GetName())
w = n1 * m1arr + n2 * m2arr
n = slicer.util.getNode(vn.GetName())
slicer.util.updateVolumeFromArray(n, w)
# the power operator
def onPow(self):
a, b = (raw_input("Enter x and y such that x * IMAGE ^ y respecitvely: Note that numbers are seperated by a colon ").split(':'))
print("First number is {} and second number is {}".format(a, b))
print()
n1 = int(a)
n2 = int(b)
m1 = self.inputSelector.currentNode()
vn = self.outputSelector.currentNode()
print(np.array(m1.GetName()))
m1arr = slicer.util.array(m1.GetName())
w = n1 * np.power(m1arr, n2)
n = slicer.util.getNode(vn.GetName())
slicer.util.updateVolumeFromArray(n, w)
# the log operator
def onLog(self):
a = (raw_input("Enter a value for scaling the Volume "))
print("Your number is: " + a)
print()
n1 = int(a)
m1 = self.inputSelector.currentNode()
vn = self.outputSelector.currentNode()
print(np.array(m1.GetName()))
m1arr = slicer.util.array(m1.GetName())
w = n1 * np.power(m1arr, d)
n = slicer.util.getNode(vn.GetName())
slicer.util.updateVolumeFromArray(n, w)
# the exponential operator
def onExp(self):
a = (raw_input("Enter a value for scaling the Volume "))
print("Your number is: " + a)
print()
n1 = int(a)
m1 = self.inputSelector.currentNode()
vn = self.outputSelector.currentNode()
print(np.array(m1.GetName()))
m1arr = slicer.util.array(m1.GetName())
w = n1 * np.log(m1arr + 1)
n = slicer.util.getNode(vn.GetName())
slicer.util.updateVolumeFromArray(n, w)
# the multiplication operator
def onApply(self):
a, b = (raw_input("Enter two values for scaling 1, 2 respecitvely: Note that numbers are seperated by a colon ").split(':'))
print("First number is {} and second number is {}".format(a, b))
print()
n1 = int(a)
n2 = int(b)
m1 = self.inputSelector.currentNode()
m2 = self.inputSelector2.currentNode()
vn = self.outputSelector.currentNode()
print(np.array(m1.GetName()))
m1arr = slicer.util.array(m1.GetName())
m2arr = slicer.util.array(m2.GetName())
w = n1 * m1arr * n2 * m2arr
n = slicer.util.getNode(vn.GetName())
slicer.util.updateVolumeFromArray(n, w)
# the multiplication operator
def onDiv(self):
a, b = (raw_input("Enter two values for scaling 1, 2 respecitvely: Note that numbers are seperated by a colon ").split(':'))
print("First number is {} and second number is {}".format(a, b))
print()
n1 = int(a)
n2 = int(b)
m1 = self.inputSelector.currentNode()
m2 = self.inputSelector2.currentNode()
vn = self.outputSelector.currentNode()
print(np.array(m1.GetName()))
m1arr = slicer.util.array(m1.GetName())
m2arr = slicer.util.array(m2.GetName())
w = (n1 * (m1arr + 1)) / (n2 * (m2arr + 1))
n = slicer.util.getNode(vn.GetName())
slicer.util.updateVolumeFromArray(n, w)
# the refresh command to make onApply (multiply) true when both volumes are selected
def onSelect(self):
self.applyButton.enabled = self.inputSelector.currentNode() and self.inputSelector2.currentNode() and self.outputSelector.currentNode()
self.div.enabled = self.inputSelector.currentNode() and self.inputSelector2.currentNode() and self.outputSelector.currentNode()
self.add.enabled = self.inputSelector.currentNode() and self.inputSelector2.currentNode() and self.outputSelector.currentNode()
self.exp.enabled = self.inputSelector.currentNode() and self.outputSelector.currentNode()
self.pow.enabled = self.inputSelector.currentNode() and self.outputSelector.currentNode()
self.logg.enabled = self.inputSelector.currentNode() and self.outputSelector.currentNode()
# these are test cases. I did not do anything with this, the code is probably incorrect.
class HelloSharpenLogic(ScriptedLoadableModuleLogic):
def hasImageData(self,volumeNode):
if not volumeNode:
logging.debug('hasImageData failed: no volume node')
return False
if volumeNode.GetImageData() is None:
logging.debug('hasImageData failed: no image data in volume node')
return False
return True
def isValidInputOutputData(self, inputVolumeNode, outputVolumeNode):
if not inputVolumeNode:
logging.debug('isValidInputOutputData failed: no input volume node defined')
return False
if not outputVolumeNode:
logging.debug('isValidInputOutputData failed: no output volume node defined')
return False
if inputVolumeNode.GetID()==outputVolumeNode.GetID():
logging.debug('isValidInputOutputData failed: input and output volume is the same. Create a new volume for output to avoid this error.')
return False
return True
def run(self, inputVolume, outputVolume, imageThreshold, enableScreenshots=0):
"""
Run the actual algorithm
"""
logging.info('Processing started')
# Compute the thresholded output volume using the Threshold Scalar Volume CLI module
cliParams = {'InputVolume': inputVolume.GetID(), 'OutputVolume': outputVolume.GetID(), 'ThresholdValue' : imageThreshold, 'ThresholdType' : 'Above'}
cliNode = slicer.cli.run(slicer.modules.thresholdscalarvolume, None, cliParams, wait_for_completion=True)
# Capture screenshot
if enableScreenshots:
self.takeScreenshot('HelloSharpenTest-Start','MyScreenshot',-1)
logging.info('Processing completed')
return True
class HelloSharpenTest(ScriptedLoadableModuleTest):
"""
This is the test case for your scripted module.
Uses ScriptedLoadableModuleTest base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setUp(self):
""" Do whatever is needed to reset the state - typically a scene clear will be enough.
"""
slicer.mrmlScene.Clear(0)
def runTest(self):
"""Run as few or as many tests as needed here.
"""
self.setUp()
self.test_HelloSharpen1()
def test_HelloSharpen1(self):
""" Ideally you should have several levels of tests. At the lowest level
tests should exercise the functionality of the logic with different inputs
(both valid and invalid). At higher levels your tests should emulate the
way the user would interact with your code and confirm that it still works
the way you intended.
One of the most important features of the tests is that it should alert other
developers when their changes will have an impact on the behavior of your
module. For example, if a developer removes a feature that you depend on,
your test should break so they know that the feature is needed.
"""
self.delayDisplay("Starting the test")
#
# first, get some data
#
import SampleData
SampleData.downloadFromURL(
nodeNames='FA',
fileNames='FA.nrrd',
uris='http://slicer.kitware.com/midas3/download?items=5767')
self.delayDisplay('Finished with download and loading')
volumeNode = slicer.util.getNode(pattern="FA")
logic = HelloSharpenLogic()
self.assertIsNotNone( logic.hasImageData(volumeNode) )
self.delayDisplay('Test passed!')
| aa944832cff7f1260a11af80591cc89b11736f42 | [
"Markdown",
"Python"
] | 2 | Markdown | molocule/basic-transforms | dfa2fdd7b236fe00d87e193c16725d5e8b8986b0 | 6753d1c40638e1a0faaad34a604d2c52497f1be8 |
refs/heads/master | <repo_name>joehbenti/mobilemoney_android<file_sep>/app/src/main/java/com/example/joe/mobilemoney/transaction.java
package com.example.joe.mobilemoney;
import android.app.ActionBar;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.*;
public class transaction extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction);
// ActionBar actionBar = getActionBar();
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// for navigating the bottom navigation
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(2);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.bottomNav_home:
Intent home_intent = new Intent(transaction.this, MainActivity.class);
startActivity(home_intent);
break;
case R.id.bottomNav_service:
Intent service_intent = new Intent(transaction.this, services.class);
startActivity(service_intent);
break;
case R.id.bottomNav_transaction:
break;
}
return false;
}
});
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
<file_sep>/app/src/main/java/com/example/joe/mobilemoney/TransferAccountSelect.java
package com.example.joe.mobilemoney;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class TransferAccountSelect extends BottomSheetDialogFragment {
private BottomSheetListener mListener;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_sheet_transfer, container,false);
Button wallet = (Button) view.findViewById(R.id.transfer_wallet);
Button card = (Button) view.findViewById(R.id.transfer_card);
Button bank = (Button) view.findViewById(R.id.transfer_bank);
wallet.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
mListener.onButtonClicked("wallet");
dismiss();
}
});
// add the button listeners here for each button like above
return view;
}
public interface BottomSheetListener {
void onButtonClicked(String text);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (BottomSheetListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "Must Implement BottomSheetListener");
}
}
}
<file_sep>/app/src/main/java/com/example/joe/mobilemoney/MainActivity.java
package com.example.joe.mobilemoney;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements TransferAccountSelect.BottomSheetListener{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
public static final String BILL_PAYMENT = "com.example.joe.mobilemoney";
public static int SPLASH_TIME_OUT = 4000;
// TODO: Main-todo here
// TODO: Make splash screen appear before the main screen
// TODO: Finish the modal intereraction when i click cash in and clicking the option like digaf wallet
// TODO: Back button should clean the previous activity
// TODO: Finish Bill Payment and Bus Ticket Payment
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// actionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
// mDrawerLayout.addDrawerListener(actionBarDrawerToggle);
// actionBarDrawerToggle.syncState();
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// for bottom sheet overlay
Button buttonTransfer = (Button) findViewById(R.id.cashin);
buttonTransfer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
TransferAccountSelect transferAccountSelect = new TransferAccountSelect();
transferAccountSelect.show(getSupportFragmentManager(), "Cash in Deposit");
}
});
// for navigating the bottom navigation
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(0);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.bottomNav_home:
// no need navigating to the active activity when we are already here
break;
case R.id.bottomNav_service:
Intent service_intent = new Intent(MainActivity.this, services.class);
startActivity(service_intent);
break;
case R.id.bottomNav_transaction:
Intent transaction_intent = new Intent(MainActivity.this, transaction.class);
startActivity(transaction_intent);
break;
}
return false;
}
});
}
public void cash_out(View view){
Intent intent = new Intent(this, login_signup.class);
startActivity(intent);
}
public void book_bus(View view){
Intent intent = new Intent(this, bus.class);
startActivity(intent);
}
// calling bill payment activity
public void bill_payment(View view){
// bill payment button clicked
Intent intent = new Intent(this, bill_payment_input_screen.class);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.userAccount:
Intent intent = new Intent(this, login_signup.class);
startActivity(intent);
return true;
case R.id.appbar_notification:
Intent intent_notification = new Intent(this, notification.class);
startActivity(intent_notification);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar, menu);
return true;
}
@Override
public void onButtonClicked(String text) {
// call another activity for wallet transfer from modal bottomsheet popup
// this is how you bind a fragment and the underlaying aactivity
}
}
| 92be3b517d5a68656403643af877cf1a947c435a | [
"Java"
] | 3 | Java | joehbenti/mobilemoney_android | 57aca82e2ed782d0cad2cdb5e8b6db0ffcaab443 | 7fad788e0addec34499d915aad1d6fafd2fa55ba |
refs/heads/master | <repo_name>aparajita15/Preliminary_Fake_News_Analysis<file_sep>/README.md
# Fake_News_Analysis
The increased reliance of general public on social media has engendered the problem of fake articles and it needs to be addressed urgently. Fake news can be used to manipulate individual users and masses alike - it is capable of providing a trigger for communal riots and violence.
###################
TO DO:
add seq-to-seq trained model
<file_sep>/pre_processing_training_data.py
####### Pre-processing
import os
import swifter
import numpy as np
import pandas as pd
import pdb
import argparse
import pickle
from collections import Counter
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import json
import tqdm
#####################################
'SPACY'
import spacy
#spacy.load('en')
from spacy import displacy
#import en_core_web_sm
nlp = spacy.load('en_core_web_sm')
######################################
'GLOVE VECTORS'
from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
glove_file = datapath('test_glove.txt')
tmp_file = get_tmpfile("test_word2vec.txt")
from gensim.scripts.glove2word2vec import glove2word2vec
glove2word2vec(glove_file, tmp_file)
model = KeyedVectors.load_word2vec_format(tmp_file)
######################################
global fake
global real
global all_indices
def combine(ll):
## Needed because bow vectorizer tokenizes the text and doesnt accept tokens
## Needed only when working with entitites
st=''
for i in ll['entities']:
st+=i+' '
return st
def get_entities(text):
## Analyzing the performance with two entity extraction packages
###################Stanford CoreNLP Implementation
## Stanford CoreNLP server should be running in the background for this to work
## Extracting the article body and returning the list of words which were found as entities
#text = row['articleBody']
'''with open('inp.txt', 'w') as f:
f.write(text)
os.system("java -cp \"*\" -Xmx5g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner -file inp.txt -outputFormat json")
with open('inp.txt.json', 'r') as f1:
js = json.load(f1)
'''
################ Spacy implementation
#doc = nlp(unicode(text, "utf-8"))
doc = nlp(text)
t = [""]*len(doc.ents)
i=0
for X in doc.ents:
t[i] = X.text
i+=1
return t
def get_all_labels(row ):
reals = ['mediabiasfactcheck', 'alexa', 'vargo']
fakes =['mediabiasfactcheck', 'politifact', 'zimdars', 'min2', 'dailydot']
t = []
for i in reals:
for j in fakes:
label = i + '_' + j
t+= [row[label]]
return t
def get_labels(row ):
global fake
global real
if row[fake]=='0': return 0
elif row[real] == '1': return 1
else:
## The source hasn't listed this domain as either fake or real
return -1
def main():
global real
global fake
global all_indices
all_indices = []
# Reading the input file
file_name = 'temporal_sample_with_content.csv' # --> #Original file
#file_name = 'temporal_testing_sample_with_content.csv' ## --> Testing data
file_data = "C:/Users/Aparajita/Desktop/FakeNews/"+file_name;
df = pd.read_csv(file_data, sep="\t", header=None, dtype=str)
#Renaming the column names: Changing names for consistency
col_names = list(df.iloc[0])
col_names[col_names.index('content')] = 'articleBody'
col_names[col_names.index('title')] = 'Headline'
df.columns = col_names
df=df.iloc[1:]
# Label to consider
reals = ['mediabiasfactcheck', 'alexa', 'vargo']
fakes =['mediabiasfactcheck', 'politifact', 'zimdars', 'min2', 'dailydot']
label_names = []
for i in reals:
for j in fakes:
label = i + '_' + j
label_names += [label]
real = i
fake = j
# Getting goroundtruth labels
df[label] = df.swifter.apply( get_labels, axis=1)
df[label] = pd.to_numeric(df[label], errors='ignore')
df = df[df[label] >= 0]
df['all_indices'] = np.nan
df['all_indices'] = df.swifter.apply( get_all_labels, axis=1) #df.columns.get_loc(df.columns[-1])
#Labels stored by considering all the fake and real categories
##############################################################
''' Processing begins here '''
##############################################################
#Running a simple bag of words model on the entire dataset
#Extracting entities and then running the same model
#Evaluaitng if the GloVe vecotrs can be useful? --> Checking how many words are out of vocabulary --> not informative
# Runnning a basic BiLSTM model (check - what features were captured <iff good accuracy and auc is obtained>) -- complete before feb
##############################################################
#Extracting entities
df['entities_head'] = np.nan
df['entities'] = np.nan
for i in range(len(df)):
print(i)
df['entities'].iloc[i] = get_entities(df['articleBody'].iloc[i])
df['entities_head'].iloc[i] = get_entities(df['Headline'].iloc[i])
df['entities'] = df.swifter.apply( combine, axis=1)
df['entities_head'] = df.swifter.apply( combine, axis=1)
################################################################################################################
#### Extracting vectorizers from the training dataset
stop_words = [
"a", "about", "above", "across", "after", "afterwards", "again", "against", "all", "almost", "alone", "along",
"already", "also", "although", "always", "am", "among", "amongst", "amoungst", "amount", "an", "and", "another",
"any", "anyhow", "anyone", "anything", "anyway", "anywhere", "are", "around", "as", "at", "back", "be",
"became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind", "being",
"below", "beside", "besides", "between", "beyond", "bill", "both", "bottom", "but", "by", "call", "can", "co",
"con", "could", "cry", "de", "describe", "detail", "do", "done", "down", "due", "during", "each", "eg", "eight",
"either", "eleven", "else", "elsewhere", "empty", "enough", "etc", "even", "ever", "every", "everyone",
"everything", "everywhere", "except", "few", "fifteen", "fifty", "fill", "find", "fire", "first", "five", "for",
"former", "formerly", "forty", "found", "four", "from", "front", "full", "further", "get", "give", "go", "had",
"has", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself",
"him", "himself", "his", "how", "however", "hundred", "i", "ie", "if", "in", "inc", "indeed", "interest",
"into", "is", "it", "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd", "made",
"many", "may", "me", "meanwhile", "might", "mill", "mine", "more", "moreover", "most", "mostly", "move", "much",
"must", "my", "myself", "name", "namely", "neither", "nevertheless", "next", "nine", "nobody", "now", "nowhere",
"of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours",
"ourselves", "out", "over", "own", "part", "per", "perhaps", "please", "put", "rather", "re", "same", "see",
"serious", "several", "she", "should", "show", "side", "since", "sincere", "six", "sixty", "so", "some",
"somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "system", "take",
"ten", "than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby",
"therefore", "therein", "thereupon", "these", "they", "thick", "thin", "third", "this", "those", "though",
"three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", "twelve",
"twenty", "two", "un", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what",
"whatever", "when", "whence", "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "whereupon",
"wherever", "whether", "which", "while", "whither", "who", "whoever", "whole", "whom", "whose", "why", "will",
"with", "within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves"
]
lim_unigram = 2000
train_head = df['entities_head'].tolist()
train_bodies = df['entities'].tolist()
train_label = df['all_indices'].tolist()
# Using the tf and tfidf features
bow_vectorizer = CountVectorizer(max_features=lim_unigram, stop_words=stop_words)#, stop_words=stop_words)
bow = bow_vectorizer.fit_transform( train_head + train_bodies ) # Train set only
tfreq_vectorizer = TfidfTransformer(use_idf=False).fit(bow)
tfreq = tfreq_vectorizer.transform(bow).toarray() # Train set only
tfidf_vectorizer = TfidfVectorizer(max_features=lim_unigram, stop_words=stop_words).\
fit((train_head+ train_bodies) ) # T
## Calculating the vectorizers and the training\tetsing features
# training features
train_set = []
train_stances = []
id_ref = {}
for i, elem in enumerate(train_head + train_bodies ):
id_ref[elem] = i
for i in range(len(train_head)):
head_tfidf = tfidf_vectorizer.transform([train_head[i]]).toarray()
body_tfidf = tfidf_vectorizer.transform([train_bodies[i]]).toarray()
#cosine similarity
tfidf_cos = cosine_similarity(head_tfidf, body_tfidf)[0].reshape(1, 1)
#tf
head_tf = tfreq[id_ref[train_head[i]]].reshape(1, -1)
body_tf = tfreq[id_ref[train_bodies[i]]].reshape(1, -1)
feat_vec = np.squeeze(np.c_[head_tf, body_tf, tfidf_cos])
train_set.append(feat_vec)
train_stances.append(train_label[i])
with open('Pickled_data/training_file_everything', 'wb') as wr:
pickle.dump([train_set, train_stances, label_names], wr)
with open('Pickled_data/bow_tfreq_tfidf', 'wb') as fil:
pickle.dump([bow_vectorizer, tfreq_vectorizer, tfidf_vectorizer], fil)
if __name__ == '__main__':
main()
<file_sep>/classifier_analysis.py
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import roc_auc_score
import numpy as np
import time
start_time = time.time();
import random
import pdb
import sys
import csv
import pickle
import os
import argparse
import random
### Classifier and accuracy/auc analysis
def get_acc_auc(pred, actual):
actual =np.array(actual)
# Checking accuracy only for the values where the value of label is 0 or 1
indices = np.where(actual>=0)
ac = actual[indices]
pd = pred[indices]
auc = roc_auc_score(ac, pd)
#fpr, tpr, thres = (roc_curve(ac, pd, pos_label=2))
accuracy = sum( ac ==pd ) * 1.0 / len(ac)
print('\n Accuracy obtained on the test set: ' + str(accuracy ))
print('\n AUC obtained on the test set: ' + str(auc ))
return accuracy, auc
def get_split(data, labels, percent):
list_1 = np.arange(len(data)) # example list
np.random.shuffle(list_1)
ind = int(len(data)*percent)
pdb.set_trace()
sec1 = data[list_1[:ind]]
lab1 = labels[list_1[:ind]]
sec2 = data[list_1[ind:]]
lab2 = labels[list_1[ind:]]
return sec1, lab1, sec2, lab2
'''
def get_split(data, labels, percent):
sec1 = data.sample(frac=percent)
lab1 = labels.loc[data.index.isin(sec1.index)]
sec2 = data.loc[~data.index.isin(sec1.index)]
lab2 = labels.loc[~data.index.isin(sec1.index)]
return sec1, lab1, sec2, lab2
'''
def timer1(end):
global start_time
start = start_time
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
def main(label='mediabiasfactcheck_mediabiasfactcheck', clf_opt='log_reg'):
path = 'C:/Users/Aparajita/Desktop/FakeNews/Pickled_data'
##############Loading the training and test dataset
with open('Pickled_data/training_file_everything_without', 'rb') as wr:
train_set, train_stances, label_names = pickle.load( wr)
with open('Pickled_data/testing_file_everything_without', 'rb') as wr:
test_set, actual_labels, label_names = pickle.load( wr)
#pdb.set_trace()
reals = ['mediabiasfactcheck', 'alexa', 'vargo']
fakes =['mediabiasfactcheck', 'politifact', 'zimdars', 'min2', 'dailydot']
classifiers = ['log_reg', 'svm', 'dec_tree', 'mlp']
for ir in reals:
for ifa in fakes:
for clf_opt in classifiers:
label = ir+'_'+ifa
##Prepare the data accordingly
label_index = label_names.index(label)
y_train_label = []
y_test_label = []
for i in range(len(train_stances)):
y_train_label+= [ train_stances[i][label_index] ]
for i in range(len(actual_labels)):
y_test_label+= [ actual_labels[i][label_index] ]
###########################Splitting into training and vlaidation test
###############Balancing the training dataset
#val_perc = 0.8
#train_set, train_label , vali_set, val_label = get_split(train_set, train_stances, val_perc)
real_indices = [i for i, x in enumerate(y_train_label) if x == 1]
fake_indices = [i for i, x in enumerate(y_train_label) if x == 0]
mn = min(len(real_indices), len(fake_indices))
t_real = [train_set[i] for i in real_indices]
t_fake = [train_set[i] for i in fake_indices]
#Shuffling needed
t_x = t_real[:mn] + t_fake[:mn]
t_y = [1]*mn+ [0]*mn
'''
if ratio<1:
fake_sample = fake_sample.sample(frac=ratio)
else:
real_sample = real_sample.sample(frac=1/ratio)
print('Downsampling ratio ' + str(ratio))
train_percent = 0.8
real_s1 , real_s2 = get_split(real_sample, train_percent)
fake_s1 , fake_s2 = get_split(fake_sample, train_percent)
## The balanced sampled train and test set
train = pd.concat([real_s1, fake_s1])
test = pd.concat([real_s2, fake_s2])
'''
####################################
if clf_opt == 'log_reg':
### Logistic regression classifier begins:i
print('Logistic Regression classifier started')
#timer1(end = time.time())
param_grid = {'C': [ 0.1, 1 ] ,'penalty': [ 'l2'] , 'solver' : [ 'liblinear', 'sag'] }
clf = GridSearchCV(LogisticRegression( max_iter=10000 , class_weight ='balanced',verbose = True, random_state=0, solver='lbfgs', n_jobs = 4 ), n_jobs=4 ,scoring='roc_auc', param_grid = param_grid ,verbose = 100 , cv=StratifiedKFold()).fit(t_x, t_y)
#clf = LogisticRegression(class_weight ='balanced' , dual = True, solver = 'liblinear', random_state=0 ).fit(train_set, train_stances)
#clf = LogisticRegression(class_weight = {1: train_ratio/(train_ratio+1), 0: 1/(train_ratio + 1)}, random_state=0, solver='lbfgs',multi_class='multinomial').fit(train_set, train_stances)
print('\n Training completed')
elif clf_opt == 'svm':
print('SVM classifier started')
C_range = np.logspace(-2, 10, 13)
gamma_range = np.logspace(-9, 3, 13)
param_grid = dict(gamma=gamma_range, C=C_range)
cv =StratifiedKFold()#StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
grid = GridSearchCV(SVC(), param_grid=param_grid, cv=cv, n_jobs=4, scoring='roc_auc' )
grid.fit(train_set, train_stances)
#timer1(end = time.time())
clf = grid
print('\n Training completed')
elif clf_opt == 'dec_tree':
print('Decision Tree classifier started')
timer1(end = time.time())
#clf = DecisionTreeClassifier(class_weight = {1: train_ratio/(train_ratio+1), 0: 1/(train_ratio + 1)} ).fit(train_set, train_stances)
rfc = RandomForestClassifier(n_jobs=-1,max_features= 'sqrt' ,n_estimators=50, oob_score = True)
param_grid = { 'n_estimators': [200, 700], 'max_features': ['auto', 'sqrt', 'log2'] }
CV_rfc = GridSearchCV(estimator=rfc,param_grid=param_grid, cv=StratifiedKFold(), n_jobs = 4, scoring='roc_auc')
CV_rfc.fit(train_set, train_stances)
clf = CV_rfc
print('\n Training completed')
elif clf_opt=='mlp':
### Logistic regression classifier begins:i
print('MLP classifier started')
timer1(end = time.time())
clf = MLPClassifier(learning_rate_init = 0.005, hidden_layer_sizes=(2000,),alpha=0.0001, verbose=True, early_stopping=True).fit(train_set, train_stances)
print('\n Training completed')
###########################################################################
###########################################################################
''' Accurracy AUC Analysis'''
###########################################################################
f6 = 'C:/Users/Aparajita/Desktop/FakeNews/Saved_classifiers/'+ clf_opt +'_trained_on'+label +'_labels'
with open(f6, 'wb') as f:
pickle.dump(clf, f)
test_stances = clf.predict(test_set)
acc, auc = get_acc_auc(test_stances, y_test_label)
if __name__== '__main__':
main()
## Classifiers saved
## Accuracy and AUC calculated<file_sep>/pre_processing_test_data.py
####### Pre-processing
import os
import swifter
import numpy as np
import pandas as pd
import pdb
import argparse
import pickle
from collections import Counter
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import json
import tqdm
#####################################
'SPACY'
import spacy
#spacy.load('en')
from spacy import displacy
#import en_core_web_sm
nlp = spacy.load('en_core_web_sm')
######################################
'GLOVE VECTORS'
from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
glove_file = datapath('test_glove.txt')
tmp_file = get_tmpfile("test_word2vec.txt")
from gensim.scripts.glove2word2vec import glove2word2vec
glove2word2vec(glove_file, tmp_file)
model = KeyedVectors.load_word2vec_format(tmp_file)
######################################
global fake
global real
global all_indices
def combine(ll):
st=''
for i in ll['entities']:
st+=i+' '
return st
def get_entities(text):
## Analyzing the performance with two entity extraction packages
###################Stanford CoreNLP Implementation
## Stanford CoreNLP server should be running in the background for this to work
## Extracting the article body and returning the list of words which were found as entities
#text = row['articleBody']
'''with open('inp.txt', 'w') as f:
f.write(text)
os.system("java -cp \"*\" -Xmx5g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner -file inp.txt -outputFormat json")
with open('inp.txt.json', 'r') as f1:
js = json.load(f1)
'''
################ Spacy implementation
#doc = nlp(unicode(text, "utf-8"))
doc = nlp(text)
t = [""]*len(doc.ents)
i=0
for X in doc.ents:
t[i] = X.text
i+=1
return t
def get_all_labels(row ):
reals = ['mediabiasfactcheck', 'alexa', 'vargo']
fakes =['mediabiasfactcheck', 'politifact', 'zimdars', 'min2', 'dailydot']
t = []
for i in reals:
for j in fakes:
label = i + '_' + j
t+= [row[label]]
return t
def get_labels(row ):
global fake
global real
if row[fake]=='0':
return 0
elif row[real] == '1':
return 1
else:
## The source hasn't listed this domain as either fake or real
return -1
def main():
global real
global fake
global all_indices
all_indices = []
# Reading the input file
#file_name = 'temporal_sample_with_content.csv' # --> #Original file
file_name = 'temporal_testing_sample_with_content.csv' ## --> Testing data
file_data = "C:/Users/Aparajita/Desktop/FakeNews/"+file_name;
df = pd.read_csv(file_data, sep="\t", header=None, dtype=str)
#Renaming the column names:
## Changing names for consistency
col_names = list(df.iloc[0])
col_names[col_names.index('content')] = 'articleBody'
col_names[col_names.index('title')] = 'Headline'
df.columns = col_names
df=df.iloc[1:]
# Label to consider
reals = ['mediabiasfactcheck', 'alexa', 'vargo']
fakes =['mediabiasfactcheck', 'politifact', 'zimdars', 'min2', 'dailydot']
label_names = []
for i in reals:
for j in fakes:
label = i + '_' + j
label_names += [label]
real = i
fake = j
# Getting goroundtruth labels
df[label] = df.swifter.apply( get_labels, axis=1)
df[label] = pd.to_numeric(df[label], errors='ignore')
df = df[df[label] >= 0]
df['all_indices'] = np.nan
df['all_indices'] = df.swifter.apply( get_all_labels, axis=1) #df.columns.get_loc(df.columns[-1])
#Labels stored by considering all the fake and real categories
##############################################################
''' Processing begins here '''
##############################################################
#Running a simple bag of words model on the entire dataset
#Extracting entities and then running the same model
#Evaluaitng if the GloVe vecotrs can be useful? --> Checking how many words are out of vocabulary
# Runnning a basic BiLSTM model (check - what features were captured <iff good accuracy and auc is obtained>)
##############################################################
#
##Extracting entities
#df['entities_head'] = np.nan
#df['entities'] = np.nan
#for i in range(len(df)):
# print(i)
# try:
#
# # df['entities'].iloc[i] = get_entities(df['articleBody'].iloc[i])
# # df['entities_head'].iloc[i] = get_entities(df['Headline'].iloc[i])
# # except:
# # pdb.set_trace()
# #df['entities'] = df.swifter.apply( combine, axis=1)
# #df['entities_head'] = df.swifter.apply( combine, axis=1)
#
################################################################################################################
#### Loading vectorizers from the trained data00
with open('Pickled_data/bow_tfreq_tfidf', 'rb') as fil:
bow_vectorizer, tfreq_vectorizer, tfidf_vectorizer = pickle.load(fil)
lim_unigram = 2000
#test_head = df['entities_head'].tolist()
#test_bodies = df['entities'].tolist()
#test_label = df['all_indices'].tolist()
#
test_head = df['Headline'].tolist()
test_bodies = df['articleBody'].tolist()
test_label = df['all_indices'].tolist()
test_set = []
test_stances = []
id_ref = {}
actual_labels =[]
for i in range(len(test_bodies)):
head = test_head[i]
body_id = test_bodies[i]
head_bow = bow_vectorizer.transform([head]).toarray()
head_tf = tfreq_vectorizer.transform(head_bow).toarray()[0].reshape(1, -1)
head_tfidf = tfidf_vectorizer.transform([head]).toarray().reshape(1, -1)
body_bow = bow_vectorizer.transform([body_id]).toarray()
body_tf = tfreq_vectorizer.transform(body_bow).toarray()[0].reshape(1, -1)
body_tfidf = tfidf_vectorizer.transform([body_id]).toarray().reshape(1, -1)
tfidf_cos = cosine_similarity(head_tfidf, body_tfidf)[0].reshape(1, 1)
feat_vec = np.squeeze(np.c_[head_tf, body_tf, tfidf_cos])
test_set.append(feat_vec)
actual_labels.append(test_label[i])
pdb.set_trace()
with open('Pickled_data/testing_file_everything_without', 'wb') as wr:
pickle.dump([test_set, actual_labels, label_names], wr)
if __name__ == '__main__':
main()
| 838847824b9b4a5137d5f6e88aa3bc7809e2e5b4 | [
"Markdown",
"Python"
] | 4 | Markdown | aparajita15/Preliminary_Fake_News_Analysis | 9c85206a798ea0936dce9dcd810452c7f9f6ce26 | 749e558f3038edab7a27ba9de58ef782e0130b2c |
refs/heads/master | <file_sep>package konox.di_evaluacioninicial;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public mainController Controller;
public Button btnCambiarImg;
public Button btnCambiarColor;
public Button btnOcultar;
public Button btnEliminarImg;
public Button btnCambiarTxt;
public Button btnMostrar;
public Button btnFinalizar;;
public TextView txtTitle;
public ImageView imgView;
public RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Controller = new mainController(this);
btnCambiarImg=(Button) this.findViewById(R.id.btCambiarImg);
btnCambiarColor=(Button) this.findViewById(R.id.btCambiarCLR);
btnOcultar=(Button) this.findViewById(R.id.bt_Ocul);
btnEliminarImg=(Button) this.findViewById(R.id.btDelImg);
btnCambiarTxt=(Button) this.findViewById(R.id.btCambiarTxt);
btnMostrar=(Button) this.findViewById(R.id.btMostar);
btnFinalizar=(Button) this.findViewById(R.id.btFinalizar);
txtTitle=(TextView) this.findViewById(R.id.textView_Title);
imgView = (ImageView) this.findViewById(R.id.imgView);
relativeLayout = (RelativeLayout) this.findViewById(R.id.activity_main);
btnCambiarColor.setOnClickListener(Controller);
btnOcultar.setOnClickListener(Controller);
btnCambiarImg.setOnClickListener(Controller);
btnFinalizar.setOnClickListener(Controller);
}
}
| e3f4e09ee58fdd85c5cc4e51e3a353ac8de9cd87 | [
"Java"
] | 1 | Java | konox95/DI_Ev0 | 6a8cb5cc0affa701afb5a6bdbf7b6c7fe3c93c40 | 23ac77f1c7e280b4bc70f1ff722ee2b4d570821c |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using DataAccess.Model;
using DataAccess.SearchModel;
using FarmFresh.DBContext;
using FarmFresh.Repo;
using PagedList;
namespace DataAccess.DA
{
public class DA_Product
{
public List<Product> GetAllProducts()
{
List<Product> lst = new List<Product>();
try
{
FarmFreshDBContext ctx = new FarmFreshDBContext();
ProductRepository uirepo = new ProductRepository(ctx);
IQueryable<Product> dbList = uirepo.GetDataSet().Where(a => a.Status == 1).AsQueryable();
lst = dbList.ToList();
ctx.Dispose();
}
catch (Exception e)
{
string error = e.Message;
}
return lst;
}
public List<Product> GetProductsAdmin(SM_Product searchData)
{
List<Product> list = this.GetAllProducts();
list = list.Where(a => (searchData.ProductType != null) ? a.ProductType == searchData.ProductType : true).ToList();
list = list.ToPagedList(searchData.CurrentPage++, CommonClass.PageSize).ToList();
return list;
}
public int Count_GetProductsAdmin(SM_Product searchData)
{
int Count = 0;
List<Product> list = this.GetAllProducts();
list = list.Where(a => (searchData.ProductType != null) ? a.ProductType == searchData.ProductType : true).ToList();
Count = list.Count;
return Count;
}
public List<Product> GetProducts_ByProductType(SM_Search searchData)
{
List<Product> list = this.GetAllProducts();
list = list.Where(a => (searchData.SerachType != null) ? a.ProductType == searchData.SerachType : true).ToList();
list = list.ToPagedList(searchData.CurrentPage++, CommonClass.PageSize).ToList();
return list;
}
public int Count_GetProducts_ByProductType(SM_Search searchData)
{
int Count = 0;
List<Product> list = this.GetAllProducts();
list = list.Where(a => (searchData.SerachType != null) ? a.ProductType == searchData.SerachType : true).ToList();
Count = list.Count;
return Count;
}
public List<Product> GetProducts_ByOnSale(SM_Search searchData)
{
List<Product> list = this.GetAllProducts();
list = list.Where(a => a.OnSale == true).ToList();
list = list.ToPagedList(searchData.CurrentPage++, CommonClass.PageSize).ToList();
return list;
}
public int Count_GetProducts_ByOnSale(SM_Search searchData)
{
int Count = 0;
List<Product> list = this.GetAllProducts();
list = list.Where(a => a.OnSale == true).ToList();
Count = list.Count;
return Count;
}
public List<Product> GetProducts_ByShopByStore(SM_Search searchData)
{
List<Product> list = this.GetAllProducts();
list = list.Where(a => a.ShopByStore == true).ToList();
list = list.ToPagedList(searchData.CurrentPage++, CommonClass.PageSize).ToList();
return list;
}
public int Count_GetProducts_ByShopByStore(SM_Search searchData)
{
int Count = 0;
List<Product> list = this.GetAllProducts();
list = list.Where(a => a.ShopByStore == true).ToList();
Count = list.Count;
return Count;
}
public List<Product> GetProducts_ByNew(SM_Search searchData)
{
List<Product> list = this.GetAllProducts();
string FromDate = DateTime.Now.AddDays(-7).ToString();
string ToDate = DateTime.Now.ToString();
list = list.Where(a => DateTime.Parse(Convert.ToDateTime(a.CreatedDate).ToString("yyyy-MM-dd")) >= DateTime.Parse(Convert.ToDateTime(FromDate).ToString("yyyy-MM-dd"))
&& DateTime.Parse(Convert.ToDateTime(a.CreatedDate).ToString("yyyy-MM-dd")) <= DateTime.Parse(Convert.ToDateTime(ToDate).ToString("yyyy-MM-dd"))).ToList();
list = list.ToPagedList(searchData.CurrentPage++, CommonClass.PageSize).ToList();
return list;
}
public int Count_GetProducts_ByNew(SM_Search searchData)
{
int Count = 0;
string FromDate = DateTime.Now.AddDays(-7).ToString();
string ToDate = DateTime.Now.ToString();
List<Product> list = this.GetAllProducts();
list = list.Where(a => DateTime.Parse(Convert.ToDateTime(a.CreatedDate).ToString("yyyy-MM-dd")) >= DateTime.Parse(Convert.ToDateTime(FromDate).ToString("yyyy-MM-dd"))
&& DateTime.Parse(Convert.ToDateTime(a.CreatedDate).ToString("yyyy-MM-dd")) <= DateTime.Parse(Convert.ToDateTime(ToDate).ToString("yyyy-MM-dd"))).ToList();
Count = list.Count;
return Count;
}
public List<Product> GetProducts_ByAllPossibleSearch(string searchData)
{
searchData = searchData.ToLower().Replace(" ", "");
List<Product> returnList = new List<Product>();
List<Product> list = this.GetAllProducts();
returnList.AddRange(list.Where(a => a.ProductName.ToLower().Contains(searchData)).ToList());
//returnList.AddRange(list.Where(a => searchData.Contains(a.ProductName)).ToList());
returnList.AddRange(list.Where(a => a.ProductType.ToLower().Contains(searchData)).ToList());
//returnList.AddRange(list.Where(a => searchData.Contains(a.ProductType)).ToList());
returnList.AddRange(list.Where(a => a.PackingType.ToLower().Contains(searchData)).ToList());
//returnList.AddRange(list.Where(a => searchData.Contains(a.PackingType)).ToList());
string onsale = "onsale";
string shopbystore = "shopbystore";
string newitem = "new";
string all = "all";
if (onsale.Contains(searchData))
{
returnList.AddRange(list.Where(a => a.OnSale).ToList());
}
if (shopbystore.Contains(searchData))
{
returnList.AddRange(list.Where(a => a.ShopByStore).ToList());
}
if (newitem.Contains(searchData))
{
string FromDate = DateTime.Now.AddDays(-7).ToString();
string ToDate = DateTime.Now.ToString();
returnList.AddRange(list.Where(a => DateTime.Parse(Convert.ToDateTime(a.CreatedDate).ToString("yyyy-MM-dd")) >= DateTime.Parse(Convert.ToDateTime(FromDate).ToString("yyyy-MM-dd"))
&& DateTime.Parse(Convert.ToDateTime(a.CreatedDate).ToString("yyyy-MM-dd")) <= DateTime.Parse(Convert.ToDateTime(ToDate).ToString("yyyy-MM-dd"))).ToList());
}
if (all.Contains(searchData))
{
returnList.AddRange(list);
}
return returnList;
}
public bool AddProduct(Product data)
{
bool added = false;
FarmFreshDBContext ctx = new FarmFreshDBContext();
ProductRepository uirepo = new ProductRepository(ctx);
try
{
data.Status = 1;
uirepo.Add(data);
added = true;
}
catch (Exception e)
{
string error = e.Message;
added = false;
}
finally
{
ctx.Dispose();
}
return added;
}
public bool UpdateProduct(Product data)
{
bool updated = false;
FarmFreshDBContext ctx = new FarmFreshDBContext();
ProductRepository uirepo = new ProductRepository(ctx);
try
{
uirepo.update(data);
updated = true;
}
catch (Exception e)
{
string error = e.Message;
updated = false;
}
finally
{
ctx.Dispose();
}
return updated;
}
public Product GetProductByGUID(string GUID)
{
Product mdl = new Product();
FarmFreshDBContext ctx = new FarmFreshDBContext();
ProductRepository uirepo = new ProductRepository(ctx);
mdl = uirepo.Get(GUID);
return mdl;
}
public bool DeleteProduct(string GUID)
{
bool deleted = false;
FarmFreshDBContext ctx = new FarmFreshDBContext();
ProductRepository uirepo = new ProductRepository(ctx);
try
{
Product mdl = new Product();
mdl = GetProductByGUID(GUID);
mdl.Status = 0;
uirepo.update(mdl);
deleted = true;
}
catch (Exception e)
{
string error = e.Message;
deleted = false;
}
finally
{
ctx.Dispose();
}
return deleted;
}
}
}
<file_sep>using DataAccess;
using DataAccess.DA;
using DataAccess.Model;
using DataAccess.SearchModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace FarmFresh.Controllers
{
public class AdminController : Controller
{
DA_Product da = new DA_Product();
CommonClass cs = new CommonClass();
// GET: Admin
public ActionResult ProductListAdmin(SM_Product data)
{
List<ProductType> lst = cs.ProductTypeList();
lst.Add(new ProductType { Value = "all", ProductTypeName = "All" });
ViewBag.ProductTypeList = lst.OrderBy(a => a.ProductTypeName);
ViewBag.PackingType = cs.PackingType();
data.ProductType = null;
data.TotalPage = cs.TotalPage(da.Count_GetProductsAdmin(data));
data.TotalCount = da.Count_GetProductsAdmin(data);
data.CurrentPage = 1;
return View(data);
}
public ActionResult ProductListAdminPartial(string getpassdata)
{
List<Product> list = new List<Product>();
if (!string.IsNullOrEmpty(getpassdata))
{
var serializeData = JsonConvert.DeserializeObject<SM_Product>(getpassdata);
if (serializeData.ProductType == "all")
serializeData.ProductType = null;
list = da.GetProductsAdmin(serializeData);
ViewBag.CurrentPagePartial = serializeData.CurrentPage - 1;
}
return PartialView("ProductListAdminPartial",list);
}
public ActionResult GetTotalPage(string getpassdata)
{
List<Product> list = new List<Product>();
int TotalPage = 0;
if (!string.IsNullOrEmpty(getpassdata))
{
var serializeData = JsonConvert.DeserializeObject<SM_Product>(getpassdata);
if (serializeData.ProductType == "all")
serializeData.ProductType = null;
TotalPage = cs.TotalPage(da.Count_GetProductsAdmin(serializeData));
}
return Json(TotalPage, JsonRequestBehavior.AllowGet);
}
public ActionResult EditProductForm(string GUID)
{
Product data = new Product();
ViewBag.ProductTypeList = cs.ProductTypeList();
ViewBag.PackingType = cs.PackingType();
if (!string.IsNullOrEmpty(GUID))
{
data = da.GetProductByGUID(GUID);
ViewBag.SelectedProductType = data.ProductType;
}
return PartialView("EditProductForm", data);
}
[HttpPost]
public async Task<JsonResult> UploadProductPhoto()
{
string fileName = string.Empty;
try
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs methodC:\Projects\Ant Tech\HIMS\HIMS\HIMS\UploadData\PatientPhoto\
file.SaveAs(Server.MapPath("~/ProductUploadPhotos/") + fileName); //File will be saved in application root
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Upload failed");
}
return Json(fileName);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult EditProduct(Product data)
{
data.ProductType = Request.Form["ProductType"];
data.PackingType = Request.Form["PackingType"];
if (!string.IsNullOrEmpty(data.GUID))
{
data.CreatedDate = DateTime.Now.ToString("dd/MM/yyyy hh:mm tt");
bool updated = da.UpdateProduct(data);
if (updated)
{
return Json("Success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("Fail", JsonRequestBehavior.AllowGet);
}
}
else
{
data.GUID = Guid.NewGuid().ToString();
data.CreatedDate = DateTime.Now.ToString("dd/MM/yyyy hh:mm tt");
data.Status = 1;
bool added = da.AddProduct(data);
if (added)
{
return Json("Success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("Fail", JsonRequestBehavior.AllowGet);
}
}
}
public JsonResult DeleteProduct(string GUID)
{
bool deleted = da.DeleteProduct(GUID);
if (deleted)
{
return Json("Success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("Fail", JsonRequestBehavior.AllowGet);
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.SearchModel
{
public class SM_Search
{
public string SerachType { get; set; }
public int TotalPage { get; set; }
public int CurrentPage { get; set; }
}
}
<file_sep>using DataAccess.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess
{
public class CommonClass
{
public static int PageSize = 8;
public static string NulltoEmptyString(string data)
{
if (string.IsNullOrEmpty(data))
data = "";
return data;
}
public int TotalPage(int totalCount)
{
int Total = 0;
Total = totalCount;
float Pages_Count = Total / PageSize;
float pages_count_mod = Total % PageSize;
if (pages_count_mod != 0)
{
Pages_Count++;
}
Total = Convert.ToInt32(Pages_Count);
return Total;
}
public List<string> PackingType()
{
List<string> lst = new List<string>();
lst.Add("Packet");
lst.Add("Box");
lst.Add("Bag");
return lst;
}
public List<ProductType> ProductTypeList()
{
List<ProductType> lst = new List<ProductType>();
lst.Add(new ProductType { Value = "fruitandveg", ProductTypeName = "Fruit & veg" });
lst.Add(new ProductType { Value = "meatandseafood", ProductTypeName = "Meat & Seafood" });
lst.Add(new ProductType { Value = "dairyandchilled", ProductTypeName = "Dairy and Chilled" });
lst.Add(new ProductType { Value = "bakery", ProductTypeName = "Bakery" });
lst.Add(new ProductType { Value = "beverages", ProductTypeName = "Beverages" });
return lst;
}
public static List<ProductType> ProductTypeListStatic()
{
List<ProductType> lst = new List<ProductType>();
lst.Add(new ProductType { Value = "fruitandveg", ProductTypeName = "Fruit & veg" });
lst.Add(new ProductType { Value = "meatandseafood", ProductTypeName = "Meat & Seafood" });
lst.Add(new ProductType { Value = "dairyandchilled", ProductTypeName = "Dairy and Chilled" });
lst.Add(new ProductType { Value = "bakery", ProductTypeName = "Bakery" });
lst.Add(new ProductType { Value = "beverages", ProductTypeName = "Beverages" });
return lst;
}
}
}
<file_sep># FarmFresh
## Project Scope and Usage Guide
### 1.FarmFresh (Asp.net MVC) (Front-End)
- Search Bar function will work for all types of searching (Product Name(eg.Fish,cake), Product Type(eg.Fruit,Meat,Beverages), On Sale, Shop By Store).

- Categorize Product list can be reach by clickling on the shopping cart.


- Product Detail can be view by clicking on the product photo.

- AdminDashboard for managing product can be found under (YourHost)/Admin/ProductListAdmin where you can add new products, edit their details and type.


- I had used Ajax funtions call for all kind of request(Search, Paging, TabChange).
### 2.DataAccess (Class Library)
- I had used Entity Framework (Code First) with generic repository pattern for data access layer.
- All Pagination are server side only since I fetch only 8 rows and fetching consecutive only on clicking the next paging and u can check it in the codes too.
- Instead of using API, I just used this DataAcess Layer within the Same Project and directly called from the controller.
- The database backup file was also in the project file and u can find it as farmfresk.bak.
<file_sep>using DataAccess.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace FarmFresh.DBContext
{
public class FarmFreshDBContext : DbContext
{
static FarmFreshDBContext()
{
Database.SetInitializer<FarmFreshDBContext>(null);
}
public FarmFreshDBContext() :base("Name=myconnection")
{ }
public DbSet<Product> ProductSet { get; set; }
/*public DbSet<Test> TestSet { get; set; }*/
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Product>().HasKey<int>(e => e.ID);
}
}
}<file_sep>using DataAccess.Model;
using FarmFresh.DBContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FarmFresh.Repo
{
public class ProductRepository : DataRepositoryBase<Product>
{
public FarmFreshDBContext _context;
public ProductRepository(FarmFreshDBContext context)
{
_context = context;
}
public ProductRepository()
{
}
protected override Product AddEntity(FarmFreshDBContext entityContext, Product entity)
{
return entityContext.ProductSet.Add(entity);
}
protected override Product UpdateEntity(FarmFreshDBContext entityContext, Product entity)
{
return entityContext.ProductSet.FirstOrDefault(a => a.ID == entity.ID);
}
protected override IQueryable<Product> GetEntities(FarmFreshDBContext entityContext)
{
return entityContext.ProductSet;
}
protected override IQueryable<Product> GetEntitiesWithoutTracking(FarmFreshDBContext entityContext)
{
return entityContext.ProductSet.AsNoTracking();
}
protected override IQueryable<Product> GetEntitiesWithoutTracking()
{
return _context.ProductSet.AsNoTracking();
}
protected override IQueryable<Product> GetQueryable()
{
return _context.ProductSet;
}
// Was faked with Count due to issure with GUID
protected override Product GetEntity(FarmFreshDBContext entityContext, int id)
{
return entityContext.ProductSet.FirstOrDefault(a => a.ID == id);
}
protected override Product GetEntity(FarmFreshDBContext entityContext, string GUID)
{
return entityContext.ProductSet.FirstOrDefault(a => a.GUID == GUID);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess.Model;
using DataAccess.DA;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using DataAccess.Model;
namespace FarmFresh.Controllers
{
public class CommonController : Controller
{
// GET: Common
public ActionResult Pagination(int Page, int Count)
{
ViewBag.Page = Page;
ViewBag.Count = Count;
return PartialView();
}
[HttpPost]
public JsonResult GetProductName(string Prefix)
{
//Note : you can bind same list from database
List<Product> ObjList = new List<Product>();
DA_Product daMT = new DA_Product();
ObjList = daMT.GetAllProducts();
//Searching records from list using LINQ query
var CityList = (from N in ObjList
where N.ProductName.ToLower().Contains(Prefix.ToLower())
select new { N.ProductName, N.ID });
return Json(CityList, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.SearchModel
{
public class SM_Product
{
public int ProductID { get; set; }
public string GUID { get; set; }
public string ProductName { get; set; }
public string ProductPhoto { get; set; }
public string ProductType { get; set; }
public string PackingType { get; set; }
public string OnSale { get; set; }
public string ShopByStore { get; set; }
public int TotalCount { get; set; }
public int TotalPage { get; set; }
public int CurrentPage { get; set; }
}
}
<file_sep>using DataAccess.Model;
using DataAccess.SearchModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess.DA;
using DataAccess;
namespace FarmFresh.Controllers
{
public class ProductController : Controller
{
DA_Product da = new DA_Product();
CommonClass cs = new CommonClass();
// GET: Product
public ActionResult ProductList()
{
return View();
}
public ActionResult ProductListPartial(string getpassdata)
{
List<Product> list = new List<Product>();
if (!string.IsNullOrEmpty(getpassdata))
{
var serializeData = JsonConvert.DeserializeObject<SM_Search>(getpassdata);
if (serializeData.SerachType == "onsale")
{
list = da.GetProducts_ByOnSale(serializeData);
ViewBag.TotalPagePartial = cs.TotalPage(da.Count_GetProducts_ByOnSale(serializeData));
}
else if (serializeData.SerachType == "new")
{
list = da.GetProducts_ByNew(serializeData);
ViewBag.TotalPagePartial = cs.TotalPage(da.Count_GetProducts_ByNew(serializeData));
}
else if (serializeData.SerachType == "shopbystore")
{
list = da.GetProducts_ByShopByStore(serializeData);
ViewBag.TotalPagePartial = cs.TotalPage(da.Count_GetProducts_ByShopByStore(serializeData));
}
else
{
list = da.GetProducts_ByProductType(serializeData);
ViewBag.TotalPagePartial = cs.TotalPage(da.Count_GetProducts_ByProductType(serializeData));
}
ViewBag.CurrentPagePartial = serializeData.CurrentPage - 1;
}
return PartialView("ProductListPartial", list);
}
public ActionResult ProductDetail(string GUID)
{
Product modal = da.GetProductByGUID(GUID);
return PartialView("ProductDetail", modal);
}
public ActionResult SearchMain(string getpassdata)
{
List<Product> list = new List<Product>();
if (!string.IsNullOrEmpty(getpassdata))
{
list = da.GetProducts_ByAllPossibleSearch(getpassdata);
}
return PartialView("SearchMain", list);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Model
{
public class Product
{
public int ID { get; set; }
public string GUID { get; set; }
public string ProductName { get; set; }
public string ProductPhoto { get; set; }
public string ProductType { get; set; }
public string PackingType { get; set; }
public bool OnSale { get; set; }
public bool ShopByStore { get; set; }
public string CreatedDate { get; set; }
public int Status { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using DataAccess.Model;
using FarmFresh.DBContext;
using FarmFresh.Utils;
namespace FarmFresh.Repo
{
public abstract class DataRepositoryBase<T> where T : class, new()
{
protected abstract T AddEntity(FarmFreshDBContext entityContext, T entity);
protected abstract T UpdateEntity(FarmFreshDBContext entityContext, T entity);
protected abstract IQueryable<T> GetEntities(FarmFreshDBContext entityContext);
protected abstract IQueryable<T> GetEntitiesWithoutTracking(FarmFreshDBContext entityContext);
protected abstract IQueryable<T> GetEntitiesWithoutTracking();
protected abstract IQueryable<T> GetQueryable();
protected abstract T GetEntity(FarmFreshDBContext entityContext, int id);
protected abstract T GetEntity(FarmFreshDBContext entityContext, string GUID);
public T Add(T entity)
{
try
{
using (FarmFreshDBContext entityContext = new FarmFreshDBContext())
{
T addedEntity = AddEntity(entityContext, entity);
entityContext.SaveChanges();
return addedEntity;
}
}
catch(Exception ex)
{
return null;
}
}
public void Remove(T entity)
{
using(FarmFreshDBContext entityContext = new FarmFreshDBContext())
{
entityContext.Entry<T>(entity).State = EntityState.Deleted;
entityContext.SaveChanges();
}
}
public void Remove(int id)
{
using(FarmFreshDBContext entityContext = new FarmFreshDBContext())
{
T entity = GetEntity(entityContext, id);
entityContext.Entry<T>(entity).State = EntityState.Deleted;
entityContext.SaveChanges();
}
}
public T update(T entity)
{
using(FarmFreshDBContext entityContext = new FarmFreshDBContext())
{
T existingEntity = UpdateEntity(entityContext, entity);
SimpleMapper.PropertyMap(entity, existingEntity);
entityContext.SaveChanges();
return existingEntity;
}
}
public IEnumerable<T> Get()
{
using (FarmFreshDBContext entityContext = new FarmFreshDBContext())
{
//return (GetEntities(entityContext).ToArray().AsEnumerable());
return (GetEntities(entityContext).AsEnumerable());
}
}
public IQueryable<T> Get(FarmFreshDBContext entityContext)
{
//return (GetEntities(entityContext).ToArray().AsEnumerable());
return (GetEntities(entityContext));
}
//public IQueryable<T> GetWithoutTracking()
//{
// //return (GetEntities(entityContext).ToArray().AsEnumerable());
// return (GetEntitiesWithoutTracking(Context entityContext));
//}
public T Get(int id)
{
using(FarmFreshDBContext entityContext = new FarmFreshDBContext())
{
return GetEntity(entityContext, id);
}
}
public T Get(string GUID)
{
using (FarmFreshDBContext entityContext = new FarmFreshDBContext())
{
return GetEntity(entityContext, GUID);
}
}
public IQueryable<T> GetDataSet()
{
return (GetQueryable()).AsQueryable();
}
public IQueryable<T> GetDataSetWithoutTracking()
{
return (GetEntitiesWithoutTracking()).AsQueryable();
}
}
} | 0a9abc4e2144c4ac6b00ddde051b129087e85556 | [
"Markdown",
"C#"
] | 12 | C# | ArunAron/FarmFresh | af9c354cfb47b66f54d98e7ae23dc95c5a3df7c4 | 8ce54eb9cc28eae71a0bc4f8c002551cb1152169 |
refs/heads/master | <file_sep>FactoryBot.define do
factory :exchange_rate do
from_currency_id { 1 }
to_currency_id { 1 }
rate { "9.99" }
from_date { "2021-04-30 04:47:29" }
end
end
<file_sep>require 'jwt'
class JsonWebToken
class << self
SECRET_KEY = Rails.application.credentials.secret_key_base
def encode(payload)
payload.reverse_merge!(meta)
JWT.encode(payload, SECRET_KEY)
end
def decode(token)
JWT.decode(token, SECRET_KEY).first
end
def meta
{ exp: 7.days.from_now.to_i }
end
end
end
<file_sep>class ApplicationController < ActionController::API
before_action :check_api_key
def not_found
render json: { error: 'not_found' }
end
def check_api_key
header = request.headers['api-key']
header = header.split(' ').last if header
if header != ENV['API_KEY']
render json: { error: "incorrect api key" }, status: :unauthorized
end
end
end
<file_sep>class Api::V1::ExchangeRatesController < ApplicationController
before_action :set_exchange_rate, only: [:show, :update, :destroy]
# GET /exchange_rates/base/:base/to/:to
def get_rates
@euro_currency = Currency.find_by(code: "EUR")
@base_currency = Currency.find_by(code: params[:base])
@to_currency = Currency.find_by(code: params[:to])
@base_exchange_rates = ExchangeRate.select("rate, from_date").where(
base_currency_id: @euro_currency.id,
to_currency_id: @base_currency.id,
).order(:from_date)
@to_exchange_rates = ExchangeRate.select("rate, from_date").where(
base_currency_id: @euro_currency.id,
to_currency_id: @to_currency.id,
).order(:from_date)
@exchange_rates = []
if @base_exchange_rates.size == @to_exchange_rates.size
@base_exchange_rates.zip(@to_exchange_rates).each do |base, to|
@exchange_rates << {
"rate": (to.rate/base.rate).round(2),
"from_date": base.from_date
}
end
end
render json: @exchange_rates
end
# GET /exchange_rates/base/:base/to/:to/at/:date
def get_rate_for_date
@euro_currency = Currency.find_by(code: "EUR")
@base_currency = Currency.find_by(code: params[:base])
@to_currency = Currency.find_by(code: params[:to])
@base_exchange_rate = ExchangeRate.select("rate, from_date").find_by(
base_currency_id: @euro_currency.id,
to_currency_id: @base_currency.id,
from_date: params[:date].to_datetime
)
@to_exchange_rate = ExchangeRate.select("rate, from_date").find_by(
base_currency_id: @euro_currency.id,
to_currency_id: @to_currency.id,
from_date: params[:date].to_datetime
)
rate = @to_exchange_rate.rate/@base_exchange_rate.rate
@exchange_rate = {
"rate": rate.round(2),
"from_date": @to_exchange_rate.from_date
}
render json: @exchange_rate
end
# GET /exchange_rates/base/:base/to/:to/from_date/:from_date/to_date/:to_date
def get_rate_for_date_range
@euro_currency = Currency.find_by(code: "EUR")
@base_currency = Currency.find_by(code: params[:base])
@to_currency = Currency.find_by(code: params[:to])
@base_exchange_rates = ExchangeRate.select("rate, from_date").where(
base_currency_id: @euro_currency.id,
to_currency_id: @base_currency.id,
from_date: params[:from_date].to_datetime..params[:to_date].to_datetime,
).order(:from_date)
@to_exchange_rates = ExchangeRate.select("rate, from_date").where(
base_currency_id: @euro_currency.id,
to_currency_id: @to_currency.id,
from_date: params[:from_date].to_datetime..params[:to_date].to_datetime,
).order(:from_date)
@exchange_rates = []
if @base_exchange_rates.size == @to_exchange_rates.size
@base_exchange_rates.zip(@to_exchange_rates).each do |base, to|
@exchange_rates << {
"rate": (to.rate/base.rate).round(2),
"from_date": base.from_date
}
end
end
render json: @exchange_rates
end
# POST /exchange_rates
def create
start_date = Date.parse('2020-05-02')
end_date = Date.parse('2020-05-04')
(start_date..end_date).each do |day|
exchange_rate = JSON.parse(RestClient.get "http://data.fixer.io/api/#{day.strftime("%Y-%m-%d")}?access_key=84c960ca7f193d2306f7ac23196f9db9")
exchange_rate["rates"].each_with_index do |rate, index|
@new_exchange_rate = ExchangeRate.new
@new_exchange_rate.base_currency = Currency.find_by(code: exchange_rate["base"])
@new_exchange_rate.to_currency = Currency.find_by(code: rate[0])
@new_exchange_rate.from_date = exchange_rate["date"].to_datetime
@new_exchange_rate.rate = rate[1]
if @new_exchange_rate.save
else
render json: @new_exchange_rate.errors, status: :unprocessable_entity
end
end
end
end
# PATCH/PUT /exchange_rates/1
def update
end
# DELETE /exchange_rates/1
def destroy
@exchange_rate.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_exchange_rate
@exchange_rate = ExchangeRate.find(params[:id])
end
end
<file_sep>require 'json_web_token'
class AuthenticateUser
prepend SimpleCommand
attr_accessor :email, :password
def initialize(email, password)
@email = email
@password = <PASSWORD>
end
def call
return unless user
JsonWebToken.encode(user_id: user.id)
end
private
def user
current_user = User.find_by(email: email)
return current_user if current_user&.authenticate(password)
errors.add(:user_authentication, 'Invalid credentials')
end
end
<file_sep>FactoryBot.define do
factory :currency do
name { "MyString" }
symbol { "MyString" }
code { "MyString" }
country { "MyString" }
flag { "MyString" }
end
end
<file_sep>Rails.application.routes.draw do
namespace :api do
namespace :v1 do
#exchange rates
get 'exchange_rates', to: 'exchange_rates#index'
get 'exchange_rates/base/:base/to/:to', to: 'exchange_rates#get_rates'
get 'exchange_rates/base/:base/to/:to/at/:date', to: 'exchange_rates#get_rate_for_date'
get 'exchange_rates/base/:base/to/:to/from_date/:from_date/to_date/:to_date', to: 'exchange_rates#get_rate_for_date_range'
post 'exchange_rates', to: 'exchange_rates#create'
delete 'exchange_rates/:id', to: 'exchange_rates#destroy'
#currencies
get 'currencies', to: 'currencies#index'
end
end
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# Seeding Currencies
require 'json'
path = Rails.root.join('app', 'assets','currencies.json')
currencies = JSON.parse(File.read(path))
currencies["currencies"].each do |currency|
Currency.create(currency)
end
<file_sep>class ExchangeRate < ApplicationRecord
belongs_to :base_currency, class_name: "Currency", foreign_key: :base_currency_id
belongs_to :to_currency, class_name: "Currency", foreign_key: :to_currency_id
validates :from_date, uniqueness: { scope: :to_currency,
message: "should have only one rate per day" }
end
<file_sep>class Currency < ApplicationRecord
has_many :base_exchange_rates, class_name: "ExchangeRate", foreign_key: :base_currency_id
has_many :to_exchange_rates, class_name: "ExchangeRate", foreign_key: :to_currency_id
end
| 2958c237f70d52502be12ee21bda7502d745be0b | [
"Ruby"
] | 10 | Ruby | davichaves/monetae-api | 3892575172014a4a572bf43a483ba4748ad05778 | 48581ef6c4204761e1a92d6fe3f38bb748da6d5b |
refs/heads/master | <repo_name>diego1504/AluraGit<file_sep>/src/br/com/bytebank/banco/teste/TesteTributaveis.java
package br.com.bytebank.banco.teste;
import br.com.bytebank.banco.modelo.CalculadorDeImposto;
import br.com.bytebank.banco.modelo.ContaCorrente;
import br.com.bytebank.banco.modelo.SeguroDeVida;
/**
* Esta é uma classe teste desenvolvida para fins didaticos
*
* @version 1.0
* @author <NAME>
*@category aprendizado
*/
public class TesteTributaveis {
public static void main(String[] args) {
ContaCorrente cc= new ContaCorrente(222, 333);
cc.deposita(100.0);
// System.out.println(calc.getTotalImposto());
}
}
| 94cfaecd3dc8826b2b18edb15bc6a5a98e97f745 | [
"Java"
] | 1 | Java | diego1504/AluraGit | b8ffbe92c271b50246a76bfb9ca9c603760ef9b2 | 0f68909f8fb7ab5706397cfca99d4f47efabb98c |
refs/heads/master | <repo_name>williamshiwenhao/jpeg_coder<file_sep>/bmp.h
#ifndef __BMP_H__
#define __BMP_H__
#include <cstdio>
#include "types.h"
namespace bmp {
Img<Rgb> ReadBmp(const char* fileName);
int WriteBmp(const char* fileName, Img<Rgb>);
};//namespace bmp
#endif /*__BMP_H__*/<file_sep>/dct.cpp
#include <cmath>
#include <vector>
#include "utilities.h"
#include "jpeg.h"
namespace jpeg {
void DCTCore(double *);
void IDCTCore(double *);
void FDCTRaw(Block<double> & block, void(*core)(double*));
ImgBlock<double> JpegCoder::FDCT(ImgBlock<double> block) {
for (auto &b : block.data) {
FDCTRaw(b, DCTCore);
}
return block;
}
ImgBlock<double> JpegCoder::FIDCT(ImgBlock<double> block) {
for (auto &b : block.data) {
FDCTRaw(b, IDCTCore);
}
return block;
}
void FDCTRaw(Block<double> & block, void(*core)(double*)) {
double res[8];
//line
double* ptr[] = { block.y, block.u, block.v };
for (int color = 0; color < 3; ++color) {
for (int x = 0; x < 8; ++x) {
for (int y = 0; y < 8; ++y) {
int idx = y * 8 + x;
res[y] = ptr[color][idx];
}
core(res);
for (int y = 0; y < 8; ++y) {
int idx = y * 8 + x;
ptr[color][idx] = res[y];
}
}
for (int y = 0; y < 8; ++y) {
for (int x = 0; x < 8; ++x) {
int idx = y * 8 + x;
res[x] = ptr[color][idx];
}
core(res);
for (int x = 0; x < 8; ++x) {
int idx = y * 8 + x;
ptr[color][idx] = res[x];
}
}
}
}
static const double S[] = {
0.353553390593273762200422,
0.254897789552079584470970,
0.270598050073098492199862,
0.300672443467522640271861,
0.353553390593273762200422,
0.449988111568207852319255,
0.653281482438188263928322,
1.281457723870753089398043,
};
static const double A[] = {
NAN,
0.707106781186547524400844,
0.541196100146196984399723,
0.707106781186547524400844,
1.306562964876376527856643,
0.382683432365089771728460,
};
// DCT AAN
void DCTCore(double *vector) {
const double v0 = vector[0] + vector[7];
const double v1 = vector[1] + vector[6];
const double v2 = vector[2] + vector[5];
const double v3 = vector[3] + vector[4];
const double v4 = vector[3] - vector[4];
const double v5 = vector[2] - vector[5];
const double v6 = vector[1] - vector[6];
const double v7 = vector[0] - vector[7];
const double v8 = v0 + v3;
const double v9 = v1 + v2;
const double v10 = v1 - v2;
const double v11 = v0 - v3;
const double v12 = -v4 - v5;
const double v13 = (v5 + v6) * A[3];
const double v14 = v6 + v7;
const double v15 = v8 + v9;
const double v16 = v8 - v9;
const double v17 = (v10 + v11) * A[1];
const double v18 = (v12 + v14) * A[5];
const double v19 = -v12 * A[2] - v18;
const double v20 = v14 * A[4] - v18;
const double v21 = v17 + v11;
const double v22 = v11 - v17;
const double v23 = v13 + v7;
const double v24 = v7 - v13;
const double v25 = v19 + v24;
const double v26 = v23 + v20;
const double v27 = v23 - v20;
const double v28 = v24 - v19;
vector[0] = S[0] * v15;
vector[1] = S[1] * v26;
vector[2] = S[2] * v21;
vector[3] = S[3] * v28;
vector[4] = S[4] * v16;
vector[5] = S[5] * v25;
vector[6] = S[6] * v22;
vector[7] = S[7] * v27;
}
// A straightforward inverse of the forward algorithm.
void IDCTCore(double *vector) {
const double v15 = vector[0] / S[0];
const double v26 = vector[1] / S[1];
const double v21 = vector[2] / S[2];
const double v28 = vector[3] / S[3];
const double v16 = vector[4] / S[4];
const double v25 = vector[5] / S[5];
const double v22 = vector[6] / S[6];
const double v27 = vector[7] / S[7];
const double v19 = (v25 - v28) / 2;
const double v20 = (v26 - v27) / 2;
const double v23 = (v26 + v27) / 2;
const double v24 = (v25 + v28) / 2;
const double v7 = (v23 + v24) / 2;
const double v11 = (v21 + v22) / 2;
const double v13 = (v23 - v24) / 2;
const double v17 = (v21 - v22) / 2;
const double v8 = (v15 + v16) / 2;
const double v9 = (v15 - v16) / 2;
const double v18 = (v19 - v20) * A[5]; // Different from original
const double v12 = (v19 * A[4] - v18) / (A[2] * A[5] - A[2] * A[4] - A[4] * A[5]);
const double v14 = (v18 - v20 * A[2]) / (A[2] * A[5] - A[2] * A[4] - A[4] * A[5]);
const double v6 = v14 - v7;
const double v5 = v13 / A[3] - v6;
const double v4 = -v5 - v12;
const double v10 = v17 / A[1] - v11;
const double v0 = (v8 + v11) / 2;
const double v1 = (v9 + v10) / 2;
const double v2 = (v9 - v10) / 2;
const double v3 = (v8 - v11) / 2;
vector[0] = (v0 + v7) / 2;
vector[1] = (v1 + v6) / 2;
vector[2] = (v2 + v5) / 2;
vector[3] = (v3 + v4) / 2;
vector[4] = (v3 - v4) / 2;
vector[5] = (v2 - v5) / 2;
vector[6] = (v1 - v6) / 2;
vector[7] = (v0 - v7) / 2;
}
};//namespace jpeg<file_sep>/main.cpp
#include <cstdio>
#include <string>
#include <fstream>
#include <cmath>
#include "bmp.h"
#include "types.h"
#include "jpeg.h"
using namespace std;
char encodeInput[] = "test2.bmp";
char encodeOutput[] = "test2.jpg";
char decodeInput[] = "PsResult.jpg";
char decodeOutput[] = "test1Decode.bmp";
void Encode(const char* name, int level = 0) {
Img<Rgb> img = bmp::ReadBmp(encodeInput);
jpeg::JpegCoder writer;
writer.Encode(img, level);
writer.Write(name);
}
void Decode() {
Img<Rgb> decode;
jpeg::JpegCoder reader;
reader.Read(decodeInput);
reader.Decode(decode);
bmp::WriteBmp(decodeOutput, decode);
}
int main()
{
string encodeNameBase{ "encode" };
for (int i = 0; i < 4; ++i) {
//level test
string name = encodeNameBase + to_string(i) + ".jpg";
Encode(name.c_str(), i);
}
Decode();
return 0;
}<file_sep>/jpeg.h
#pragma once
#ifndef __JPEG_H__
#define __JPEG_H__
#include <cmath>
#include <unordered_map>
#include <queue>
#include "bmp.h"
#include "types.h"
#include "utilities.h"
#include "huffman.h"
namespace jpeg
{
int *GetYTable(int level);
int *GetUvTable(int level);
class JpegCoder
{
public:
int Encode(const Img<Rgb> &s, int level);
int Decode(Img<Rgb> &t);
int Write(const char *fileName);
int Read(const char *fileName);
private:
/*Function*/
/*Write to file **********************************************************/
inline void Write16(uint16_t val)
{
uint8_t res;
res = (val >> 8) & 0xff;
data.push_back(res);
res = val & 0xff;
data.push_back(res);
}
inline uint16_t Read16(int idx)
{
uint16_t ans = 0;
uint16_t res1, res2;
res1 = data[idx];
res2 = data[idx + 1];
ans = (res1 << 8) | (res2 & 0xff);
return ans;
}
void EncodePicHead();
void EncodeQuantTable(int level = 0);
void EncodePicInfo(uint16_t w, uint16_t);
void EncodeHuffmanTable(const int *bitSize, const std::vector<int> &bitTable, bool isDc, uint8_t htid);
void EncodeImg(uint8_t *s, int length);
int DecodeQuantTable(int base, int length);
int DecodePicInfo(int base, int length, int &w, int &h);
int DecodeHuffmanTable(int base, int length);
int DecodeImg(int base, int length);
/*Encode and decode algorithm*/
ImgBlock<double> FDCT(ImgBlock<double>);
ImgBlock<double> FIDCT(ImgBlock<double>);
template <class T>
ImgBlock<int> Quant(T &block, int level = 0);
template <class T>
ImgBlock<double> Iquant(T &block);
template <class T>
void ZigZag(ImgBlock<T> &block);
template <class T>
void IZigZag(ImgBlock<T> &block);
ImgBlockCode RunLengthCode(const ImgBlock<int> &block);
ImgBlock<int> RunLengthDecode(const ImgBlockCode &code);
void BuildHuffman(ImgBlockCode &block);
int HuffmanEncode(ImgBlockCode &block, BitStream &stream);
int HuffmanDecode(ImgBlockCode &code);
Symbol GetVLI(int val);
int DeVLI(Symbol s);
/*Data*/
std::vector<BitStream> stream;
std::vector<uint8_t> data; //Encoded data, write to file or read from file
Huffman yDcHuff, yAcHuff, uvDcHuff, uvAcHuff; //4 Huffman table
Huffman dcHuff[4], acHuff[4];
std::vector<int> qTable[16]; //Quant table for decode, read from file. Not for encode!
std::vector<int> *pYTable, *pUvTable;
};
}; //namespace jpeg
#endif /*__JPEG_H__*/<file_sep>/jpeg.cpp
#include <cstdio>
#include <random>
#include <algorithm>
#include <string>
#include <fstream>
#include "jpeg.h"
#include "huffman.h"
#include "utilities.h"
#include "types.h"
namespace jpeg
{
static const int ZIGZAG[64] =
{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63 };
void BitStreamTest()
{
std::vector<int> ones;
for (int i = 0; i <= 16; ++i)
{
ones.push_back((1 << i) - 1);
}
BitStream stream;
const int TESTSIZE = 1 << 16;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> length(1, 16);
std::uniform_int_distribution<int> value(0, (1 << 16) - 1);
std::vector<Symbol> data;
printf("Adding\n");
for (int i = 0; i < TESTSIZE; ++i)
{
Symbol s;
s.length = length(gen);
s.val = value(gen) & ones[s.length];
data.push_back(s);
stream.Add(s);
}
printf("Getting\n");
for (int i = 0; i < TESTSIZE; ++i)
{
Symbol s;
s.length = data[i].length;
if (stream.Get(s))
{
fprintf(stderr, "Get error\n");
}
if (s.val != data[i].val)
{
fprintf(stderr, "%d Value not equal, original value = %x now value = %x\n", i + 1, data[i].val, s.val);
}
}
}
int JpegCoder::Encode(const ::Img<Rgb> &s, int level)
{
data.clear();
::Img<Yuv> imgy = ImgRgb2YCbCr(s);
ImgBlock<double> block = Img2Block(imgy);
ImgBlock<double> dct = FDCT(block);
ImgBlock<int> quant = Quant(dct, level);
ZigZag<int>(quant);
ImgBlockCode code = RunLengthCode(quant);
BitStream imgStream;
BuildHuffman(code);
if (HuffmanEncode(code, imgStream))
{
fprintf(stderr, "[Error] Huffman encode error\n");
return -1;
}
//Write
EncodePicHead();
EncodeQuantTable(level);
EncodePicInfo(s.w, s.h);
//Huffman table
Huffman *huff[] = { &yDcHuff, &yAcHuff, &uvDcHuff, &uvAcHuff };
bool isDc[] = { true, false, true, false };
uint8_t htid[] = { 0, 0, 1, 1 };
for (int tables = 0; tables < 4; ++tables)
{
const int *bitSize = huff[tables]->GetSize();
const std::vector<int> &bitTable = huff[tables]->GetTable();
EncodeHuffmanTable(bitSize, bitTable, isDc[tables], htid[tables]);
}
uint8_t *imgData = NULL;
int imgLength = imgStream.GetData(&imgData);
EncodeImg(imgData, imgLength);
return 0;
}
int JpegCoder::Decode(Img<Rgb> &t)
{
unsigned idx = 0;
int w = 0, h = 0;
/*Handle file***********************************************************************************/
bool isCommand = false; //Read 0xff
uint8_t command = 0;
bool finished = false;
while (idx < data.size() && !finished)
{
while (data[idx] == 0xff)
{
//read 0xff, prepare for command
isCommand = true;
idx++;
}
if (!isCommand && data[idx] != 0xff)
{
fprintf(stderr, "[Error] Decode error, Unexpected byte 0x%u at %d\n", data[idx], idx);
return -1;
}
command = data[idx];
isCommand = false;
//no length command
if (command == 0xd8 || command == 0xd9)
{
idx++;
continue;
//start of image and end of image
}
if (idx + 2 >= data.size())
{
fprintf(stderr, "[Error] Read error, need more bytes than read\n");
return -1;
}
int length = Read16(idx + 1); //Get segment length
if (idx + 1 + length >= data.size())
{ //Check data size
fprintf(stderr, "[Error] Read error, need more bytes than read\n");
return -1;
}
int returnVal = 0;
switch (command)
{
case 0xe0:
//picture head, not necessary for decode
break;
case 0xdb:
//Quantization table
returnVal = DecodeQuantTable(idx + 3, length - 2); //length should - 2bytes for length itself
break;
case 0xc0:
returnVal = DecodePicInfo(idx + 3, length - 2, w, h);
break;
case 0xc4:
//Huffman table
returnVal = DecodeHuffmanTable(idx + 3, length - 2);
break;
case 0xda:
//img table
returnVal = DecodeImg(idx + 3, length - 2);
finished = true;
break;
default:
//other unnecessary code
break;
}
if (returnVal != 0)
{
fprintf(stderr, "[Error] Decode error, exit\n");
return -1;
}
idx += length + 1;
}
/*Decode*******************************************************************************/
delete[] t.data;
int wb = w / 8 + ((w % 8 == 0) ? 0 : 1);
int hb = h / 8 + ((h % 8 == 0) ? 0 : 1);
ImgBlockCode decode;
decode.w = w;
decode.h = h;
decode.wb = wb;
decode.hb = hb;
decode.data = std::vector<BlockCode>(wb * hb);
if (HuffmanDecode(decode))
{
fprintf(stderr, "[Error] Huffman decode error\n");
return -1;
}
ImgBlock<int> dBlock = RunLengthDecode(decode);
IZigZag<int>(dBlock);
ImgBlock<double> dquant = Iquant(dBlock);
ImgBlock<double> idct = FIDCT(dquant);
Img<Yuv> iblock = Block2Img(idct);
t = ImgYCbCr2Rgb(iblock);
printf("[Decode] Finished\n");
return 0;
}
int JpegCoder::Write(const char *fileName)
{
std::ofstream fd(fileName, std::ofstream::binary | std::ofstream::trunc);
if (!fd)
{
fprintf(stderr, "[Error] Cannot open jpeg file\n");
return -1;
}
fd.write((char *)(data.data()), data.size());
fd.close();
return 0;
}
int JpegCoder::Read(const char *fileName)
{
//Clear all
data.clear();
for (auto &t : qTable)
{
t.clear();
}
//Read data
std::ifstream fd;
fd.open(fileName, std::ifstream::binary);
if (!fd)
{
fprintf(stderr, "[Error] Cannot read file %s\n", fileName);
return -1;
}
fd.seekg(0, fd.end);
int length = static_cast<int>(fd.tellg());
uint8_t *buf = new uint8_t[length];
fd.seekg(0, fd.beg);
printf("[Reading] %d bytes\n", length);
fd.read((char *)buf, length);
if (!fd)
{
fprintf(stderr, "[Error] Read error\n");
return -1;
}
data.insert(data.end(), buf, buf + length);
delete[] buf;
return 0;
}
void JpegCoder::EncodePicHead()
{
static const uint8_t headInfo[] = {
0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00,
0x01, 0x01, 0x01, 0x00, 0x60, 0x00, 0x60, 0x00, 0x00 };
data.insert(data.end(), headInfo, headInfo + sizeof(headInfo));
}
void JpegCoder::EncodeQuantTable(int level)
{
/*The first table, for Y**************************/
//write quantization table symbol
uint8_t res;
data.push_back(0xff);
data.push_back(0xdb);
//write table length
uint16_t length = 67;
Write16(length);
//write table id, first table
//low 4bit :id high 4bit precision
data.push_back(0x00);
int *yTable = GetYTable(level);
//zigzag quant table
for (int i = 0; i < 64; ++i)
{
res = static_cast<uint8_t>(yTable[ZIGZAG[i]]);
data.push_back(res);
}
/*The second table, for C**************************/
//write quanttable symbol
data.push_back(0xff);
data.push_back(0xdb);
//write table length
Write16(length);
//write table id, second table
//low 4bit :id high 4bit precision
data.push_back(0x01);
int *uvTable = GetUvTable(level);
//zigzag quant table
for (int i = 0; i < 64; ++i)
{
res = static_cast<uint8_t>(uvTable[ZIGZAG[i]]);
data.push_back(res);
}
}
void JpegCoder::EncodePicInfo(uint16_t w, uint16_t h)
{
//Id
data.push_back(0xff);
data.push_back(0xc0);
//length
uint16_t length = 17;
Write16(length);
data.push_back(0x08); //precision
Write16(h); //height
Write16(w); //weight
data.push_back(0x03); //number of component,3 component for YCbCr
/*
Each component 3 byte
ID | Sample rate | Quant table id
Component id:
1: Y
2: Cb
3: Cr
4: I
5: Q
*/
uint8_t component[] = {
0x01, 0x11, 0, //Y
0x02, 0x11, 1, //Cb
0x03, 0x11, 1 //Cr
};
for (int i = 0; i < sizeof(component); ++i)
{
data.push_back(component[i]);
}
}
void JpegCoder::EncodeHuffmanTable(const int *bitSize, const std::vector<int> &bitTable, bool isDc, uint8_t htid)
{
data.push_back(0xff);
data.push_back(0xc4);
uint16_t length = static_cast<uint16_t>(2 + 1 + 16 + bitTable.size()); //length(2) + HT info(1) + Ref(16) + Val(huffman.length)
Write16(length);
//HT info
uint8_t htInfo = 0;
htInfo = htid & 0x0f;
if (!isDc)
{
htInfo |= 0x10;
}
data.push_back(htInfo);
for (int i = 0; i < 16; ++i)
{
data.push_back(static_cast<uint8_t>(bitSize[i]));
}
for (unsigned i = 0; i < bitTable.size(); ++i)
{
data.push_back(static_cast<uint8_t>(bitTable[i]));
}
}
void JpegCoder::EncodeImg(uint8_t *s, int length)
{
//write header
data.push_back(0xff);
data.push_back(0xda);
uint16_t headLength = 12;
Write16(headLength);
data.push_back(3); //component number
/*
Each have its id and huffman table id;
Component id start from 1
table id:
high 4bit: DC table
low 4bit : Ac table
*/
uint8_t componentTable[] = {
1, 0x00,
2, 0x11,
3, 0x11 };
data.insert(data.end(), componentTable, componentTable + sizeof(componentTable));
//fixed value:Ss = 0x00, Se=63, Ah=Al=0x0(4bit)
data.push_back(0);
data.push_back(63);
data.push_back(0);
/*************************************************************************/
//write image
for (int i = 0; i < length; ++i)
{
data.push_back(s[i]);
if (s[i] == 0xff)
data.push_back(0x00);
}
//End of data
data.push_back(0xff);
data.push_back(0xd9);
}
int JpegCoder::DecodeQuantTable(int base, int length)
{
if (length < 65)
{ //64 value and 1 QT info
fprintf(stderr, "[Error] Bad quant table\n");
return -1;
}
int quantNum = length / 64;
for (int num = 0; num < quantNum; ++num)
{
uint8_t res;
res = data[base + num * 65]; //qt info
if (res >> 4 != 0)
{
fprintf(stderr, "[Error] Can only handle 8bit quantization table\n");
return -1;
}
std::vector<int> &table = qTable[res & 0x0f]; //table id
table.assign(64, 0);
for (int i = 1; i <= 64; ++i)
{
table[ZIGZAG[i - 1]] = data[base + num * 65 + i];
}
}
return 0;
}
int JpegCoder::DecodePicInfo(int base, int length, int &w, int &h)
{
if (length != 15)
{
fprintf(stderr, "[Error] Can only handle picture info segment with length 17\n");
return -1;
}
//picture info
/*
Name length begin end
Precision 8 0 1
Height 16 1 3
Wight 16 3 5
Components 8 5 6
Each Component Each Component
ComponentId 8 6 9 12
SampleRate 8 7 10 13
QuantTable 8 8 11 14
*/
if (data[base] != 8 || data[base + 5] != 3)
{
fprintf(stderr, "[Error] Can only handle 8bit precision and 3 component\n");
return -1;
}
h = Read16(base + 1);
w = Read16(base + 3);
uint8_t sample[3], quantTable[3];
bool getYuv[3] = {};
for (int i = 6; i <= 12; i += 3)
{
int id = data[base + i];
if (id == 0 || id > 3)
{
fprintf(stderr, "[Error] Only support YCbCr\n");
return -1;
}
sample[id - 1] = data[base + i + 1];
quantTable[id - 1] = data[base + i + 2];
}
if (sample[0] != sample[1] || sample[1] != sample[2])
{
fprintf(stderr, "[Error] Down sample are not supported\n");
return -1;
}
if (quantTable[1] != quantTable[2])
{
fprintf(stderr, "[Error] Cb and Cr only can share the same quantization table\n");
return -1;
}
pYTable = &qTable[quantTable[0]];
pUvTable = &qTable[quantTable[1]];
return 0;
}
int JpegCoder::DecodeHuffmanTable(int base, int length)
{
if (length < 17)
{
fprintf(stderr, "[Error] Huffman table length error\n");
return -1;
}
while (length > 17)
{
uint8_t ht = data[base];
int id = ht & 0x0f;
if (id > 3)
{
fprintf(stderr, "[Error] HT id should be 0-3\n");
return -1;
}
bool isDc = true;
if ((ht >> 4) & 1)
isDc = false;
if (ht >> 5 != 0)
{
fprintf(stderr, "[Warning] Check error, ht high 3 bit should be 0\n");
}
int numCode = 0;
for (int i = 0; i < 16; ++i)
{
numCode += data[base + i + 1];
}
if (17 + numCode > length)
{
fprintf(stderr, "[Error] Huffman table error\n");
return -1;
}
Huffman *pTable;
if (isDc)
{
pTable = &dcHuff[id];
}
else
{
pTable = &acHuff[id];
}
pTable->SetTable(data.data() + base + 1, data.data() + base + 17, numCode);
base += 17 + numCode;
length -= 17 + numCode;
}
return 0;
}
int JpegCoder::DecodeImg(int base, int length)
{
if (length != 10)
{
fprintf(stderr, "[Error] Img segment length error\n");
return -1;
}
int acHuffId[3] = {};
int dcHuffId[3] = {};
if (data[base] != 3)
{
fprintf(stderr, "[Error] Only 3 components are supported\n");
return -1;
}
for (int i = 1; i <= 5; i += 2)
{
int id = data[base + i];
if (id < 1 || id > 3)
{
fprintf(stderr, "[Error] Only support Y Cb Cr\n");
return -1;
}
acHuffId[id - 1] = data[base + i + 1] & 0x0f;
dcHuffId[id - 1] = data[base + i + 1] >> 4;
}
if (dcHuffId[1] != dcHuffId[2] || acHuffId[1] != acHuffId[2])
{
fprintf(stderr, "[Error] Cb and Cr should share the same huffman table, this software do not support two huffman tables\n");
return -1;
}
if (data[base + 7] != 0x00 || data[base + 8] != 0x3f || data[base + 9] != 0x00)
{
fprintf(stderr, "[Warning] Img decode warning, check error\n");
}
yDcHuff = dcHuff[dcHuffId[0]];
yAcHuff = acHuff[acHuffId[0]];
uvDcHuff = dcHuff[dcHuffId[1]];
uvAcHuff = acHuff[acHuffId[1]];
base += 10;
stream.clear();
stream.push_back(BitStream{});
BitStream *pImgStream = &stream[0];
for (; (unsigned)base < data.size(); base++)
{
if (data[base] == 0xff)
{
if (data[base + 1] == 0)
{
pImgStream->PushBack(0xff);
base++;
}
else if ((data[base + 1] & 0xf8) == 0xd0)
{
//RST
base++;
stream.push_back(BitStream{});
pImgStream = &stream[stream.size() - 1];
}
else
{
break;
}
}
else
{
pImgStream->PushBack(data[base]);
}
}
return 0;
}
//Quant
template <class T>
ImgBlock<int> JpegCoder::Quant(T &block, int level)
{
int *yTable = GetYTable(level);
int *uvTable = GetUvTable(level);
ImgBlock<int> ans;
ans.w = block.w;
ans.h = block.h;
ans.wb = block.wb;
ans.hb = block.hb;
ans.data = std::vector<Block<int>>(ans.wb * ans.hb);
for (int i = 0; i < ans.wb * ans.hb; ++i)
{
for (int j = 0; j < 64; ++j)
{
ans.data[i].y[j] = static_cast<int>(block.data[i].y[j] / yTable[j]);
ans.data[i].u[j] = static_cast<int>(block.data[i].u[j] / uvTable[j]);
ans.data[i].v[j] = static_cast<int>(block.data[i].v[j] / uvTable[j]);
}
}
return ans;
}
template <class T>
ImgBlock<double> JpegCoder::Iquant(T &block)
{
const std::vector<int> &yTable = *pYTable;
const std::vector<int> &uvTable = *pUvTable;
ImgBlock<double> ans;
ans.w = block.w;
ans.h = block.h;
ans.wb = block.wb;
ans.hb = block.hb;
ans.data = std::vector<Block<double>>(ans.wb * ans.hb);
for (int i = 0; i < ans.wb * ans.hb; ++i)
{
for (int j = 0; j < 64; ++j)
{
ans.data[i].y[j] = block.data[i].y[j] * yTable[j];
ans.data[i].u[j] = block.data[i].u[j] * uvTable[j];
ans.data[i].v[j] = block.data[i].v[j] * uvTable[j];
}
}
return ans;
}
//ZigZag
template <class T>
void JpegCoder::ZigZag(ImgBlock<T> &block)
{
Block<T> res;
for (int i = 0; i < block.wb * block.hb; ++i)
{
T *s[] = { block.data[i].y, block.data[i].u, block.data[i].v };
T *t[] = { res.y, res.u, res.v };
for (int color = 0; color < 3; ++color)
{
for (int j = 0; j < 64; ++j)
{
t[color][j] = s[color][ZIGZAG[j]];
}
for (int j = 0; j < 64; ++j)
{
s[color][j] = t[color][j];
}
}
}
}
template <class T>
void JpegCoder::IZigZag(ImgBlock<T> &block)
{
Block<T> res;
for (int i = 0; i < block.wb * block.hb; ++i)
{
T *s[] = { block.data[i].y, block.data[i].u, block.data[i].v };
T *t[] = { res.y, res.u, res.v };
for (int color = 0; color < 3; ++color)
{
for (int j = 0; j < 64; ++j)
{
t[color][ZIGZAG[j]] = s[color][j];
}
for (int j = 0; j < 64; ++j)
{
s[color][j] = t[color][j];
}
}
}
}
ImgBlockCode JpegCoder::RunLengthCode(const ImgBlock<int> &block)
{
ImgBlockCode code;
code.w = block.w;
code.h = block.h;
code.wb = block.wb;
code.hb = block.hb;
code.data = std::vector<BlockCode>(code.wb * code.hb);
int lastYDc = 0, lastUDc = 0, lastVDc = 0;
for (int i = 0; i < block.wb * block.hb; ++i)
{
//*****************************************************************
//Get dc
//*****************************************************************
int diffY = block.data[i].y[0] - lastYDc;
int diffU = block.data[i].u[0] - lastUDc;
int diffV = block.data[i].v[0] - lastVDc;
//code dc
code.data[i].ydc = GetVLI(diffY);
code.data[i].udc = GetVLI(diffU);
code.data[i].vdc = GetVLI(diffV);
lastYDc = block.data[i].y[0];
lastUDc = block.data[i].u[0];
lastVDc = block.data[i].v[0];
//****************************************************************
//Get Ac
//****************************************************************
const int *s[] = { block.data[i].y, block.data[i].u, block.data[i].v };
std::vector<std::pair<uint8_t, Symbol>> *t[] = { &code.data[i].yac, &code.data[i].uac, &code.data[i].vac };
for (int color = 0; color < 3; ++color)
{
int zeroNum = 0;
auto ss = s[color];
auto tt = t[color];
//find eob
int eob = 0;
for (int i = 63; i >= 0; --i)
{
if (ss[i] != 0)
{
eob = i;
break;
}
}
for (int i = 1; i <= eob; ++i)
{
if (ss[i] == 0)
{
zeroNum++;
if (zeroNum == 16)
{
zeroNum = 0;
tt->emplace_back(0xf0, Symbol{ 0, 0 });
}
}
else
{
Symbol val = GetVLI(ss[i]);
uint8_t head = 0;
head |= val.length & 0x0f;
head |= (zeroNum & 0x0f) << 4;
tt->emplace_back(head, val);
zeroNum = 0;
}
}
if (eob < 63)
{
tt->emplace_back(0x00, Symbol{ 0, 0 });
}
}
}
return code;
}
ImgBlock<int> JpegCoder::RunLengthDecode(const ImgBlockCode &code)
{
ImgBlock<int> block;
block.w = code.w;
block.h = code.h;
block.wb = code.wb;
block.hb = code.hb;
int size = block.wb * block.hb;
block.data = std::vector<Block<int>>(size);
int lastYDc = 0;
int lastUDc = 0;
int lastVDc = 0;
for (int i = 0; i < size; ++i)
{
if (code.data[i].restart) {
lastYDc = 0;
lastUDc = 0;
lastVDc = 0;
}
lastYDc += DeVLI(code.data[i].ydc);
lastUDc += DeVLI(code.data[i].udc);
lastVDc += DeVLI(code.data[i].vdc);
block.data[i].y[0] = lastYDc;
block.data[i].u[0] = lastUDc;
block.data[i].v[0] = lastVDc;
int *t[] = { block.data[i].y, block.data[i].u, block.data[i].v };
const std::vector<std::pair<uint8_t, Symbol>> *s[] = { &code.data[i].yac, &code.data[i].uac, &code.data[i].vac };
for (int color = 0; color < 3; ++color)
{
int *tt = t[color];
const std::vector<std::pair<uint8_t, Symbol>> &ss = *s[color];
int idx = 1;
for (auto &p : ss)
{
uint8_t head = p.first;
Symbol data = p.second;
if (head == 0x00)
{ //EOB
break;
}
int zeros = head >> 4;
idx += zeros;
if (idx >= 64)
{
fprintf(stderr, "[Error] RunLengthDecode error, try to get idx > 64\n");
return block;
}
data.length = head & 0x0f;
tt[idx] = DeVLI(data);
idx++;
}
}
}
return block;
}
void JpegCoder::BuildHuffman(ImgBlockCode &block)
{
for (auto &b : block.data)
{
yDcHuff.Add(b.ydc.length);
uvDcHuff.Add(b.udc.length);
uvDcHuff.Add(b.vdc.length);
for (auto &val : b.yac)
yAcHuff.Add(val.first);
for (auto &val : b.uac)
uvAcHuff.Add(val.first);
for (auto &val : b.vac)
uvAcHuff.Add(val.first);
}
yDcHuff.BuildTable();
yAcHuff.BuildTable();
uvDcHuff.BuildTable();
uvAcHuff.BuildTable();
//print huffman table
printf("L Dc table\n");
yDcHuff.PrintTable();
printf("L Ac table\n");
yAcHuff.PrintTable();
printf("C Dc table\n");
uvDcHuff.PrintTable();
printf("C Ac table\n");
uvAcHuff.PrintTable();
}
int JpegCoder::HuffmanEncode(ImgBlockCode &block, BitStream &stream)
{
auto PrintErr = [](std::string msg = "") {
fprintf(stderr, "[Error] Huffman Encode error %s\n", msg.data());
};
for (auto &b : block.data)
{
Symbol s;
Symbol *dc[] = { &b.ydc, &b.udc, &b.vdc };
std::vector<std::pair<uint8_t, Symbol>> *ac[] = { &b.yac, &b.uac, &b.vac };
Huffman *dcCoder[] = { &yDcHuff, &uvDcHuff, &uvDcHuff };
Huffman *acCoder[] = { &yAcHuff, &uvAcHuff, &uvAcHuff };
for (int color = 0; color < 3; ++color)
{
if (dcCoder[color]->Encode(dc[color]->length, s))
{
PrintErr("Dc");
return -1;
}
stream.Add(s);
stream.Add(*dc[color]);
for (auto &val : *ac[color])
{
if (acCoder[color]->Encode(val.first, s))
{
PrintErr("Ac");
return -1;
}
stream.Add(s);
stream.Add(val.second);
}
}
}
return 0;
}
int JpegCoder::HuffmanDecode(ImgBlockCode &code)
{
if (code.w == 0 || code.wb == 0 || code.h == 0 || code.hb == 0 || code.data.size() != code.hb * code.wb)
{
fprintf(stderr, "[Error] Huffman decode need image size\n");
return -1;
}
int blockId = 0;
std::vector<BitStream>::iterator pStream = stream.begin();
while (blockId < code.wb * code.hb)
{
BlockCode &b = code.data[blockId];
Symbol *dc[] = { &b.ydc, &b.udc, &b.vdc };
std::vector<std::pair<uint8_t, Symbol>> *ac[] = { &b.yac, &b.uac, &b.vac };
Huffman *dcCoder[] = { &yDcHuff, &uvDcHuff, &uvDcHuff };
Huffman *acCoder[] = { &yAcHuff, &uvAcHuff, &uvAcHuff };
for (int color = 0; color < 3; color++)
{
Symbol readData;
readData.length = 0;
readData.val = 0;
Symbol tmp;
tmp.length = 1;
tmp.val = 0;
uint8_t dcLength = 0;
//Get Dc
do
{
tmp.length = 1;
if (pStream->Get(tmp) == -2) {
//meet the end, change stream
pStream++;
if (pStream == stream.end()) {
fprintf(stderr, "[Error] Want to read more than have\n");
return -1;
}
b.restart = true;
tmp.length = 1;
tmp.val = 0;
readData.length = 0;
readData.val = 0;
uint8_t acVal = 0;
continue;
}
readData.length++;
readData.val = readData.val << 1 | tmp.val;
if (readData.length > 16)
{
fprintf(stderr, "[Error] Huffman decode error, dc decode error\n");
return -1;
}
} while (dcCoder[color]->Decode(readData, dcLength));
readData.length = dcLength;
if (pStream->Get(readData) == -2) {
//unexpected broken
fprintf(stderr, "[Error] Unexpected broken\n");
return -1;
}
*dc[color] = readData;
//Get Ac
int numValue = 1;
while (numValue < 64)
{
readData.length = 0;
readData.val = 0;
uint8_t acVal = 0;
do
{
tmp.length = 1;
tmp.val = 0;
if (pStream->Get(tmp) == -2) {
//unexpected broken
fprintf(stderr, "[Error] Unexpected broken\n");
return -1;
}
readData.length++;
readData.val = (readData.val << 1) | tmp.val & 1;
if (readData.length > 16)
{
fprintf(stderr, "[Error] Huffman decode error, ac decode error\n");
return -1;
}
} while (acCoder[color]->Decode(readData, acVal));
if (acVal == 0xf0)
{
numValue += 16;
ac[color]->emplace_back(acVal, Symbol{ 0, 0 });
continue;
}
if (acVal == 0)
{
//EOB end of block
ac[color]->emplace_back(0x00, Symbol{ 0, 0 });
break;
}
int zeroNum = acVal >> 4;
readData.length = acVal & 0x0f;
if (pStream->Get(readData) == -2) {
//unexpected broken
fprintf(stderr, "[Error] Unexpected broken\n");
return -1;
}
numValue += zeroNum + 1;
ac[color]->emplace_back(acVal, readData);
}
}
blockId++;
}
return 0;
}
Symbol JpegCoder::GetVLI(int val)
{
if (val == 0)
return { 0, 0 };
int middle = (val > 0) ? val : -val;
Symbol ans;
ans.length = 0;
while (middle >> ans.length > 0)
{
ans.length++;
}
if (ans.length > 11)
{
fprintf(stderr, "[Warning] VLI value >= 2048\n");
}
if (val < 0)
ans.val = (~middle) & ((1 << ans.length) - 1);
else
ans.val = middle;
return ans;
}
int JpegCoder::DeVLI(Symbol s)
{
if (s.length == 0)
return 0;
if (s.val >> (s.length - 1) & 0x01)
{
return s.val;
}
int ans = ((~s.val) & ((1 << s.length) - 1));
return -ans;
}
}; //namespace jpeg<file_sep>/huffman.cpp
#include "huffman.h"
#include "utilities.h"
#include <queue>
#include <string>
#include <algorithm>
namespace jpeg
{
void BitStream::PushBack(const uint8_t &val)
{
data.push_back(val);
}
void BitStream::Add(const Symbol &s)
{
if (s.length > 16 || s.length < 0)
{
fprintf(stderr, "[Error] Bitstream add length %d\n", s.length);
return;
}
int remainBit = 8 - tail;
if (remainBit > s.length)
{
uint8_t &res = data.back();
SetBitByte(res, tail, s.length, s.val);
tail += s.length;
}
else
{
int sPos = 0;
if (remainBit > 0)
{
uint8_t res = GetBitSymbol(s, sPos, remainBit);
uint8_t &last = data.back();
SetBitByte(last, tail, remainBit, res);
sPos += remainBit;
}
tail = 8;
while (s.length - sPos > 8)
{
uint8_t res = GetBitSymbol(s, sPos, 8);
data.push_back(res);
sPos += 8;
}
if (s.length - sPos > 0)
{
tail = s.length - sPos;
uint8_t res = GetBitSymbol(s, sPos, tail);
uint8_t last = 0;
SetBitByte(last, 0, tail, res);
data.push_back(last);
}
}
}
//************************************
// Method: Get
// FullName: jpeg::BitStream::Get
// Access: public
// Returns: int,0 for normal return, and -2 for meet end٬ -1
// Qualifier:
// Parameter: Symbol & s
//************************************
int BitStream::Get(Symbol &s)
{
if (s.length > 16 || s.length < 0)
{
fprintf(stderr, "[Error] BitStream get length %d\n", s.length);
return -1;
}
s.val = 0;
int remainBit = 8 - head;
if (remainBit >= s.length)
{
if (readIdx >= data.size())
{
//more than have, next stream
return -2;
}
s.val = GetBitByte(data[readIdx], head, s.length);
head += s.length;
}
else
{
int sPos = 0;
uint8_t res = 0;
if (remainBit > 0)
{
res = GetBitByte(data[readIdx], head, remainBit);
SetBitSymbol(s, sPos, remainBit, res);
sPos += remainBit;
}
readIdx++;
if (readIdx >= data.size()) {
//want more than have
return -2;
}
head = 0;
while (s.length - sPos >= 8)
{
if (readIdx >= data.size())
{
return -2;
}
SetBitSymbol(s, sPos, 8, data[readIdx++]);
sPos += 8;
}
if (s.length - sPos > 0)
{
if (readIdx >= data.size())
{
return -2;
}
head = s.length - sPos;
res = GetBitByte(data[readIdx], 0, head);
SetBitSymbol(s, sPos, head, res);
}
}
return 0;
}
int BitStream::print()
{
for (auto &i : data)
{
printf("%x ", i);
}
printf("\n");
return data.size() * 8 - tail;
}
int BitStream::GetData(uint8_t **t)
{
if (t != NULL)
*t = data.data();
return data.size();
}
void BitStream::SetData(const std::vector<uint8_t> &s)
{
data = s;
tail = 8;
head = 0;
readIdx = 0;
}
void Huffman::Add(int val)
{
if (val >= 0 && val < 256)
frequence[val]++;
else
{
fprintf(stderr, "[Warning] Huffman add warning, val >= 256 or <0\n");
}
}
void Huffman::SetTable(const uint8_t *bitSize, const uint8_t *bitTable, const int tableLength)
{
for (int i = 0; i < 16; ++i)
{
(this->bitSize)[i] = bitSize[i];
}
this->bitTable.assign(tableLength, 0);
for (int i = 0; i < tableLength; ++i)
{
(this->bitTable)[i] = bitTable[i];
}
}
/*
Build huffman table (the code order and each code size)
Follow ISO/IEC 10918-1:1993(E)(ITU-T81) K.2
*/
void Huffman::BuildTable()
{
struct SymbolAndFre
{
int frequence;
int symbol;
bool operator<(const SymbolAndFre &s) const { return frequence < s.frequence; }
bool operator>(const SymbolAndFre &s) const { return frequence > s.frequence; }
};
std::vector<SymbolAndFre> symbols(257);
symbols.clear();
for (int i = 0; i < 257; ++i)
{
if (frequence[i] > 0)
symbols.emplace_back(SymbolAndFre{ frequence[i], i });
}
/*Because all one code is not allowed,
symbol 256 is added to avolid it.
If there must be all one code, 256 will get it
so it would not apear in file;
*/
symbols.emplace_back(SymbolAndFre{ 0, 256 });
std::sort(symbols.begin(), symbols.end(), std::greater<SymbolAndFre>());
for (auto &s : symbols)
if (s.frequence != 0)
bitTable.emplace_back(s.symbol);
std::priority_queue<SymbolAndFre, std::vector<SymbolAndFre>, std::greater<SymbolAndFre>> q(symbols.begin(), symbols.end());
std::vector<int> codeSize, others;
codeSize.assign(257, 0);
others.assign(257, -1);
while (q.size() > 1)
{
SymbolAndFre m1 = q.top();
q.pop();
SymbolAndFre m2 = q.top();
q.pop();
m1.frequence += m2.frequence;
int v1, v2;
for (v1 = m1.symbol; others[v1] != -1; v1 = others[v1])
{
codeSize[v1]++;
}
codeSize[v1]++;
others[v1] = m2.symbol;
for (v2 = m2.symbol; v2 != -1; v2 = others[v2])
{
codeSize[v2]++;
}
q.push(m1);
}
int bitLength = *std::max_element(codeSize.begin(), codeSize.end());
std::vector<int> bits(bitLength + 1, 0);
for (auto &val : codeSize)
{
if (val > 0)
bits[val]++;
}
while (bitLength > 16)
{
int &i = bitLength;
int j = i - 2;
if (bits[i] == 0)
i--;
while (j > 0 && bits[j] == 0)
j--;
bits[i] -= 2;
bits[i - 1]++;
bits[j + 1] += 2;
bits[j]--;
}
for (int tail = bitLength; tail > 0; --tail)
{
if (bits[tail] != 0)
{
bits[tail]--;
break;
}
}
for (unsigned i = 0; i < 16; ++i)
{
if (i + 1 >= bits.size())
{
bitSize[i] = 0;
}
else
{
bitSize[i] = bits[i + 1];
}
}
}
void Huffman::PrintTable()
{
if (!CheckSize())
return;
int idx = 0;
for (int i = 0; i < 16; ++i)
{
printf("%d : \t", i + 1);
for (int j = 0; j < bitSize[i]; ++j)
{
printf("%X ", bitTable[idx++]);
}
printf("\n");
}
printf("Total size = %d\n", bitTable.size());
}
int Huffman::Encode(uint8_t source, Symbol &target)
{
if (symbolMap.empty())
{
BuildSymbolMap();
}
std::map<int, Symbol>::iterator it = symbolMap.find(source);
if (it == symbolMap.end())
{
fprintf(stderr, "[Error] Huffman encode error, unkonw symbol\n");
return -1;
}
target = it->second;
return 0;
}
int Huffman::Decode(Symbol &source, uint8_t &target)
{
if (valueMap.empty())
BuildValueMap();
std::map<Symbol, int>::iterator it = valueMap.find(source);
if (it == valueMap.end())
return -1;
target = it->second;
return 0;
}
const int *Huffman::GetSize() const
{
return bitSize;
}
const std::vector<int> &Huffman::GetTable() const
{
return bitTable;
}
Huffman &Huffman::operator=(const Huffman &s)
{
memcpy(bitSize, s.bitSize, sizeof(bitSize));
bitTable = s.bitTable;
symbolMap.clear();
valueMap.clear();
return *this;
}
void Huffman::BuildSymbolMap()
{
symbolMap.clear();
if (!CheckSize())
{
return;
}
Symbol s;
s.length = 1;
s.val = 0;
int idx = 0;
for (int i = 0; i < 16; ++i)
{
for (int j = 0; j < bitSize[i]; ++j)
{
symbolMap.emplace(bitTable[idx++], s);
s.val++;
}
s.length++;
s.val <<= 1;
}
}
void Huffman::BuildValueMap()
{
symbolMap.clear();
if (!CheckSize())
{
return;
}
Symbol s;
s.length = 1;
s.val = 0;
int idx = 0;
for (int i = 0; i < 16; ++i)
{
for (int j = 0; j < bitSize[i]; ++j)
{
valueMap.emplace(s, bitTable[idx++]);
s.val++;
}
s.length++;
s.val <<= 1;
}
}
bool Huffman::CheckSize()
{
int val = 2;
for (int i = 0; i < 16; ++i)
{
if (val < 0)
{
fprintf(stderr, "[Error] Huffman tree error\n");
return false;
}
val -= bitSize[i];
val <<= 1;
}
return true;
}
}; //namespace jpeg<file_sep>/types.h
#ifndef __TYPE_H__
#define __TYPE_H__
#include <cstdint>
#include <vector>
static const uint8_t ones[9] = { 0, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
struct Rgb {
uint8_t r;
uint8_t g;
uint8_t b;
};
struct Yuv {
uint8_t y;
uint8_t cb;
uint8_t cr;
};
template<class Color>
struct Img {
int w, h;
Color *data;
Img() :w(0), h(0), data(NULL) {}
};
template<class T>
struct Block {
T y[64] = {};
T u[64] = {};
T v[64] = {};
};
template<class T>
struct ImgBlock {
int w, h, wb, hb;
std::vector<Block<T>> data;
};
struct Symbol {
uint32_t val;
int length;
bool operator<(const Symbol& s)const {
if (length == s.length)
return val < s.val;
return length < s.length;
}
};
struct BlockCode {
Symbol ydc, udc, vdc;
bool restart = false;
std::vector<std::pair<uint8_t, Symbol>> yac, uac, vac;//<zeroNumber|size, number in vli>
};
struct ImgBlockCode {
int w, h, wb, hb;
std::vector<BlockCode> data;
};
#endif // !__TYPE_H__
<file_sep>/utilities.h
#pragma once
#ifndef __UTILITIES_H__
#define __UTILITIES_H__
#include "types.h"
//Change image color
Img<Yuv> ImgRgb2YCbCr(const Img<Rgb>);
Img<Rgb> ImgYCbCr2Rgb(const Img<Yuv>);
//Change color
inline Yuv Rgb2YCbCr(const Rgb);
inline Rgb YCbCr2Rgb(const Yuv);
//double to uint8_t, handle value > 255 and < 0
template<class T> inline uint8_t ColorCast(const T&);
ImgBlock<double> Img2Block(Img<Yuv> img);
Img<Yuv> Block2Img(ImgBlock<double>& block);
//For bit stream
inline uint8_t GetBitSymbol(const Symbol &s, int pos, int length)
{
uint8_t ans = 0;
if (length < 0 || length > 8 || pos + length > s.length) {
fprintf(stderr, "[Error] Get Bit error, length error\n");
return ans;
}
ans = s.val >> (s.length - pos - length);
ans &= ones[length];
return ans;
}
inline void SetBitSymbol(Symbol &s, int pos, int length, uint8_t value) {
int base = s.length - pos - length;
uint32_t mask = ones[length] << base;
uint32_t res = value;
res = (res << base) & mask;
s.val = (s.val & ~mask) | res;
}
inline uint8_t GetBitByte(const uint8_t s, int pos, int length) {
uint8_t ans = 0;
if (length < 0 || length > 8 || pos + length > 8) {
fprintf(stderr, "[Error] GetBit byte error, length error\n");
return ans;
}
int base = 8 - pos - length;
ans = (s >> base) & ones[length];
return ans;
}
inline void SetBitByte(uint8_t &s, int pos, int length, uint8_t value) {
if (length < 0 || length > 8 || pos + length > 8) {
fprintf(stderr, "[Error] SetBit byte error, length error\n");
return;
}
int base = 8 - pos - length;
uint8_t mask = ones[length] << base;
uint8_t res = (value << base) & mask;
s = (s & ~mask) | res;
}
#endif/*__UTILITIES_H__*/<file_sep>/utilities.cpp
#include "utilities.h"
Img<Yuv> ImgRgb2YCbCr(const Img<Rgb> imgrgb) {
Img<Yuv> imgy;
imgy.w = imgrgb.w;
imgy.h = imgrgb.h;
imgy.data = new Yuv[imgy.w * imgy.h];
for (int i = 0; i < imgy.w * imgy.h; ++i) {
imgy.data[i] = Rgb2YCbCr(imgrgb.data[i]);
}
return imgy;
}
Img<Rgb> ImgYCbCr2Rgb(const Img<Yuv> imgy) {
Img<Rgb> imgrgb;
imgrgb.w = imgy.w;
imgrgb.h = imgy.h;
imgrgb.data = new Rgb[imgy.w * imgy.h];
for (int i = 0; i < imgy.w * imgy.h; ++i) {
imgrgb.data[i] = YCbCr2Rgb(imgy.data[i]);
}
return imgrgb;
}
inline Yuv Rgb2YCbCr(const Rgb rgb) {
Yuv y;
y.y = ColorCast(0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b);
y.cb = ColorCast(-0.168 * rgb.r - 0.3313 * rgb.g + 0.5 * rgb.b + 128);
y.cr = ColorCast(0.5 * rgb.r - 0.4187 * rgb.g - 0.0813 * rgb.b + 128);
return y;
}
inline Rgb YCbCr2Rgb(const Yuv y) {
Rgb r;
r.r = ColorCast(y.y + 1.402 * (y.cr - 128));
r.g = ColorCast(y.y - 0.34414 * (y.cb - 128) - 0.71414 * (y.cr - 128));
r.b = ColorCast(y.y + 1.772 * (y.cb - 128));
return r;
}
template<class T>
inline uint8_t ColorCast(const T& dc) {
if (dc < 0)
return 0;
if (dc > 255)
return 255;
return static_cast<uint8_t>(dc);
}
static const double dctBase = 128;
ImgBlock<double> Img2Block(Img<Yuv> img) {
int wb = (img.w >> 3) + ((img.w % 8 > 0) ? 1 : 0);
int hb = (img.h >> 3) + ((img.h % 8 > 0) ? 1 : 0);
ImgBlock<double> block;
block.w = img.w;
block.h = img.h;
block.wb = wb;
block.hb = hb;
block.data = std::vector<Block<double>>(wb * hb);
for (int i = 0; i < img.w * img.h; ++i) {
int x = i % img.w;
int y = i / img.w;
int xb = x / 8;
int yb = y / 8;
int blkId = yb * wb + xb;
int xIn = x % 8;
int yIn = y % 8;
int inId = yIn * 8 + xIn;
block.data[blkId].y[inId] = img.data[i].y - dctBase;
block.data[blkId].u[inId] = img.data[i].cb - dctBase;
block.data[blkId].v[inId] = img.data[i].cr - dctBase;
}
return block;
}
Img<Yuv> Block2Img(ImgBlock<double>& block) {
int &wb = block.wb;
int &hb = block.hb;
Img<Yuv> img;
img.w = block.w;
img.h = block.h;
img.data = new Yuv[img.w * img.h];
for (int i = 0; i < img.w * img.h; ++i) {
int x = i % img.w;
int y = i / img.w;
int xb = x / 8;
int yb = y / 8;
int blkId = yb * wb + xb;
int xIn = x % 8;
int yIn = y % 8;
int inId = yIn * 8 + xIn;
img.data[i].y = ColorCast(block.data[blkId].y[inId] + dctBase);
img.data[i].cb = ColorCast(block.data[blkId].u[inId] + dctBase);
img.data[i].cr = ColorCast(block.data[blkId].v[inId] + dctBase);
}
return img;
}<file_sep>/bmp.cpp
#include <cstring>
#include <iostream>
#include <atlimage.h>
#include "bmp.h"
#include "types.h"
namespace bmp {
Img<Rgb> ReadBmp(const char* fileName) {
CImage img;
Img<Rgb> rgbImg;
if (img.Load(fileName))
{
fprintf(stderr, "[BMP Error] Cannot load bmp picture\n");
return rgbImg;
}
printf("[Read] Succeed\n");
int bitCount = img.GetBPP();
int w = img.GetWidth();
int h = img.GetHeight();
printf("[Info] BitCount=%d Width=%d Height=%d\n", bitCount, w, h);
if (bitCount != 24)
{
fprintf(stderr, "[BMP Error] Can only handle 24bit bitmap\n");
return rgbImg;
}
Rgb* data = new Rgb[w*h];
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
int idx = y * w + x;
COLORREF color = img.GetPixel(x, y);
Rgb &target = data[idx];
uint8_t * cColor = (uint8_t*)&color;
target.r = cColor[0];
target.g = cColor[1];
target.b = cColor[2];
}
}
rgbImg.data = data;
rgbImg.w = w;
rgbImg.h = h;
return rgbImg;
}
int WriteBmp(const char* fileName, Img<Rgb> rgbImg)
{
CImage img;
if (img.Create(rgbImg.w, rgbImg.h, 24) == 0) {
//set bitcount to default 24
fprintf(stderr, "[Error] CImage create error\n");
return -1;
}
for (int x = 0; x < rgbImg.w; ++x)
{
for (int y = 0; y < rgbImg.h; ++y) {
int idx = y * rgbImg.w + x;
Rgb& color = rgbImg.data[idx];
img.SetPixel(x, y, RGB(color.r, color.g, color.b));
}
}
HRESULT result = img.Save(fileName);
if (result != 0) {
fprintf(stderr, "[Error] Save bmp error, error number: %d\n", result);
}
return 0;
}
};//namespace bmp<file_sep>/huffman.h
#ifndef __HUFFMAN_H__
#define __HUFFMAN_H__
#include <map>
#include <unordered_map>
#include <queue>
#include "types.h"
namespace jpeg
{
class BitStream
{
public:
BitStream() = default;
BitStream(const std::vector<uint8_t> &data_)
{
data = data_;
tail = 8;
head = 0;
}
void PushBack(const uint8_t &val);
void Add(const Symbol &s);
int Get(Symbol &s);
int print(); //for debug
int GetData(uint8_t **);
void SetData(const std::vector<uint8_t> &s);
private:
std::vector<uint8_t> data;
int tail = 8;
int head = 0;
unsigned int readIdx = 0;
};
class Huffman
{
public:
/*Add a value to Huffman tree, statistic frequencies*/
void Add(int val);
void SetTable(const uint8_t *bitSize, const uint8_t *bitTable, const int tableLength);
void BuildTable();
void PrintTable();
int Encode(uint8_t source, Symbol &target);
int Decode(Symbol &source, uint8_t &target);
const int *GetSize() const;
const std::vector<int> &GetTable() const;
Huffman &operator=(const Huffman &s);
private:
void BuildSymbolMap();
void BuildValueMap();
bool CheckSize();
int frequence[257] = {};
int bitSize[16]; //number of code of length idx
std::vector<int> bitTable;
std::map<int, Symbol> symbolMap; //for encode, value to symbol
std::map<Symbol, int> valueMap; //for decode, symbol to value
};
}; //namespace jpeg
#endif //__HUFFMAN_H__ | e026b9a2c8fca6d20c8e7412df686f02b2445465 | [
"C++"
] | 11 | C++ | williamshiwenhao/jpeg_coder | 137327bffbd6ed7af1c2cbfe2eabcd2ab7510e96 | 2016b042760351f971c7442866d13c274842e96c |
refs/heads/master | <file_sep>Author : <NAME>
The vlt module aims to bring some useful tool for easy instrument scripts
and control.
It is not aimed to replace the vlt template and script but to provide
to the non-vtl-software expert a way to script VLT instruments quickly and easely.
The vlt module use configuration files to create the python objects. For instance, Process objects are created from `*.cdt` files on the fly; dictionary files are red and can be used into a FunctionDict objects ...
Main capabilities are:
Process
=======
You can open a `process` to send command (based on the msgSend unix command)
The process object are dynamicaly created from instrument CDT file.
e.g. (on PIONIER):
proc = vlt.openProcess("pnoControl")
proc.help() # give a help on all commands
proc.help("setup") # help on "setup" command
#-or-#
print proc.setup.__doc__ # return help on command setup as well
vlt.setDefaultProcess("pnoControl") # set the default process for
# Functions (see below)
proc.setup(function=[("DET.DIT", 0.01)], timeout=1000)
Function and FunctionDict
=========================
Function
--------
What we call here Function (also called Keyword in VLTSW) are objects
containing a keyword/value pair plus extra stuff like unit, class, context,
description, format, ...
Function provide some smart indexing capability:
e.g:
f = vlt.Function("INSi.FILTi.ENC", dtype=int)
is understood to be a table of value because of the 'i' iterator.
Therefore:
f[1,2].value = 120000 # set the value of INS1.FILT1.ENC
f[1,2] # return the corresponding Function
f[1,2] is equivalent to f["INS1","FILT2"]
The index 0 return the keyword without number:
f[0,2] return the Function of "INS.FILT2.ENC"
Also one can set value of several indexes in one command:
f[1] = { 1:10000, 2:50000, 3:3400 } # will set value for "INS1.FILT1.ENC",
# "INS1.FILT2.ENC" and "INS1.FILT3.ENC"
so `f[1,1].value is 10000, f[1,2].value is 50000`, etc ...
To know if a function contains iterable keys use the isIterable method
Function("INSi.FILTi.ENC").isIterable() # -> true
Function("INS1.FILT2.ENC").isIterable() # -> False
Function("DETj.DIT").isIterable() # -> True
Function("DET.DIT").isIterable() # -> False
### key methods of function object:
#### set
`set(value)`
set the value in the function and return the Function itself. This allow to do quick command.
f.set(30000).setup() # set and then send setup (see bellow)
#### setup
`setup()`
`setup(3.4, proc)`
Send a setup command with the process proc= -or if None-
the default process defined by vlt.setDefaultProcess
Without argument the setup is sent with the current Function
value. Or with the optional value argument.
e.g.:
vlt.setDefaultProcess("pnoControl")
f = vlt.Function("DET.DIT", 0.001)
f.setup(timeout=1000, expoId=0)
is equivalent to the system command:
> msgSend "" pnoControl SETUP "-function DET.DIT 0.001 -expoId 0" 1000
#### status
ask the Function status to process
FunctionDict
------------
FunctionDict() objects are dictionary of Function() object.
They are basically a collection of keyword/pair values with fast search
keyword methods.
A FunctionDict can be created by hand or directly from ESO dictionary files:
dcs = readDictionary('PIONIER_DCS') # read the ESO-VLT-DIC.PIONIER_DCS file
dcs['DET.DIT'].description
'Time in seconds of each integration ramp.'
# etc ....
A FunctionDict is smart enought to understand iterable functions query.
For instanse if one has `INSi.OPTi.VAL` in the FunctionDict `fd` : `fd['INS1.OPT2.VAL']` will return `fd['INSi.OPTi.VAL'][1,2]`.
### Key Methods:
#### restrict
`restrict(pattern)`
take a string or list of string and return a restricted FunctionDict
If a string, the restricted dictionary is limited to the Function with key that
start with the input string. e.g. on PIONIER :
df = vlt.readDictionary("PIONIER_ICS")
df.restrict("INS.SENS1")
return a FunctionDict like:
{
'MAX': Function("INS.SENS1.MAX", None),
'MEAN': Function("INS.SENS1.MEAN", None),
'MIN': Function("INS.SENS1.MIN", None),
'STAT': Function("INS.SENS1.STAT", None),
'VAL': Function("INS.SENS1.VAL", None)}
}
One can see that the "INS.SENS1" has been droped, so one can use the
restricted dictionary with the "MAX", "MIN", etc keys, but also the
full 'path' will work :
rs = df.restrict("INS.SENS1")
rs["VAL"] #-> works
rs["INS.SENS1.VAL"] #-> works also
So imagine you have a function that plot stuf from sensors you can parse
the restricted dictionary. The function will not care from what ever it comes from.
def plotsensor (df):
# do something here with df['VAL'], df['NAME'], etc...
plotsensor( df.restrict("INS.SENS1"))
plotsensor( df.restrict("INS.SENS2"))
etc ...
#### restricMatch :
`restricMatch(pattern)`
allow to return any Function that match any part of the key. Again an example
on PIONIER:
ics = vlt.readDictionary("PIONIER_ICS")
ics.restricMatch("STOP")
Will return a FunctionDict containing Function that have "SOPT" in the keyword eg. in this case "INSi.GRATi.STOP", "INSi.LAMPi.STOP, etc, ...
#### Other restric function
- restrictContext : restrict the dictionary to the ones mathing context
- restrictHasValue : restrict the dictionary to the ones that has value
- restrictHasNoValue : restrict the dictionary to the ones that has no value
- restrictClass : restrict the dictionary to the ones that match the class
- restrictValue : restrict the dictionary to the ones that match the value
#### setup
setup a bunch of Functions in one call
#### qsetup
does the same than setup but in a easier fashion
#### cmd
get command list to be parsed to process
#### copy
copy the FunctionDict
Devices
=======
Devices are derived from FunctionDict. They are a list of function wrapped
with addiotional usefull capabilities, like e.g. : moveTo, close, etc ...
A few built-in Devices exists:
Motor, Shutter, Detector
!! The devices capability is not complete and should be updated.
Example to create/use a device, on Pionier:
pnoc = vlt.openProcess("pnoControl")
ics = vlt.readDictionary("PIONIER_ICS")
dispersor = vlt.devices.Motor(ics.restrict("INS.OPTI3"), statusItems=[""], proc=pnoc)
# (proc can be also the default process vlt.setDefaultProcess(pnoc) )
dispersor.statusUpdate() # ask the instrument and update values
dispersor.moveTo("FREE") # move to FREE position
dispersor.moveTo(120000) # move to 120000 enc position
dispersor.moveBy(10000) # offset of 10000 enc
Also e.g. `cmd_moveBy` do not do anything but return the function command in a list so commands can be stacked together:
pnoc = vlt.openProcess("pnoControl")
ics = vlt.readDictionary("PIONIER_ICS")
shut1 = vlt.devices.Shutter(ics.restrict("INS.SHUT1"))
pnoc.setup(function=dispersor.cmd_moveTo("FREE")+sh1.cmd_close())
<file_sep>from ..device import Device
class Lamp(Device):
def _check(self):
""" the simple Lamp device needs these keys to work
corectly : "ST"
"""
self._check_keys(["", "ST"])
def cmd_turnOn(self):
return self['ST'].cmd(True, context=self)
def cmd_turnOff(self):
return self['ST'].cmd(False, context=self)
def turnOn(self, proc=None):
return self.getProc(proc).setup(function=self.cmd_turnOn())
def turnOff(self, proc=None):
return self.getProc(proc).setup(function=self.cmd_turnOff())
def getStatus(self, proc=None):
response = self.status(proc=self.getProc(proc))
try:
status = response["ST"]
except KeyError:
raise RunTimeError("Cannot read lamp status: 'ST' function keyword not found in response")
return status
<file_sep>""" Not functional yet """
def _updatedm(dm):
dm.updateZernStatus()
dm.updateActStatus()
class DM(Device):
functions = None
allfunctions = None
xtilt = "ZERN3"
ytilt = "ZERN2"
setup_callback = None
def __init__(self,proc, pref, functions):
self.proc = proc
self.functions = functions.restrict(pref)
self.allfunctions = functions
self.prefix = self.functions._prefix
self.onSetup = Actions(_updatedm)
self.onUpdate = Actions()
self.onUpdateZern = Actions()
self.onUpdateAct = Actions()
def __getitem__(self, item):
return self.functions[item]
def update(self, *args, **kwargs):
return self.functions.update(*args, **kwargs)
def set(self, k,v):
return self.functions.set(k,v)
def cmdSetup(self, dictval=None, **kwargs):
cmd = []
if dictval:
kwargs.update(dictval)
for k,v in kwargs.iteritems():
self.set(k,v)
cmd += self.functions[k].getCmd()
return cmd
def cmdTmpSetup(self, dictval=None, **kwargs):
cmd = []
if dictval:
kwargs.update(dictval)
for k,v in kwargs.iteritems():
cmd += self.functions[k].getCmd(v)
return cmd
def setup(self, dictval=None, **kwargs):
out = self.proc.setup(self.cmdSetup(dictval,**kwargs))
self.onSetup.run(self)
return out
def tmpSetup(self, dictval=None, **kwargs):
out = self.proc.setup(self.cmdTmpSetup(dictval,**kwargs))
self.onSetup.run(self)
return out
def cmdTiptilt(self, x, y):
return self.cmdSetup( {self.xtilt:x, self.ytilt:y} )
def getTiptilt(self):
return (self.functions[self.xtilt].get(), self.functions[self.ytilt].get())
def parseTiptilt(self, x, y):
return {self.xtilt:x , self.ytilt:y}
def tiptilt(self,x,y):
return self.setup(self.parseTiptilt(x,y))
def setOffset(self):
return self.tmpSetup( {"OFVO.CTRL":"SET"})
def resetOffset(self):
return self.tmpSetup( {"OFVO.CTRL":"SET"})
def saveOffset(self, fileName=None):
cmd = {"OFVO.FILE":fileName} if fileName else {}
cmd["OFVO.CTRL"] = "SAVE"
return self.tmpSetup(cmd)
def loadOffset(self, fileName=None):
cmd = {"OFVO.FILE":fileName} if fileName else {}
cmd["OFVO.CTRL"] = "LOAD"
return self.tmpSetup(cmd)
def load(self, fileName, mode="modal"):
if not mode in ["modal", "local"]:
raise KeyError("mode should be 'modal' or 'local'")
if mode=="local":
return self.tmpSetup( {"ACT FILE":fileName} )
else:
return self.tmpSetup( {"ZERN FILE":fileName} )
def save(self, fileName, mode="modal"):
try:
import pyfits as pf
except:
from astropy.io import fits as pf
import numpy as np
if not mode in ["modal", "local"]:
raise KeyError("mode should be 'modal' or 'local'")
if mode == "local":
N = self.getNact()
data = [self.functions["ACT%d"%i].get() for i in range(1, N+1)]
elif mode == "modal":
N = self.getNzern()
data = [self.functions["ZERN%d"%i].get() for i in range(1, N+1)]
f = pf.PrimaryHDU(np.array( data, dtype=np.float64))
return f.writeto(fileName, clobber=True)
def cmdZern(self, modes):
return self.cmdSetup(self.parseZern(modes))
def getZern(self, z):
return self.functions[self.parseZernKey(z)]
def getZerns(self, lst=None, update=False):
if lst is None:
lst = range(1,self.getNzern()+1)
funcs = self.functions.restrict( self.parseZernKeys(lst))
if update:
funcs.statusUpdate(None)
return funcs
def parseZernKey(self, m):
if isinstance(m,str):
if m[0:4].upper() == "ZERN":
m = int(m[4:None])
elif m[0:1].upper() == "Z":
m = int(m[1:None])
else:
raise KeyError("cannot understand zernic key '%s'"%m)
return "ZERN%d"%m
def parseZernKeys(self, keys):
return [self.parseZernKey(m) for m in keys]
def parseZern(self, modes):
it = modes.iteritems() if isinstance(modes,dict) else enumerate(modes,1)
setout = {}
for m,v in it:
if isinstance(m,str):
if m[0:4].upper() == "ZERN":
m = int(m[4:None])
elif m[0:1].upper() == "Z":
m = int(m[1:None])
else:
raise KeyError("cannot understand zernic key '%s'"%m)
setout["ZERN%d"%m] = v
return setout
def zern(self, modes, mode=None):
dzern = self.parseZern(modes)
if mode:
dzern.setdefault("CTRL OP",mode)
return self.setup(dzern)
def getAct(self, a):
return self.functions[self.parseActKey(a)]
def getActs(self, lst=None, update=False):
if lst is None:
lst = range(1,self.getNact()+1)
funcs = self.functions.restrict( self.parseActKeys(lst))
if update:
funcs.statusUpdate(None)
return funcs
def getZernValues(self, lst=None, update=False):
return self.getZerns(lst, update).todict()
def getActValues(self, lst=None, update=False):
return self.getActs(lst, update).todict()
def parseActKey(self, m):
if isinstance(m,str):
if m[0:3].upper() == "ACT":
m = int(m[3:None])
elif m[0:1].upper() == "A":
m = int(m[1:None])
else:
raise KeyError("cannot understand actuator key '%s'"%m)
return "ACT%d"%m
def parseActKeys(self, acts):
return [self.parseActKey(m) for m in acts]
def parseAct(self, acts):
it = acts.iteritems() if isinstance(acts,dict) else enumerate(acts,1)
setout = {}
for m,v in it:
if isinstance(m,str):
if m[0:3].upper() == "ACT":
m = int(m[3:None])
elif m[0:1].upper() == "A":
m = int(m[1:None])
else:
raise KeyError("cannot understand actuator key '%s'"%m)
setout["ACT%d"%m] = v
return setout
def cmdAct(self, acts):
return self.cmdSetup(self.parseAct(acts))
def act(self, acts, mode=None):
dact = self.parseAct(acts)
if mode:
dact.setdefault("CTRL OP",mode)
return self.setup(dact)
def cmdReset(self):
return self.cmdSetup(self.getReset())
def getReset(self):
return {"CTRL.OP":"RESET"}
def reset(self):
return self.setup(self.getReset())
def getNact(self):
return self.allfunctions["AOS.ACTS"].getOrUpdate(proc=self.proc)
def getNzern(self):
return self.allfunctions["AOS.ZERNS"].getOrUpdate(proc=self.proc)
def status(self, statusItems=None):
return self.functions.status(statusItems, proc=self.proc)
def statusUpdate(self, statusItems=None):
return self.functions.statusUpdate(statusItems, proc=self.proc)
def getActStatus(self, nums=None, indict=None):
return self.getIterableKeysStatus("ACT", nums or self.getNact(), indict=indict)
def updateActStatus(self, nums=None, indict=None):
out = self.updateIterableKeysStatus("ACT", nums or self.getNact(), indict=indict)
self.onUpdateAct.run(self)
return out
def updateZernStatus(self, nums=None, indict=None):
out = self.updateIterableKeysStatus("ZERN", nums or self.getNzern(), indict=indict)
self.onUpdateZern.run(self)
return out
def getZernStatus(self, nums=None, indict=None):
return self.getIterableKeysStatus("ZERN", nums or self.getNzern(), indict=indict)
def updateAll(self):
keys = ["%s%d"%("ZERN",i) for i in range(1,self.getNzern()+1)]+["%s%d"%("ACT",i) for i in range(1,self.getNact()+1)]
self.functions.restrict(keys).statusUpdate(None)
self.onUpdate.run(self)
def updateIterableKeysStatus(self,key , nums, indict=None):
if isinstance(nums, int):
nums = range(1,nums+1)
if indict is None:
indict = True
else:
indict = False
keys = ["%s%d"%(key,i) for i in nums]
frest = self.functions.restrict(keys)
frest.statusUpdate(None)
self.onUpdate.run(self)
if indict:
return {n:frest["%s%d"%(key,n)].get() for n in nums}
else:
return [frest["%s%d"%(key,n)].get() for n in nums]
def getIterableKeysStatus(self,key , nums , indict=None):
if isinstance(nums, int):
nums = range(1,nums+1)
if indict is None:
indict = False
else:
indict = True
keys = ["%s%d"%(key,i) for i in nums]
vals = self.status(keys)
pref = self.functions._prefix+"." if self.functions._prefix else ""
if indict:
return {n:vals[pref+"%s%d"%(key,n)] for n in nums}
else:
return [vals[pref+"%s%d"%(key,n)] for n in nums]
class DMs(list):
def plot(self, axes=None, fig=None, vmin=None, vmax=None, cmap=None):
if axes is None:
if fig is not None:
axes = fig.get_axes()
else:
if self[0].graph:
import math as m
N = len(self)
nx = int(m.sqrt(N))
ny = int(m.ceil(N/float(nx)))
fig = self[0].graph.plt.figure("actuactors")
fig.clear()
axes = [fig.add_subplot(nx,ny, i+1) for i in range(N)]
#fig, axes = self[0].graph.plt.subplots(nx,ny)
#axes = axes.flatten().tolist()
if len(axes)<len(self):
raise Exception("not enought axes to plot %d dm"%(len(self)))
for i in range(len(self)):
a = axes[i]
dm = self[i]
dm.plot(axes=a, vmin=vmin, vmax=vmax, cmap=cmap )
def plotzern(self, axes=None, fig=None, **kwargs):
if axes is None:
if fig is not None:
axes = fig.get_axes()
else:
if self[0].zerngraph:
import math as m
N = len(self)
nx = int(m.sqrt(N))
ny = int(m.ceil(N/float(nx)))
fig = self[0].graph.plt.figure("zernics")
fig.clear()
axes = [fig.add_subplot(nx,ny, i+1) for i in range(N)]
#fig, axes = self[0].graph.plt.subplots(nx,ny)
#fig, axes = self[0].graph.plt.subplots(N)
#axes = axes.flatten().tolist()
else:
raise Exception("no zeengraph set")
if len(axes)<len(self):
raise Exception("not enought axes to plot %d dm"%(len(self)))
print kwargs
for i in range(len(self)):
a = axes[i]
dm = self[i]
dm.plotzern(axes=a, **kwargs)
def reset(self):
for dm in self:
dm.reset()
def zern(self, modes):
for dm in self:
dm.zern(modes)
def act(self, actvals):
for dm in self:
dm.act(actvals)
<file_sep>import re
from .keywords import KeywordFile
from ..config import config, log
from ..template import TemplateSignature
from . import ospath
import os
log = log.new(context="TSF/IO")
# opened ISF_FILE
ISF_PARAMS = None
def _start_header(f, key, value, more):
f.start_header()
return f.parse_line(more)
def _end_header(f, key, value, more):
f.end_header()
return f.parse_line(more)
def _new_param(f, key, value, more):
f.parameters[value] = {}
return f.parse_line(more)
def _isisf(value):
return value[0:4] == "ISF "
def _isfvalue(f, value):
isfvalue = value[4:]
if f.isf is None or (not isfvalue in f.isf):
f.log.warning("ISF linked value left has it is for %s " % value)
return value
return f.isf[isfvalue]
class TSF(KeywordFile):
# match : INS.FILT1.RANGE "value"; # more stuff
_c1 = """[ \t]+["]([^"]*)["][ \t]*[;](.*)"""
# match : INS.FILT1.RANGE "value" # comment
_c2 = """[ \t]+["]([^"]*)["]().*"""
# match : INS.FILT1.RANGE value; # more stuff
_c3 = """[ \t]*([^;#" \t]+)[ \t]*[;](.*)"""
# match : INS.FILT1.RANGE value # comment
_c4 = """[ \t]*([^;#" \t]+)().*"""
# match : PAF.HDR.START; #more stuff
_c5 = """[ \t]*[;]()(.*)"""
# match : PAF.HDR.START # comment
_c6 = """[ \t#]?.*()()"""
log = log
reg = re.compile("""^([^ \t;#]+)({c1}|{c2}|{c3}|{c4}|{c5}|{c6})$""".format(
c1=_c1, c2=_c2, c3=_c3, c4=_c4, c5=_c5, c6=_c6
)
)
cases = {
# func of signautre (f, key, value, more)
"PAF.HDR.START": _start_header,
"PAF.HDR.END": _end_header,
"TPL.PARAM": _new_param
}
value_cases = {
_isisf:_isfvalue
}
def __init__(self, *args, **kwargs):
isf = kwargs.pop("isf", None)
super(TSF,self).__init__(*args, **kwargs)
if isinstance(isf, basestring):
isf_file = ISF(isf)
isf_file.parse()
self.isf = isf_file.parameters
else:
self.isf = isf
def key2path(self, key):
keys = key.split(".")
N = len(keys)
if N<2:
return keys[0], None
return ".".join(keys[0:-1]), keys[-1]
def match_line(self, line):
m = self.reg.match(line.strip())
if not m:
return None, None, None
groups = m.groups()
gi = range(2,14,2)# [2,4,6,8, ...]
for i in gi:
if groups[i] is not None:
return groups[0], groups[i], groups[i+1]
raise Exception("BUG none of the group founf in match")
class ISF(TSF):
# same as TSF except that value are stacked in a flat dictionary
value_keys = {}
def key2path(self, key):
return [key]
def findTemplateSignatureFile(file_name, path=None, prefix=None, extention=None):
"""
find the tsf file_name inside the path list.
by default path list is config["tsfpath"]
"""
return ospath.find(file_name, path=path, prefix=prefix, extention=extention,
defaults=config['tsf']
)
def findInstrumentSummaryFile(file_name, path=None, prefix=None, extention=None):
"""
find the tsf file_name inside the path list.
by default path list is config["tsfpath"]
"""
return ospath.find(file_name, path=path, prefix=prefix, extention=extention,
defaults=config['isf']
)
def openTemplateSignature(file_name, path=None, prefix=None, extention=None):
global ISF_PARAMS
if ISF_PARAMS is None: #and config.get("isffile", None):
try:
isffile = findInstrumentSummaryFile(config['isf']['default'])
except IOError:
log.warning("Cannot find isf file %r in any of %r directories"%(config['isf']['default'],config['isf']['path']))
else:
isf = ISF(isffile)
isf.parse()
ISF_PARAMS = isf.parameters
tsffile = findTemplateSignatureFile(file_name, path=path, prefix=prefix,
extention=extention)
f = TSF(tsffile, isf=ISF_PARAMS)
f.parse()
return TemplateSignature.from_dict(f.parameters,f.header, path=tsffile)
<file_sep>from .tsf import openTemplateSignature, findTemplateSignatureFile
from .dictionary import Dictionary, openDictionary, findDictionaryFile
from .cdt import openProcess, processClass, Cdt, findCdtFile, findProcessFile
from .obd import openObd, findObdFile
<file_sep>from os.path import *
def find(name, path=None, prefix=None, extention=None, defaults={}):
path = defaults.get('path',[]) if path is None else path
prefix = defaults.get('prefix',"") if prefix is None else prefix
extention = defaults.get("extention", "") if extention is None else extention
if extention and not name.endswith("."+extention):
name += "."+extention
if prefix and not name.startswith(prefix):
name = prefix+name
for directory in path:
file_path = join(directory, name)
if exists(file_path):
return file_path
raise IOError("cannot find file {0} in any of the path: {1}".format(name, path))
<file_sep>from .mainvlt import Option, VLTError
from .config import config
from .buffread import ErrorStructure
from subprocess import Popen, PIPE
msgSend_cmd = config.get("msgSend_cmd", "msgSend")
def getProc(proc=None):
return proc if proc is not None else getDefaultProcess()
_defaultProcess = None
def setDefaultProcess(proc):
""" set the default process for the vlt module.
if process is a string open it with vlt.io.openProcess
"""
global _defaultProcess
if isinstance(proc, basestring):
from .io.cdt import openProcess
proc = openProcess(proc)
if not isinstance(proc, Process):
raise ValueError("Expecting a Process object got %s"%type(proc))
_defaultProcess = proc
def getDefaultProcess():
""" return the default process of the vlt module """
global _defaultProcess
if _defaultProcess is None:
raise TypeError("There is no default process define, use setDefaultProcess to set")
return _defaultProcess
class Param(Option):
"""
Samething than Option except that if the value is None,
an empty string is return from the function cmd()
"""
def cmd(self,value):
if value is None:
return ""
return "%s %s"%(self.msg, self.formatValue(value))
class Command(object):
options = {}
helpText = ""
_debugBuffer = None
def __init__(self, msg, options, helpText="", bufferReader=None):
self.msg = msg
self.options = options
self.helpText = helpText
self.bufferReader = bufferReader
def cmd(self, kwargs):
for k,opt in self.options.iteritems():
kwargs.setdefault(k, opt.default)
cmds = []
for k,value in kwargs.iteritems():
if not k in self.options:
raise KeyError("The option '%s' is unknown for command %s"%(k,self.msg))
## ignore the value None
opt = self.options[k]
cmdstr = opt.cmd(value)
if cmdstr.strip():
cmds.append(cmdstr)
return """%s \"%s\""""%(self.msg, " ".join(cmds))
def readBuffer(self, buff):
if self.bufferReader is None:
return buff
return self.bufferReader(buff)
def getDebugBuffer(self):
return self._debugBuffer
def setDebugBuffer(self, buf):
self._debugBuffer= buf
def status(self):
return self.proc.status()
class Process(object):
commands = {}
_debug = config.get("debug", False)
_debugBuffer = None
_verbose = config.get("verbose",1)
msg = ""
def __init__(self, msg=None, environment="", commands=None, doubleQuote=False):
commands = commands or {}
for k,cmd in commands.iteritems():
if not issubclass(type(cmd), Command):
raise TypeError("expecting a Command object got %s for key '%s'"%(type(cmd), k))
self.commands[k] = cmd
if msg is not None:
self.msg = msg
self._environment = environment
self.doubleQuote = doubleQuote
self.msgSend_cmd = msgSend_cmd
def setVerbose(self, val):
self._verbose = int(verbose)
def setDebug(self,value):
self._debug = bool(value)
def getDebug(self):
return self._debug
def getVerbose(self):
return self._verbose
def getEnvironment(self):
return self._environment
def setEnvironment(self, environment):
self._environment = environment
def cmd(self, command, options=None, timeout=config.get("timeout",None)):
options = options or {}
if not command in self.commands:
raise KeyError("command '%s' does not exists for this process"%(command))
cmd = self.commands[command]
return _timeout_( "%s %s"%(self.msg, cmd.cmd(options)), timeout)
def cmdMsgSend(self, command, options=None, timeout=config.get("timeout",None), environment=None):
options = options or {}
environment = self._environment if environment is None else environment
return _timeout_("""%s "%s" %s"""%(self.msgSend_cmd, environment, self.cmd(command,options)), timeout)
def msgSend(self, command, options=None, timeout=None, environment=None):
global LASTBUFFER
options = options or {}
cmdLine = self.cmdMsgSend(command, options, timeout=timeout, environment=environment)
if self.getVerbose():
print cmdLine
if self.getDebug():
buf = self.commands[command].getDebugBuffer() or "MESSAGEBUFFER:\n"
objout = self.commands[command].readBuffer(buf)
LASTBUFFER = "DEBUG: %s"%(cmdLine)
return objout
###
## Warning shell=True can represent some danger
## we need to split the command line into arge and options and make shell=False
p = Popen(cmdLine, shell=True, stdout=PIPE, stderr=PIPE)
status = p.wait()
if status:
raise VLTError.from_pipe("msgSend", p)
# stdout = p.stdout.read()
# stderr = p.stderr.read()
# e = VLTError("msgSend reseived error %d\nSTDERR:\n%s\nSTDOUT:\n%s\n"%(status,stderr,stdout))
# try:
# errorStructure = ErrorStructure(stdout)
# except:
# pass
# else:
# e.errorStructure = errorStructure
# ## put the stdout and stderr in the Exception class for
# ## eventual smart catch
# e.stdout = stdout
# e.stderr = stderr
# raise e
output = p.stdout.read()
# status, output = commands.getstatusoutput(cmdLine)
# if status:
# raise VLTError("msgSend reseived error %d"%status)
LASTBUFFER = output
objOutput = self.commands[command].readBuffer(output)
return objOutput
# status, output = commands.getstatusoutput(cmdLine)
# if status:
# raise VLTError("msgSend reseived error %d"%status)
# LASTBUFFER = output
# objOutput = self.commands[command].readBuffer(output)
# return objOutput
def help(self,command=None):
if command is None:
for c in self.commands:
self.help(c)
return
if not command in self.commands:
raise KeyError("command '%s' does not exists for this process"%(command))
opts = ", ".join( "{}={}".format(k,o.dtype) for k,o in self.commands[command].options.iteritems())
print "-"*60
print "{}({})".format(command, opts)
print self.commands[command].helpText
def getCommandList(self):
return self.commands.keys()
def _timeout_(cmd, timeout):
"""
just return the command cmd with the timeout attahced if any
"""
if timeout:
return "%s %d"%(cmd,timeout)
return cmd
class SendCommand(Process):
msg_cmd = "pndcomSendCommand"
def cmdMsgSend(self, command, options=None, timeout=None):
options = options or {}
return """%s %s"""%(self.msg_cmd, self.cmd(command,options))
<file_sep>import re
import os
from ..config import config
from ..function import Function
from ..functiondict import FunctionDict
from ..mainvlt import cmd
from . import ospath
from collections import OrderedDict
cdtconfig = config["cdt"]
cdtpydir = cdtconfig["pydir"]
debug = cdtconfig["debug"]
indentStr = " " # python indent string. Do not change that
vltModuleImport = """from vlt.process import Process, Param, Command;from vlt.mainvlt import formatBoolCommand"""
generalMouleImport ="""
from collections import OrderedDict
"""
vltModulePref = "" # The prefix for vlt module, used to call vlt functions
cdtModuleImport = "from vlt.io import cdt"
cdtModulePref = "cdt." # The prefix for this module, used to call vlt functions
# submodule and class name for buffer reader
buffreadModuleImport = "from vlt.buffread import buffreader"
buffreadClassName = "buffreader"
# Some parameters need special treatment before returned to msgSend
# like function
# which can accept as argument a list of tuple:
# [("cmd1","opt1"),("cmd2","opt2"), ...]
# Add the functions string name in this directory
typeExeption = {
"": { # default ones
"function": cdtModulePref+"dtypeFunctionList",
"params": cdtModulePref+"dtypeFunctionList"
},
"status": { # specific to command status
"function": cdtModulePref+"dtypeFunctionListMsg"
}
}
def msg_send_decorator(msg, commands):
options = commands[msg].options
def tmp(self, *args, **kwargs):
for arg, option in zip(args,options):
if option in kwargs:
raise TypeError("got multiple values for keyword argument '%s'"%option)
kwargs[option] = arg
timeout = kwargs.pop("timeout", None)
return self.msgSend(msg, kwargs, timeout=timeout)
tmp.__doc__ = form_cmd_help(msg,commands[msg])
return tmp
def form_cmd_help(msg,command):
return msg+"("+" ,".join(k+"=%s"%o.dtype for k,o in command.options.iteritems())+")\n\n"+command.helpText
def dtypeFunctionList(function):
"""
write a command line based on an array of tuple :
[("cmd1","opt1"),("cmd2","opt2"), ...]
or an array of string ["cmd1 opt1", "cmd2 opt2", ...]
e.g:
dtypeFunctionList ( [("cmd1","opt1"),("cmd2","opt2"), ...])
will return "cmd1 opt1 cmd2 opt2 ..."
This function is used for instance in message send command
if the unique argument is a str, it is returned as it is.
argument can also be a FunctionDict or a System object, in this case
the command for all functions with a values set is returned.
"""
if issubclass(type(function), str):
return function
if issubclass(type(function), (FunctionDict,)):
return "{}".format(function)
if issubclass(type(function), Function):
return dtypeFunctionList(function.cmd())
function = cmd(function) #to make sure it is a flat list
out = []
for func in function:
if issubclass( type(func), tuple):
if len(func)!=2:
raise TypeError("Expecting only tuble of dim 2 in setup list")
if isinstance( func[1], str):
fs = func[1].strip()
if fs.find(" ")>-1:
out.append("%s '%s'"%(func[0],fs))
else:
out.append("%s %s"%(func[0],fs))
else:
out.append("%s %s"%func)
else:
out.append("%s"%(func))
return " ".join(out)
def dtypeFunctionListMsg(function):
if issubclass( type(function), str) :
return function
if issubclass( type(function), (FunctionDict)):
return " ".join( [f.getMsg() for f in function] )
if issubclass( type(function), (Function)):
return function.getMsg()
return " ".join(function)
class Cdt(file):
"""
A file description parser for CDT ESO files.
the Cdt class is derived from the python file object
# parse the file and return a string of python code containing
# the new class definition
f.parse2pycode(className="pnoControl")
# parse and write the python class definition in a file
parse2pyfile(fileName="pnoControl.py", lassName="pnoControl")
"""
indentSize = 4
indent = 0
commands = {}
cte = {}
curentParameter = None
curentParameters = None
debug = []
def parse(self, line=None, count=0):
if debug:
if line is not None:
self.debug += ["|"+line.rstrip()+"|"]
if line is None:
if debug:
self.debug += [">>> line is None"]
line = self.readline()
while len(line):
if debug:
self.debug += [">>> End of file"]
count += 1
# empty line just continue
if not len(line.strip()):
line = self.readline()
continue
stline = line.lstrip()
# comment line (do actually nothing)
if stline[0:2] == "//":
line = self.commentLine(line)
continue
# include line mut include the new file
# on place
if stline[0:8] == "#include":
line = self.includeLine(line)
continue
# all other type of lines are handled
# by commandLine
line = self.commandLine(line)
return count
def parse2dict(self):
""" Parse the CDT file and return the dictionary containing
the cdt definition.
use parse2pycode to get a more usefull python code.
"""
self.parse()
return self.commands
def parse2pycode(self, className=None, classComment=None,
derived=vltModulePref+"Process"):
"""
parse the file and return a python code containing the class
definition.
equivalent of:
f.parse()
f.pycode(**kwargs)
Keywords
--------
className : (str) the class name. Default, is the Cdt file name
if it does not have invlid python characters
classComment : (str) doc of the class. Default is a explantion
of how the code as been created and general uses
derived : (str) the string of the derived class default is vlt.Process
"""
self.parse()
return self.pycode(className=className, derived=derived,
classComment=classComment)
def pycode(self, className=None, classComment=None, derived=vltModulePref+"Process"):
"""
return the python code definition of this file.
The file MUST have been parsed first.
Keywords
--------
className = (str) the class name. Default, is the Cdt file name
if it does not have invlid python characters
classComment = (str) doc of the class. Default is a explantion
of how the code as been created and general uses
derived = (str) the string of the derived class default is vlt.Process
"""
if className is None:
#take the file name (without extention) as default for className
className = os.path.splitext(os.path.split( self.name)[1])[0]
if re.search( "[^a-zA-Z0-9_]" , className) or re.search( "[^a-zA-Z_]" , className[0]):
raise TypeError("Cannot convert filename '%s' to python class name, contains invalid caracheters, please provide a class name"%(className))
return dict2py(self.commands, className, derived=derived,
classComment=classComment, fileName=self.name)
def write_pyfile(self, filePath=None, className=None,
derived=vltModulePref+"Process",
classComment=None, overWrite=True):
""" write the python code of the curent Cdt file.
The file MUST have been parsed first: f.parse()
Return
------
The file path
Keywords
--------
filePath = (str) path to the file. Default will be the cdt file
name, with the .py extention inside the
config["cdtpydir"] directory.
overWrite = (bool) over write the file if exists. Default is True
** + same keywords as for pycode method **
"""
if filePath is None:
fileName = os.path.split(self.name)
fileName = os.path.splitext(fileName)[0]+".py"
filePath = cdtpydir + "/" + fileName
if not overWrite and os.path.exists(filePath):
raise IOError("The file %s already exists" % (filePath))
g = open(filePath, "w")
g.write(
self.pycode(className=className,
classComment=classComment,
derived=derived
)
)
g.close()
return filePath
def parse2pyfile(self, filePath=None, className=None,
derived=vltModulePref+"Process", classComment=None, overWrite=True):
"""
parse the file and write the process class definition to
a python file.
equivalent to do:
> f.parse()
> f.write_pyfile(file_path)
Keywords
--------
filePath = (str) path to the file. Default will be the cdt file
name, with the .py extention inside the
config["cdtpydir"] directory.
overWrite = (bool) over write the file if exists. Default is True
** + same keywords as for pycode method **
"""
self.parse()
return self.write_pyfile(filePath=filePath, className=className,
classComment=classComment, derived=derived
)
def reset(self):
pass
def commentLine(self, line):
if debug:
self.debug += [">>> Read a comment line"]
return self.readline()
def textLine(self, line, param):
if debug:
self.debug += [">>> Read a help text"]
while True:
tmpline = self.readline()
if not len(tmpline):
if debug:
self.debug += [">>> Finished help text because end of file"]
self.curentCommand[param] = line
return ''
stmpline = tmpline.lstrip()
if len(stmpline) and stmpline[0]=="@":
if debug:
self.debug += [">>> Finished help text because '@' found"]
self.curentCommand[param] = line
return self.readline()
line += tmpline
def cteLine(self, line):
self.cte[line.strip()] = True
return self.readline()
def findIncludeFile(self, fl):
return ospath.find(fl, defaults=cdtconfig)
def includeLine(self, line):
inc, ifl = line.split()
ifl = ifl.strip().strip('"').strip("'")
fl = self.findIncludeFile(ifl)
if fl is None:
raise Exception("coud not fin cdt file '%s'" % (ifl))
f = Cdt(fl)
# make the commands dictionary of f and self the
# same. So everything added by f.parse() will be
# added in self.commands
f.commands = self.commands
# parse the include file
f.parse()
f.close()
return self.readline()
def parameterListStart(self, paramkey):
if debug:
self.debug += [">>> Starting parameter list"]
self.curentCommand[paramkey] = OrderedDict()
self.curentParameters = self.curentCommand[paramkey]
return self.parameterStart(self.readline())
def parameterListEnd(self, line):
if debug:
self.debug += [">>> ending parameter list"]
self.curemtParameters = None
self.curentParameter = None
#return self.parse(line)
return line
def parameterStart(self, line):
if debug:
self.debug += [">>> starting parameter"]
self.curentParameter = {}
return self.parameterLine(line)
def parameterLine(self, iline):
"""
From what I understand each parameters definition
are separated by an empty line or PAR_NAME, see example:
TODO: check what define a new parameter definition block
Empty line or PAR_NAME keyword ?
Should be PAR_NAME i think
PARAMETERS=
PAR_NAME= type
PAR_TYPE= STRING
PAR_OPTIONAL= NO
PAR_MAX_REPETITION= 1
PAR_NAME= params
PAR_TYPE= STRING
PAR_OPTIONAL= YES
PAR_MAX_REPETITION= 999
"""
if not len(iline):
# the line is empty end the curent
# parameter definition
self.parameterEnd()
return self.parameterListEnd()
line = iline.strip()
# a line can have space in it, in this case
# it is not considered as a end of Parameter definition
# not sure about the grammar
if not len(line) or line[0:2] == "//":
return self.readline()
if line[0:4] != "PAR_":
# end the previous/current parameter
self.parameterEnd()
# exit from the Parameters definition
return self.parameterListEnd(iline)
spline = line.split("=", 1)
param, value = spline
param = param.strip()
if param[0:4] == "PAR_": # at this point always true normaly
param = param[4:None]
value = value.strip()
# value can have trailing comment
value = value.split("//")[0]
# well if we found PAR_NAME and the name is already
# defined in curentParameter so we we end the curent
# parameter definition and start a fresh new one
if param == "NAME" and "NAME" in self.curentParameter:
self.parameterEnd()
return self.parameterStart(iline)
self.curentParameter[param] = value
return self.readline()
def parameterEnd(self):
if debug:
self.debug += [">>> ending parameter"]
if not len(self.curentParameter):
#return self.parameterStart()
return None
if not "NAME" in self.curentParameter:
raise Exception("No PAR_NAME for one of the parameter")
pname = self.curentParameter.pop('NAME')
self.curentParameters[pname] = self.curentParameter
self.curentParameter = None
return None
def commandStart(self, commandName):
if debug:
self.debug += [">>> starting command %s "%commandName]
self.commands[commandName] = {}
self.curentCommand = self.commands[commandName]
return self.readline()
def commandEnd(self):
self.curentCommand = None
return self.readline()
def commandLine(self, line):
if self.curentParameter is not None:
# we are curently inside a parameter list
# definition.
return self.parameterLine(line)
spline = line.split("=", 1)
if len(spline) is 1:
return self.cteLine(line)
param, value = spline
param = param.strip()
value = value.strip()
value = value.split("//")[0] # remove comments after value
if param == "COMMAND":
return self.commandStart(value)
if param in ["PARAMETERS","REPLY_PARAMETERS"]:
return self.parameterListStart(param)
if param == "HELP_TEXT":
return self.textLine(self.readline(), param )
if debug:
self.debug += [">>> Set param %s to value %s"%(param, value)]
self.curentCommand[param] = value
return self.readline()
def findCdtFile(file_name, path=None, prefix=None, extention=None):
"""
find the cdt file_name inside the path list.
by default path list is in config["cdt"]["path"]
"""
return ospath.find(file_name, path=path, prefix=prefix,
extention=extention, defaults=cdtconfig
)
findProcessFile = findCdtFile
def processClass(processname, path=None, prefix=None, extention=None):
"""
Return the dynamicaly created python class of a process
The program look for the file processname.cdt into the list of path
directories wich can be set by the path= keyword.
By default config['cdt']['path'] is used
"""
fileName = findCdtFile(processname, path=path, prefix=prefix,
extention=extention)
pycode = Cdt(fileName).parse2pycode()
exec pycode
# the pycode should contain the variable proc
# witch is the newly created object
# and cls for the class
return cls
def openProcess(processname, environment="", path=None, prefix=None,
extention=None):
"""
return processClass(processname, path)()
Prameters
---------
processname: string
the process name (without '.cdt' extention)
environment: string, optional
The envirnoment name used for the process
path: list, optionale
list of path where to find the '.cdt' files, default is config['cdt']['path']
Example
-------
pnoc = openProcess("pnoControl")
pnoc.setup( function="INS.MODE ENGENIERING DET.DIT 0.01" )
"""
return processClass(processname, path=path, prefix=prefix,
extention=extention)(environment=environment)
_cmd2ClassDef_str = """
{idt}def {name}(self, **kwargs):
{idt}{idt}return self.msgSend('{name}', kwargs)
{idt}{className}_commands[{name}]
"""
def cmd2ClassDef(nm, helpText="", indent=1):
"""
internal function used ro create dynamicaly class definition
of VLT msgSend commands.
Add the definition of function named nm with its optional helptext
"""
s = indentStr*(indent)+"def %s(self, **kwargs):\n"%(nm)
s += '%s"""\n%s\n%s"""\n'%( indentStr*(indent+1), helpText, indentStr*(indent+1))
s += "%sreturn self.msgSend('%s', kwargs)\n\n"%(indentStr*(indent+1), nm);
#s += "def msg%s(self, **kwargs):\n"%(nm.capitalize())
#s += '"""\n%s\n"""\n'%command.helpText
#s+=" return self.cmdMsgSend('%s', kwargs)\n\n";
return s
def dict2ClassDef(data, indent=1):
text = ""
for cmdname, cmd in data.iteritems():
text += cmd2ClassDef(cmdname.lower(), cmd.get("HELP_TEXT", ""), indent=indent)
return text
def _wrf(nm, p):
return """ "%s"\t:_ic("%s", "%s"),"""%(nm, nm.upper(), p)
_dict2py_str = """
{generalMouleImport}
{vltModuleImport}
{cdtModuleImport}
class {className}({derived}):
{idt}\"\"\"
{classComment}
{idt}\"\"\"
{idt}{vltModuleImport}
{idt}{cdtModuleImport}
{idt}{buffreadModuleImport}
{idt}commands = {dictpycmd}
{idt}msg = "{className}"
{idt}for c in commands: exec("%s = {cdtModulePref}msg_send_decorator('%s',commands)"%(c,c))
cls = {className}
"""
def dict2py(data, className, derived=vltModulePref+"Process", indent=0,
classComment=None, fileName=""):
"""
Transform a cdt definition dictionary (parsed from Cdt class)
to a string containing the class python code definition
"""
if classComment is None:
classComment = """
This is a {className} class vlt.Process automaticaly generated from file
{fileName}
To get a list of commands:
proc.getCommandList()
To print a help on a specific command (e.g. setup)
proc.help("setup")
proc.help() will return help for every commands
""".format(className=className, fileName=fileName)
dictpycmd = dict2pyCommands(data, indent=indent)
idt = indentStr * (indent+1)
return _dict2py_str.format(**dict(globals().items()+locals().items()))
def keyCommandMaker(command):
command = command.lower()
if command in ["in", "as", "if", "or", "and", "with", "break", "continue", "for", "while", "class", "def", "print"]:
return command.capitalize()
return command
def keyOptionMaker(option):
return option
def scripOptionMaker(option):
return "-%s" % option
# CDT type to python type dictionary transformation
typeDict = {
"INTEGER": "int",
"STRING": "str",
"LOGICAL": "bool",
"REAL": "float"
}
# CDT type to format dictionary transformation
formatDic = {
"INTEGER": '"%d"',
"LOGICAL": vltModulePref+"formatBoolCommand",
"REAL": '"%f"'
}
def type2py(cdt_type, name="", cmd=""):
"""
convert a CDT type to python type string
"""
cmd = cmd.lower()
if cmd in typeExeption:
if name in typeExeption[cmd]:
return typeExeption[cmd][name]
if name in typeExeption['']: #general type exception
return typeExeption[''][name]
if cdt_type not in typeDict:
raise Exception("unknown type '%s'" % cdt_type)
return typeDict[cdt_type]
def type2pyFormat(cdt_type):
""" convert a cdt_type to a python format string
"""
return formatDic.get(cdt_type, '"%s"')
def dict2pyCommands(commands, indent=0):
""" convert a commands dictionary as parsed by Cdt object
to a python code Command definition.
"""
return "OrderedDict([\n"+(",\n".join([dict2pyCommand(k, cmd, indent=indent+1) for k,cmd in commands.iteritems() ] ))+"])"
def dict2pyCommand(command, data, keyMakerFunc=keyCommandMaker, indent=0):
return '%s("%s"\t,%sCommand("%s",%s,helpText="""%s""", bufferReader=%s.getreader("%s")))'%(
indentStr*indent,
keyMakerFunc(command), vltModulePref, command,
dict2pyOptions(data.get("PARAMETERS",{}), cmd=command),
data.get("HELP_TEXT", ""), buffreadClassName , command)
def dict2pyOptions(options, indent=0, cmd=""):
#return [dict2pyOption(k,opt) for k,opt in options.iteritems() ]
return indentStr*indent+"OrderedDict(["+(",".join([dict2pyOption(k,opt,cmd=cmd) for k,opt in options.iteritems() ] ))+"])"
def dict2pyOption(name, option, cmd=""):
return """("%s",%sParam("%s", %s, %s))""" % (keyOptionMaker(name),vltModulePref,scripOptionMaker(name), type2py(option.get('TYPE',"str"), name, cmd), type2pyFormat(option.get("TYPE",'"%s"')))
<file_sep>from ..device import Device
from .detector import Detector
from .motor import Motor
from .shutter import Shutter, Shutters
<file_sep>from __future__ import print_function
from .mainvlt import dotkey, undotkey
from collections import OrderedDict
def dict2param(name, d):
ptype = d.get('TYPE', 'keyword')
cls_lookup = {"number":NumberParam, "integer":IntegerParam,
"keyword":KeywordParam, "coord":CoordParam,
"boolean":BooleanParam, "string":StringParam
}
try:
cls = cls_lookup[ptype]
except KeyError:
raise ValueError("The Parameter type '%s' is not understood"%ptype)
return cls(name=name, default=d.get('DEFAULT',None),
range=d.get("RANGE", None),
label=d.get("LABEL",""), minihelp=d.get("MINIHELP",""),
hide=d.get("HIDE", "")
)
class RangeError(ValueError):
""" Error when a value is out of range """
pass
class ParamRange(object):
pass
class DumyRange(ParamRange):
def __init__(self):
pass
def parse(self, value):
return value
@classmethod
def from_str(cl, st):
raise RangeError("Cannot parse anything to a dummy range")
class NumberRange(ParamRange):
def __init__(self, mini, maxi):
""" Template signature range reader of the for '1..34'
Example
-------
>>> r = NumberRange.fom_str("1..9")
>>> r.parse(4) == 4
True
>> r.parse(13)
RangeError value must be <= 9, got 13
"""
self.mini = mini
self.maxi = maxi
def parse(self, value):
if value<self.mini:
raise RangeError("value must be >= %s, got %s"%(self.mini, value))
if value>self.maxi:
raise RangeError("value must be <= %s, got %s"%(self.maxi, value))
return value
@classmethod
def from_str(cl, st, type=float):
if not ".." in st:
raise ValueError("Invalid range for NumberRange expecting 'min..max' got '%s'"%st)
mini, maxi = st.split("..")
return cl(type(mini), type(maxi))
def to_str(self):
return "%s..%s"%(self.mini, self.maxi)
class KeywordRange(ParamRange):
""" Template signature keyword list range
Example
-------
>>> r = template.KeywordRange.from_str("FREE BEACON LAZER")
>>> r.parse("FREE")
"FREE"
>>> r.parse("HOLE")
RangeError: value must one of 'FREE' 'BEACON' 'LAZER', got HOLE
"""
def __init__(self, lst):
self.lst = list(lst)
def parse(self, value):
if value not in self.lst:
lstsrt = " ".join("%r"%v for v in self.lst)
raise RangeError("value must one of %s, got %s"%(lstsrt, value))
return value
@classmethod
def from_str(cl, st, type=str):
lst = [type(v) for v in st.split(" ") if v]
return cl(lst)
def to_str(self):
return " ".join([str(v) for v in self.lst])
class BooleanRange(KeywordRange):
@classmethod
def from_str(cl, st, type=str):
lst = [type(v) for v in st.split(" ") if v]
return cl([True if v is "T" else False for v in lst] )
class CoordRange(ParamRange):
def __init__(self, coordtype):
coordtype = coordtype.lower()
lookup = ["ra", "dec"]
if coordtype not in lookup:
raise ValueError("Invalid Range for coord expecting one of %s got '%s'"%(" ".join("%r"%l for l in lookup), coordtype))
def parse(self, value):
## :TODO: make the coordinate parser
print("WARNING coordinate parser not yet implemented")
return value
@classmethod
def from_str(cl, st):
return cl(st)
class TemplateSignatureParam(object):
""" Template Param object hold Param definition and value/range parser """
_range = None
_default = None
_miniHelp = ""
_hide = ""
def __init__(self, name="", type="", default=None,
range=None,
label="", minihelp="", hide=""):
self.setName(name)
self.setRange(range)
self.setDefault(default)
## heart of the object type parser
## list of range classes excepted by this Parameter
_range_classes = [ParamRange]
def _parse_type(self, value):
return str(value)
def _parse_range(self, value):
try:
newval = self.range.parse(value)
except RangeError as e:
raise RangeError("When parsing '%s' for key '%s' : %s"%(value, self.name, e))
return newval
def parse(self, value):
value = self._parse_type(value)
value = self._parse_range(value)
return value
def match(self, pattern):
patterns = dotkey(pattern).split(".")
keys = self.name.split(".")
shortkeys = keys[0:len(patterns)]
return shortkeys==patterns, ".".join(keys[len(patterns):])
#############################
# name
def setName(self, name):
self._name = dotkey(str(name))
def getName(self):
return self._name
@property
def name(self):
return self.getName()
@name.setter
def name(self, name):
self.setName(name)
#############################
# default
def setDefault(self, default):
try:
self._default = self.parse(default)
except RangeError:
print ("Warning default value %r of '%s' is out of range"%(default,self.name))
def getDefault(self):
return self._default
@property
def default(self):
return self.getDefault()
@default.setter
def default(self, default):
self.setDefault(default)
#############################
# minihelp
def setMiniHelp(self, miniHelp):
self._miniHelp = str(miniHelp)
def getMiniHelp(self):
return self._miniHelp
@property
def miniHelp(self):
return self.getMiniHelp()
@miniHelp.setter
def miniHelp(self, miniHelp):
self.setMiniHelp(miniHelp)
#############################
# label
def setLabel(self, label):
self._label = str(label)
def getLabel(self):
return self._label
@property
def label(self):
return self.getLabel()
@label.setter
def label(self, label):
self.setLabel(label)
#############################
# hide
def setHide(self, hide):
self._hide = str(hide)
def getHide(self):
return self._hide
@property
def hide(self):
return self.getHide()
@hide.setter
def hide(self, hide):
self.setHide(hide)
#############################
# range
def setRange(self, range):
if range is None:
self._range = DumyRange()
return
elif range is tuple:
if len(range)!=2:
raise ValueError("range must be None, a 2 tuple or a list")
self._range = NumberRange(*range)
return
elif hasattr(range,"__iter__"):
self._range = KeywordRange(range)
elif isinstance(range, basestring):
for cl in self._range_classes:
try:
rg = cl.from_str(range)
except ValueError:
continue
else:
range = rg
break
else:
raise ValueError("Invalid string range '%s' for '%s'"%(range, self.name))
self._range = range
return
elif isinstance(range, ParamRange):
self._range = range
return
raise ValueError("range must be None, a 2 tuple, a list or a ParamRange instance got a '%s'"%type(range))
def getRange(self):
return self._range
@property
def range(self):
return self.getRange()
@range.setter
def range(self, range):
self.setRange(range)
class NumberParam(TemplateSignatureParam):
_range_classes = [NumberRange, KeywordRange]
def _parse_type(self, value):
return float(value)
class IntegerParam(TemplateSignatureParam):
_range_classes = [NumberRange, KeywordRange]
def _parse_type(self, value):
return int(value)
class KeywordParam(TemplateSignatureParam):
_range_classes = [KeywordRange]
def _parse_type(self, value):
return str(value)
class StringParam(TemplateSignatureParam):
_range_classes = [KeywordRange]
def _parse_type(self, value):
return str(value)
class KeywordListParam(TemplateSignatureParam):
_range_classes = [KeywordRange]
def _parse_type(self, value):
if isinstance(value, basestring):
value = [str(v) for v in value.split(" ") if v]
else:
value = [str(v) for v in value]
return value
def _parse_type(self, value):
if isinstance(value, basestring):
value = [str(v) for v in value.split(" ") if v]
value = [self.range.parse(v) for v in value]
return value
class KeywordListParam(TemplateSignatureParam):
_range_classes = [KeywordRange]
def _parse_type(self, value):
if isinstance(value, basestring):
value = [str(v) for v in value.split(" ") if v]
else:
value = [str(v) for v in value]
return value
def _parse_type(self, value):
if isinstance(value, basestring):
value = [str(v) for v in value.split(" ") if v]
value = [self.range.parse(v) for v in value]
return value
class CoordParam(TemplateSignatureParam):
_range_classes = [CoordRange]
def _parse_type(self, value):
return str(value)
class BooleanParam(TemplateSignatureParam):
_range_classes = [BooleanRange]
def _parse_type(self, value):
return bool(value)
class TemplateSignature(OrderedDict):
def __init__(self, *args, **kwargs):
header = kwargs.pop("header", {})
info = kwargs.pop("info", {})
super(TemplateSignature, self).__init__(*args, **kwargs)
for key, param in self.iteritems():
if not isinstance(param, TemplateSignatureParam):
raise ValueError("all items value should be of instance TemplateSignatureParam got a '%s'"%(type(param)))
self._header = header
self._info = info
self._path = ""
def __getitem__(self, item):
item = dotkey(item)
try:
return super(TemplateSignature,self).__getitem__(item)
except KeyError:
for param in self.itervalues():
if item == param.name:
return param
raise KeyError("%r"%item)
def __contains__(self, item):
item = dotkey(item)
if super(TemplateSignature,self).__contains__(item):
return True
for param in self.itervalues():
if item == param.name:
return True
return False
@classmethod
def from_dict(cls, parameters, header={}, path=""):
parameters = parameters.copy()
tplinfo = parameters.pop("TPL", {})
parameters = [(key,dict2param(key,param)) for key,param in parameters.iteritems()]
new = cls(parameters, header=header, info=tplinfo)
new.path = path
return new
@property
def info(self):
return self._info
@property
def header(self):
return self._header
def _copy_attr(self, new):
d = dict(self.__dict__)
d.pop('_OrderedDict__root', None)
d.pop('_OrderedDict__map' , None)
new.__dict__.update(d)
return new
def getPath(self):
return self._path
@property
def path(self):
return self._path
def restrict(self, patter_or_list):
items = []
if isinstance(patter_or_list, basestring):
pattern = patter_or_list
for key, param in self.iteritems():
match, shortkey = param.match(pattern)
if match:
items.append( (shortkey, param))
else:
lst = patter_or_list
for key in lst:
items.append( (key, self[key]) )
new = self.__class__(items)
self._copy_attr(new)
return new
class ObdParam(object):
""" OBD Parameter is a TemplateSignatureParam with Value attached """
def __init__(self, param, value):
self._param = param
self._value = param.parse(value)
@property
def param(self):
""" Value Paramter """
return self._param
def __str__(self):
return """{0}="{1}" """.format(self.name, self.value)
def __repr__(self):
return """{0:25}\t{1!r} """.format(self.name, self.value)
def setValue(self, value):
self._value = self.param.parse(value)
def getValue(self):
return self._value if self._value is not None else self.param.default
@property
def value(self):
return self.getValue()
@value.setter
def value(self, value):
self.setValue(value)
@property
def name(self):
return self.param.name
def hasValue(self):
""" True if OB Param has a value set """
return self.value is not None
def match(self, pattern):
return self.param.match(pattern)
class Obd(list):
def __init__(self, templates, info={}, path=""):
super(Obd,self).__init__(templates)
self._info = info
self._path = ""
def __getitem__(self, item):
value = super(Obd,self).__getitem__(item)
if isinstance(value, ObdTemplate):
return value
return self.__class__(value, info=self._info.copy())
def __setitem__(self, item, tpl):
if not isinstance(tpl, ObdTemplate):
raise ValueError("item must be of instance ObdTemplate got a '%s'"%(type(tpl)))
super(Obd, self).__setitem__(item, tpl)
def __repr__(self):
return "\n\n".join("%r"%tpl for tpl in self)
def getPath(self):
return self._path
@property
def path(self):
return self._path
def append(self, tpl):
if not isinstance(tpl, ObdTemplate):
raise ValueError("item must be of instance ObdTemplate got a '%s'"%(type(tpl)))
super(Obd, self).append(tpl)
def extend(self, tpls):
for tpl in tpls:
if not isinstance(tpl, ObdTemplate):
raise ValueError("all items must be of instance ObdTemplate got one '%s'"%(type(tpl)))
super(Obd, self).extend(tpl)
def restrict(self, name_or_list):
if isinstance(name_or_list, basestring):
return self.__class__( [tpl for tpl in self if tpl.match(name_or_list)], self._info.copy())
else:
return self.__class__( [self[index] for index in name_or_list], self._info.copy())
class ObdTemplate(OrderedDict):
def __init__(self, id, name, obdParams, info={}):
super(ObdTemplate, self).__init__(obdParams)
self._id = id
self._name = name
self._info = info
for key, value in self.iteritems():
if not isinstance(value, ObdParam):
raise ValueError("All params items must be ObdParam object")
def __getitem__(self, item):
item = dotkey(item)
try:
return super(ObdTemplate, self).__getitem__(item)
except KeyError:
for param in self.itervalues():
if item == param.name:
return param
raise KeyError("%r"%item)
def __setitem__(self, item, value):
super(ObdTemplate, self).__setitem__(dotkey(item),value)
def __contains__(self, item):
item = dotkey(item)
if super(ObdTemplate, self).__contains__(item):
return True
for param in self.itervalues():
if item == param.name:
return True
return False
def __repr__(self):
text = """###### {self.id} {self.name} ###### \n""".format(self=self)
for key, param in self.iteritems():
key = "[%s]"%key
text += """ {key:27} {param!r}\n""".format(key=key,param=param)
return text
def __str__(self):
super(ObdTemplate, self).__str__()
@property
def info(self):
return self._info
# def get(self, item , default):
# return self.params.get(item, default)
# def update(self, __d__={}, **kwargs):
# return self.params.update(__d__, **kwargs)
# def keys(self):
# return self.params.keys()
# def values(self):
# return self.params.values()
# def items(self):
# return self.params.items()
# def iterkeys(self):
# return self.params.iterkeys()
# def itervalues(self):
# return self.params.itervalues()
# def iteritems(self):
# return self.params.iteritems()
# def match(self, name):
# self.name == name
@property
def id(self):
return self._id
@property
def name(self):
return self._name
@property
def params(self):
return self._params
def restrict(self, name_or_list):
if isinstance(name_or_list, basestring):
outitems = []
for key, param in self.iteritems():
match, shortkey = param.match(name_or_list)
if match:
outitems.append((shortkey, param))
return self.__class__( self.id, self.name, OrderedDict(outitems), self.info.copy())
else:
return self.__class__( self.id, self.name, {key:self[keys] for key in name_or_list}, self.info.copy())
<file_sep>import re
from .mainvlt import dotkey, undotkey, EmbigousKey
from .function import Function, upperKey, FunctionMsg
from .process import getProc
from .action import Actions
from .config import config
from .process import Process
KEY_MATCH_CASE = config.get("key_match_case", False)
def remove_dict_prefix(din, prefix, err=False):
plen = len(prefix)
for k, v in din.items(): # do not use iteritems here
if not isinstance(k,str): continue
if k[0:plen] == prefix:
newk = k[plen:None].strip(". ")
if not newk in din:
din.pop(k)
din[newk] = v
elif err:
raise KeyError("key '%s' already exists"%newk)
elif err:
raise KeyError("cannot match prefix '%s' in key '%s'"%(prefix, k))
def merge_function_dict(left, right):
trueKey = (bool(left._prefix) or bool(right._prefix)) and (left._prefix!=right._prefix)
left = left.copy( trueKey=trueKey)
right = right.copy(trueKey=trueKey)
left.update(right)
if trueKey:
left._prefix = None
return left
def functionlist(*args):
""" return a FunctionDict from a list of Function or string
or tuple defining the function.
"""
fd = FunctionDict()
fd.add(*args)
return fd
def _test_rec_value(ftest, f, out):
if not f.isIterable():
if ftest(f.getValue()):
out[f.getMsg()] = f
return
for k in f:
_test_rec_value(ftest, f[k], out)
class FunctionDict(dict):
""" Collection of Function with handy methods.
"""
keySensitive = False
dotSensitive = False
noDuplicate = False
_child_object = Function
_prefix = None
_proc = None
_context = None
statusItems = None
onSetup = None # ignitialised in __init__
onUpdate = None
def __init__(self, *args, **kwargs):
super(FunctionDict,self).__init__(*args, **kwargs)
for k, opt in self.iteritems():
if not issubclass( type(opt), self._child_object):
raise ValueError("All element of %s must be a subclass of %s"%(self.__class__, self._child_object))
if self.noDuplicate:
dup = self._checkduplicate(k, opt)
if dup:
raise ValueError("Duplicate not permited. The parameter '%s' already exists under the key '%s' for message '%s'"%(k, dup, self[dup].getMsg()))
self.onSetup = Actions()
self.onUpdate = Actions()
def __call__(self, preforlist):
out = self.restrict( preforlist )
if len(out)==1:
return out['']
return out
def __getitem__(self,item):
if issubclass(type(item), tuple):
if len(item)>2:
raise IndexError("axcept no more than two items, second item should be a string")
if len(item)>1:
attr_key = [item[1]]
else:
# case of f[key,] by default this is "value"
attr_key = "value"
attr = "get"+attr_key.capitalize()
out = self[item[0]]
if not hasattr(out, attr):
raise AttributeError("method %s does not exists for obj of class"%(attr, out.__class__))
out = getattr(out, attr)
if isinstance(out, dict) and self._prefix:
out.setPrefix(self._prefix)
if isinstance( out, FunctionDict):
self._copy_attr(out)
return out
if not item in self:
raise KeyError("item '%s' does not exists for the FunctionDict"%item)
return self.get(item)
def __setitem__(self,item, val):
""" d[item] = val
see method .setVal for more help
"""
# setitem understand what to do function to the value
# if value is a self._child_object it will be set like on a dictionary
# else try to set the value inside the _child_object, if that case if the key does not
# exists raise a KeyError
if issubclass(type(item), tuple):
if len(item)>2:
raise IndexError("axcept no more than 2 items, second item should be a string")
if len(item)>1:
self[item[0]][item[1]] = val
return None
else:
# case of f[key,] by default this is "value"
self[item[0]]["value"] = val
return None
return self.setVal(item, val)
def __contains__(self,item):
if super(FunctionDict, self).__contains__(item):
return True
context = self.getContext()
keys = FunctionMsg(dotkey(item))
for f in self.itervalues():
if f.match(keys, context=context):
return True
if False and self._prefix:
item = "%s.%s"%(self._prefix,keys)
for f in self.itervalues():
if f.match(keys, context=context):
return True
return False
def key(self,item):
if super(FunctionDict, self).__contains__(item):
return item #key is the item
keys = FunctionMsg(dotkey(item))
for k,f in self.iteritems():
if f.match(keys):
########
# Check if self[k] is the same than self[item]
# because, e.g. DET.DIT can match DETi.DIT but are not
# the same output
if self[k]==self[item]: return k
return item
if False and self._prefix:
item = "%s.%s"%(self._prefix,keys)
for k,f in self.iteritems():
if f.match(keys):
if self[k]==self[item]: return k
return item
return None
def __radd__(self, left):
return merge_function_dict(self,left)
return self.__class__(left.copy().items()+self.copy().items())
def __add__(self, right):
return merge_function_dict(right, self)
return self.__class__(self.copy().items()+right.copy().items())
def __format__(self, format_spec):
if not len(format_spec):
format_spec = "s"
if format_spec[-1] != "s":
raise Exception("FunctionDict accept only 's' formater ")
return cmd2str(self.rcopy().cmd())
def getProc(self, proc=None):
try:
return proc if proc is not None else getProc(self._proc)
except:
raise Exception("No default process in the FunctionDict neither in the VLT module")
def setProc(self, proc):
if not isinstance(proc, Process):
raise ValueError("Expecting a procees object")
self._proc = proc
proc = property(fget=getProc, fset=setProc,
doc="vlt process run .proc.help() for more doc"
)
def getSelected(self, id=True):
out = {k:f for k,f in self.iteritems() if f.isSelected(id)}
return self._copy_attr(self.__class__(out))
def getUnSelected(self, id=True):
out = {k:f for k,f in self.iteritems() if not f.isSelected(id)}
return self._copy_attr(self.__class__(out))
def selectAll(self, id=True):
for f in self.itervalues():
f.select(id)
def unselectAll(self):
for f in self.itervalues():
f.unselect()
def setPrefix(self, prefix):
""" To be droped """
remove_dict_prefix(self, prefix, True)
self._prefix = prefix
def restrict(self, preforlist, context=None):
""" restrict the FunctionDict to matched items
Parameters
----------
preforlist : string or list of string
- if a string. in this case the returned dictionary will be restricted
to all Function with a key starting by the string
e.g.:
d = vlt.functionlist( "INS1.OPT1.NAME grism", "INS1.OPT1.ENC 1200",
"INS1.OPT2.NAME grism", "INS1.OPT2.ENC 800")
restricted = d.restrict("INS1.OPT1")
return a dictionary with only the element starting by "INS1.OPT1"
The "INS1.OPT1" will be dropped in the return dictionary.
So restricted["NAME"] will work but conveniently
restricted["INS1.OPT1.NAME"] will work as well
- if a list of string keys:
the returned FunctionDict will be restricted to the matched keys
context : any object, optional
the context object use to rebuild Function keys if needed.
see setContext method help for more info.
Returns
-------
df : FunctionDict
Restricted FunctionDictionary
See Also
---------
restrictClass, restrictContext, restrictValue, restrictHasValue,
restrictHasNoValue
Examples
--------
restricted = fd.restrict("INS.SENS1")
"""
context = self.getContext(context)
if issubclass( type(preforlist), str):
pref = dotkey(preforlist)
out = {}
for k,f in self.iteritems():
m = f.match(pref, context=context, prefixOnly=True)
if m:
nf = f[m.indexes] if m.indexes else f
out[m.suffix] = nf
if self._prefix: # try the same with prefix
pref = dotkey("%s.%s"%(self._prefix,preforlist))
m = f.match(pref, context=context, prefixOnly=True)
if m:
nf = f[m.indexes] if m.indexes else f
out[m.suffix] = nf
out = self._copy_attr(self.__class__(out))
out._prefix = (self._prefix+"." if self._prefix else "")+preforlist
return out
lst = preforlist
keys = [k if isinstance(k,tuple) else (k,k) for k in lst]
return self._copy_attr(self.__class__({ka:self[k] for k,ka in keys}))
def restrictParam(self, params, getmethod, test):
if not isinstance(params , (list,tuple)):
params = [params]
out = {}
for k,f in self.iteritems():
for p in params:
t = test( p,getmethod(f))
if isinstance(t, tuple): # got a test, key pair
t, matched_f = t
out[matched_f.getMsg()] = matched_f
elif t:
out[k] = f
continue
return self._copy_attr( self.__class__(out))
def restrictClass( self, cls):
""" return a restricted FunctionDict of Function of 'class' cls
Parameters
----------
cls : string, list
can be a string or a list of string match
Returns
-------
df : FunctionDict
Restricted FunctionDictionary
"""
return self.restrictParam(cls, self._child_object.getCls, lambda p,l:p in l)
def restrictContext( self, context):
""" return a restricted FunctionDict of Function of 'context' context
Parameters
-----------
context : string, list
can be a string or a list of string match
Returns
-------
df : FunctionDict
Restricted FunctionDictionary
"""
return self.restrictParam(context, self._child_object.getContext, lambda p,l: p==l)
def restrictValue(self, value):
""" return a restricted FunctionDict of Function with the given value
Parameters
----------
value : any or method
If value is a list, return Function of all matched values.
value can be a function that takes one argument (the value to test)
The test is executed only on Functions that has a value, so :
d.restrictValue( lambda v:True)
is equivalent to
d.restrictHasValue()
Returns
-------
df : FunctionDict
Restricted FunctionDictionary
Examples
--------
d.restrictValue([1,10])
d.restrictValue(lambda v:v>1.0)
d.restrictValue(lambda v: v is "TEMPERATURE")
"""
if hasattr(value, "__call__"):
ftest = value
else:
if not isinstance(value , (list,tuple)):
value = [value]
ftest = lambda v: v in value
out = {}
for k,f in self.restrictHasValue().iteritems():
_test_rec_value(ftest, f, out)
return self._copy_attr( self.__class__(out))
return self.restrictHasValue().restrictParam([value],
lambda f: f,
_test_rec_value)
def restrictHasValue(self):
""" Return a FunctionDict restrited to functions with value defined
Parameters
-----------
Returns
-------
df : FunctionDict
Restricted FunctionDictionary
"""
return self.restrict([k for k,f in self.iteritems() if f.hasValue()])
def restrictHasNoValue(self):
""" Return a FunctionDict restrited to functions *without* value defined
Parameters
-----------
Returns
-------
df : FunctionDict
Restricted FunctionDictionary
"""
return self.restrict([k for k,f in self.iteritems() if not f.hasValue()])
def restrictMatch(self, pattern, context=None):
""" Reutnr a FunctionDict restricted to mathed Key Function
Parameters
----------
patern : string
the patern to be matched in the function names
e.g.: restrictedMatch( "VALUE")
will return a FunctionDict containing the "VALUE" key like
for instance "INS1.FILT1.VALUE"
context : any object, optional
the context object use to rebuild Function keys if needed.
see setContext method help for more info.
Returns
-------
df : FunctionDict
Restricted FunctionDictionary
"""
context = self.getContext(context)
return self.restrict([k for k,f in self.iteritems() if f.match(pattern, context=context)])
def has_key(self,key):
return key in self
def add(self, *args):
""" Add item(s) to the dictionary.
Parameters
----------
*items : Function or string or tuple
- if Function. Added as it is
- if string. Should be a space separated key value string which will be converted
on the fly to a new function.
- if tuple. should be a 2 tuple (key, value) pair which will be converted
on the fly to a new function.
Returns
-------
None
Examples
--------
d.add( "INS1.OPT1.ENCREL 2400", Function("DET.DIT", 0.0001),
("DET.NDIT", 1000), .....
)
"""
for arg in args:
if isinstance(arg, (tuple,basestring)):
arg = Function.newFromCmd(arg)
if not isinstance(arg, self._child_object):
raise TypeError("argument should be tuple or Function, got %s" % arg)
super(FunctionDict, self).__setitem__(arg.getMsg(), arg)
def setVal(self, item, val):
""" Set a function child value
fd.setVal(item, value) equivalent to fd[item] = value
Parameters
----------
item : string
The function item to be modified.
value : Function or tuple or any value
If the item *already exists* in the FunctionDict the value can be both:
- a new Function object (will replace the previous)
- a value (str, int, etc ...) in that case the value is set in
the coresponding Function.
If the item *does not exists* value should be:
- a Function object
- a (key, value) pair : key being the function message (e.g. 'ISN1.OPT1.VALUE')
Examples
---------
d = FunctionDict( dit=Function("DET.DIT", float) )
d['dit'] = Function("DET.DIT", float) #will work
d['dit'] = 0.001 #will work
d['DET.DIT'] = 0.001 #will work
d['dummy'] = 10 #ERROR dummy does not exists
d['dummy'] = Function("DET.DUMMY", int) #will work
"""
if isinstance(val, tuple):
val = Function.newFromCmd(val)
if not KEY_MATCH_CASE:
item = upperKey(item)
if issubclass(type(val), self._child_object):
if self.noDuplicate:
dup = self._checkduplicate(item, val)
if dup:
raise ValueError("Duplicate not authorized. The parameter already exists under the key '%s' for message '%s'"%(dup, self[dup].getMsg()))
super(FunctionDict, self).__setitem__(item, val)
return None
if not item in self:
ikey = self.getIterableKeyLike(item)
if ikey[0] in self:
return self[ikey[0]][ikey[1]].setValue(val)
raise KeyError("Element '%s' does not exist. Cannot set a none %s object if the item does not exists"%(item,self._child_object))
return self[item].setValue(val)
_match_iter_num_re = re.compile("[0-9]+")
def getIterableKeyLike(self, key):
ikey = self._match_iter_num_re.sub( "i", key)
indexes = tuple([int(m) for m in self._match_iter_num_re.findall(key)])
return (ikey, indexes)
def hasIterableKeyLike( self, key):
""" Look if can find a iterable param that match a numbered param
e.g. "DET0 SUBWIN4" should return True if "DETi SUBWINi" exists
"""
return self.getIterableKeyLike(key)[0] in self
def getContext(self, context=None):
""" get the default FunctionDict context
context is any object that is used to rebuild Function keys or function
values. If a key contains {var} var is searched in context['var'] and
{var} is replaced by its string value representation.
Parameters
----------
context : any object, optional
An alternative context, if not None
Returns:
context : any object
the recorded or user provided context
"""
if context is None:
context = self._context
if context is False:
return None
if context is True:
return self
return context
def setContext(self, context):
""" set the default FunctionDict context
Parameters
----------
context : any object
the context object to be recorded as default
Returns
-------
None
"""
self._context = context
@property
def context(self):
""" FunctionDict context
if setted as True, the context is the FunctionDict itself
"""
return self.getContext()
@context.setter
def context(self, context):
self.setContext(context)
def update(self, __d__={}, **kwargs):
""" Upadte the FunctionDict with new values of Functions
All values should follow the setVal method protocol
Parameters
----------
fd : dict or FunctionDict or list of item/value pairs
The item/function or item/tuple or item/value pairs
(see setVal)
**kwargs : dict
additional pairs, overwrite the one of *fd*
Returns
-------
None
"""
iterator = __d__.iteritems() if isinstance( __d__, dict) else __d__
for k,a in iterator:
self[k] = a
for k,a in kwargs.iteritems():
self[k] = a
def set(self, *args, **kwargs):
""" alias of update except that set return the object for quick access
Parameters
----------
see update
Returns
-------
fd : FunctionDict
the called FunctionDict : e.i. fd.set() is fd -> True
Example
-------
df.set(dit=0.003).setup()
"""
self.update(*args, **kwargs)
return self
def get(self, item, default=None, context=None):
""" get a Function inside the FunctionDict
fd.get(item) is equivalent to fd[item]
Parameters
----------
item : string
the item string to match either the FunctionDict key or a
child Function key.
meaning that :
fd = vlt.FunctionDict( dit=vlt.Function("DET1.DIT", 0.003) )
fd.get("dit")
fd.get("DET1.DIT")
fd.get("DIT")
are equivalent because is not embigous.
However in embigous case :
fd = vlt.FunctionDict( dit =vlt.Function("DET1.DIT", 0.003),
ndit=vlt.Function("DET1.NDIT", 10)
)
fd.get("dit") -> ok
fd.get("ndit") -> ok
fd.get("NDIT") -> ok
fd.get("DET1.NDIT") -> ok
fd.get("DET1") -> *NOT OK* raise a embigousKey error:
EmbigousKey: "Embigous key 'DET1'"
default : Function
a default Function object if the item is not in the FunctionDict
Returns
-------
f : the found child Function
Raises
------
EmbigousKey : if item key is embigous
"""
if default is not None and not isinstance(default, self._child_object):
raise ValueError( "default should be None or a %s object "%self._child_object)
context = self.getContext(context)
if super(FunctionDict, self).__contains__(item):
return super(FunctionDict, self).get(item, default)
if not KEY_MATCH_CASE:
uitem = upperKey(item)
if super(FunctionDict, self).__contains__(uitem):
return super(FunctionDict, self).get(uitem, default)
fout = None
for f in self.values():
m = f.match(item, context=context)
if m:
if fout:# and fout.match(item):
if m.partialy:
raise EmbigousKey("Embigous key '%s'"%item)
fout = f[m.indexes] if m.indexes else f
if not m.partialy: break #no embiguity stop here
if fout:return fout
if self._prefix:
item = "%s.%s"%(self._prefix,item)
for f in self.values():
m = f.match(item, context=context)
if m:
if fout:
raise EmbigousKey("Embigous key '%s'"%item)
fout = f[m.indexes] if m.indexes else f
if not m.partialy: break #no embiguity stop here
if fout:return fout
return default
def _status(self, statusItems=None, proc=None):
statusItems = statusItems or []
return self.getProc(proc).status(function=statusItems)
_spacereg = re.compile("[ ]+")
def status(self, statusItems=None, proc=None, indict=False):
""" status return a dictionary of key/value pairs returned from the process
Parameters
----------
statusItems : list or string or False or None, optional
- if string must be space separated items ("DIT NDIT" equivalent to ["DIT", "NDIT"])
is transformed to a list.
- if None the default fd.statusItems is used
- if explicitely False all the items of the dictionary are used to ask status
The items in statusItems are used to query the process. Some time items cannot
be parsed in the status command. For instance, to know the status of a device
only the e.g. 'INS.OPTI3' key is needed to query all information about INS.OPTI3
proc : Process, optional
If None use the default process of this FunctionDict or the default process
( see vlt.setDefaultProcess ) raise an Exception if no process can be found.
indict : bool, optional
if True the key/pairs results are returned in a classic dictionary
if False (default) resutls is returned in a FunctionDict
Returns
-------
fd : dict or FunctionDict
the key/value pairs returned
Examples
--------
statusvalue = fd.status( ["INS.OPT3", "INS.SHUT1"] )
See Also Method
---------------
statusUpdate : update the dictionary value returned by the process status command
"""
if statusItems is None:
statusItems = self.statusItems
if isinstance(statusItems, str):
statusItems = self._spacereg.split(statusItems)
if (statusItems is None) or (statusItems is False):
# Take alle the keys to ask status
statusItems = self.keys()
if statusItems:
statusMsg = [self[k].getMsg() for k in statusItems]
st = self.getProc(proc).status(function=statusMsg)
valdict = st
if indict:
return valdict
return self.dict2func(valdict)
def dict2func(self, dictval):
""" Transform a dictionary to a new FunctionDict
If the item is present in the FunctionDict the matched Function is copied
and the value is update to the copy. If the item is not present a new Function
is created as Function(key, value).
This method allows to use a FunctionDict as a template.
Parameters
----------
dictval : dict like object
key/value pairs to be transfomed to Function
Returns
-------
fd : created FunctionDict obect
"""
output = FunctionDict()
for k,v in dict(dictval).iteritems():
ks = self.key(k)
if ks:
f = self[ks].copy()
f.set(v)
output[ks] = f
else:
output[k] = Function(k,v)
return self._copy_attr(output)
def statusUpdate(self, statusItems=None, proc=None):
""" Update the disctionary Function values from the Process.
Parameters
----------
statusItems : list or string or False or None, optional
- if string must be space separated items ("DIT NDIT" equivalent to ["DIT", "NDIT"])
is transformed to a list.
- if None the default fd.statusItems is used
- if explicitely False all the items of the dictionary are used to ask status
The items in statusItems are used to query the process. Some time items cannot
be parsed in the status command. For instance, to know the status of a device
only the e.g. 'INS.OPTI3' key is needed to query all information about INS.OPTI3
proc : Process, optional
If None use the default process of this FunctionDict or the default process
( see vlt.setDefaultProcess ) raise an Exception if no process can be found.
Returns
-------
fd : FunctionDict
A restricted vertion of the FunctionDict. Restricted to items that
has been updated.
Examples
--------
fd.statusUpdate( ["INS.OPT3", "INS.SHUT1"] )
See Also Method
---------------
status : get the status key/pair values without affecting the FunctionDict
"""
vals = self.status(statusItems, proc=proc, indict=True)
setkeys = []
for k,v in vals.iteritems():
if k in self:
self[k].setValue(v)
setkeys.append(k)
self.onUpdate.run(self)
return self.restrict(setkeys)
def _checkduplicate(self, key, opt):
"""
check if there is any duplicates Function inside the dictionary
return the key if one is found.
"""
optmsg = opt.getMsg()
for k,f in self.iteritems():
if k!=key and optmsg == f.getMsg():
return k
return ""
def _copy_attr(self, new):
"""
Internal function to copy parameters from one object instance to an other
"""
new.__dict__.update(self.__dict__)
return new
#new._proc = self._proc
#new.onSetup = self.onSetup
#new.onUpdate = self.onUpdate
#new._prefix = self._prefix
#new._context = self._context
#return new
def setAliases(self, __aliases__={}, **aliases):
""" set Function aliases
fd.setAliases( dit="DET1.DIT", ndit="DET1.NDIT")
is equivalent to :
fd["dit"] = fd["DET1.DIT"]
fd["ndit"] = fd["DET1.NDIT"]
Parameters
----------
aliases : dict like object, optional
**aliases : additional alias/key pairs
Returns
-------
None
"""
aliases = dict(__aliases__, **aliases)
for k,alias in aliases.iteritems():
self[alias] = self[k]
def copy(self, deep=False, trueKey=False):
""" Copy the FunctionDict
Parameters
----------
deep : bool, optional
if True the child Function are copied in the FunctionDict copy.
if False (default) the child Function are not copied.
Meaning that:
fd["DET.DTI"] is fd.copy()["DET.DIT"]
fd["DET.DTI"] is not fd.copy(True)["DET.DIT"]
trueKey : bool, optional
If True the FunctionDict will have the true Function Keys as keys,
meaning that any aliases will be droped.
If False (default) keys are copied as they are in the original FunctionDict
Returns
-------
fd : FunctionDict
The copied FunctionDict
"""
if trueKey:
if deep:
new = {f.getMsg():f.copy(True) for f in self.itervalues()}
else:
new = {f.getMsg():f for f in self.itervalues()}
else:
if deep:
new = {k:f.copy(True) for k,f in self.iteritems()}
else:
new = super(FunctionDict, self).copy()
return self._copy_attr(self.__class__(new))
def rcopy(self, deep=False, default=False):
""" Return a restricted copy of a FunctionDict with only the Function with value set
df.rcopy()
is equivalent to
df.rcopy().restrictHasValue()
Parameters
----------
deep : bool, optional
default if False see method copy for more details
default : bool, optional
if True copy also the Function that have default value
**The default capability may be dropped in future release**
Returns
-------
fd : FunctionDict
The copied FunctionDict
"""
if deep:
return self._copy_attr( self.__class__({k:f.copy() for k,f in self.iteritems() if f.hasValue(default=default)}))
return self._copy_attr( self.__class__({k:f for k,f in self.iteritems() if f.hasValue(default=default)}))
def msgs(self, context=None):
""" Return the list of keys (or message) for all child Function
Parameter:
context : any object, optional
An alternative context, see getContext method
"""
context = self.getContext()
return [f.getMsg(context=context) for f in self.values()]
def todict(self, context=None, default=False):
""" Create a symple dictionary of all key/value pairs that have a value set
Parameters
----------
context : any object, optional
context object to rebuild key and values if needed
see method getContext()
default : bool, optional
True/False use/no use default if value is not set
**default** may be deprecated in future release
Returns
-------
d : dict
A dictionary of key/value pair for all function with a value set
"""
context = self.getContext()
return {k:f.get(default=default, context=context) for k,f in self.iteritems() if f.hasValue(default=default)}
def toalldict(self, default=False, context=None, exclude=[]):
""" same than `todict` method except that aliases are added to the list of keys
Parameters
----------
context : any object, optional
context object to rebuild key and values if needed
see method getContext()
default : bool, optional
True/False use/no use default if value is not set
**default** may be deprecated in future release
exclude : list of Function
Functions instances to be exclude from result
Returns
-------
d : dict
A dictionary of key/value pair for all function with a value set
"""
output = {}
for k in set( self.keys()+self.msgs(context=context)):
f = self[k].get(default=default)
if not f in exclude:
output[k] = f
return output
#return {k:self[k].get(default=default) for k in set( self.keys()+self.msgs(context=context))}
def tocmd( self, values=None, include=None, withvalue=True,
default=False,
context=None, contextdefault=True):
""" make a list of commands ready to be parsed to process
cmd is an alias of tocmd
Parameters
----------
values : dict, optional
A key/value pairs to be parsed temporary in the result, without changing
values set inside the FunctionDict.
include : list, optional
A list of keys of Function to be include, make sense to use if withvalue
is false e.g. fd.tocmd(withvalue=False, include=["DET.DIT", "DET.NDIT"])
withvalue : bool, optional
If True (default), add the command pair to all the child Function
that has a value defined otherwise setup only the Function from the
input *values* dictionary.
default : bool optional
if True use default if value is not set
**default can be deprecated in future release**
context : any object, optional
context is used as replacement for string value and or keys.
Context can be any object with a obj[item] and/or obj.attr capability
bracketed keys or values are replaced by its target value
For instance:
- "{[DPR.TYPE]}" will be replaced by the value context["DPR.TYPE"]
- "INS OPT{.number}" will be "INS OPT"+context.number
see getContext method
Returns
-------
List of (key,string value) pair ready to be passed in setup process
Examples:
--------
fd = FunctionDict(type = Function("DPR.TYPE", value="test"),
file = Function("DPR.FILE", value="result_{[type]}_{[dit:2.3f]}.fits"),
dit = Function("DET.DIT", value=0.1)
)
fd.tocmd(context=fd)
[('DET.DIT', '0.1'), ('DPR.TYPE', 'test'), ('DPR.FILE', 'result_test_0.100.fits')]
"""
if values:
self = self.copy(True)
for k,f in dict(values).iteritems():
self[k] = f
else:
values = {}
context = self.getContext(context)
out = []
funcs = []
for k in values:
f = self[k]
if not f in funcs:
out.extend(f.cmd(value=values.get(k),
default=default, context=context)
)
funcs.append(f)
if withvalue:
for k,f in self.iteritems():
if f.hasValue(default):
if not f in funcs:
out.extend(f.cmd(default=default,context=context))
funcs.append(f)
if include:
for k in include:
f = self[k]
if not f in funcs:
if not f.hasValue():
raise ValueError("Key '%s' is mandatory but do not have value set" % f.getMsg())
out.extend(f.cmd(default=default, context=context))
return out
cmd = tocmd
def qcmd(self, _values_=None, _include_=None, **kwargs):
""" Do the same thing than cmd but accept any keywords for key/value pairs
see cmd or tocmd method
"""
values = _values_ or {}
values.update(kwargs)
return self.cmd(values, include=_include_)
def setup(self, values=None, include=None,
withvalue=True, default=False, context=None,
proc=None, contextdefault=True, function=[], **kwargs):
""" Send a Setup from all the child Function with a value set.
This call the tocmd method, so method parameter are the same some related
to processes.
Parameters
----------
values : dict, optional
A key/value pairs to be parsed temporary in the result, without changing
values set inside the FunctionDict.
include : list, optional
A list of keys of Function to be include, make sense to use if withvalue
is false e.g. fd.tocmd(withvalue=False, include=["DET.DIT", "DET.NDIT"])
withvalue : bool, optional
If True (default), add the command pair to all the child Function
that has a value defined otherwise setup only the Function from the
input *values* dictionary.
default : bool optional
if True use default if value is not set
**default can be deprecated in future release**
context : any object, optional
context is used as replacement for string value and or keys.
Context can be any object with a obj[item] and/or obj.attr capability
see getContext method
proc : Process, optional
Process to use instead of the default one if any
see getProc method
function : list, optional
a list of command pair to be added to the setup.
**kwargs: dict, optional
all other key/pairs are passed to the setup function process,
they are usually (but depend on the instrument SETUP command):
expoId, noMove, check, noExposure
Returns
-------
The process setup tuple output
See Also
--------
qsetup method for a more user friendly way to setup
"""
cmdfunc = self.tocmd(values=values, withvalue=withvalue,
include=include,
default=default, context=context,
contextdefault=contextdefault)
cmdfunc = cmdfunc+function
out = self.getProc(proc).setup(function=cmdfunc, **kwargs)
self.onSetup.run(self)
return out
def qsetup(self, _values_=None, _include_=None, **kwargs):
""" qsetup stand for quick setup do the same thing than setup
Accept any key/val assignment. They are condition where this method cannot work
so use setup instead, it is just a 'for lazy people' method.
Note that qsetup send the setup for only the keywords provided in
the function call (e.i.: equivalent to withvalue=False in setup function)
For this function to work a default process must be defined.
Parameters
----------
**kwargs : dict, optional
Could be
- option to the process (e.g. timeout, expoId, etc)
- key/value pair to send message. Key cannot be SETUP process option
Examples
--------
qsetup( dit=0.01, ndit=1000, expoId=0, timeout=1000)
is equivalent to:
setup( {"DIT":0.01, "NDIT":1000}, expoId=0, timeout=1000)
If the keyword exist in the FunctionDict it is used at it is
otherwhise try with an upper case keyword.
d.qsetup( dit=0.001, ndit=1000 )
can also be decomposed:
d["DIT"] = 0.001
d["NDIT"] = 1000
d.setup()
"""
proc = self.getProc(None)
# Remove all the option for the setup command
pkeys = proc.commands["setup"].options.keys()+["timeout"]
pkwargs = {k:kwargs.pop(k) for k in kwargs.keys() if k in pkeys}
cmdfunc = self.qcmd(_values_, _include_=_include_, **kwargs)+pkwargs.pop("function",[])
out = self.getProc(proc).setup(function=cmdfunc, **pkwargs)
self.onSetup.run(self)
return out
<file_sep>
_loop_class = (list, tuple)
def sequence(func, *args, **kwargs):
""" built a sequence object on one function
Args:
func : the function to execute
*args : function argument if list or tuple they are cycled
**kwargs function kwargs, list/ tuple are cycled as well
"""
return Sequence( (func, args, kwargs), modulo=True )
def sequences(*m_args, **options):
return Sequence( *m_args, **options)
class Sequence(object):
def __init__(self, *m_args, **options):
self.m_args = self._check_m_args(m_args)
self.counter = -1
size = options.pop("size", None)
modulo = options.pop("modulo",False)
if len(options):
raise KeyError("Accept only size and modulo keywords")
if modulo:
self.size = self.getMaxLen() if size is None else size
else:
self.size = self.checkLens(size)
def getMaxLen(self):
n = 0
for m,args,kwargs in self.m_args:
for k,p in kwargs.iteritems():
if issubclass(type(p), _loop_class):
n = max(n,len(p))
for p in args:
if issubclass(type(p), _loop_class):
n = max(n,len(p))
return n or 1
def checkLens(self, size):
for m,args,kwargs in self.m_args:
for k,p in kwargs.iteritems():
if issubclass(type(p), _loop_class):
if size is None:
size = len(p)
elif len(p)!=size:
raise ValueError("list for keyword %s does not have the right len expected %d got %d"%(k,size,len(p)))
for p in args:
if issubclass(type(p), _loop_class):
if size is None:
size = len(p)
elif len(p)!=size:
raise ValueError("list for args num %d does not have the right len expected %d got %d"%(args.index(p),size,len(p)))
return size
def call(self):
return self.rebuildMethodKwargs()
@staticmethod
def _check_m_args(m_args):
out = []
for m_a in m_args:
if not issubclass( type(m_a), tuple):
raise ValueError("Arguments must be tuple of one two or three")
Nm_a = len(m_a)
if Nm_a<1:
raise ValueError("Empty tuple")
if not hasattr( m_a[0], "__call__"):
raise ValueError("first element of tuple must have a call method (a function ro class)")
if Nm_a<2:
args, kwargs = [], {}
elif Nm_a<3:
args , kwargs = m_a[1], {}
if issubclass( type(args), dict): # reverse args and kwargs
args, kwargs = [], args
elif Nm_a<4:
args , kwargs = m_a[1:3]
else:
raise ValueError("tuple must have one two or three elements")
if issubclass( type(args), dict): # reverse args and kwargs
args, kwargs = kwargs, args
if issubclass( type(args), dict) or issubclass( type(kwargs), (list,tuple)):
raise ValueError("tuple must contain at least a method then a list or a dict or both")
out.append( (m_a[0], args, kwargs.copy()))
return out
def rebuildMethodKwargs(self):
out = []
for m,a,kw in self.m_args:
out.append( (m, self.rebuildArgs(a), self.rebuildKwargs(kw) ) )
return MethodArgsList(out)
def rebuildKwargs(self, kwargs):
kout = kwargs.copy()
for k,v in kwargs.iteritems():
if issubclass( type(v), _loop_class):
kout[k] = v[self.counter%len(v)]
return kout
def rebuildArgs(self, args):
aout = []
for a in args:
if issubclass( type(a), _loop_class):
aout.append(a[self.counter%len(a)])
else:
aout.append(a)
return aout
def next(self):
if self.counter>=(self.size-1):
raise StopIteration()
self.counter += 1
return self.call()
def __iter__(self):
self.counter = -1
return self
def go(self):
return [ l.call() for l in self]
def control(self):
for l in self:
l.control()
class MethodArgsList(list):
def call(self):
out = []
for method,args,kwargs in self:
#if len(kwargs) and "kwargs" in method.im_func.func_code.co_varnames:
# tmp = method(*args, kwargs=kwargs)
#else:
tmp = method(*args, **kwargs)
out.append(tmp)
return out
def control(self):
for method,args,kwargs in self:
print method,args,kwargs
<file_sep>
import vlt
import vlt.buffread as buffread
def msgdef(msg,commands):
def tmp(self,**kwargs):
return self.msgSend( msg, kwargs)
tmp.__doc__ = commands[msg].helpText
return tmp
buffreader = buffread.buffreader
boss_commands = {
"expend" :vlt.Command("EXPEND",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s"),"path":vlt.Param("-path", str, "%s")},helpText="""Internal SOS-OS command. SOS sends this command to its OS and ICS subsystems.
When OS receives this command it forwards it to its ICS subsystems.
""", bufferReader=buffreader.getreader("EXPEND")),
"gethdr" :vlt.Command("GETHDR",{"expoId":vlt.Param("-expoId", int, "%d"),"btblFileName":vlt.Param("-btblFileName", str, "%s"),"detId":vlt.Param("-detId", str, "%s"),"hdrFileName":vlt.Param("-hdrFileName", str, "%s")},helpText="""Internal command. Creates a header file.
""", bufferReader=buffreader.getreader("GETHDR")),
"expstrt" :vlt.Command("EXPSTRT",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s")},helpText="""Internal SOS-OS command. SOS sends this command to the OS-es which
are on the subsystemlist but not started.
When OS receives this command it calles the startpreproc function.
""", bufferReader=buffreader.getreader("EXPSTRT")),
"clean" :vlt.Command("CLEAN",{},helpText="""Internal command. Clears the OS exposure table and sets the expoId
to zero, i.e to the initial value.
""", bufferReader=buffreader.getreader("CLEAN"))}
class boss(vlt.Process):
"""
This is a boss class vlt.Process automaticaly generated from file
/Users/guieu/python/Catalog/vlt/CDT/boss.cdt
To get a list of commands:
proc.getCommandList()
To print a help on a specific command (e.g. setup)
proc.help("setup")
proc.help() will return a complete help
"""
commands = boss_commands
for c in boss_commands: exec("%s = msgdef('%s',boss_commands)"%(c,c))
proc = boss("boss")
<file_sep>"""
The vlt module aims to bring some useful tool for easy instrument scripts
and control.
It is not aimed to replace the vlt template and script but to provide
to the non-vtl-software expert a way to script VLT instruments.
Main capabilities are:
Process
=======
You can open a 'process' to send command (based on the msgSend unix command)
The process object are dynamicaly created from instrument CDT file.
e.g. (on PIONIER):
proc = vlt.openProcess("pnoControl")
proc.help() # give a help on all commands
proc.help("setup")
-or-
print proc.setup.__doc__ # return help on command setup
vlt.setDefaultProcess("pnoControl") # set the default process for
# Functions (see below)
Dictionary/Function
===================
Function
--------
What we call here Function (also called Keyword in VLTSW) are objects
containing a keyword/value pair plus extra stuff like unit, context,
comment, ...
Function provide some smart indexing capability:
e.g:
f = vlt.Function("INSi.FILTi.ENC", dtype=int) is understood to be
a table of value because of the 'i' iterator.
Therefore:
f[1,2].value = 120000 # set the value of INS1.FILT1.ENC
f[1,2] # return the corresponding Function
f[1,2] is equivalent to f["INS1","FILT2"]
The index 0 return the keyword without number:
f[0,2] return the Function of "INS.FILT2.ENC"
Also one can set value of several indexes in one command:
f[1] = { 1:10000, 2:50000, 3:3400 } # will set value for "INS1.FILT1.ENC",
# "INS1.FILT2.ENC" and "INS1.FILT3.ENC"
so f[1,1].value is 10000, f[1,2].value is 50000, etc ...
To know if a function contains iterable keys use the isIterable method
Function("INSi.FILTi.ENC").isIterable() # -> true
Function("INS1.FILT2.ENC").isIterable() # -> False
Function("DETj.DIT").isIterable() # -> True
Function("DET.DIT").isIterable() # -> False
Some key methods of function object:
- set(value) : set the value in the function and return the Function
itself. This allow to do quick command.
f.set(30000).setup() # set and then send setup (see bellow)
- setup([value=, proc=]):
Send a setup command with the process proc= -or if None-
the default process defined by vlt.setDefaultProcess
Without argument the setup is sent with the current Function
value. Or with the value optional keyword.
e.g.:
vlt.setDefaultProcess("pnoControl")
f = vlt.Function("DET.DIT", 0.001)
f.setup(timeout=1000, expoId=0)
is equivalent to the system command:
> msgSend "" pnoControl SETUP "-function DET.DIT 0.001 -expoId 0" 1000
- status
FunctionDict
------------
FunctionDict() objects are dictionary of Function() object.
They are basically a collection of keyword/pair values with fast search
keyword methods.
Key Methods:
- restrict : take a string or list of string and return a restricted FunctionDict
If a string the restricted dictionary is all keys limited to the one that
start with the input string. e.g.:
>>> d = vlt.readDictionary("PIONIER_ICS")
>>> d.restrict("INS.SENS1")
return a FunctionDict like:
{
'MAX': Function("INS.SENS1.MAX", None),
'MEAN': Function("INS.SENS1.MEAN", None),
'MIN': Function("INS.SENS1.MIN", None),
'STAT': Function("INS.SENS1.STAT", None),
'VAL': Function("INS.SENS1.VAL", None)}
}
One can see that the "INS.SENS1" has been droped, so one can use the
restricted dictionary with the "MAX", "MIN", etc keys, but also the
full path will work :
>>> rs = d.restrict("INS.SENS1")
>>> rs["VAL"] #-> works
>>> rs["INS.SENS1.VAL"] #-> works also
So imagine you have a function that plot stuf from sensors you can parse
the restricted dictionary. The function will not care from what ever it comes from
>>> plotsensor( d.restrict("INS.SENS1"))
>>> plotsensor( d.restrict("INS.SENS2"))
etc ...
- restricMatch : allow to return any Function that match a part of the key
e.g :
>>> d.restricMatch("NAME")
- restrictContext/ restrictHasValue/ restrictClass /
restrictHasNoValue / restrictMatch / restrictValue
plotsensor( d.restrict("INS.SENS1"))
- setup : setup a bunch of Functions in one call
- qsetup : does the same in a easier way to
Devices
-------
Devices are derived from FunctionDict. They are a list of function wrapped
with addiotional usefull capabilities, like e.g. : moveTo, close, etc ...
They are defined in the devices repertory a few are set so far but that can grow.
Motor, Shutter, Detector are three builtins
Example to create/use a device, on Pionier:
>>> pnoc = vlt.openProcess("pnoControl")
>>> ics = vlt.readDictionary("PIONIER_ICS")
>>> dispersor = vlt.devices.Motor(ics.restrict("INS.OPTI3"), statusItems=[""], proc=pnoc)
# (proc can be also the default process vlt.setDefaultProcess(pnoc) )
>>> dispersor.statusUpdate() # ask the instrument and update values
>>> dispersor.moveTo("FREE") # move to FREE position
>>> dispersor.moveTo(120000) # move to 120000 enc position
>>> dispersor.moveBy(10000) # offset of 10000 enc
Also cmd_moveBy do not do anything but return the function command in a list
so commands can be stacked together:
>>> sh1 = vlt.devices.Shutter(ics.restrict("INS.SHUT1"))
>>> pnoc.setup(function=dispersor.cmd_moveTo("FREE")+sh1.cmd_close())
"""
from .config import (config, INTROOT,
INS_ROOT,INSROOT, VLTROOT,
DPR_ID, VLTDATA, HOST
)
import mainvlt as vlt
from process import setDefaultProcess, getDefaultProcess
from mainvlt import EmbigousKey, cmd, dotkey, undotkey
from .function import Function
from .functiondict import FunctionDict, functionlist
from .sequence import sequence, sequences
from . import devices
from io import openProcess, processClass, openDictionary
#import processes as proc
import glob
import os
__path__ += [os.path.dirname(__file__)+"/CDT"]
#import pnoControl
#__all__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__)+"/CDT/*.py")]
<file_sep>import vlt
d = vlt.readDictionary("PIONIER_ICS")
d["INS.TEMP1.VAL"] = 1.0;
d["INS.TEMP2.VAL"] = 10.0
print d.restrictValue([1, 10])
print d.restrictValue(lambda v: v>1.0)
<file_sep>from __future__ import print_function
from vlt import processClass, devices
from vlt.io import readDictionary
def log(*msg, **kwargs):
print(*msg, **kwargs)
import os
import vlt
dpr_id = os.getenv("DPR_ID")
dpr_id = dpr_id or "PIONIER"
log( "opening new process pnoc ...",end=" ")
if dpr_id == "PIONIER":
pnoc = vlt.openProcess("pnoControl")
elif dpr_id == "BETI":
pnoc = vlt.openProcess("beoControl")
vlt.setDefaultProcess(pnoc)
log("ok")
####
# Load the functional dictionaries
#
log("Reading Dictionaries ...", end=" ")
if dpr_id == "PIONIER":
log("ACS", end=" ")
acs = readDictionary(dpr_id+"_ACS")
aos = vlt.FunctionDict()
elif dpr_id == "BETI":
log("AOS", end=" ")
aos = readDictionary(dpr_id+"_AOS")
acs = vlt.FunctionDict()
log("CFG", end=" ")
cfg = readDictionary(dpr_id+"_CFG")
log("DCS", end=" ")
dcs = readDictionary(dpr_id+"_DCS")
log("ICS", end=" ")
ics = readDictionary(dpr_id+"_ICS")
log("OS", end=" ")
os = readDictionary(dpr_id+"_OS")
log("DPR", end=" ")
dpr = readDictionary("DPR")
log("OSB", end=" ")
osb = readDictionary("OSB")
log(" => allf")
allf = acs + aos + cfg + dcs + ics + os + dpr + osb
####
# Add the 4 shuters
shutters = devices.Shutters([devices.Shutter(ics.restrict("INS.SHUT%d"%i),
statusItems=[""]) for i in range(1, 5)])
shut1, shut2, shut3, shut4 = shutters
####
# dispersion motor
disp = devices.Motor(ics.restrict("INS.OPTI3"), statusItems=[""])
####
# Detector
# needs the DET. keywords plus some extras
class PionierDetector(devices.Detector):
def statusUpdate(self, statusItems=None, proc=None):
super(PionierDetector, self).statusUpdate()
if statusItems is None:
statusItems = self.statusItems
if "SUBWINS" in statusItems and self["SUBWINS"].hasValue():
subs_status = []
for i in range(1, self["SUBWINS"].getValue()+1):
subs_status.expend(
self.restrict("SUBWIN%d"%i).msgs()
)
if len(subs_status):
self.statusUpdate(subs_status)
det = PionierDetector(
dcs.restrict("DET")+
dpr+
osb.restrict("OCS.DET")+
ics.restrict([("INS.MODE", "MODE")]),
statusItems=["DIT", "NDIT", "POLAR", "SUBWINS"]
)
##
# To remove some keyword embiguities
det["TYPE"] = det["DPR.TYPE"]
# set the default mode to ENGINEERING
det["mode"] = "ENGINEERING"
det["imgname"] = dpr_id+"_"
<file_sep>import re
class KeywordFile(file):
in_header = False
reg = re.compile("""^([^:]*):([^:]*)$""")
cases = {
# func of signautre (f, key, value, more)
}
# key_case is a dict of dict.
# Each item is the level of the path to test the keys
key_cases = {
# func of signature (f, path, value, more)
# 0: {"NEW":func}
# 1: {"NAME": func_for_name"}
}
# value cases is a dictionary with a test function as key
# and a function that return the new value
# this is helpfull for instance for "ISF INS.DEFAULT" to
# return the value of INS.DEFAULT in ISF
value_cases = {
# test func siganture is (value)
# called func signature is (f, value) and should return a new value
}
comment_char = "#"
cdict = "parameters"
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **kwargs)
self.parameters = {}
self.header = {}
def say(self, txt):
print txt
def start_header(self):
self.in_header = True
self.cdict = "header"
def end_header(self):
self.in_header = False
self.cdict = "parameters"
def match_line(self, line):
"""match line should return a tuple of 3 string
key, value, more
more is eventual things left on line, for instance, if line is:
KEY1 "VAL1" ; KEY2 "VAL2"
and ';' act as a new line, more will be: KEY2 "VAL2"
"""
m = self.reg.match(line.strip())
if not m:
return None, None, None
groups = m.groups()
return groups[0], groups[1], ""
def get(self, path, default=None):
d = self.dictionary
for item in path:
if not item in d:
return default
d = d[item]
return d
def set(self, path, value):
d = self.dictionary
last = path[-1]
if not isinstance(last, basestring):
# the last element is suposed to be a function
# of signature (previous_value, new_value)
# e.g : lambda p,n: p+n
if len(path)<2:
raise Exception("If last path is not string path must have a len of at least 2 got %s" % path)
for item in path[:-2]:
if not item in d:
d[item] = {}
d = d[item]
item = path[-2]
d[item] = last(d[item],value)
else:
for item in path[:-1]:
if not item in d:
d[item] = {}
d = d[item]
last = path[-1]
d[path[-1]] = value
def key2path(self, key):
return [key]
def get_cdict(self):
return getattr(self, self.cdict)
dictionary = property(fget=get_cdict)
def parse(self):
self.line = self.readline()
while len(self.line):
self.parse_line(self.line)
self.line = self.readline()
self.end()
def end(self):
pass
def parse_line(self, line):
if line is None or not len(line):
return
if self.comment_char and line[0] == self.comment_char:
return
key, value, more = self.match_line(line)
if more:
more = more.strip()
if key is None:
return
if key in self.cases:
return self.cases[key](self, key, value, more)
path = self.key2path(key)
for ftest, ffix in self.value_cases.iteritems():
if ftest(value):
value = ffix(self, value)
N = len(path)
for depth,cases in self.key_cases.iteritems():
if depth>=N: break
if path[depth] in cases:
return cases[path[depth]](self, path, value, more)
self.set(path, value)
if more and len(more):
return self.parse_line(more)
<file_sep>from ..device import Device, cmd
from ..sequence import sequence
class Detector(Device):
""" Detector is a Device with the followin additional method:
start : start an exposure
wait : wait for the exposure to end
abord : abord the curent exposure
takeExposure : setup the detector take the exposure and wait
"""
def start(self, expoId=None, detId=None, at=None, timeout=None):
"""
"""
return self.getProc().msgSend("start",
dict(expoId=expoId, detId=detId, at=at),
timeout=timeout
)
def wait(self, timeout=None, **kwargs):
""" run the command wait
.proc.help("wait") for more info
"""
return self.getProc().msgSend("wait",
kwargs,
timeout=timeout
)
def takeExposure(self, _kwargs_=None,
_include_= ["MODE", "IMGNAME"],
expoId=0, timeout=None,
**morekw):
"""
takeExposure({"KEY1":val1}, KEY2=val2, expoId=0, timeout=1000 )
Setup the instrument if any keywords are provided, start the exposure
and wait for reult.
The expoId is returned.
"""
kwargs = _kwargs_ or {}
kwargs.update(morekw)
if len(kwargs):
expoId = self.qsetup(kwargs,_include_=_include_,
expoId=expoId, timeout=timeout)
self.start(expoId=expoId)
self.wait(expoId=expoId)
return expoId
def takeExposureSeq(self, *args, **kwargs):
"""
Same as takeExposure but run it in a sequence, one after the other
where all individual argument are taken from list.
The size of the repeat sequence is set by the bigest list, all other
smaller list arguments are cycled.
Example:
det.takeExposure(dit=0.0 , ndit=1000, type="BIAS")
det.takeExposure(dit=0.001, ndit=1000, type="DARK")
det.takeExposure(dit=0.0 , ndit=1000, type="BIAS")
det.takeExposure(dit=0.002, ndit=1000, type="DARK")
Is equivalent to:
det.takeExposureSeq(dit=[0.0, 0.001, 0.0, 0.002],
ndit=1000
type=["BIAS", "DARK"]
)
see also:
sequence
"""
return sequence(self.takeExposure , *args, **kwargs).go()
def abort(self, expoId=0, timeout=None):
return self.proc.msgSend("ABORT", dict(expoId=expoId), timeout=timeout)
def cmd_subwins( self, coordinates, width=1, height=1, ref='ABSOLUTE'):
l = len(coordinates)
if not hasattr(width , "__iter__"): width=[width ]*l
if not hasattr(height, "__iter__"): height=[height]*l
cmd = self["SUBWINS"].getCmd(value=l)
cmd += self["SUBWIN COORDINATES"].getCmd(value=ref)
for i,(x,y),w,h in zip(range(1,l+1), coordinates, width, height):
sv = "{w}x{h}+{x}+{y}".format(x=x,y=y,w=w,h=h)
cmd += self["SUBWINi GEOMETRY"][i].getCmd(value=sv)
return cmd
def subwins(self, coordinates, width=1, height=1, ref='ABSOLUTE'):
return self.proc.setup(function=self.cmd_subwins(coordinates, width, height, ref=ref))
<file_sep>from .functiondict import FunctionDict
from .mainvlt import DEFAULT_TIMEOUT, EmbigousKey, cmd
class Device(FunctionDict):
""" Device object is subclasse from a FunctionDict object with additional
usefull methods dedicated to the device e.g. move, close, takeExposure,...
"""
def __init__(self, fdict, statusItems=None, proc=None):
FunctionDict.__init__(self, fdict)
if statusItems is not None:
self.statusItems = statusItems
self._check()
if proc:
self.proc = proc
def _check_keys(self, klist):
""" check a list of keys, they must be in the dictionary and
they must not be embigous
"""
for k in klist:
if k not in self:
raise KeyError("Device '%s' Nead the key '%s' to work corectly" % (self.__class__.__name__, k))
try:
self[k]
except EmbigousKey:
raise KeyError("It seems that the needed key '%s' is not unique" % k)
def _check(self):
""" Function to check if all the functionality are here
for a normal behavior.
"""
pass
def newDevice(name, proc, dictionary, cls=Device):
new = cls(dictionary)
new.proc = proc
new.update(proc.status(function=name))
return new
<file_sep>import os
import commands
import re
import numpy as np
_db_write_cmd = "dbWrite"
_db_read_cmd = "dbRead"
_db_types_convertion = {
"INT32/UINT32":np.int32,
"BYTES":str,
"LOGICAL":int
}
def get_type(strtype):
if strtype in _db_types_convertion:
return _db_types_convertion[strtype]
if hasattr( np, strtype.lower()):
return np.__getattribute__( strtype.lower() )
raise TypeError("Type \"{0}\" unknown ".format(strtype))
def convert_value(strtype, value):
return get_type(strtype)(value)
class db(object):
debug = False
verbose = True
def __init__(self,name):
self.name = name
def writeList(self, addrs=None, var=None, index=0, values=None):
addrs = addrs or []
var = var or ""
values = values or []
tps = self.readTypes( addrs, "{0}({1})".format(var, index) )
if len(tps)!= len( values):
raise ValueError("got %d type in data base for %d values"%(len(tps),len(values)))
i = 0
for t,v in zip(tps, values):
self.write( addrs, "{0}({1},{2})".format(var,index, i), t(v))
return None
def writeDict(self, addrs=None, var=None, index=0, values=None):
addrs = addrs or []
var = var or ""
values = values or {}
for k,v in values.iteritems():
self.write( addrs, "{0}({1},{2})".format(var,index, k), v)
def cmdWrite(self, addrs=None, var=None, value=None):
addrs = addrs or []
var = var or ""
if isinstance( value, str):
svalue = "\"{0}\"".format(value)
else:
svalue = "{0}".format(value)
return """{cmd} "{0}:{1}:{2}" {3}""".format(self.name, ":".join(addrs), var, svalue, cmd=_db_write_cmd)
def write(self,addrs=None, var=None, value=None ):
cmdLine = self.cmdWrite( addrs, var=var, value=value)
if self.debug:
print cmdLine
return ""
if self.verbose:
print cmdLine
status, output = commands.getstatusoutput(cmdLine)
return output
def cmdRead( self, addrs=None, var=None):
addrs = addrs or []
var = var or ""
return """{cmd} \"{0}:{1}:{2}\"""".format(self.name, ":".join(addrs), var, cmd=_db_read_cmd)
def read(self,addrs, var=None):
cmdLine = self.cmdRead( addrs, var=var)
if self.debug:
print cmdLine
return []
if self.verbose:
print cmdLine
status, output = commands.getstatusoutput(cmdLine)
return self.readBuffer(output)
def readTypes(self, addrs, var=None):
cmdLine = self.cmdRead( addrs, var=var)
if self.debug:
print cmdLine
return []
status, output = commands.getstatusoutput(cmdLine)
return self.readBufferTypes(output)
_re_read_buffer = re.compile("([^ ]+)[ ]+value[ ]+=[ ]*(.+)")
def readBuffer( self, buff):
lbuff = buff.split("\n")
out = []
for l in lbuff:
matches = self._re_read_buffer.findall( l)
for m in matches:
out.append( convert_value(m[0].strip(), m[1].strip()) )
return out
def readBufferTypes( self, buff):
lbuff = buff.split("\n")
out = []
for l in lbuff:
matches = self._re_read_buffer.findall( l)
for m in matches:
out.append( get_type(m[0].strip()) )
return out
<file_sep>#from vlt import vltdb as db
import vltdb as db
# LOGICAL value = 1
# INT32/UINT32 value = 0
# BYTES value =
# DOUBLE value = 260
# DOUBLE value = 95
# DOUBLE value = 288
# DOUBLE value = 97
# BYTES value = blue
# BYTES value =
# BYTES value =
# INT32/UINT32 value = 2
# DOUBLE value = 0
class rect(object):
datapos = {"vis":0 , "x0":3, "y0":4, "x1":5, "y1":6, "color":7, "width":10}
addrs = ["graph"]
this = "rect"
def __init__(self, name, rectNumbers=None):
self.db = db.db(name)
if rectNumbers is None:
rectNumbers = self.db.read(self.addrs, self.this+".maxNumElem")
if not len(rectNumbers):
raise ValueError("Cannot read the maximum number of element on the data base")
rectNumbers = range(int(rectNumbers[0]))
self.rectNumbers = list(rectNumbers)
self.index = 0
def read(self, index):
return self.db.read( self.addrs , self.this+".itemConfig({0:d})".format(index))
def write(self, index, vals):
return self.db.writeList( self.addrs,self.this+".itemConfig", index, vals)
def writeDict(self, index, vals):
return self.db.writeDict( self.addrs,self.this+".itemConfig", index, vals)
def show(self, show=True):
return self.db.write(self.addrs, self.this+".showGroup", int(show))
def redraw( self ):
return self.db.write(self.addrs, self.this+".drawGraphics", self.this)
def add(self, x0, y0, width, height, color="green"):
x1 = x0 + width
y1 = y0 + height
if self.index>=len(self.rectNumbers):
raise Exception("Exceeded the number of rectangle allowed")
self.write( self.rectNumbers[self.index] ,[True,0,"",x0,y0,x1,y1,color, "", "", 2, 0])
self.index += 1
def change( self, index, **kwargs):
vals = {}
for k,v in kwargs.iteritems():
if not k in self.datapos:
raise KeyError("unknown param '%s'"%k)
vals[self.datapos[k]] = v
self.writeDict(index, vals)
def shift( self, index, xshift=0, yshift=0):
vals = self.read(index)
x0 = vals[self.datapos["x0"]]
y0 = vals[self.datapos["y0"]]
x1 = vals[self.datapos["x1"]]
y1 = vals[self.datapos["y1"]]
return self.change(index, x0=x0+xshift, x1=x1+xshift, y0=y0+yshift, y1=y1+yshift)
def shiftAll( self, xshift=0, yshift=0):
for i in self.rectNumbers:
self.shift(i, xshift, yshift)
def clear(self):
for i in self.rectNumbers:
self.write(i, [False,0,"",0 , 0,0,0,"white", "", "", 1, 0] )
self.index = 0
def fromRectangles(self, rect, xmargin=0, ymargin=0, **kwargs):
"""
change the dadabase values according to the list of rectanges as defined in mathplotlib:
[ [ (x0,y0), width, hwight], ... ]
"""
kwargs.setdefault("vis",1)
kwargs.setdefault("color", "green")
kwargs.setdefault("width",2)
for i,r in enumerate(rect):
x0 = r[0][0]
x1 = x0+r[1]+xmargin
y0 = r[0][1]
y1 = y0+r[2]+ymargin
self.change(self.rectNumbers[i], x0=x0, y0=y0, x1=x1, y1=y1, **kwargs)
<file_sep>import re
from .keywords import KeywordFile
from .tsf import openTemplateSignature
from collections import OrderedDict
from ..template import ObdParam, ObdTemplate, Obd
from ..config import config
from . import ospath
######
## already opened templates
TEMPLATES = {}
def _start_header(f, key, value, more):
f.start_header()
return f.parse_line(more)
def _end_header(f, key, value, more):
f.end_header()
return f.parse_line(more)
def _new_template(f, key, value, more):
f.template = OrderedDict([(key,value)])
f.parameters[f.template_counter] = f.template
f.cdict = "template"
f.template_counter += 1
return f.parse_line(more)
class OBD(KeywordFile):
# match : INS.FILT1.RANGE "value"; # more stuff
_c1 = """[ \t]+["]([^"]*)["][ \t]*[;](.*)"""
# match : INS.FILT1.RANGE "value" # comment
_c2 = """[ \t]+["]([^"]*)["]().*"""
# match : INS.FILT1.RANGE value; # more stuff
_c3 = """[ \t]*([^;#" \t]+)[ \t]*[;](.*)"""
# match : INS.FILT1.RANGE value # comment
_c4 = """[ \t]*([^;#" \t]+)().*"""
# match : PAF.HDR.START; #more stuff
_c5 = """[ \t]*[;]()(.*)"""
# match : PAF.HDR.START # comment
_c6 = """[ \t#]?.*()()"""
reg = re.compile("""^([^ \t;#]+)({c1}|{c2}|{c3}|{c4}|{c5}|{c6})$""".format(
c1=_c1, c2=_c2, c3=_c3, c4=_c4, c5=_c5, c6=_c6
)
)
cases = {
# func of signautre (f, key, value, more)
"PAF.HDR.START": _start_header,
"PAF.HDR.END": _end_header,
"TPL.ID": _new_template,
}
value_cases = {
}
def __init__(self, *args, **kwargs):
super(OBD, self).__init__(*args, **kwargs)
self.parameters = OrderedDict()
self.template = None
self.template_counter = 0
def match_line(self, line):
m = self.reg.match(line.strip())
if not m:
return None, None, None
groups = m.groups()
gi = range(2,14,2)# [2,4,6,8, ...]
for i in gi:
if groups[i] is not None:
return groups[0], groups[i], groups[i+1]
raise Exception("BUG none of the group founf in match")
def findObdFile(file_name, path=None, prefix=None, extention=None):
"""
find the tsf file_name inside the path list.
by default path list is config["tsfpath"]
"""
return ospath.find(file_name, path=path, prefix=prefix, extention=extention,
defaults=config['obd']
)
def openObd(file_name, path=None, prefix=None, extention=None):
obd_file = ospath.find(file_name, path=path, prefix=prefix, extention=extention,
defaults=config['obd']
)
f = OBD(obd_file)
f.parse()
obd = f.parameters
obdtemplates = []
for i in range(f.template_counter):
tpl_dict = obd.pop(i)
tpl_id = tpl_dict.pop("TPL.ID", None)
tpl_name = tpl_dict.pop("TPL.NAME", None)
if not tpl_id:
raise ValueError("cannot find a TPL.ID for template #%d"%i)
if tpl_id in TEMPLATES:
tpl = TEMPLATES[tpl_id]
else:
try:
tpl = openTemplateSignature(tpl_id)
except IOError as e:
raise IOError("Ob is attached to a tsf that cannot be opened : %s "%e)
TEMPLATES[tpl_id] = tpl
#info = {key:obd.pop(key) for key, val in obd.items() if key.startswith("OBS.")}
parameters = {key:ObdParam(tpl[key], val) for key, val in tpl_dict.iteritems()}
obdtpl = ObdTemplate(tpl_id, tpl_name, parameters)
obdtemplates.append(obdtpl)
return Obd(obdtemplates, info=obd, path=obd_file)
<file_sep>import numpy as np
import re
import mainvlt
import os
from .config import config
from .functiondict import FunctionDict
from .function import Function
# valid default parameters types
def vltbool(val):
return bool( val!='F' and val!=False and val)
param_types = {
"double" : np.float64,
"float" : float,
"logical" : bool,
"integer" : int,
"string" : str
}
dictionaryPath = config["dictionarypath"]
def findDictionaryFile(dictsufix, path=None, fileprefix="ESO-VLT-DIC."):
path = path or dictionaryPath
if dictsufix[0:len(fileprefix)] == fileprefix:
# the full file name is given
fileprefix = ""
for d in path:
p = d+"/"+fileprefix+dictsufix
if os.path.exists(p):
return p
raise ValueError("cannot find file {} in any of the path {}".format(fileprefix+dictsufix,path))
def _pname(f, value):
f.parameterEnd()
f.curentParameterName = value
f.curentParameter = Parameter(name=value)
f.dictionary[f.curentParameterName] = f.curentParameter
return f.readline()
def _context(f, value):
f.curentParameter['context'] = value
if not value in f.dictionaryContext:
f.dictionaryContext[value] = Context()
f.dictionaryContext[value][f.curentParameterName] = f.curentParameter
return f.readline()
def _class(f, value):
f.curentParameter['class'] = value
classes = value.split("|")
for cls in classes:
if not cls in f.dictionaryClass:
f.dictionaryClass[cls] = Class()
f.dictionaryClass[cls][f.curentParameterName] = f.curentParameter
return f.readline()
def _type(f, value):
value = value.lower()
if not value in f.types:
raise TypeError("the type '%s' for parameter '%s' is unknown"%(value, f.curentParameterName))
f.curentParameter["type"] = f.types[value]
return f.readline()
def _vformat(f, value):
f.curentParameter['format'] = value
return f.readline()
def _unit(f, value):
f.curentParameter['unit'] = value
return f.readline()
def _cformat(f, value):
f.curentParameter['comment'] = value
return f.readline()
def _description(f, value):
desc = ""
while True:
spv = value.split(":",1)
#if value[0:4] == " ":
if len(spv)==2 and spv[0].strip() in f.cases:
# End of the description
# they probably have better way to check that how ?
f.curentParameter['description'] = desc
return value # return the curent lie to be treated
if not len(value): # end of file
return ''
desc += value.strip()+" "
value = f.readline()
def _config( f, key, value):
f.config[key] = value
return f.readline()
def _undefined(f, key, value):
f.curentParameter[key] = value
return f.readline()
class Parameter(dict):
def cmd(self, value):
value = self['type'](value)
return [( ".".join( re.split("[. ]",self['name']) ) , self['format']%(value))]
def __call__(self, value):
return self.cmd(value)
class ParameterDictionary(dict):
_path = []
def __getattribute__(self, key):
if (key[0:1]=="_" and len(key)>1) or key in dict.__dict__ or key in ["cmd","cl"]:
return super(dict, self).__getattribute__(key)
return self.get(key)
def cmd(self, *args, **kwargs):
outputcmd = []
for a in args:
if issubclass( type(a), tuple):
if len(a)<2:
raise TypeError("Expecting key/value pairs in a tuple")
tmpcmd = self.get( a[0].upper() )
if not issubclass( type(tmpcmd), Parameter):
raise TypeError("keyword '%s' results in a non Parameter object, got '%s' "%(a[0], type(tmpcmd)))
outputcmd += tmpcmd.cmd(a[1])
elif issubclass( type(a), list):
outputcmd += self.cmd(*a)
else:
raise TypeError("expecting a tuple or a list got '%s'"%(type(a)))
for k,v in kwargs.iteritems():
tmpcmd = self.get(k.upper())
if not issubclass( type(tmpcmd) , Parameter):
raise TypeError("keyword '%s' results in a non Parameter object, got '%s' "%(k, type(tmpcmd)))
outputcmd += tmpcmd.cmd(v)
return outputcmd
def get(self, key, default=None):
spkey = re.split("[ .]", key, 1)
if len(spkey)>1:
return self.get( spkey[0]).get(spkey[1])
out = ParameterDictionary({})
findnums = re.findall( "[0-9]+$", key)
num = None
if key=="_":
key = ""
if len(findnums):
num = findnums[0]
root_key = key[0:-len(num)]
num = int(num)
key = "%s%d"%(root_key, num)
else:
root_key = key
for k in self:
sk = re.split("[ .]", k, 1)
if len(sk[0]) and sk[0][-1] == "i":
rk = sk[0][0:-1]
else:
rk = sk[0]
if rk==root_key:
if len(sk)<2:
out[""] = self[k]
#p = Parameter(self[k].copy())
#p['name'] = " ".join(self._path+[key])
#return p
else:
out[sk[1]] = self[k]
if not len(out):
raise KeyError("Cannot find keyword '%s' in the dictionary"%(key))
if len(out)==1:
p = Parameter(out[out.keys()[0]].copy())
p['name'] = " ".join(self._path+[key])
return p
out._path = self._path + [key]
return out
def cl(self, clname):
"""
Filter the keyword container by class
"""
out = ParameterDictionary()
for k,p in self.iteritems():
if "class" in p:
if clname in p['class'].split("|"):
out[k] = p
return out
class Class(ParameterDictionary):
pass
class Context(ParameterDictionary):
pass
class Dictionary(file):
config = {}
dictionary = None # will be set in init
#ParameterDictionary()
dictionaryClass = {}
dictionaryContext = {}
types = param_types
curentParameter = None
curentParameterName = ""
cases = {"Parameter Name":_pname,
"Class":_class,
"Context":_context,
"Type":_type,
"Value Format": _vformat,
"Unit": _unit,
"Comment Format": _cformat,
"Comment Field": _cformat,
"Description": _description
}
"""
A file descriptor for dictionary parsor
"""
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **kwargs)
self.dictionary = ParameterDictionary()
def parse(self, line=None, count = 0):
if line is None:
line = self.readline()
while len(line):
count += 1
nline = line.strip()
if not len(nline):
line = self.readline()
continue
if nline[0] == "#":
line = self.readline()
continue
spline = nline.split(":", 1)
if len(spline)<2:
line = self.readline()
continue
key, value = spline
key = key.strip()
value = value.strip()
if not key:
line = self.readline()
continue
if self.curentParameter is None and not key=="Parameter Name":
line = _config(self, key, value)
continue
if not key in self.cases:
line = _undefined(self,key, value )
line = self.cases[key](self, value)
return count
def parameterEnd(self):
self.curentParameter = None
self.curentParameterName = ""
def to_functionDict(self):
return parameterDictionary2functionDict(self.dictionary)
def parameter2function(param):
if param['type'] is bool:
param["format"] = mainvlt.formatBoolFunction
param['type'] = mainvlt.vltbool
return Function(param['name'],
dtype=param['type'],
format=param.get("format", "%s"),
default=None, value=None, index=None,
comment=param.get("comment", "%s"),
description=param.get("description", ""),
unit=param.get("unit", ""),
context=param.get("context", ""),
cls=param.get("class", "").split("|"))
def parameterDictionary2functionDict( pdictionary):
out = FunctionDict()
for k,p in pdictionary.iteritems():
out[k] = parameter2function(p)
return out
<file_sep>#!/usr/bin/python
import os
import re
from .config import config
from .buffread import ErrorStructure
msgSend_cmd = "msgSend"
debug = not os.getenv("HOST") in ["wbeti" , "wpnr" , "wbeaos"]
verbose = 1
LASTBUFFER = ""
DEFAULT_TIMEOUT = None
############################################################
# Some functions which are used as dtype or format
############################################################
def formatBoolFunction(value):
"""
return "T" or "F" if the input boolean value is True or False.
Used to format VLT message command
"""
if value:
return "T"
return "F"
def formatBoolCommand(value):
""" this return an empty string.
Used to format boolean values in commands, they do not accept
argument
"""
# command does not accept argument when they are boolean
return ""
class Option(object):
"""
Option class for VLT command.
Option have is a pair of key (or message) and value
for instantce in:
msgSend "" pnoControl SETUP "-function DET.DIT 0.005 DET.NDIT 1000 -expoId 0"
'-function' and '-expoId' are Option
p = Option(msg, dtype)
"""
default = None
format = "%s"
def __init__(self, msg, dtype , format="%s", default=None, name=""):
self.name = name #not used
self.msg = msg
self.dtype = dtype
if default is not None:
self.default = self.parseValue(default)
self.format= format
def __str__(self):
if self.default is None:
dfs = "None"
else:
default = self.getDefault()
if issubclass(type(default), str):
dfs = "'%s'"%(self.getFormatedDefault())
else:
dfs = self.getFormatedDefault()
return """%s("%s", %s, default=%s, format="%s")""" % (self.__class__.__name__, self.msg, self.dtype, dfs, self.format)
def __repr__(self):
return self.__str__()
def cmd(self, value=None):
if value is None:
value = self.default
msg = self.msg
return cmd((msg, self.formatValue(value)))
def getDefault(self):
""" Return the default value for this Option """
return self.parseValue(self.default)
def setDefault(self, value):
""" Set the default value for this Option """
self.default = self.parseValue(value)
def getFormatedDefault(self):
""" return the fromated defaultValue if any """
if self.default is None:
return ""
return self.formatValue(self.default)
def parseValue(self, value):
""" Parse the value according to the dtype of this Option
The parsed value is returned.
e.g:
o = Option("expoId",int)
o.parse("45") # return int(45)
"""
try:
return self.dtype(value)
except ValueError:
raise ValueError("Cannot convert '%s' to the expecting type %s for param '%s'"%(value,self.dtype, self.msg))
def formatValue(self, value):
""" Parse and format value according to the dtype and format """
value = self.parseValue(value)
# format can be a string or a function
if issubclass(type(self.format), str):
return self.format%(value)
else:
return self.format(value)
class EmbigousKey(KeyError):
pass
class VLTError(Exception):
errorStructure = None
stdout = ""
stderr = ""
@classmethod
def from_stdout(cl, msg, stdout):
e = cl(msg)
if "Error Structure" in stdout:
try:
e.errorStructure = ErrorStructure(stdout)
except:
pass
e.stdout = stdout
return e
@classmethod
def from_pipe(cl, cmd, pipe):
stdout = pipe.stdout.read()
stderr = pipe.stderr.read()
status = pipe.returncode
e = cl("%s reseived error %d\nSTDERR:\n%s\nSTDOUT:\n%s\n"%(cmd,status,stderr,stdout))
if "Error Structure" in stdout:
try:
e.errorStructure = ErrorStructure(stdout)
except:
pass
e.stdout = stdout
e.stderr = stderr
return e
def cmd2Option(msg,fromdict=None):
return Function.newFromCmd(msg, fromdict=fromdict)
def cmd2Function(msg, fromdict=None):
return Function.newFromCmd(msg, fromdict=fromdict)
def dotkey(key):
return ".".join( key.split(" ") )
def undotkey(key):
return ".".join( key.split(" ") )
def vltbool(val):
return bool( val!='F' and val!=False and val)
class Cmd(list):
def __add__(self, right):
return cmds(self, right)
def __addr__(self, left):
return cmds(left, self)
def cmd(st):
"""
From a string or list or list of tuple return a flat list of valid
command frunction/key pair
> cmd( ("DET.DIT", 0.003) )
[('DET', 'DIT')]
> cmd( [ ("DET.DIT",0.001), [[("DET.NDIT",100)]]] )
[('DET.DIT', 0.001), ('DET.NDIT', 100)]
"""
if issubclass(type(st), (list)):
# Always return a flat list
cmds = []
for c in st:
cmds += cmd(c)
return Cmd(cmds)
#this is always a flat list
return Cmd([st])
def cmd2str(tcmd):
tcmd = cmd(tcmd) # make a flat list
out = []
for c,v in tcmd:
if isinstance(v, str) and v.find(" ")>-1:
v = "'{}'".format(v)
out.append( "{} {}".format(c,v))
return " ".join(out)
def cmds(*args):
output = []
for a in args:
output += cmd(a)
#
# Return the list and elimiminate duplicate
return Cmd(dict(output).items())
class Params(dict):
def __init__(self, *args, **kwargs):
super(Params,self).__init__(*args, **kwargs)
for p,v in self.iteritems():
if not issubclass(type(v),Param):
raise TypeError("Params Accept only Param type got %s"%(type(v)))
class System(object):
# a list of function of the system
# e.g. for a detector
# functions = {
# 'dit' :Function("DET.DIT" , float, "%f", 0.0 ),
# 'ndit' :Function("DET.NDIT" , long, "%d", 10 ),
# 'polar':Function("DET.POLAR", int , "%04d", 0),
#
# 'type':Function( "DPR.TYPE", str , "%s", "TEST" ),
# 'tech':Function( "DPR.TECH", str , "%s", "image"),
# 'imgname':Function( "OCS.DET.IMGNAME", str , "%s", "IMG_{type}"),
#
# 'mode':Function( "INS.MODE", str , "%s", "ENGINEERING" ),
# 'readoutmode':Function("INS.READOUT.MODE", str , "%s", "DOUBLE")
# }
#functions = FunctionDict({})
# a list of mendatory functions for instance "INS.MODE"
# a list of function for wich the value should be rebuild from others function
# for instance rebuild = ["type","imgname"] , order matter
# type and then imgname will be rebuilt if e.g.
# type = "BIAS-{polar}" # {polar} will be replaced by the value of polar
# imgname = "INSTRUMENT-{type}_" # {type} will be replaced by the previously rebuilt type
rebuild = []
module = True
counter = 0
def __init__(self, proc):
self.proc = proc
def __setitem__( self, item, value):
# set the item in the self.function
self.functions[item] = value
def __getitem__( self, item):
# return the item inside the functiondic
return self.functions[item]
def __iter__(self):
# return the functionsDict as iterator
return self.functions.__iter__()
def __contains__(self, item):
# return the functionsDict as iterator
return self.functions.__contains__(item)
def __format__(self, fmt_spec):
# return the functionsDict as iterator
return self.functions.__format__(fmt_spec)
def copy(self):
new = self.__class__(self.proc)
new.functions = self.functions.copy(True)
return new
def iteritems(self):
return self.functions.iteritems()
def iterkeys(self):
return self.functions.iterkeys()
def items(self):
return self.functions.items()
def keys(self):
return self.functions.keys()
def pop(self, *args):
return self.functions.pop(*args)
def setdefault(self, *args):
return self.functions.setdefault(*args)
def new(self, *args, **kwargs):
kwargs = kwargs or {}
new = self.__class__( self.proc)
new.function = self.functions.copy(True) # make a deep copy
new.update(*args, **kwargs)
return new
def get(self, key, default=False):
return self.functions[key].get(default)
def set(self, key , val):
self.functions[key] = val
def update( self, *args, **kwargs):
return self.functions.update( *args, **kwargs)
def cmd(self, *args, **kwargs):
self = self.copy()
vals = self.functions#.copy()
vals.update(*args, **kwargs)
vals = vals.rcopy()
#for k in self.mandatory:
# if not vals[k].hasValue():
# self.set( k, vals[k].get(True)) # copy is default to value for mandatory
cmds = vals.cmd(context = self)
return cmd(cmds)
def sequence(self, method, *args, **kwargs):
if issubclass(type(method), str):
method = self.__getattribute__(method)
elif not hasattr(self, "__call__"):
raise TypeError("Method shoud have a __call__ method")
return Sequence( ( method, args, kwargs) )
def setup(self, kwargs=None , expoId=0, timeout=None):
kwargs = kwargs or {}
return self.proc.msgSend("setup", dict(function=self.cmd(kwargs), expoId=expoId), timeout= timeout)
<file_sep>import re
import pandas as pd
import datetime
import time
import os
from inspect import getargspec
def _issignature(want,signature):
return signature == want
def _getsignature(method):
spec = getargspec(method)
# nargs = nargs-1 if method is bounded
return len(spec.args) - (hasattr(method, "__self__") and
(method.im_self is not None))
def _call_decorator_parser(signature, method):
if signature == 1:
def tmp(date, key, value):
return method(value)
return tmp
if signature == 2:
def tmp(date, key, value):
return method(key, value)
return tmp
if signature == 3:
def tmp(date, key, value):
return method(date, key, value)
return tmp
if signature == 4:
def tmp(info, date, key, value):
return method(date, key, value)
return tmp
raise Exception("Signature function must be (value) or (key,value) or (date,key,value) (infodict, date, key, value)")
def _call_decorator_matcher(signature, method):
if signature == 1:
def tmp(date, key, value):
return method(key)
return tmp
if signature == 2:
def tmp(date, key, value):
return method(key, value)
return tmp
if signature == 3:
def tmp(date, key, value):
return method(date, key, value)
return tmp
raise Exception("Signature function must be (key) or (key,value) or (date,key,value)")
reg_date_file = re.compile("^.*([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9]).*$")
def _true(date, key, val):
return True
def guesstype(val):
try:
return int(val)
except:
try:
return float(val)
except:
return val
class LogFile(file):
data = {}
linereg = re.compile("([a-zA-Z]+) +([0-9]+) +([0-9:]+) +([^ ]+) +([^ ]+) +([^ ]+) +([0-9:]+)> ([^/=]+) = ([^/]*) / +(.+)$")
keys = ["month", "day", "time", "host", "who", "env", "time2", "key", "val", "comment"]
time_resolution = 1
dumpfile = None
date = None
before = None
after = None
_callparse = None
_callmatch = None
#fparse = None
fmatch = None
def fparse(self, key, val):
return self.guesstype(val)
def info2date(self, info):
"""extract from a parsed line (the info dictionary) the date(/time)
object.
"""
t = datetime.datetime.strptime(info['time'], "%H:%M:%S")
if self.time_resolution>1:
t = roundTime(t, self.time_resolution)
# convert month to numeric value
if "month" in info:
month = datetime.datetime.strptime(info['month'], "%b").month
else:
month = self._month
return t.replace(year=int(info.get("year", self._year)), month=month,
day =int(info.get('day', self._day)))
firstLine = True
date = None
def __init__(self, *args, **kwargs):
""" Open a logfile reader
same arguments than file plus:
Keywords [all these keywords are also valid in the parse function]
--------
- year: the default year for date
- month: the default month (numerical)
- day: the default day
These keywords are usefull only if the data cannot be read from the
log file. If omited guess the date from the filename or the creation
date.
- fmatch: a function of signature (key) or (key,val) or (date, key,val)
must return a boolean.
if fmatch(key) is True fparse(val) is executed (see below)
- fparse: a function of signature (val) or (key,val) or (date,key,val)
must return anything that will be stored in the data.
if return is None the value will be ignored
if fmatch *is* None and fparse *is not* None:
fparse is called for each lines
if fmatch *is not* None and fparse *is* None:
the value is stored in data only if the result of
fmatch is True.
One can use this function to parse type, to plot, to print lines etc...
example:
f = LogFile("/vltdata/tmp/logFile")
f.parse( fmatch = lambda key: "SENS" in key, fparse = lambda val: float(val))
-or-
f.parse( fparse=f.gesstype )
definition = a dictionary with keywords definition.
"""
#self.data = pd.DataFrame()
lt = time.localtime()
kwdate = {k:kwargs.pop(k) for k in ["year","month","day"] if k in kwargs}
self.definition = kwargs.pop("definition", None)
self.fparse = kwargs.pop("fparse", self.fparse)
self.fmatch = kwargs.pop("fmatch", _true if self.fparse is not None else self.fmatch)
self.data = {}
self.lastdata = {}
self.lastdate = None
self.keyset = set()
super(LogFile,self).__init__(*args, **kwargs)
year, month, day = filepath2date(self.name)
self._year = kwdate.pop("year", None) or year
self._month = kwdate.pop("month", None) or month
self._day = kwdate.pop("day", None) or day
guesstype = staticmethod(guesstype)
def parseLine(self, line):
m = self.linereg.match( line)
if m:
info = dict( zip( self.keys, m.groups()))
date = self.info2date(info)
if info["key"]=="DATE":
try:
date = datetime.datetime.strptime(info["val"], "%Y-%m-%dT%H:%M:%S.%f" )
self.date = date
except:
pass
if self.before and date>self.before: return
if self.after and date<self.after : return
self.firstLine = False
#date = "{month}-{day}-{time}".format(**info)
key = info["key"]
val = info["val"]
if self._callmatch:
test = self._callmatch(date, key, val)
if test and self._callparse:
val = self._callparse(date, key, val)
elif not test and not self._callparse:
val = None
elif self.definition is not None:
if not key in self.definition:
return None
definition = self.definition[key]
if "name" in definition:
key = definition["name"]
if "dtype" in definition:
val = definition["dtype"](val)
if val is None:
return
if not date in self.data:
self.data[date] = {}
self.data[date][key] = val
self.lastdata[key] = val
self.lastdate = date
if self.dumpfile:
self.dumpfile.write(line)
#self.data.set_value(date, key, val)
def parse(self, time_resolution=None, before=None, after=None,
fmatch=None, fparse=None, year=None, month=None, day=None
):
if time_resolution: self.time_resolution = time_resolution
if before: self.before= before
if after : self.after = after
if year : self._year = int(year)
if month : self._month= int(month)
if day : self._day = int(day)
if fparse: self.fparse= fparse
if fmatch: self.fmatch = fmatch
if self.fparse and self.fmatch is None:
self.fmatch = _true
if self.fparse:
self._callparse = _call_decorator_parser(_getsignature(self.fparse), self.fparse)
if self.fmatch:
self._callmatch = _call_decorator_matcher(_getsignature(self.fmatch), self.fmatch)
line = self.readline()
while len(line):
self.parseLine(line)
line = self.readline()
return self.data
def to_df(self, keys=[]):
return pd.DataFrame( self.data.values(), self.data.keys())
def to_array(self, keys=["mjd"], dtype=float, fillvalue=-9.99,
allkeys=False):
import numpy as np
fillvalue = dtype(fillvalue)
shape = ( len(self.data), len(keys) )
dtypes = [ (k,dtype) for k in keys]
#A = np.ndarray( shape, dtype=dtype)
A = np.ndarray(len(self.data), dtype=dtypes)
mask = np.ndarray((len(self.data),), dtype=bool)
mask[:] = True
i=0
j=0
for date, dv in self.data.iteritems():
vl = []
for k in keys:
if k=="mjd":
v = time.mktime(date.timetuple())-time.timezone
else:
if k in dv:
v = dv[k]
else:
v = fillvalue
mask[i] = False
vl.append(v)
#A[i,j] = v
j +=1
A[i] = tuple(vl)
j = 0
i += 1
if allkeys:
A = A[mask]
if "mjd" in keys:
A.sort(order="mjd")
return A
class OpsLogFile(LogFile):
linereg = re.compile("^[^>]*([0-9][0-9][:][0-9][0-9][:][0-9][0-9])> ([^/=]+) = ([^/]*) / +(.+)$")
keys = ["time", "key", "val", "comment"]
# date = datetime.datetime(2014, 01,01)
# year = 2014
# month = 01
# day = 01
# def info2date(self, info):
#
#
# t = datetime.datetime.strptime(info['time'], "%H:%M:%S")
# if self.time_resolution>1:
# t = roundTime(t, self.time_resolution)
#
# if self.date:
# return t.replace( year=self.date.year, month=self.date.month, day=self.date.day)
# return t.replace( year=self.year, month=self.month, day=self.day)
def filepath2date(path):
""" try to guess year, month, day from a file name """
name = os.path.split(path)[1]
m = reg_date_file.match(name)
if not m:
try:
lt = time.localtime(os.path.getctime(path))
except:
lt = time.localtime()
return lt.tm_year, lt.tm_mon, lt.tm_mday
return tuple( int(g) for g in m.groups() )
def readSensors(filename):
definition = { "INS SENS%d STAT"%i:{"name":"S%d"%i,"dtype":float} for i in range(1,16)}
f = LogFile(filename, definition=definition)
f.parse()
return f
# temp = (S6 - 1080+ (-1.71)*66.93)/-1.71
###############################################################################
#
# Time Conversions
#
################################################################################
import math, sys, string
def gd2jd(year, month, day, hh, min, sec):
UT = hh+min/60. +sec /3600.
# Formula for Conversion:
#
# JD =367K - <(7(K+<(M+9)/12>))/4> + <(275M)/9> + I + 1721013.5 + UT/24
# - 0.5sign(100K+M-190002.5) + 0.5
#where K is the year (1801 <= K <= 2099), M is the month (1 <= M <= 12), I is the day of the month (1 <= I <= 31), and UT is the universal time in hours ("<=" means "less than or equal to"). The last two terms in the formula add up to zero for all dates after 1900 February 28, so these two terms can be omitted for subsequent dates. This formula makes use of the sign and truncation functions described below:
#
#The sign function serves to extract the algebraic sign from a number.
#Examples: sign(247) = 1; sign(-6.28) = -1.
#
#The truncation function < > extracts the integral part of a number.
#Examples: <17.835> = 17; <-3.14> = -3.
#
#The formula given above was taken from the 1990 edition of the U.S. Naval Observatory's Almanac for Computers (discontinued).
#
#Example: Compute the JD corresponding to 1877 August 11, 7h30m UT.
#Substituting K = 1877, M = 8, I = 11 and UT = 7.5,
#JD = 688859 - 3286 + 244 + 11 + 1721013.5 + 0.3125 + 0.5 + 0.5
#= 2406842.8125
JD = 367*year - int((7*(year+ int((month+9)/12.)))/4.) + int((275*month)/9.) + day + 1721013.5 + UT/24. - 0.5*math.copysign(1,100*year+month-190002.5) + 0.5
return JD
def gd2mjd( year, month, day, hh, min, sec):
# see http://tycho.usno.navy.mil/mjd.html
return gd2jd( year, month, day, hh, min, sec) - 2400000.5
def date2jd(date):
return gd2jd( date.year,
date.month,
date.day,
date.hour,
date.minute,
date.second+date.microsecond*1e-6
)
def date2mjd(date):
return date2jd(date) - 2400000.5
def jd2gd(jd):
jd=jd+0.5
Z=int(jd)
F=jd-Z
alpha=int((Z-1867216.25)/36524.25)
A=Z + 1 + alpha - int(alpha/4)
B = A + 1524
C = int( (B-122.1)/365.25)
D = int( 365.25*C )
E = int( (B-D)/30.6001 )
dd = B - D - int(30.6001*E) + F
if E<13.5:
mm=E-1
if E>13.5:
mm=E-13
if mm>2.5:
yyyy=C-4716
if mm<2.5:
yyyy=C-4715
h=int((dd-int(dd))*24)
min=int((((dd-int(dd))*24)-h)*60)
sec=86400*(dd-int(dd))-h*3600-min*60
return ( int(yyyy), int(mm), int(dd), int(h), int(min), sec)
def mjd2gd(jd):
return jd2gd( jd + 2400000.5 )
def jd2date(jd):
d = list(jd2gd(jd))
sec = d[-1]
#convert the fractional seconds to integer second and microsecond
d[-1] = int(sec)
microsec = int( (sec-d[-1]) * 1e6)
d.append(microsec)
return datetime.datetime(*d)
def mjd2date(jd):
return jd2date( jd + 2400000.5 )
def roundTime(dt, roundTo=60):
"""Round a datetime object to any time laps in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: <NAME> 2012 - Use it as you want but don't blame me.
"""
seconds = (dt - dt.min).seconds
# // is a floor division, not a comment on following line:
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
<file_sep>from ..device import Device
class Motor(Device):
""" Motor is a device with the following additional methods
moveTo : move to one position
moveBy : move by a relative number of encrel
and their coresponding cmd method cmdMoveTo, cmdMoveBy, ...
"""
def _check(self):
""" the simple motor device needs these keys to work
corectly : "NAME", "ENC", "ENCREL", "INIT", "STOP"
"""
self._check_keys(["NAME", "ENC", "ENCREL", "INIT", "STOP"])
def cmd_moveTo(self,targetpos):
if issubclass(type(targetpos), str):
return self['NAME'].cmd(targetpos, context=self)
return self['ENC'].cmd(targetpos, context=self)
def cmd_moveBy(self,encrel):
return self['ENCREL'].cmd(encrel, context=self)
def moveTo(self, targetpos, proc=None):
return self.getProc(proc).setup(function=self.cmd_moveTo(targetpos))
def moveBy(self,encrel, proc=None):
return self.getProc(proc).setup(function=self.cmd_moveBy(encrel))
<file_sep>
import vlt
import vlt.buffread as buffread
def msgdef(msg,commands):
def tmp(self,**kwargs):
return self.msgSend( msg, kwargs)
tmp.__doc__ = commands[msg].helpText
return tmp
buffreader = buffread.buffreader
osbControl_commands = {
"cont" :vlt.Command("CONT",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s"),"at":vlt.Param("-at", str, "%s")},helpText="""Continue a paused exposure at a given optional time. The following options are
supported:
at <time> specify the time when the exposure must be resumed
(default is now). The time format is (ISO8601):
[[CC]YY[-]MM[-]DD[T| ]]HH[:]MM[[:]SS[.TTT]]
expoId <expoId> integer number specifying exposure number (optional)
""", bufferReader=buffreader.getreader("CONT")),
"addfits" :vlt.Command("ADDFITS",{"info":vlt.Param("-info", str, "%s"),"expoId":vlt.Param("-expoId", int, "%d"),"extname":vlt.Param("-extname", str, "%s"),"detId":vlt.Param("-detId", str, "%s"),"extnum":vlt.Param("-extnum", int, "%d")},helpText="""Add information to the FITS header of an acquisition frame. The following
options are supported:
expoId <expoId> integer number specifying exposure number (optional)
info <keyword1> <value1> [<keyword2> <value2> ...]
specify one or more parameters with the associated
value which have to be added to FITS header. With:
keywordX: a short-FITS keyword
valueX: the value for the keyword
extnum Serial number of the extention (1..n)
If parameter is omitted the kw is stored in
the primary header (optional)
extname Name of extention where the keywords (specified via -info)
should be stored. Both parameters -extnum or -extname
are optional but only one of them should be present.
""", bufferReader=buffreader.getreader("ADDFITS")),
"standby" :vlt.Command("STANDBY",{"subSystem":vlt.Param("-subSystem", str, "%s")},helpText="""Switches the local server and its associated subsystems or only the specified
subsystem to the STANDBY state. The following option is
supported:
subSystem <subSystem> name of the subsystem to switch to STANDBY state.
""", bufferReader=buffreader.getreader("STANDBY")),
"stopopt" :vlt.Command("STOPOPT",{},helpText="""Abort on-going flux optimazation
""", bufferReader=buffreader.getreader("STOPOPT")),
"setup" :vlt.Command("SETUP",{"function":vlt.Param("-function", vlt.dtypeFunctionList, "%s"),"noMove":vlt.Param("-noMove", bool, vlt.formatBoolCommand),"expoId":vlt.Param("-expoId", int, "%d"),"noExposure":vlt.Param("-noExposure", bool, vlt.formatBoolCommand),"file":vlt.Param("-file", str, "%s"),"check":vlt.Param("-check", bool, vlt.formatBoolCommand)},helpText="""Set-up functions, as part of the preparation of an exposure. The following
options are supported:
expoId <expoId> A unique id of an exposure. The expoId should be set
to 0 in order to setup a new exposure. The successful
command returns a new valid expoId (increasing by 1
the last expoId), which is always greater then 0. Any
consequent setup and commands belonging to this
exposure must use this expoId.
file <file1> [<file2>]
specify one or more set-up files
function <keyword1> <value1> [<keyword2> <value2> ...]
specify one or more parameters with the associated
value. keywordN: a short-FITS keyword
valueN: the value for the keyword
First setup must contain the instrument mode (INS.MODE).
An image taking exposure should setup the imagefilename
(OCS.DET.IMGNAME) befor the exposure can be started.
noMove indicate that the functions contained in the setup
files and/or list of parameters are not moved, but
otherwise the values get the full setup treatment.
check indicate that list of parameters is checked for
semantic validity, without storing values or moving
functions.
noExposure In special cases the SETUP may not correspond to any
exposures (e.g. there is no detector connected to
the OS). In this case the parameter noExposure is
applicable. Use with caution, and do not use together
with parameter expoId. Command returns: -1
(invalid expoId).
""", bufferReader=buffreader.getreader("SETUP")),
"debug" :vlt.Command("DEBUG",{"action":vlt.Param("-action", int, "%d"),"log":vlt.Param("-log", int, "%d"),"timer":vlt.Param("-timer", int, "%d"),"verbose":vlt.Param("-verbose", int, "%d")},helpText="""Changes logging levels on-line. Levels are defined from 1 to 5 whereby
level 1 produces only limited number of logs, and level 5 produces logs
at a very detailed level. The following options are supported:
log <level> level for standards logs which are stored into the
standard VLT log file.
verbose <level> level for logs that are written to stdout.
action <level> level for action logs which are written into a DB
attribute.
timer <level> level for timer logs which are used to report the
time for performing a given action. This information
is stored into the standard VLT log file and written
to stdout, according to the level of these logs.
""", bufferReader=buffreader.getreader("DEBUG")),
"off" :vlt.Command("OFF",{"subSystem":vlt.Param("-subSystem", str, "%s")},helpText="""Switches the local server and its associated subsystems or only the specified
subsystem to the OFF state. The following option is supported:
subSystem <subSystem> name of the subsystem to switch to the OFF state.
""", bufferReader=buffreader.getreader("OFF")),
"optflux" :vlt.Command("OPTFLUX",{"gridGeom":vlt.Param("-gridGeom", str, "%s"),"beam":vlt.Param("-beam", int, "%d"),"save":vlt.Param("-save", str, "%s"),"gridStep":vlt.Param("-gridStep", float, "%f"),"nDit":vlt.Param("-nDit", int, "%d")},helpText="""Perform flux optimazation
""", bufferReader=buffreader.getreader("OPTFLUX")),
"comment" :vlt.Command("COMMENT",{"expoId":vlt.Param("-expoId", int, "%d"),"clear":vlt.Param("-clear", bool, vlt.formatBoolCommand),"detId":vlt.Param("-detId", str, "%s"),"string":vlt.Param("-string", str, "%s")},helpText="""Add a comment to the FITS header of an exposure. The following options are
supported:
expoId <expoId> integer number specifying exposure number (optional)
comment <comment> comment string to be added to the FITS header.
clear if 'true' the list of comments already added will
first be cleared.
""", bufferReader=buffreader.getreader("COMMENT")),
"gethdr" :vlt.Command("GETHDR",{"expoId":vlt.Param("-expoId", int, "%d"),"btblFileName":vlt.Param("-btblFileName", str, "%s"),"detId":vlt.Param("-detId", str, "%s"),"hdrFileName":vlt.Param("-hdrFileName", str, "%s")},helpText="""Internal command. Creates a header file.
""", bufferReader=buffreader.getreader("GETHDR")),
"expstrt" :vlt.Command("EXPSTRT",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s")},helpText="""Internal SOS-OS command. SOS sends this command to the OS-es which
are on the subsystemlist but not started.
When OS receives this command it calles the startpreproc function.
""", bufferReader=buffreader.getreader("EXPSTRT")),
"online" :vlt.Command("ONLINE",{"subSystem":vlt.Param("-subSystem", str, "%s")},helpText="""Switches the local server and its associated subsystems or only the specified
subsystem from STANDBY state to the ON-LINE state. The following option is
supported:
subSystem <subSystem> name of the subsystem to switch from STANDBY state
to the ON-LINE state.
""", bufferReader=buffreader.getreader("ONLINE")),
"status" :vlt.Command("STATUS",{"function":vlt.Param("-function", vlt.dtypeFunctionList, "%s"),"expoId":vlt.Param("-expoId", int, "%d")},helpText="""Get the status of the functions in the list of arguments (default: get the
status of all functions). The following options are supported:
expoId <expoId> integer number specifying exposure number (optional)
function [<keyword1> <keyword2> ...]
specify any detector, instrument or telescope
function.
The reply buffer has the format:
"<no of keys>,<key 1> <value 1>,<key 2> <value 2>,..."
""", bufferReader=buffreader.getreader("STATUS")),
"pause" :vlt.Command("PAUSE",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s"),"at":vlt.Param("-at", str, "%s")},helpText="""Pause the current exposure at a given optional time. The following options are
supported:
at <time> specify the time when the exposure has to be paused
(default is now). The time format is (ISO8601):
[[CC]YY[-]MM[-]DD[T| ]]HH[:]MM[[:]SS[.TTT]]
expoId <expoId> integer number specifying exposure number (optional)
""", bufferReader=buffreader.getreader("PAUSE")),
"end" :vlt.Command("END",{"expoId":vlt.Param("-expoId", int, "%d"),"all":vlt.Param("-all", bool, vlt.formatBoolCommand),"detId":vlt.Param("-detId", str, "%s")},helpText="""End the current exposure as soon as possible and read out the data. The
following options are supported:
expoId <expoId> integer number specifying exposure number (optional)
detId ends the exposure specified on the given detector
all ends all running exposures and cancells exposures
that has not yet been started
""", bufferReader=buffreader.getreader("END")),
"measure" :vlt.Command("MEASURE",{"params":vlt.Param("-params", vlt.dtypeFunctionList, "%s"),"type":vlt.Param("-type", str, "%s")},helpText="""Performs measurement. The following options are supported:
type <measType> specify the type of measurement to be performed.
params <param1> <value1> [<param2> <value2> ...]
specify one or more parameters with the associated
value. With:
paramX: a short-FITS keyword
valueX: the value for the keyword
""", bufferReader=buffreader.getreader("MEASURE")),
"start" :vlt.Command("START",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s"),"at":vlt.Param("-at", str, "%s")},helpText="""Start an exposure at a given optional time. The following options are supported:
expoId <expoId> integer number specifying exposure number (optional)
at <time> specify the time when the exposure must be started
(default is now). The time format is (ISO8601):
[[CC]YY[-]MM[-]DD[T| ]]HH[:]MM[[:]SS[.TTT]]
""", bufferReader=buffreader.getreader("START")),
"state" :vlt.Command("STATE",{"subSystem":vlt.Param("-subSystem", str, "%s")},helpText="""Returns the current state and sub-state of the server or of the specified
subsystem. The format of the returned string is STATE/SUBSTATE, e.g.
ONLINE/IDLE. The following options are supported:
subSystem <subSystem> specify the name of the sub-system for which
the state or sub-state has to be returned
The standard states of a server are:
OFF: the software is loaded, but it is not operational.
STANDBY: the software is loaded and initialised, the hardware is software
initialised, but in standby (applicable parts switched off,
brakes clamped, etc.)
ONLINE: the software is loaded and initialised, the hardware is hardware
initialised and fully operational.
""", bufferReader=buffreader.getreader("STATE")),
"version" :vlt.Command("VERSION",{},helpText="""Returns the version of the software.
""", bufferReader=buffreader.getreader("VERSION")),
"clean" :vlt.Command("CLEAN",{},helpText="""Internal command. Clears the OS exposure table and sets the expoId
to zero, i.e to the initial value.
""", bufferReader=buffreader.getreader("CLEAN")),
"forward" :vlt.Command("FORWARD",{"subSystem":vlt.Param("-subSystem", str, "%s"),"command":vlt.Param("-command", str, "%s"),"arguments":vlt.Param("-arguments", str, "%s")},helpText="""This command is forwards the specified commands with a specified arguments
to the specified sub-system.
FORWARD returns the reply of the sub-system command as a
string.The following option is supported:
subSystem <subSystem> name of the subsystem to which the command has to
be forwarded.
command <command> name of the command.
arguments <params> optional command parameters.
""", bufferReader=buffreader.getreader("FORWARD")),
"wait" :vlt.Command("WAIT",{"all":vlt.Param("-all", bool, vlt.formatBoolCommand),"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s"),"header":vlt.Param("-header", bool, vlt.formatBoolCommand),"cond":vlt.Param("-cond", str, "%s"),"mode":vlt.Param("-mode", str, "%s"),"detlist":vlt.Param("-detlist", str, "%s"),"first":vlt.Param("-first", bool, vlt.formatBoolCommand)},helpText="""Wait for exposure completion and return the exposure status.
The following parameters are supported:
expoId <expoId> integer number specifying exposure number (optional);
The expoId must be in correspondace with the expoid
returned by the first SETUP command of the
belonging exposure. The exoposure with the same expoId
has to be started via START command before WAIT command
is sent. If expoId is omitted, the command refers to
the last started exposure.
detId <detname> string specifying the the detector
first This parameter is useful for optimising the execution
of parallel exposures. It can be run in two ways
(depending on the setting of parameter mode ):
CurrRunning (default):
Waits until one of the currently running
exposures is completed/failed/aborted.
Returns the name of the detector.
detlist: Carries out an initial check to see if any of
the detectors (given by parameter 'detlist')
has already reached the given condition
(finished as default).
Should not be used together with parameter 'detId'.
all Wait untill all the exposures has been succesfully
finished or reached the specificed condition.
cond Condition of exposure to be reached before the last
reply sent. Typically used for optimised exposure
sequence. The following conditions can be set:
ObsEnd; CanSetupNextObs; CanStartNextObs
ObsEnd (default): Condition denoting that the exposure
is completed and the image file has been merged
with headers and archived.
CanSetupNextObs: Condition when new exposure can be
setup without interrupting the currently
running exposure. For NGCOPT it means reaching
the status READING_OUT. For NGCIR detector it
means reaching the status TRANSFERRING. Please
see also configuration OCS.DETi.OPTSEQ to alter
the behaviour.
CanStartNextObs: Condition when next exposure can be
started. I.e. the currently running observation
has been successfully finished, headers from
other subsystems has been collected and merging
process has been informed to archive the image.
header (obsolate) equivalent to '-cond CanStartNextObs'. Kept
for backcompatibility.
mode only together with 'first' see description at first
detlist only together with 'first' see description at first
For more details see BOSS usermanual: VLT-MAN-ESO-17240-2265
""", bufferReader=buffreader.getreader("WAIT")),
"expend" :vlt.Command("EXPEND",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s"),"path":vlt.Param("-path", str, "%s")},helpText="""Internal SOS-OS command. SOS sends this command to its OS and ICS subsystems.
When OS receives this command it forwards it to its ICS subsystems.
""", bufferReader=buffreader.getreader("EXPEND")),
"ping" :vlt.Command("PING",{},helpText="""Returns a reply.
Used to check if the process is alive.
""", bufferReader=buffreader.getreader("PING")),
"access" :vlt.Command("ACCESS",{"subSystem":vlt.Param("-subSystem", str, "%s"),"info":vlt.Param("-info", bool, vlt.formatBoolCommand),"mode":vlt.Param("-mode", str, "%s")},helpText="""Changes the ACCESS mode of the subsystems.
subSystem <subSystem> Name of the subsystem the access mode of which
is to be changed. Name should be given according to
the configuration file.
When set to 'ALL' the mode of all subsystems is changed.
mode <mode> Value can be set to IGNORE or NORMAL.
If subsystem mode set to IGNORED, all commands that are sent to
this are ignored.
info returns the ACCESS mode of all subsystems
""", bufferReader=buffreader.getreader("ACCESS")),
"abort" :vlt.Command("ABORT",{"expoId":vlt.Param("-expoId", int, "%d"),"detId":vlt.Param("-detId", str, "%s")},helpText="""Abort the current exposure immediately. Image data are lost. The following
options are supported:
expoId <expoId> integer number specifying exposure number (optional)
""", bufferReader=buffreader.getreader("ABORT")),
"exit" :vlt.Command("EXIT",{},helpText="""Terminates the process.
""", bufferReader=buffreader.getreader("EXIT")),
"config" :vlt.Command("CONFIG",{},helpText="""Read again the configuration files of the instrument.
""", bufferReader=buffreader.getreader("CONFIG"))}
class osbControl(vlt.Process):
"""
This is a osbControl class vlt.Process automaticaly generated from file
/Users/guieu/python/Catalog/vlt/CDT/osbControl.cdt
To get a list of commands:
proc.getCommandList()
To print a help on a specific command (e.g. setup)
proc.help("setup")
proc.help() will return a complete help
"""
commands = osbControl_commands
for c in osbControl_commands: exec("%s = msgdef('%s',osbControl_commands)"%(c,c))
proc = osbControl("osbControl")
<file_sep>from __future__ import print_function
import re
from .action import Actions
from .mainvlt import cmd, dotkey, undotkey, vltbool, cmd2str
from .process import getProc
from .config import config
KEY_MATCH_CASE = config.get("key_match_case", False)
def context_format(strin, context, origin=''):
"""
{item} -> context[item]
{[item]} -> context[item]
{.attr} -> context.attr
{item.attr} -> context[item].attr
{.attr[item]} -> context.attr[item]
{item1[item2]} -> context[item1][item2]
{[item1][item2]} -> context[item1][item2]
"""
origin = origin or strin
strout = ""
for before, field, fmt, q in strin._formatter_parser():
strout += before
if field is None:
continue
item, path = field._formatter_field_name_split()
context_value = context
if item: # {item} is considered as context[item] here
try:
context_value = context_value[item]
except KeyError:
raise KeyError("Error when trying to reformat '%s' : '%s' item no found in context"%(origin, item))
if isinstance(context_value,Function):
context_value = context_value.getValue()
if isinstance(context_value, basestring):
context_value = context_format(context_value, context, origin)
for tpe, item in path:
if tpe:
try:
context_value = getattr(context_value,item)
except AttributeError:
raise AttributeError("Error when trying to reformat '%s' : '%s' attribute no found in context"%(origin, item))
else:
try:
context_value = context_value[item]
except KeyError:
raise KeyError("Error when trying to reformat '%s' : '%s' item no found in the path"%(origin, item))
if isinstance(context_value,Function):
context_value = context_value.getValue()
if isinstance(context_value, basestring):
context_value = context_format(context_value, context, origin)
strout += format(context_value, fmt)
return strout
def context_format_test():
class Test(dict):
pass
context = Test({
"a" : "a is {b}",
"b" : "b is {c}",
"c" : 10,
"d" : "d is {.toto:03d}"
})
context.toto = Function("yo", 9)
print (context_format(context["a"], context))
print (context_format(context["d"], context))
class FunctionMatch(object):
def __init__(self, indexes, partialy, prefix="", suffix=""):
""" A simple class returned by Function match
m = f.match("SOME.KEY")
m.indexes is None if f is not iterable (see Function)
m.indexes is a tuple of indexes if f is iterable
m.partialy is True if the key is partialy matched
if partialy matched m.prefix and m.suffix return what is before
and after the match
"""
self.indexes = indexes
self.partialy = bool(partialy)
self.prefix = str(prefix)
self.suffix = str(suffix)
class FunctionMsg(object):
def __init__( self, valin, sep=None):
if isinstance(valin, str):
if sep is None:
vspace, vdot = valin.split(" "), valin.split(".")
valin, sep = (vspace, " ") if len(vspace)>len(vdot) else (vdot, ".")
else:
valin = valin.split(sep)
self.keys = []
for s in valin:
k = matchKey(s)
if k is None:
raise KeyError("the Key '%s' is not valid in '%s'" % (s,valin))
self.keys.append(k)
#self.keys = [matchKey(s) or s for s in valin]
self.sep = sep or "."
@classmethod
def new(cls, keys, sep="."):
""" Return a new FunctionMsg object with the same message """
new = cls([], sep=sep)
new.keys = keys
return new
def match(self, keys, prefixOnly=False, partialy=True):
""" match if the input keys match this message.
Return a FunctionMatch object if the match is succesful else None
By default partialy=True, means that the message can be matched
if only a part of it is matched.
e.i:
import vlt
vlt.FunctionMsg("INS.OPT1.NAME").match("OPT1") # match
vlt.FunctionMsg("INS.OPT1.NAME").match("NAME") # match
vlt.FunctionMsg("INS.OPT1.NAME").match("NAME", prefixOnly=True) # NO match
vlt.FunctionMsg("INS.OPT1.NAME").match("INS.OPT1", prefixOnly=True) match
vlt.FunctionMsg("INS.OPT1.NAME").match("NAME", partialy=True) # NO match
etc ....
"""
if not isinstance(keys, FunctionMsg):
keys = FunctionMsg(dotkey(keys))
keyslen = len(keys.keys)
selfkeyslen = len(self.keys)
if keyslen>selfkeyslen: return None
partialy = (partialy and (selfkeyslen != keyslen))
if partialy or prefixOnly:
it = [0] if prefixOnly else range(selfkeyslen-keyslen+1)
for i in it:
prefix = FunctionMsg.new(self.keys[0:i] , self.sep)
suffix = FunctionMsg.new(self.keys[i+keyslen:None], self.sep)
trimed = FunctionMsg.new(self.keys[i:i+keyslen] , self.sep)
m = trimed.match(keys)
if m:
newindexes = tuple(list(prefix.getIndex())+list(m.indexes or []))
return FunctionMatch(newindexes, True, prefix.reform(), suffix.reform())
return m
return None
else:
if keyslen != selfkeyslen: return None
indexes = []
for k, sk in zip(keys.keys,self.keys):
m = sk.match( k )
if m is False: return None
if m is True: continue
indexes.append( m )
return FunctionMatch(tuple(indexes), partialy)
#if len(indexes):
#return FunctionMatch(None, partialy)
def reIndex(self, indexes):
"""
Return a new re-indexed FunctionMsg if it is indexable.
The entry is a tuple of index the len of the tuple should not
exceed the number of indexable keys.
parts of FunctionMsg, Keys, are indexable if they have i,j,h or k at the
end.
The 0 index means that index number is removed.
e.g : "INSi" is considered as iterable
"INSi.OPTi" is twice iterable
> vlt.FunctionMsg("INSi.OPTi.NAME").reIndex( (1,2) )
will return vlt.FunctionMsg('INS1.OPT2.NAME')
> vlt.FunctionMsg("INSi.OPTi.NAME").reIndex( (1,) )
will return vlt.FunctionMsg('INS1.OPTi.NAME')
> vlt.FunctionMsg("INSi.OPTi.NAME").reIndex( (1,2,1) )
will Raise a IndexError
> vlt.FunctionMsg("INSi.OPTi.NAME").reIndex( (0,2) )
will return vlt.FunctionMsg('INS.OPT2.NAME')
"""
if not isinstance( indexes, tuple):
raise ValueError( "expecting a tuple has unique argument got %s"%type(indexes))
offset = 0
out = []
indexeslen = len(indexes)
for ik in self.keys:
if ik.iterable and offset<indexeslen:
out.append( ik.reIndex(indexes[offset]))
offset +=1
else:
out.append(ik)
if offset<indexeslen:
raise IndexError("to many indices (%d) for key %s"%(indexeslen, self))
return self.new( out , self.sep)
def getIndex(self):
#if not self.isIterable():
# return tuple()
return tuple( [s.index for s in self.keys if s.isIterable()] )
def reform(self, sep=None):
sep = sep or self.sep
return sep.join( s.reform() for s in self.keys)
def reformAll(self, sep=None):
sep = sep or self.sep
out = [""]
first = True
for s in self.keys:
keys= s.reformAll()
tmp = []
for i,o in enumerate( out):
for k in keys:
tmp.append(o+("" if first else sep)+k)
out = tmp
first = False
return out
def isIterable(self):
return any(s.isIterable() for s in self.keys)
def __repr__(self):
return "'%s'"%self.reform()
def __str__(self):
return self.reform()
def __getitem__(self, item):
if not isinstance(item , tuple): item = (item,)
return self.reIndex(item)
class FunctionKeyi(object):
iterable = True
re = re.compile(r'([^ijkl]*)([ijkl])$')
mkey = 0
mindex = 1
def __init__(self, strin, index=""):
self.key = str(strin)
if isinstance( index, str):
self.strindex = index
self.readIndex(index)
else:
self.index = index
self.strindex = self.writeIndex
@classmethod
def matchNew(cls, strin):
m = cls.re.match(strin)
if m:
g = m.groups()
new = cls(g[cls.mkey], g[cls.mindex])
return new
return None
def match(self, key, prefixOnly=False):
if not isinstance(key, FunctionKeyi):
key = matchKey(key)
if key.key != self.key:
if KEY_MATCH_CASE: return False
if key.key.upper() != self.key:
return False
if key.index == None:
" For an iterable KEY is equivalent to KEY0 "
if self.index == None and isinstance(key, FunctionKey):
return 0
return None
try:
return self.reIndex(key.index or 0).index
except IndexError:
return False
def readIndex(self, strindex):
if not strindex in "ijkl":
raise Exception("index should only be i,j,k or l")
self.index = None
@staticmethod
def _writeIndex(index):
if index is None:
return "i"
if index == 0:
return ""
return "%d"%(index)
@classmethod
def _reform(cls, key, index):
return "%s%s"%(key, cls._writeIndex(index))
def getIndex(self):
if not self.isIterable():
raise IndexError("'%s' is not iterable "%self)
return self.index
def isIterable(self):
return self.iterable
def hasIndex(self):
return True
def hasLen(self):
return False
def writeIndex(self):
return self._writeIndex( self.index)
def reIndex(self, newindex):
if self.index is not None:
raise IndexError("Key %s not iterable"%self)
if newindex is None:
return FunctionKeyi( self.key, None) # return a copy
if isinstance(newindex, str):
m = matchKey(newindex)
if m.key != self.key:
raise IndexError("'%s' does not match %s"%(newindex,self))
newindex = m.index or 0
if isinstance(newindex, slice):
start, stop = newindex.start or 0 , newindex.stop
if stop is None:
raise IndexError("stop slice mandatory")
return FunctionKeySlice( self.key, slice(start, stop))
if hasattr(newindex, "__iter__"):
return FunctionKeyList( self.key, list( newindex))
# the return key is no longer iterable, return a string
return FunctionKey(self.key, newindex)
def reform(self):
return self._reform( self.key, self.index)
def reformAll( self):
return [self.reform()]
def __repr__(self):
return "'%s'"%self.reform()
def __str__(self):
return self.reform()
def __getitem__(self, item):
return self.reIndex(item)
class FunctionKey(FunctionKeyi):
iterable = False
#re = re.compile(r'^([^0-9][0-9a-zA-Z_-]*)([0-9]*)$')
re = re.compile(r'^(.+[^0-9]|.)([0-9]*)$')
#rei = re.compile(r'^([0-9]+)$')
#@classmethod
#def matchNew(cls, strin):
# m = cls.re.match(strin)
# if m :
# mindex = m.groups()[0]
# return cls( strin[0:-len(mindex)], mindex)
# else:
# return cls( strin, "")
def readIndex(self, strindex):
if strindex=="":
self.index = None
else:
self.index = int(strindex)
@staticmethod
def _writeIndex(index):
if index==0 or index is None:
return ""
return "%d"%index
def reIndex(self, dummy):
raise IndexError("Not iterable key %s"%self)
def match( self, key):
selfkey = self.reform()
key = "%s"%key #keep "%" to reform in case of FunctionKey instance
if KEY_MATCH_CASE:
return selfkey==key
else:
return selfkey==key or selfkey==key.upper()
def hasIndex(self):
return not (self.index is None)
class FunctionKeyList(FunctionKeyi):
re = re.compile(r'([^[]*)[(]([0-9, ]*)[)]$') # ])
maxlenIndexWrite = 8
def readIndex(self, strindex):
self.index = map(int, strindex.split(","))
@classmethod
def _writeIndex(cls, index):
ilen = len(index)
if ilen >cls.maxlenIndexWrite:
return "(%s,...,%s)"%(
",".join( map(str,index[0:cls.maxlenIndexWrite/2-1])),
",".join( map(str,index[-cls.maxlenIndexWrite/2+1:None]))
)
return "(%s)"%(",".join(map(str,index)))
def hasLen(self):
return True
def __len__(self):
return len(self.index)
def __iter__(self):
self.iternum = -1
return self
def next(self):
self.iternum += 1
if self.iternum<len(self):
return FunctionKeyi( self.key, self.index[self.iternum])
raise StopIteration()
def reIndex(self, newindex):
# if None juste return the same index
if newindex is None:
return FunctionKeyList(self.key, list(self.index))
if isinstance(newindex, str):
m = matchKey(newindex)
if m.key != self.key:
raise IndexError("'%s' does not match %s"%(newindex,self))
newindex = m.index or 0
if isinstance(newindex, slice):
start, stop = newindex.start or 0 , max(self.index) if newindex.stop is None else newindex.stop
if (start<min(self.index)) or (stop>max(self.index)):
raise IndexError("Slice out of range for index %s"%self.writeIndex())
return FunctionKeyList( self.key , [ i for i in self.index if i>=start and i<=stop ])
if hasattr(newindex, "__iter__"):
for i in newindex:
if not i in self.index:
raise IndexError("index '%d' is not included"%i)
return FunctionKeyList(self.key , list(newindex))
if not newindex in self.index:
raise IndexError("index '%d' is not included"%newindex)
return FunctionKey(self.key, newindex )
#return FunctionKeyi(self.key , newindex )
def reformAll(self):
return [FunctionKeyi(self.key, j).reform() for j in self.index]
class FunctionKeySlice(FunctionKeyi):
#re = re.compile(r'([^[]*)[(]([0-9]*:[0-9]*:[0-9]*|[0-9]*:[0-9]*)[)]$')
re = re.compile(r'([^[]*)[(]([0-9]+->[0-9]+)[)]$') # ])
def readIndex(self, strindex):
vals = map(int, strindex.split("->"))
self.index = slice(*vals)
@staticmethod
def _writeIndex(index):
return "(%s->%s)"%(index.start, index.stop)
def __len__(self):
return self.index.stop-self.index.start+1
def __iter__(self):
self.iternum = self.index.start-1
return self
def next(self):
self.iternum += 1
if self.iternum<=self.index.stop:
return FunctionKeyi( self.key, self.iternum)
raise StopIteration()
def reIndex(self, newindex):
if newindex is None:
return FunctionKeySlice(self.key , self.index)
if isinstance(newindex, str):
m = matchKey(newindex)
if m.key != self.key:
raise IndexError("'%s' does not match %s"(newindex,self))
newindex = m.index or 0
if isinstance(newindex, slice):
start, stop = newindex.start or 0 , max(self.index) if newindex.stop is None else newindex.stop
if start<self.index.start or stop>self.index.stop:
raise IndexError("Slice out of range for range %s"%self.writeIndex())
return FunctionKeySlice(self.key ,slice( start, stop))
if hasattr(newindex, "__iter__"):
for i in newindex:
if i<self.index.start or i>self.index.stop:
raise IndexError("index '%d' is not included"%i)
return FunctionKeyList(self.key , list(newindex))
if newindex<self.index.start or newindex>self.index.stop:
raise IndexError("index '%d' is not included"%newindex)
return FunctionKey(self.key, newindex)
def reformAll(self):
return [ FunctionKeyi(self.key, j).reform() for j in range(self.index.start, self.index.stop+1) ]
#return FunctionKeyi(self.key , newindex)
def matchKey(key):
return FunctionKeyi.matchNew(key) or FunctionKeyList.matchNew(key) or FunctionKeySlice.matchNew(key) or FunctionKey.matchNew(key)
def upperKey(key):
out = []
for k in dotkey(key).split("."):
out.append(_upperKey(k))
return ".".join(out)
def _upperKey(key):
ukey = key.upper()
if key[-1] in ["i", "j", "k"]:
if key[0:-1] == ukey[0:-1]:
return key
return ukey
class FunctionIter:
def __init__(self, function):
self.function = function
self.indexes = function._getAllIndexes()
self.counter = -1
self.size = len( self.indexes)
def next(self):
self.counter += 1
if self.counter >= self.size:
raise StopIteration("out of range")
return self.function[self.indexes[self.counter]]
class Function(object):
"""
Function is basicaly an object carrying a keyword (called also function
in vlt software) and a value.
It represents any keywords found in vlt dictionaries with special and very useful
behavior for iterable keys like e.g "DETi WINi"
On top of a keyword/value pair it carries numerous parameters (see bellow).
Args
----
msg (string) : The keyword, the message function e.g. "DET DIT" same as "DET.DIT"
value (Optional[any]) : Value corresponding to function None signify no value set yet
default (=None): a default value if value is not set. This was an idea that a Function
can have a default before beeing updated from the instrument but in practic is not
realy useful
format (="%s"): the str python format to represent the object when passed
in command e.g.: "%2.3f".
format can also be a function
accepting one argument (the value) and returning a string
dtype (Optional[type]): the data type, e.g: float, int, str, ... can also be a function
if None dtype is gessed from value
unit (Optional[string]) : value unit default ""
comment (Optional[string]) : value comment , default ""
description (Optional[string]) : value desciption, default ""
context (Optional[string]) : data vlt context, e.g. "Instrument"
cls (Optional[iterable]) : list of vlt class e.g.: ['header', 'setup'], default is []
statusFunc (Optional[string]) : a string or a Function used to ask the status to the instrument,
default is the Function msg itself.
Methods
-------
Object creation/info/copy
copy : make a copy
new : copy and set new value
info : print useful information about the Function
infoStr : return a string with useful information about the Function
infoDict : return a dictionary containing the same info printed in infoStr
newFromCmd : return a new Function object from string or tuple
get/set Parameter and value
getValue : return the curent value
setValue : set a or several (if iterable) value
hasValue : return True if value is defined
hasDefault : -> True if a default is set
cleanUp : erase all values
functions : return a list of all function with a value set
setMsg : set the message, function keyword
getMsg : get the message
Other parameters set/get :
setComment/getComment, setDescription/getDescription, setUnit/getUnit
setContext/getContext, setCls/getCls, setDefault/getDefault,
setFormat/getFormat, setDtype/GetDtype, setRange/getRange
match : match if a string is part of the Function message
isIterable : -> True if Function is iterable, e.i. has "ABCDi" key likes
Process/Instrument communication:
cmd : Return process function commands in list
Others:
select : select the Function for interactive stuf
unselect, isSelected : speak by themself
"""
default = None
_value = None
index = None
#_num_re = re.compile(r'([^#]*)[#]([^#]*)')
#_num_re = re.compile(r'([^i]*)[i]([. ]*|$)')
_num_re = re.compile(r'([^i]*)[i]([^i]*)')
_num_reList = re.compile(r'([^[]*)[[]([0-9,]*)[]]([^]]*)') # ]
_num_reSlice = re.compile(r'(.*)([0-9]*:[0-9]*:[0-9]*|[0-9]*:[0-9]*)(.*)')
_num_re1 = re.compile(r'([^i]*)([i])$')
_num_reList1 = re.compile(r"([^[]*)[[]([0-9,]*)[]]$") # ])
_num_reSlice1 = re.compile(r'([^[]*)[[]([0-9]*:[0-9]*:[0-9]*|[0-9]*:[0-9]*)[]]$') # ])
_num_re2 = re.compile(r'^[i]$')
_num_reList2 = re.compile(r'^([0-9,]*)$')
_num_reSlice2 = re.compile(r'^([0-9:]*)$')
def __init__(self, msg, value=None, dtype=None, format="%s", default=None,
index=None, comment="", description="", unit="", context="",
cls=None, selected=False, statusFunc=None, range=None,
_void_=False):
if _void_: #_void_ is for internal use only. To create an empty instance
#_void_ is used by _new and therefor the copy funtions
return
self.params = {}
self.onValueChange = Actions()
self.onSetup = Actions()
self.onSelect = Actions()
self.onUnSelect = Actions()
self.selected = False
self.statusFunc = statusFunc
self.setMsg(msg) # set the message. This will decide if it is aniterable Function
self.index= index
if dtype is None:
dtype = str if value is None else type(value)
self.setFormat(format)
self.setDtype(dtype)
self.setRange(range)
self.setValue(value)
self.setDefault(default)
self.setComment(comment)
self.setDescription(description)
self.setUnit(unit)
self.setContext(context)
self.setCls(cls)
def _new(self, **attr):
return self._copyAttr(self.__class__("",_void_=True), **attr)
def _copyAttr(self, new, **attr):
for k in ["params", "msg","_value", "index", "onValueChange",
"onSetup","onSelect", "onUnSelect",
"selected", "statusFunc"]:
setattr( new, k, attr[k] if k in attr else getattr(self, k) )
return new
@classmethod
def newFromCmd(cls, cmd, fromdict=None):
"""
Build a new Function object from a tuple.
This function provide a quick way to build a function. Usefull to
parse a string into a python vlt Function object.
It tries to be smart at gessing the righ dtype: e.g '5' will be a int
'5.6' will be a float, 'T' will be True, etc ...
if the value cannot be converted to numerical or boolean it is
considered as a string.
The tuple can have:
1 element: key,: value stay None and dtype is str
2 elements: key and value, dtype is guessed
or key and dtype, value stay None
3 elements: key, value, dtype
4 elements: key, value, dtype, format
A string "KEY val" will be converted to ("KEY", "Val")
example:
newFromCmd(("INS.OPT1.ENC", 250000))
newFromCmd("INS.OPT1.ENC 250000")
newFromCmd(("INS.OPT1.ENC", 250000, str)) # to Force beeing a string
"""
if issubclass(type(cmd), basestring):
cmd = tuple(s.strip() for s in cmd.split(" ",1))
if issubclass(type(cmd), tuple):
if len(cmd)==4:
msg, sval, dtype, format = cmd
elif len(cmd)==3:
msg, sval, dtype = cmd
format = None
elif len(cmd)==2:
msg, sval = cmd
dtype, format = None, None
elif len(cmd)==1:
msg, = cmd
sval, dtype, format = None, str, None
else:
raise ValueError("command expected to be a tuple with 2,3 or 4 elements")
if not issubclass(type(msg), basestring):
raise ValueError("The first element of the tuple must be string")
else:
raise ValueError("cmd should be s tuple or a string got %s" % (cmd,))
# Try to guess the dtype from the value
if dtype is None:
if dtype is None and isinstance(sval, basestring):
try:
val = int(sval)
except:
try:
val = float(sval)
except:
if sval is "T":
val = True
elif sval is "F":
val = False
else:
val = sval
else:
val = sval
if isinstance(val, type):
val, dtype = None, val
else:
dtype = type(val)
else:
val = sval
if fromdict is not None and msg in fromdict:
return fromdict[msg].new(val)
return cls(msg, value=val, dtype=dtype)
#_mod_re = re.compile(r"[%]([+-*]*[0-9]+)([^%])")
def __rmod__(self, f_rep):
return 0
def __repr__(self):
if not self.hasDefault():
dfs = "None"
else:
default = self.getDefault()
if issubclass(type(default), str):
dfs = "'%s'"%(self.getFormatedDefault())
else:
dfs = self.getFormatedDefault()
if not self.hasValue():
vfs = "None"
else:
value = self.getValue()
if issubclass(type(value), str):
vfs = "'%s'"%(self.getFormatedValue())
else:
vfs = self.getFormatedValue()
return """{classname}("{msg}", {value})""".format(classname=self.__class__.__name__, msg=self.getMsg(), value=vfs)
##return """%s("%s", %s, format="%s", default=%s, value=%s)"""%(self.__class__.__name__, self.getMsg(), self.getDtype(), self.format, dfs, vfs)
def __str__(self):
return self.__repr__()
if not self.hasValue():
raise Exception("The element '%s' does not have value and cannot be formated"%(self.getMsg()))
return self.getFormatedValue()
def info(self):
"""
Print usefull information about the function
"""
print (self.infoStr())
def infoStr(self):
"""
Returns
-------
A string representing useful information about the function
"""
return """{iterable}Function of message {msg}
value = {value}
default = {default}
format = {format}
type = {type}
range = {range}
unit = {unit}
class : {cls}
context : {context}
comment : {comment}
description: {description}
onValueChange: {nonvaluechange:d} actions
onSetup: {nonsetup:d} actions
""".format(self,**self.infoDict())
def infoDict(self):
"""
Returns
-------
A dictionary containing useful/printable information about the function
"""
if not self.hasDefault():
default = "None"
else:
default = self.getDefault()
if issubclass(type(default), str):
default = "'%s'"%(self.getFormatedDefault())
else:
default = self.getFormatedDefault()
if not self.hasValue():
value = "None"
else:
value = self.getValue()
if issubclass(type(value), str):
value = "'%s'"%(self.getFormatedValue())
else:
value = self.getFormatedValue()
return dict(
msg = self.getMsg(),
iterable = "iterable " if self.isIterable() else "",
value= value,
range= self.getRange(),
default=default,
format=self.getFormat(),
type = self.getDtype(),
unit = self.getUnit(),
cls = self.getCls(),
context = self.getContext(),
comment = self.getComment(),
description = self.getDescription(),
nonvaluechange = len(self.onValueChange),
nonsetup = len( self.onSetup)
)
def __format__(self, format_spec, context=None):
if not len(format_spec):
return format( self.getFormatedValue(context=context), format_spec)
# format_spec = "s"
#if format_spec[-1]=="s":
# return format( self.getFormatedValue() , format_spec)
if format_spec[-1]=="m":
return format( self.getMsg(), format_spec[0:-1]+"s")
if format_spec[-1]=="c":
return format( cmd2str(self.cmd(context=context)), format_spec[0:-1]+"s")
return format(self.getValue(context=context), format_spec)
def copy(self,copyValue=False):
"""
make a copy of the function
Parameters
----------
copyValue (=False) : if True make a copy of the value, this has effect only if
the function is iterable
Return
------
a new Function object sharing same parameters (unit,format, etc...)
"""
new = self._new()
if copyValue:
if self.hasValue():
new.setValue(self.getValue()) #This will copy the values if it is an iterable
return new
def new(self, value):
"""
new (value)
Return a copy of the Function parameter with the new value set.
"""
if self.isIterable():
raise TypeError("new works only on none iterable keys")
return self._new(value=self.parseValue(value))
def __getitem__(self, item):
if isinstance(item, str):
m = self.msg.match(item)
if not m :
raise KeyError("Function '%s' dos not match '%s'"%(self.msg, item))
item = m.indexes
if not isinstance( item , tuple):
item = (item,)
if len(item) and not self.isIterable():
raise IndexError("Function '%s' is not iterable, accept only an empty tuple"%self.getMsg())
#item = itemExplode(item)
return self._getOrCreate(item)
def __setitem__(self, item, value):
self[item].set(value)
def __iter__(self):
if not self.isIterable():
raise Exception("function '%s' is not iterable"%(self.getMsg()))
return self._value.__iter__()
return FunctionIter(self)
def _rebuildIndex(self, new):
new = self.getFunctionMsg().reIndex(tuple(new))
if new.isIterable(): return new.getIndex()
return None
def _save_rebuildIndex(self, new):
orig = self.index
if not orig: return new, [True]*len(new)
if not new : return list(orig), [False]*len(orig)
out = []
isi = []
offset = 0
for i in orig:
if isinstance(i,slice): i = range(i.start or 0, i.stop or 1, i.step or 1)
if i is None:
out.append(new[offset])
isi.append(True)
offset +=1
elif hasattr(i,"__iter__"):
inew = new[offset]
if hasattr(inew,"__iter__"):
for j in inew:
if not j in i:
raise IndexError("Index %d excluded"%j)
if isinstance(inew, slice):
if (min(i)>inew.start) or (max(i)<inew.stop):
raise IndexError("Range %d:%d excluded"%(inew.start,inew.stop))
elif (inew is not None) and (not inew in i):
raise IndexError("Index %d excluded"%inew)
out.append(inew)
isi.append(True)
offset +=1
else:
out.append(i)
isi.append(False)
return tuple(out), isi
def _getOrCreate(self, indexes):
if indexes is None or (len(indexes)==1 and indexes[0] is None) or not len(indexes):
return self
#rebuild only the first one
newmsg = self.getFunctionMsg().reIndex(tuple(indexes))
for j in range(len(newmsg.keys)):
i = newmsg.keys[j]
####
# If the key has no index there is nothing to do
####
if not i.hasIndex(): continue
if self._value is None:
self._value = {}
if i.isIterable():
####
# Just copy the actual iterable function but with a the new indexed msg
####
return self._new(msg=newmsg )
else:
####
# freeze the curent key, it becomes not-iterable/no-index anymore
####
i = FunctionKey(i.reform(), None)
newmsg.keys[j] = i
if not "%s"%i in self._value:
keypref = newmsg.keys[0:j+1]
####
# To create a new iterabke function we need to be sure that all the keys
# above are in the raw form "KEYi"
####
keyrest = [FunctionKeyi(s.key, None) if s.hasIndex() else s for s in newmsg.keys[j+1:None]]
tmpmsg = FunctionMsg.new( keypref+keyrest, newmsg.sep)
self._value["%s"%i] = self._new(msg=tmpmsg ,
_value=None ,
onValueChange = self.onValueChange.derive(),
onSetup = self.onSetup.derive()
)
self = self._value["%s"%i]
return self
def keys(self):
if not self.isIterable():
raise Exception("Function '%s' is not iterable"%self.msg)
return self.msg.reformAll()
def functions(self, default=False, onlyIfHasValue=True, errorIfNoLen=False):
""" Return a list of 'scalar' function made from self
e.g.:
>>> f = Function("INSi.SENSi.VAL")
>>> f["INS1.SENS1.VAL"] = 2.3
>>> f["INS1.SENS2.VAL"] = 2.3
>>> f["INS4.SENS8.VAL"] = 9.0
>>> f.functions()
[Function("INS1.SENS2.VAL", '2.3'),
Function("INS1.SENS1.VAL", '2.3'),
Function("INS4.SENS8.VAL", '9.0')]
"""
if onlyIfHasValue and not self.hasValue(default=default):
return []
if not self.isIterable():
return [self]
funcs = []
for i,s in enumerate(self.msg.keys):
if not s.hasIndex():
continue
ikey = s.index is None
keys = self._value.keys() if ikey else s.reformAll()
if ikey and errorIfNoLen and (not len(keys)):
raise Exception("Cannot iter on '%s', it has no len"%s)
for k in keys:
sub = self[k]
funcs.extend(sub.functions(onlyIfHasValue=onlyIfHasValue, default=default))
break
return funcs
self._function(self, funcs, 0)
return funcs
def _function(self, sub , funcs, offset):
if offset >= len(self.msg.keys):
return
s = self.msg.keys[offset]
if not s.hasIndex():
return self._function( sub, funcs, offset+1)
keys = values.keys() if s.index is None else s.reformAll()
for k in keys:
self._function(sub[k] , funcs, offset+1)
def getValue(self, value=None, default=False, context=None, index=None):
"""
return the value if set (not None) else raise a ValueError
Args:
-----
value (Optional): a default if value is not set
default (Optiona[bool]): return stored default value (if exists) if
the value is not set. Default is False
context (Optional[dict/FunctionDict]) : a context FunctionDict or dictionary instance
with key/values pair.
context is used the rebuild a bracketed string value
e.g. : >>> f = Function( "DET FILE", "exop_{type}_{dit}.fits")
>>> f.getValue( context=dict(type="FLAT", dit=0.002))
index (Optional[tuple]): indexes of value if function is iterable
>>> f[1,1].getValue() <-> f.getValue(index=(1,1))
Return:
Any stored value
Raises:
ValueError if not default is given and no value is stored
"""
self = self._getOrCreate(index)
if value is None and not self.hasValue(default):
raise ValueError("'%s': no value set yet use default=True to get the default value instead, or .set(val) to set a value to this option or .new(val) to create a new one with value"%(self.getMsg()))
if self.isIterable():
if value is not None:
raise ValueError("accept value only for non iterable Function")
else:
return {k:f.getValue(default=default, context=context) for k,f in self._value.iteritems() if f.hasValue()}
if value is None:
if self._value is None:
return self.getDefault(context=context)
value = self._value
if context is not None:
return self._rebuildVal(value, context)
return value
getV = getValue
get = getValue
def getValueOrDefault(self, index=None):
""" return self.getValue(default=True) """
return self.getValue(default=True, index=index)
getVod = getValueOrDefault
def hasValue(self, default=False, index=None):
self = self._getOrCreate(index)
if self.isIterable():
#if self.index and len(Self.index):
# pass
return sum( f.hasValue() for f in self._value.values() )>0
return self._value is not None or (default and self.hasDefault())
def isDeletable(self, index=None):
self = self._getOrCreate(index)
if self.isIterable():
return sum( f.isDeletable() for f in self._value.values() )==0
return not self.hasValue()
def cleanUp(self, index=None):
""" Clean the Function, all values are erased """
self = self._getOrCreate(index)
if not self.isIterable():
return
for k,f in self._value.iteritems():
f.cleanUp()
for k in self._value.keys():
if self._value[k].isDeletable():
del self._value[k]
def select(self, id=True):
self.selected = id
self.onSelect.run(self)
def unselect(self):
self.selected = False
self.onUnSelect.run(self)
def isSelected(self, id=True):
""" Return true is the function is selected.
id is the id selection test.
"""
if id is True:
return self.selected is not False
return self.selected == id
def selectUnselect(self, id=True):
if self.isSelected(id):
self.unselect()
else:
self.select(id)
def hasDefault(self):
""" return True if function has a default values"""
return self.default is not None
def setValue(self, value, index=None):
""" set the function value.
the value must be parsable by the Function dtype
If the function is an iterable a input dictionary is accepted
Args:
-----
value : scalar value or dict if iterable Function
index (Optional[tuple]) : value index
e.g : f[1,2].setValue(3.4) <-> f.setValue(3.4, index=(1,2))
Examples:
---------
>>> f = Function("INSi.SENSi.VAL")
>>> f["INS1.SENS2.VAL"].setValue(3.4)
equivalent to
>>>> f["INS1.SENS2.VAL"] = 3.4
or
>>>> f[1,2] = 3.4
>>>> f.setValue( {1:{1:3.4, 2:6.8}} )
or
>>>> f.setValue({'INS1': {'SENS1': '3.4', 'SENS2': '6.8'}})
"""
self = self._getOrCreate(index)
if self.isIterable():
if value is None:
self._value = {}
return
if not isinstance( value, dict):
map( lambda f:f.setValue(value), self.functions(onlyIfHasValue=False, errorIfNoLen=True) )
return
for k,v in value.iteritems():
#self._getOrCreate((k,))[self.index].setValue(v)
self[k].setValue(v)
#self._getOrCreate((k,)).setValue(v)
return
oldvalue = self._value
self._value = self.parseValue(value)
self.onValueChange.run(self, oldvalue)
return self
set = setValue
def setComment(self,comment):
""" set the comment string parameter """
self.params['comment'] = str(comment)
def getComment(self):
""" get the command string parameter """
return self.params.get('comment', "")
def setDescription(self, description):
""" set the string description parameter """
self.params['description'] = str(description)
def getDescription(self):
""" get the description string parameter """
return self.params.get('description', "")
def setUnit(self,unit):
""" set the string unit parameter """
self.params['unit'] = str(unit)
def getUnit(self):
""" get the string unit parameter """
return self.params.get("unit","")
def setContext(self,context):
""" set the context string parameter e.g 'Instrument' """
self.params["context"] = str(context)
def getContext(self):
""" get the context string parameter """
return self.params.get("context")
def setCls(self,cls):
""" set a list of vlt classes e.g. ['header', 'setup'] """
self.params["cls"] = list(cls or [] )
def getCls(self):
""" return list of classes """
return self.params.get("cls",[])
def setMsg(self, msg, sep=None):
if isinstance(msg, str):
msg = FunctionMsg(msg, sep=sep)
elif not isinstance(msg, FunctionMsg):
raise ValueError("expecting a str or FunctionMsg as message got %s"%type(msg))
self.msg = msg
#self.iterable = self._num_re.search(msg) is not None and self.index is None
#self.iterable = len(self._num_re.findall(msg))
#self.iterable = len( [s for s in self.msg.keys if s.isIterable()])
#self.iterable = sum( [ True for k in dotkey(msg).split(".") if self._num_re1.match(k) or self._num_reList1.match(k) or self._num_reSlice1.match(k)] )
def getFunctionMsg( self):
return self.msg
return FunctionMsg( dotkey(self.msg) )
def getMsg(self, context=None, dot=True):
msg = self._rebuiltMsg(context)
if dot:
msg = dotkey(msg)
else:
msg = undotkey(msg)
return msg
def match(self, key, context=None, prefixOnly=False, partialy=True):
if context:
fmsg = FunctionMsg(self._rebuiltMsg(context))
else:
fmsg = self.getFunctionMsg()
return fmsg.match(key,
prefixOnly=prefixOnly,
partialy=partialy
)
def isIterable(self):
""" True if Function is iterable, e.i. has "ABCDi" keys likes
Example:
Function("INSi.SENSi.VAL").isIterable() -> True
Function("INS1.SENS1.VAL").isIterable() -> False
"""
return self.getFunctionMsg().isIterable()
def setDefault(self, default):
if default is None and "default" in self.params:
del self.params['default']
return None
self.params['default'] = self.parseValue(default)
def getDefault(self, default=None , context=None):
if not "default" in self.params or self.params['default'] is None:
if default is not None:
return default
else:
raise ValueError("'%s' has no default value"%(self.getMsg()))
if context is not None:
return self._rebuildVal(self.params["default"], context)
return self.params["default"]
def setFormat(self, fmt):
""" set the string format for value (with the %) """
if not issubclass( type(fmt), str) and not hasattr( fmt, "__call__"):
raise ValueError("if format is not a string or tuple, should be a callable function or object ")
self.params["format"] = fmt
def getFormat(self, tp=0):
"""get the fromat parameter """
if tp>1 or tp<0:
raise ValueError("type must be 0 for setup format or 1 for rebuilt format")
fmt = self.params.get("format", "%s")
if issubclass( type(fmt), tuple):
return fmt[type]
return fmt
def getDtype(self):
""" get the value type """
return self.params.get("dtype", str)
def setDtype(self, dtype):
""" set the value type """
if dtype is bool:
dtype = vltbool
self.params["dtype"] = dtype
def setRange(self, range):
if range is None:
self.params["range"] = None
return
if isinstance(range, tuple):
if len(range) != 2:
raise ValueError("expecting a 2 tuple for parameter range got %s " % (range,))
try:
range = tuple( self.parseValue(r) for r in range )
except ValueError as e:
raise ValueError("While parsing range: "+str(e))
elif not (hasattr(range, "__iter__") and
hasattr(range, "__contains__")):
raise ValueError("Expecting a iterable object for parameter range got %s " % (range,))
else:
try:
range = set( self.parseValue(r) for r in range )
except ValueError as e:
raise ValueError("While parsing range: "+str(e))
if self.isIterable():
for f in self.functions():
if f.hasValue() and not f._test_range(f.getValue(), range):
raise ValueError("Cannot change the range of '%s' to %s because the curent value is out of range, change the value first" % (f.getMsg(), range))
else:
if self.hasValue() and not self._test_range(self.getValue(), range):
raise ValueError("Cannot change the range to %s because the curent value is out of range, change the value first" % (range,))
self.params["range"] = range
def getRange(self):
"""Return the function range """
return self.params.get("range", None)
def _cmdIterableWalker(self, dval, out , itr=[], context=None):
if not isinstance( dval, dict):
out += [(self.rebuildListMsg( tuple(itr)), self.formatValue(dval , context=context))]
return None
for k,v in dval.iteritems():
self._cmdIterableWalker(v, out, itr+[k], context)
@classmethod
def _getAllIndexes(cls, indexes):
return cls._getAllIndexesWalker( cls._value, list(indexes))
@classmethod
def _getAllIndexesWalker(cls, values, idx, shift=0):
if shift == len(idx)-1:
if idx[shift] is None:
out = []
for k in values:
idx[shift] = k
out += [tuple(idx)]
return out
return [tuple(idx)]
idx = [i for i in idx]
if idx[shift] is None:
out = []
for k in values:
idx[shift] = k
out += cls._getAllIndexesWalker( values[k], idx, shift+1)
return out
return cls._getAllIndexesWalker( values[idx[shift]], idx, shift+1)
def todict( self, keyconvert=str):
""" If Function is iterable return a dictionary of non-iterable Function
affect only value already set.
Args:
keyconverter (Optional[function]) : a optional function that convert the
original key to an other. The function must take one argument.
See Also:
functions : return functions in a flat list
"""
fcs = self.functions()
return {keyconverter(f.getMsg()):f for f in fcs}
def strKeyToIndex(self, key):
if not self.isIterable():
raise Exception("not iterable function")
m = self.match(key)
if m: return m.indexes
raise KeyError("Cannot find index matching key '%s'"%key)
def cmd(self, value=None, default=False, context=None):
""" return a list of command functions ready to parse in a process
If proc is a process and f a Function :
proc.setup( function=f.cmd() )
is equivalent to:
f.setup( proc=proc )
Args:
value (Optional): change temporaly the value on the fly for the command
default (Optional[bool]) : if no value set send the default. default is False
context (Optional) : function context to convert bracketed values
See Also Method:
setup : setup the instrument
update : update current value from instrument
"""
return cmd(map( lambda f: (f.getMsg(context=context),
f.formatStripedValue(
f.getValue(default=default) if value is None else value,
context=context
)
),
self.functions(onlyIfHasValue=value is None)
))
getCmd = cmd
def _rebuiltMsg(self, context=None):
"""
msg = opt._rebuiltMsg(msg, context)
if the message of the opt object is a string of the form "INS.OPT{optnumber}_"
look for "optnumber" inside the replacement dictionary
and replace {optnumber} by its value.
Also the replacement patern can contain a format separated by a ',' : e.g. "INS.OPT{optnumber,%04d}"
Return the value of opt if it is not a string
"""
strin = self.msg.reform()
if context is None:
return strin
return context_format(strin, context)
# strin = self.msg.reform()
# if replacement is None:
# return strin
# # save some time, if no open bracket return as it is
# if not "{" in strin:
# return strin
# ## make a large list of the same replacement to fool the normal format
# ## incrementation
# args = [replacement]*99
# ## Any key should do the trick.
# kwargs = replacement if isinstance(replacement, dict) else {}
# if isinstance(replacement, dict) and hasattr(replacement,"toalldict"):
# kwargs = replacement.toalldict(context=replacement, exclude=[self])
# try:
# strout = strin.format(*args,
# **kwargs
# )
# except (AttributeError, KeyError) as e:
# message = "Problem when reformating '%s' : %s"%(strin, e)
# e.args = (message,)
# raise e
# return strout
# old stuff. to be removed
# if fromAttr:
# check = lambda k,r: hasattr(r,k)
# get = lambda k,r: r.__getattribute__(k)
# else:
# check = lambda k,r: k in r
# get = lambda k,r: r[k]
# matches = re.compile(r'[{]([^}]+)[}]').findall(strin)
# for key in matches:
# m = re.compile("[{]"+key+"[}]")
# f = m.search( strin)
# if f is not None: # shoudl not be
# start = strin[0:f.start()]
# end = strin[f.end():None]
# sp = key.split(",")
# if len(sp)>1:
# if len(sp)>2:
# raise Exception("Error to reformat '%s' must contains only one pair of name,format")
# fmt = sp[1]
# key = sp[0]
# else:
# fmt = "%s"
# if not check(key , replacement):
# raise Exception("The replacement %s '%s' does not exists to rebuild '%s'"%("attribute" if fromAttr else "key", key,strin))
# val = get(key, replacement)
# valp = fmt%(val)
# strin = "%s%s%s"%(start, valp , end)
# return strin
def rebuildVal( self, context, default=False):
"""
val = f.rebuildVal(context, default=False)
if the value of the Function object is a string of the form
"TEST_{somekey}_" look for "somekey" inside context and replace
{somekey} by its value.
Return the value of the Function object if it is not a string
"""
return self._rebuildVal( self.get(default), context)
@staticmethod
def _rebuildVal(strin, context):
if (not isinstance(strin, basestring)) or (not context):
return strin
return context_format(strin, context)
# strout = ""
# for before, field, fmt, q in strin._formatter_parser():
# strout += before
# if field is None:
# continue
# field, others = field._formatter_field_name_split()
# for tp, name in others:
# if tp:
# field += ".%s" % name
# else:
# break
# obj = context[field]
# for tp, name in others:
# if tp:
# obj = getattr(obj, name)
# else:
# obj = obj[name]
# if isinstance(obj, Function):
# strout += obj.__format__(fmt, context=context)
# else:
# strout += obj.__format__(fmt)
# return strout
def getFormatedValue(self, value=None, default=False, context=None, index=None):
self = self._getOrCreate(index)
if self.isIterable():
return {k:f.getFormatedValue(value=value, default=default, context=context) for k,f in self._value.iteritems() if f.hasValue()}
return self.formatValue( self.getValue(value=value,default=default), context=context)
getFv = getFormatedValue
def getFormatedValueOrDefault(self, value=None, context=None, index=None):
return self.getFormatedValue(value=value, default=True, context=None, index=index)
getFvod = getFormatedValueOrDefault
def getFormatedDefault(self, *args, **kwargs):
context = kwargs.pop("context", None)
if len(kwargs):
raise KeyError("getFormatedDefault accept only one keyword argument : 'replacement'")
return self.formatValue(self.getDefault(*args), context=context)
getFd = getFormatedDefault
@staticmethod
def _test_range(value, range):
""" test if value is within range """
if range is None:
return True
if isinstance(range, tuple):
# a tuple is interpreted as a (min, max) value
mini, maxi = range
if mini is not None and value<mini:
return False
if maxi is not None and value>maxi:
return False
return True
# otherwhise considers that it is a list or set
return value in range
def _parse_one(self, value):
try:
value = self.getDtype()(value)
except ValueError:
raise ValueError("Cannot convert '%s' to the expecting type %s for function '%s'"%(value, self.getDtype(), self.getMsg()))
rg = self.getRange()
if not self._test_range(value, rg):
if isinstance(rg, tuple):
raise ValueError("%s is out of range %s for function '%s'"%(value, rg, self.getMsg() ))
else:
raise ValueError("%s is in the set %s for function '%s'" % (value, rg, self.getMsg()))
return value
def _parse_walker(self, d):
if isinstance( d , dict):
return { k:self._parse_walker( subd) for k,subd in d.iteritems() }
return self._parse_one(d)
def parseValue(self, value):
# if the value is a list or any iterable and self is iterable e.i., msg containe '#'
# like for instance DET.SUBWIN1.GEOMETRY, should parse individuals value in a list
if hasattr(value, "__iter__"):
if not self.isIterable():
raise ValueError("got a iterable object but the option is not iterable")
if isinstance(value, dict):
return self._parse_walker(value)
#return {k:self.getDtype()(v) for k,v in value.iteritems()}
return [self.getDtype()(v) for v in value]
if value is None:
return None #a none value erase the previous value
return self._parse_one(value)
def formatValue(self, value, context=None):
""" return the curent value as a formated string """
if context is not None:
value = self._rebuildVal( value, context)
value = self.parseValue(value)
return self._format(self.getFormat(0) , value)
def formatStripedValue(self, value, context=None):
return self.formatValue(value, context=context).strip()
def getProc(self, proc=None):
""" getPtoc(proc) return proc if not None else return the default
if proc is None and no default was set Raise a TypeError
See Also:
vlt.setDefaultProcess
"""
return getProc(proc)
proc = property(fget=getProc, doc="Function default process")
def setup(self, value=None, proc=None, function=[], **kwargs):
""" send setup command to the default or specified process coresponding
to the keyword/value pair of the Function.
Parameters:
-------
value [optional]: use a value different than the one stored in
the Function.
proc [optional]: use the process proc otherwhise use the default one
(see vlt.setDefaultProcess)
Returns:
-------
Example:
"""
proc = getProc(proc)
out = proc.setup(function=self.cmd(value)+function, **kwargs)
self.onSetup.run(self)
return out
def status(self,proc=None, **kwargs):
""" Return the status of this function
As the buffer can take several entry, the result
is returnde in a ditionary.
"""
if proc is None:
proc = getProc()
if proc is None:
raise Exception("not defaultProcess set in vlt module")
if self.statusFunc:
msg = self.statusFunc.getMsg() if isinstance(self.statusFunc, Function) else self.statusFunc
else:
msg = self.getMsg()
return proc.status(function=msg, **kwargs)
def update(self, proc=None):
""" Get the status from the process and update the Function value
The buffer of the status function should return the Key/value pair if any
of the keys does not match the Function key (/msg) raise RunTimeError
Return nothing but modify Value.
See Also Methods:
status : just get the status without updating
getOrUpdate : return the value if defined or update then return
"""
res = self.status(proc)
msg = self.getMsg()
if not msg in res:
raise RuntimeError("weird, cannot find key '%s' in buffer result"%msg)
self.setValue(res[msg])
def updateDict(self, funcdict, proc=None):
""" From the dictionary returned by .status
update a function dictionary
Args:
funcdict : The FunctionDict or dict to update
proc : the process, if None take the defaullt one
See Also Methods:
update, setup, getOrUpdate
"""
res = self.status(proc)
funcdict.update( res )
def getOrUpdate( self, proc=None):
""" if the Function has value return it else update from proc and than return
"""
if self.hasValue():
return self.get()
self.update(proc=proc)
return self.get()
def updateAndGet(self, proc=None):
self.update(proc=proc)
return self.get()
@staticmethod
def _format(fmt,value):
if issubclass( type(fmt), str):
# format can be a string or a function
return fmt%(value)
else:
return fmt(value)
value = property(fget=getValue, fset=setValue,
doc="function value")
strvalue = property(fget=getFormatedValue, fset=setValue,
doc="function string value"
)
format = property(fget=getFormat, fset=setFormat,
doc="Function format")
dtype = property(fget=getDtype, fset=setDtype,
doc="Function data type")
comment = property(fget=getComment, fset=setComment,
doc="Function comment field")
unit = property(fget=getUnit, fset=setUnit,
doc="Function Unit")
description = property(fget=getDescription, fset=setDescription,
doc="Function description"
)
context = property(fget=getContext, fset=setContext,
doc="Function context"
)
cls = property(fget=getCls, fset=setCls,
doc="Function Class list"
)
range = property(
fget=getRange, fset=setRange,
doc="Function range"
)
<file_sep>"""
Configuration file of the vlt package. to be changed with a lot of cautions
some configuration can be changed
"""
import os
from .log import Log
INTROOT = os.getenv("INTROOT") or ""
INS_ROOT = os.getenv("INS_ROOT") or ""
INSROOT = INS_ROOT
VLTROOT = os.getenv("VLTROOT") or ""
DPR_ID = os.getenv("DPR_ID") or ""
VLTDATA = os.getenv("VLTDATA") or ""
HOST = os.getenv("HOST") or ""
config = {
# list of directories/prefix/sufix/extention for the CDT files
"cdt":{
## List of path from where to find cdt files
"path": [os.path.join(INTROOT, "CDT"),
os.path.join(VLTROOT, "CDT")],
"prefix":"",
"extention":"cdt",
# list of directory where cdt temporaly py file will be
# created
"pydir":os.path.join(os.path.dirname(__file__), "processes"),
# boolean value for cdt debug
"debug":False
},
"dictionary": {
# list of directories containing the dictionary files
"path": [os.path.join(INS_ROOT, "SYSTEM/Dictionary"),
os.path.join(VLTROOT, "config")],
# dictionary file prefix, e.g openDictionary('ACS') will look for 'ESO-VLT-DIC.ACS'
"prefix" : "ESO-VLT-DIC.",
# dictionary files has to extention
"extention" : ""
},
"tsf":{
"path": [os.path.join(INS_ROOT, "SYSTEM/COMMON/TEMPLATES/TSF"),
os.path.join(INS_ROOT, "SYSTEM/COMMON/CONFIGFILES"),
os.path.join(VLTROOT, "config/INS_ROOT/SYSTEM/COMMON/TEMPLATES/TSF"),
os.path.join(VLTROOT, "templates/forCALOB"),
os.path.join(VLTROOT, "templates/forBOB"),
VLTROOT ## MMS.tsf is there. Not sure if it is usefull
],
"extention":"tsf",
"prefix":""
},
"isf":{
"path": [os.path.join(INS_ROOT, "SYSTEM/COMMON/CONFIGFILES"),
os.path.join(INTROOT, "config/INS_ROOT/SYSTEM/COMMON/CONFIGFILES")
],
"extention":"isf",
"prefix":"",
##
# The Instrument Summary File <default>.isf that is used for the instrument
# The <default>.isf will be searched from the path list
"default":"default"
},
"obd":{
## add :: for recursive directories
"path": [os.path.join(INS_ROOT, "SYSTEM/COMMON/TEMPLATES/OBD")],
"extention":"obd",
"prefix":""
},
# if key_match_case is true, the Function anf FunctionDict objects
# becomes case sensitive meaning that, e.g, dcs["DIT"] != dcs["dit"]
# default is false
"key_match_case": False,
#
# The system command for msgSend
"msgSend_cmd": "msgSend",
# a default timeout for msgSend commands, leave it None for
# no default
"timeout": None,
# in debug mode msgSend are not sent
"debug": False,
# verbose level
"verbose": 1
}
################################################################
#
# INIT the log
#
log = Log()
# debug local configuration
# config["cdtpath"] += ["/Users/guieu/python/vlt/CDT"]
# config["dictionarypath"] += ["/Users/guieu/python/vlt/Dictionary",
# "/Users/guieu/python/vlt/Dictionary/CCSLite"
# ]
#config["debug"] = not os.getenv("HOST") in ["wbeti" , "wpnr" , "wbeaos"]
<file_sep>
import vlt
import vlt.buffread as buffread
def msgdef(msg,commands):
def tmp(self,**kwargs):
return self.msgSend( msg, kwargs)
tmp.__doc__ = formhelp(msg,commands[msg])
return tmp
def formhelp(msg,command):
return msg+"("+" ,".join(k+"=%s"%o.dtype for k,o in command.options.iteritems())+")\n\n"+command.helpText
buffreader = buffread.buffreader
ao_commands = {
"setup" :vlt.Command("SETUP",
{"":vlt.Param("", vlt.dtypeFunctionList, "%s")},
helpText="""Set-up functions to the dm
options are supported:
<keyword1> <value1> [<keyword2> <value2> ...]
specify one or more parameters with the associated
value. keywordN: a short-FITS keyword
valueN: the value for the keyword
First setup must contain the instrument mode (INS.MODE).
An image taking exposure should setup the imagefilename
(OCS.DET.IMGNAME) befor the exposure can be started.
""", bufferReader=buffreader.getreader("SETUP")),
}
class aoControl(vlt.Process):
commands = ao_commands
for c in ao_commands: exec("%s = msgdef('%s',pnoControl_commands)"%(c,c))
<file_sep>from ..device import Device, cmd
class Shutter(Device):
"""
shutter is a Device object and provide the additional
following methods:
cmdOpen: return the open command list
cmdClose: return the close command list
open: open the shutter (e.i. 'ST T')
close: close the shutter (e.i. 'ST F')
"""
def _check(self):
self._check_keys(["ST"])
def cmd_open(self):
return self['ST'].cmd(True)
open_ = property(cmd_open)
def cmd_close(self):
return self['ST'].cmd(False)
close_ = property(cmd_close)
def open(self, timeout=None):
return self.qsetup({"ST": True}, timeout=timeout)
def close(self, timeout=None):
return self.qsetup({"ST": False}, timeout=timeout)
class Shutters(list):
def cmd_open(self):
return cmd([shut.cmd_open() for shut in self])
def cmd_close(self):
return cmd([shut.cmd_close() for shut in self])
def open(self, **kwargs):
return self[0].proc.setup(function=self.cmd_open()+kwargs.pop("function",[]), **kwargs)
def close(self, **kwargs):
return self[0].proc.setup(function=self.cmd_close()+kwargs.pop("function",[]), **kwargs)
def cmd(self, *args):
if len(args)!=len(self):
raise Exception("Expecting %d booleans"%(len(self)))
return cmd([self[i].cmd(args[i]) for i in range(len(self))])
def setup(self, *args):
return self[0].proc.msgSend("setup", dict(function=self.cmd(*args)))
<file_sep>
import vlt
import vlt.buffread as buffread
def msgdef(msg,commands):
def tmp(self,**kwargs):
return self.msgSend( msg, kwargs)
tmp.__doc__ = formhelp(msg,commands[msg])
return tmp
def formhelp(msg,command):
return msg+"("+" ,".join(k+"=%s"%o.dtype for k,o in command.options.iteritems())+")\n\n"+command.helpText
buffreader = buffread.buffreader
rtdc_commands = {
"ping" :vlt.Command("PING",{},helpText="""Ping process.
""", bufferReader=buffreader.getreader("PING")),
"script" :vlt.Command("SCRIPT",{"script":vlt.Param("-script", str, "%s")},helpText="""Execute a tcl procedure (script) defined in rtdc.
""", bufferReader=buffreader.getreader("SCRIPT"))}
class rtdc(vlt.Process):
"""
This is a rtdc class vlt.Process automaticaly generated from file
/Users/guieu/python/Catalog/vlt/CDT/rtdc.cdt
To get a list of commands:
proc.getCommandList()
To print a help on a specific command (e.g. setup)
proc.help("setup")
proc.help() will return a complete help
"""
commands = rtdc_commands
for c in rtdc_commands: exec("%s = msgdef('%s',rtdc_commands)"%(c,c))
proc = rtdc("rtdc")
<file_sep>
import vlt
import vlt.buffread as buffread
def msgdef(msg,commands):
def tmp_call(self, function=""):
return self.msgSend( msg, {"function":function})
tmp_call.__doc__ = formhelp(msg,commands[msg])
return tmp_call
def formhelp(msg,command):
return msg+"("+" ,".join(k+"=%s"%o.dtype for k,o in command.options.iteritems())+")\n\n"+command.helpText
buffreader = buffread.buffreader
ao_commands = {
"setup" :vlt.Command("SETUP",
{"function":vlt.Param("", vlt.dtypeFunctionList, "%s")},
helpText="""Set-up functions to the dm
options are supported:
<keyword1> <value1> [<keyword2> <value2> ...]
specify one or more parameters with the associated
value. keywordN: a short-FITS keyword
valueN: the value for the keyword
First setup must contain the instrument mode (INS.MODE).
An image taking exposure should setup the imagefilename
(OCS.DET.IMGNAME) befor the exposure can be started.
""", bufferReader=buffreader.getreader("SETUP")),
"status" :vlt.Command("STATUS",{"function":vlt.Param("", vlt.dtypeFunctionListMsg, "%s")},helpText="""Get the status of the functions in the list of arguments (default: get the
status of all functions). The following options are supported:
[<keyword1> <keyword2> ...]
The reply buffer has the format:
"<no of keys>,<key 1> <value 1>,<key 2> <value 2>,..."
""", bufferReader=buffreader.getreader("status2"))
}
#####################
## PATCH
##
#####################
class SendCommandSSh(vlt.SendCommand):
ssh_connect = "user@host"
def cmdMsgSend(self, command, options=None):
options = options or {}
return ("""ssh %s %s %s"""%(self.ssh_connect, self.msg_cmd, self.cmd(command,options))).replace('"', '\\"')
import os
if os.getenv("HOST") == "wbeti":
class aoControl(SendCommandSSh):
ssh_connect = "betimgr@wbeaos"
commands = ao_commands
else:
class aoControl(vlt.SendCommand):
commands = ao_commands
#for c in ao_commands: exec("%s = msgdef('%s',ao_commands)"%(c,c))
for c in ao_commands:
setattr( aoControl, c, msgdef(c,ao_commands))
<file_sep>
class Actions(object):
def __init__(self, *args, **kw):
parent = kw.pop("parent",None)
if len(kw):
raise KeyError("Actions take only 'parent' has keyword")
self.actions = {}
self.actionCounter = 0
self.stopped = False
self.parent = parent
for action in args:
self.addAction(action)
def stop(self):
self.stopped = True
def release(self):
self.stopped = False
def addAction(self, action):
if not hasattr(action, "__call__"):
raise ValueError("action must have a __call__attribute")
self.actionCounter += 1
self.actions[self.actionCounter] = action
return self.actionCounter
def remove(self, id):
if not id in self.actions:
raise KeyError("Cannot find an action connected with id %s"%id)
del self.actions[id]
def pop(self, id, default=None):
return self.actions.pop(id, default)
def clear(self):
return self.actions.clear()
def run(self, *args, **kwargs):
if self.stopped: return
if not self.actionCounter: return
if self.parent:
self.parent.run(*args, **kwargs)
keys = self.actions.keys()
keys.sort()
for k in keys:
self.actions[k](*args, **kwargs)
def copy(self):
return self.__class__( **self.actions )
def derive(self):
return self.__class__(parent=self)
def __len__(self):
if self.parent:
return len(self.parent) + len(self.actions)
return len(self.actions)
def __call__(self, action):
return self.addAction(action)
<file_sep>"""
Define the Buffreader class.
"""
class Buffreader(object):
"""
Buffreader class provide functions to read buffer.
All buffer reader function can take only one argument, the string buffer
and return any object that reflect what is in the buffer.
For instance the reader status (Which correspond to the process STATUS command) return
a dictionary of key/value pair dictionary reflecting the status.
"""
def getreader(self,cmd):
cmd = cmd.lower()
if cmd in self.__class__.__dict__:
return self.__getattribute__(cmd)
return self.general
def general(self,buf):
return buf
def warning(self, msg, rtr=None):
print "Warning ",msg
return rtr
def bufferLines(self, buf):
sbuf = buf.split("\n")
if sbuf[0].lstrip() != "MESSAGEBUFFER:":
self.warning("Cannot find MESSAGEBUFFER: in output")
return []
sbuf.pop(0)
return sbuf
def expoid(self, buf):
buf = self.bufferLines(buf)
if len(buf)<1:
self.warning("Cannot read expo Id in buffer output returned -1")
return -1
try:
return int(buf[0])
except:
self.warning("Cannot read expoId as a int in %s"%(buf[0]))
return -1
setup = expoid
wait = expoid
def status(self, buf):
buf = self.bufferLines(buf)
if not len(buf):
return {}
return self._status(buf[0])
def status2(self,buf):
return self._status(buf)
def _status(self, buf, splitter=","):
buf = buf.split(splitter)
try:
narg = int(buf[0])
except:
#self.warning("cannot read the number of key/val pairs")
narg = -1
if narg>-1: buf = buf[1:None]
if narg!=len(buf) and narg>-1:
self.warning("expecting %d key/val pairs got %d "%(narg,len(buf)))
output = {}
for line in buf:
sbuf = line.split(" ",1)
if len(sbuf)<2:
self.warning("key/pairs not found in %s on buffer %s"%(line,buf))
else:
sval = sbuf[1].lstrip()
try:
val = int(sval)
except:
try:
val = float(sval)
except:
val = sval.strip('"')
output[sbuf[0].lstrip()] = val
return output
def state(self, buf):
buf = self.bufferLines(buf)
if not len(buf):
self.warning("state values not understood")
return (None,None)
sbuf = buf[0].split("/")
if len(sbuf)<2:
return (buf, None)
return tuple(sbuf)
def error_structure(self, buf):
""" read the error strcuture returned by e.g, msgSend """
pass
def paramproperty(k):
def prop(self):
return self.parameters.get(k, None)
return property(prop)
class ErrorStructure(object):
##
# read the line entirely for the following keywords
_fulllines = ["Time Stamp", "Error Text", "Location"]
##
# keyword types, unknown will be str
_types = {
"Process Number":int,
"Error Number":int,
"StackId": int,
"Sequence": int
}
def __init__(self, buffer):
self.parameters = {}
lines = [l for l in buffer.split("\n") if l.strip()]
for line in lines:
self._read_line(line.strip())
self.origin = buffer
def _read_line(self, line):
if line[:2] == "--": # ignore ---------------- Error Structure -----------------
return
key, _, val = line.partition(":")
key = key.strip()
if not key:
return
val = val.strip()
if key in self._fulllines:
self.parameters[key] = val
return
val, _, rest = val.partition(" ")
val = val.strip()
rest = rest.strip()
tpe = self._types.get(key, str)
self.parameters[key] = tpe(val)
if rest:
return self._read_line(rest)
return None
TimeStamp = paramproperty("Time Stamp")
ProcessNumber = paramproperty("Process Number")
ProcessName = paramproperty("Process Name")
Environment = paramproperty("Environment")
StackId = paramproperty("StackId")
Sequence = paramproperty("Sequence")
ErrorNumber = paramproperty("Error Number")
Severity = paramproperty("Severity")
Module = paramproperty("Module")
Location = paramproperty("Location")
ErrorText = paramproperty("Error Text")
def __repr__(self):
return """
---------------- Error Structure ----------------
Time Stamp : {0.TimeStamp}
Process Number : {0.ProcessNumber} Process Name : {0.ProcessName}
Environment : {0.Environment} StackId : {0.StackId} Sequence : {0.Sequence}
Error Number : {0.ErrorNumber} Severity : {0.Severity}
Module : {0.Module} Location : {0.Location}
Error Text : {0.ErrorText}
""".format(self)
buffreader = Buffreader()
<file_sep>from __future__ import print_function
import time
import sys
ERROR = 1
WARNING = 2
NOTICE = 4 # info and notice are aliases
INFO = 4
DATA = 8
# Buffer size
BUFFER_SIZE = 100
# default verbose type
verbose_type = ERROR+WARNING+NOTICE+DATA
# default level of verbose
verbose_level = 3
##
# convert the message type code to a string
msgtype2string_lookup = {ERROR:"ERROR", WARNING:"WARNING", NOTICE:"NOTICE", DATA:"DATA"}
##
# Try to colorate the messages
try:
import colorama
import colorama as col
except:
def colorize(s, color):
return s
else:
def colorize(s, color):
try:
clr = getattr(colorama.Fore, color.upper())
except AttributeError:
raise ValueError("wrong color %r"%color)
return clr+s+colorama.Fore.RESET
colorized_msgtype2string_lookup = {
ERROR :colorize( "ERROR", "RED"),
WARNING:colorize( "WARNING", "MAGENTA"),
NOTICE :colorize( "NOTICE" , "BLUE"),
DATA :colorize( "DATA" , "BLACK")
}
def toggle_color(flag):
""" Turn On/Off the message colorization """
global stdout_msgtype2string_lookup, msgtype2string_lookup , colorized_msgtype2string_lookup
if flag:
stdout_msgtype2string_lookup = colorized_msgtype2string_lookup
else:
stdout_msgtype2string_lookup = msgtype2string_lookup
toggle_color(True)
def contexts2str(contexts):
if contexts:
return "[%s]"%(" ".join(contexts))
return ""
class LogFormat(object):
def __init__(self, fmt="""{context} {msgtype} {date}: {msg}\n""",
msgtype="",
datefmt="%Y-%m-%dT%H:%M:%S",
contexts2str=contexts2str):
self.msgtype = msgtype
self.contexts2str = contexts2str
self.datefmt = datefmt
self.fmt = fmt
def format(self, contexts, clock, msg, level=1, count=0):
context = self.contexts2str(contexts)
date = time.strftime(self.datefmt, clock)
return self.fmt.format(
context=context,
msgtype=self.msgtype,
level=level,
date=date,
msg =msg,
count=count
)
class LogOutput(object):
def __init__(self, wf, msgtypes=None, maxlevel=None, label="", formatlookup=None, colorized=None):
if colorized:
msgtype2string = lambda tpe: colorized_msgtype2string_lookup.get(tpe,"")
else:
msgtype2string = lambda tpe: msgtype2string_lookup.get(tpe,"")
self.file = None
if isinstance(wf, basestring):
wf = open(wf, "w")
if isinstance(wf, file):
if (wf is sys.stdout):
if colorized is None:
msgtype2string = lambda tpe: colorized_msgtype2string_lookup.get(tpe,"")
wf = wf.write
label = label or "stdout"
elif (wf is sys.stderr):
if colorized is None:
msgtype2string = lambda tpe: colorized_msgtype2string_lookup.get(tpe,"")
wf = wf.write
label = label or "stderr"
else:
self.file = wf
label = label or wf.name
wf = wf.write
elif not hasattr(wf, "__call__"):
raise ValueError("Output should be a string, a file or a callable object")
self.wf = wf
self.label = label
self.msgtypes = msgtypes
self.maxlevel = maxlevel
self.formatlookup = formatlookup or {}
self.msgtype2string = msgtype2string
def close(self):
""" if output is a file, close it and return True else return False """
file = self.file
if not file:
return False
if (file is sys.stdout) or (file is sys.stderr):
return False
self.file.close()
return True
def get_format(self, parent, msgtype):
try:
fmt = self.formatlookup[msgtype]
except KeyError:
fmt = parent.formatlookup.get(msgtype, parent.default_format)
return fmt
def log(self, parent, msg, clock, level=1, msgtype=NOTICE):
msgtypes = parent.msgtypes if self.msgtypes is None else self.msgtypes
## if msgtype is not in msgtypes, return
if not msgtypes & msgtype:
return 0
maxlevel = parent.maxlevel if self.maxlevel is None else self.maxlevel
## do not do anything if level is too hight
if level>maxlevel:
return 0
fmt = self.get_format(parent, msgtype)
formated_msg = fmt.format(
context=parent.logcontext(),
msgtype=self.msgtype2string(msgtype),
msglevel=level,
date=time.strftime(parent.date_format, clock),
msg =msg,
count=parent.count
)
self.wf(formated_msg)
return 1
class Log(object):
"""A Log set of function for Gravity """
default_format = """{context} {msgtype} {date}: {msg}\n"""
formatlookup = {DATA:"{msg}"}
date_format = "%Y-%m-%dT%H:%M:%S"
msgtypes = verbose_type
maxlevel = verbose_level
context = None
BUFFER_SIZE = BUFFER_SIZE
#########################################################
#
buffer = {}
def search_buffer(self, context=None, msgtype=None, level=None, msg=None):
buffer = self.buffer
CONTEXT, MSGTYPE, LEVEL, TIME, MSG = range(5)
found = []
for info in buffer:
if context:
if info[CONTEXT][0:len(context)] != context:
continue
if msgtype and info[MSGTYPE]!=msgtype:
continue
if level is not None and info[LEVEL]>level:
continue
if msg and not msg in info[MSG]:
continue
found.append(info)
return found
def clear_buffer(self):
buffer = self.buffer
while buffer:
buffer.pop()
def add_to_buffer(self, context, tpe, level, time, msg):
""" and a message of some contexts and message type to the buffer
several instances can share the same buffer
"""
buffer = self.buffer
buffer.append((context, tpe, level, time, msg))
while len(buffer)>BUFFER_SIZE:
buffer.pop(0)
def __init__(self, outputs=None, msgtypes=None, maxlevel=None, context=None, contexts=None, buffer=None):
""" create a log writing object.
A log object is defined by
-outputs (can be stdout a file, ...)
-msgtypes allowed message type for each outputs: ERROR, WARNING, NOTICE or DATA
or combination of all
-maxlevel a maximum level for each output all call with a higher level will be ignored
-contexts : list of string that set the log context
-default_format : a default format for all msgtype
-formatlookup : a dictionary of format for each types.
the format accept the following keys:
context, msgtype, msglevel, date, count, msg
the date format can be defined with the date_format attribute
Parameters
----------
outputs : list, optional
a list of : string -> path to a file, will be opened in "w" mode
file -> f.write is used to output the message
callable object -> with a signnature func(msg) where msg is a string
tuple -> if a tuple must be (f, msgtypes) or (f, msgtypes, maxlevel)
where f can be a file or a string.
This way one can set a different maxlevel and msgtype
for each output
maxlevel and msgtype can be omited or None to set to their
default value
e.g. :
log = Log(outputs=[(sys.stdout, NOTICE+DATA), (sys.stderr, ERROR)])
If no output is given the default is stdout.
msgtypes : int(binary) or string optional
default msgtypes for each outputs if not defined.
each msgtypes bits turn on/off the allowed msgtype.
One can use the sum combination of the defined constants ERROR, WARNING, NOTICE and DATA
The bytes are as follow:
#byte int msgtype
1 1 ERROR
2 2 WARNING
3 4 NOTICE
4 8 DATA
e.g. : msgtypes = ERROR+WARNING -> will print only the error and warning messages
Also msgtypes can be astring containing a combination of the caracters 'E','W','N' or 'D'
msgtypes = ERROR+WARNING+NOTICE equivalent to msgtypes = "EWN"
maxlevel : int, optional
The default maxlevel for each output if not defined.
If not given maxlevel=1
context : string, optional
the context is added to the list of `contexts`
contexts : iterable
list of string contest
"""
if maxlevel is not None:
self.maxlevel = maxlevel
if msgtypes is not None:
if isinstance(msgtypes, basestring):
msgtypes = sum( (s in msgtypes)*bit for s,bit in [('E',ERROR),('W',WARNING),('N',NOTICE),('D',DATA)] )
self.msgtypes = msgtypes
if contexts is None:
self.contexts = tuple()
else:
self.contexts = tuple(contexts)
if context:
self.contexts += (context,)
self.outputs = []
if outputs is None:
self.add_output(sys.stdout, None, None)
else:
for output in outputs:
if isinstance(output, LogOutput):
self.outputs.append(output)
else:
output = output if isinstance(output, tuple) else (output,)
self.add_output(*output)
# make a copy of the class default
self.formatlookup = dict(self.formatlookup)
self.count = 0
if buffer is not None:
self.buffer = buffer
else:
self.buffer = []
self.enable()
def add_contexts(self, *contexts):
""" pill up new contexts to the log """
self.contexts = self.contexts+contexts
def remove_contexts(self, *contexts):
""" remove the given contexts from the context list """
newcontexts = list(self.contexts)
for context in contexts:
try:
newcontexts.remove(context)
except ValueError:
pass
self.contexts = tuple(newcontexts)
def new(self, outputs=None, msgtypes=None, maxlevel=None, context=None, contexts=None, buffer=None):
new = self.__class__(
self.outputs if outputs is None else outputs,
self.msgtypes if msgtypes is None else msgtypes,
self.maxlevel if maxlevel is None else maxlevel,
context = context,
contexts = self.contexts if contexts is None else contexts,
buffer = self.buffer if buffer is None else buffer
)
return new
def logcontext(self):
if self.contexts:
return "[%s]"%(self.contexts)
return ""
def add_output(self, wf, msgtypes=None, maxlevel=None, label="", formatlookup=None, colorized=None):
""" Add a new output to the log
Parameters
----------
output :
string -> path to a file, will be opened in "w" mode
file -> f.write is used to output the message
callable object -> with a signnature func(msg) where msg is a string
msgtype : int, optional
the message type bit value for this output
One can use the sum combination of the defined constants ERROR, WARNING, NOTICE and DATA
The bytes are as follow:
#byte int msgtype
1 1 ERROR
2 2 WARNING
3 4 NOTICE
4 8 DATA
If not given the default of the log is taken
maxlevel : int
The maximum level of message for this output
If not given take the log default
Example
-------
log = Log(msgtype=WARNING+ERROR) # by default log as only one output : sys.stdout
log.add_output(sys.stderr, msgtype=ERROR)
"""
self.outputs.append(LogOutput(wf, msgtypes, maxlevel,
label=label,
formatlookup=formatlookup,
colorized=colorized
)
)
def close(self):
""" Attempt to close all the files open as output
The log will still work with other output (e.g. stdout)
"""
for output in self.outputs:
if output.close():
self.outputs.remove(output)
def disable(self):
""" put the log quiet
use log.enable() to put it back
"""
self._disabled = True
def enable(self):
""" send back the log to normal behavior """
self._disabled = False
def log(self, msg, level=1, msgtype=NOTICE):
if self._disabled:
return
clock = time.gmtime()
cte = 0
for output in self.outputs:
cte += output.log(self, msg, clock, level, msgtype)
if cte: # add to buffer only if it has been added to some outputs
self.add_to_buffer(self.contexts, msgtype, level, clock, msg)
self.count += 1
def set_format(self, msgtype, fmt):
if msgtype == 0:
self.default_format = fmt
self.formatlookup[msgtype] = fmt
def data(self, msg, level=1):
""" log message as DATA """
self.log(msg, level, DATA)
def set_data_format(self,fmt):
""" set the format for DATA messages """
self.set_format(DATA, fmt)
def info(self, msg, level=1):
""" log message as INFO=NOTICE """
self.log(msg, level, NOTICE)
def set_info_format(self, fmt):
""" set the format for INFO messages """
self.set_format(INFO, fmt)
def notice(self, msg, level=1):
""" log message as NOTICE=INFO """
self.log(msg, level, NOTICE)
def set_notice_format(self, fmt):
""" set the format for NOTICE messages """
self.set_format(NOTICE, fmt)
def warning(self, msg, level=1):
""" log message as WARNING """
self.log(msg, level, WARNING)
def set_warning_format(self, fmt):
""" set the format for WARNING messages """
self.set_format(WARNING, fmt)
def error(self, msg, level=1):
""" log message as ERROR """
self.log(msg, level, ERROR)
def set_error_format(self, fmt):
""" set the format for ERROR messages """
self.set_format(ERROR, fmt)
## open a new log
log = Log()
<file_sep>from .keywords import KeywordFile
from ..function import Function
from ..functiondict import FunctionDict
from ..config import config
from ..mainvlt import formatBoolFunction
from . import ospath
import os
import numpy as np
dictionaryconfig = config['dictionary']
def _new_parameter(f, key, value, more):
if f.in_header:
f.end_header()
f.open_parameter(value)
def _start_header(f, key, value, more):
f.start_header()
f.set([key], value)
def _add(p,n):
return p+"\n"+n
class Dictionary(KeywordFile):
curentParameter = None
curentField = None
inField = False
inHeader = True
cases = {
"Dictionary Name": _start_header,
"Parameter Name" : _new_parameter
}
def open_parameter(self, name):
self.curentParameter = name
def close_parameter(self):
self.curentParameter = None
def open_field(self, name):
self.curentField = name
def close_field(self):
self.curentField = None
def key2path(self, key):
if not self.curentParameter:
return [key]
if self.inField:
return self.curentParameter, key, _add
return self.curentParameter, key
def match_line(self, line):
if line[0:2] == " ":
if self.curentField:
self.inField = True
return self.curentField, line.strip(), ""
return None, None, ""
self.inField = False
# m = self.reg.match(line.strip())
# if not m:
# return None, None, ""
# groups = m.groups()
groups = line.split(":",1)
if len(groups)<2:
return None, None, ""
key, value = groups[0].strip(), groups[1].strip()
self.open_field(key)
return key, value, ""
param_types = {
"double" : np.float64,
"float" : float,
"logical" : bool,
"integer" : int,
"string" : str
}
def _dictionary_type(value):
value = value.lower()
if not value in param_types:
raise TypeError("the type '%s' for parameter '%s' is unknown"%(value, f.curentParameterName))
return param_types[value]
def _dictionary_format(dtype,format):
if dtype is bool:
return formatBoolFunction
return format
def parameter2function(key, param, cls=Function):
dtype = _dictionary_type(param.get("Type","string"))
format= _dictionary_format(dtype, param.get('Value Format', "%s"))
return cls(key,
dtype = dtype,
cls = param.get('Class', "").split("|"),
context = param.get('Context', ""),
description = param.get('Description', ""),
unit = param.get('Unit',None),
format = format,
comment = param.get('Comment Format',
param.get('Comment Field',"")
)
)
def parameters2functiondict(params, cls=FunctionDict):
return cls({key:parameter2function(key, param) for key,param in params.iteritems()})
def findDictionaryFile(dictsufix, path=None, prefix=None, extention=None):
""" look for the coresponding dictionary file in the path list
default path list is dictionarypath in vlt.config
keywords
--------
fileprefix = "ESO-VLT-DIC."
"""
return ospath.find(dictsufix, path=path, prefix=prefix,
extention=extention, defaults=dictionaryconfig)
def openDictionary(dictionary_name, path=None, prefix=None, extention=None):
file_name = findDictionaryFile(dictionary_name, path=path,prefix=prefix,
extention=extention )
f = Dictionary(file_name)
f.parse()
return parameters2functiondict(f.parameters)
| 618c789cccb01d8e2cca17aa7a3b4eafedc30227 | [
"Markdown",
"Python"
] | 37 | Markdown | SylvainGuieu/vlt | 2bb8a14044a8b098d6b8b6fa0a4690a938fffd0e | 5141d26d4c0da722a6e23194bfc9f9ce412f4f5c |
refs/heads/master | <file_sep>//
// StateManager.swift
// Study Flash
//
// Created by <NAME> on 13/8/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
let stateManager = StateManager.sharedInstance
private var _SingletonSharedInstance = StateManager()
enum AppState: String {
case firstLaunch
case showMainCourseList
case courseSelected //selected a course
case courseInProgress //Taking Quiz
case beginNewCourse
case courseCompleted
}
enum LogState: String {
case loggedIn
case loggedOut
}
class StateManager {
var state: AppState!
var logState: LogState = .loggedOut
public class var sharedInstance: StateManager {
return _SingletonSharedInstance
}
private let defaults = UserDefaults.standard
func updateState() {
self.state = self.checkState()
print(self.state!)
}
private func checkState() -> AppState {
if isFirstLaunch() {
return .firstLaunch
} else {
if isBeginNewCourse() {
return .beginNewCourse
} else if isCourseSelected() {
courseManager.selectedCourseIndex = 0
return .courseSelected
}
return .showMainCourseList
}
}
private func isFirstLaunch() -> Bool {
if let _ = defaults.string(forKey: "isFirstLaunch") {
return false
} else {
defaults.set(false, forKey: "isFirstLaunch")
return true
}
}
private func isOnboardingFinish() -> Bool {
return defaults.bool(forKey: "isOnboardingFinish") == true ? true : false
}
private func isCourseSelected() -> Bool {
return defaults.bool(forKey: "isCourseSelected") == true ? true : false
}
private func isBeginNewCourse() -> Bool {
return defaults.bool(forKey: "isBeginNewCourse") == true ? true : false
}
private func isLoggedIn() -> Bool {
return defaults.bool(forKey: "isLoggedIn") == true ? true : false
}
}
<file_sep>//
// UITextfield.swift
// Study Flash
//
// Created by <NAME> on 5/29/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class TextField: UITextField {
let padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
}
<file_sep>
// Question.swift
// Study Flash
//
// Created by <NAME> on 5/15/19.
// Copyright © 2019 <NAME>. All rights reserved.
//struct Questions: Decodable {
// var questions: [Question]
//}
//
//struct Question: Decodable {
// var id: Int
// var chapterID: Int
// var topicID: Int
// var question: String
// var imageURLString: String
// var questionvalue: Int
// var answers: [Answer]
//
//
// enum CodingKeys:String, CodingKey {
// case id
// case chapterID
// case topicID
// case question
// case imageURLString = "image"
// case questionvalue
// case answers
// }
//}
//
//struct Answer: Decodable {
// var id: Int
// var body: String
// var isCorrect: Bool
//
// enum CodingKeys:String,CodingKey {
// case id
// case body
// case isCorrect
// }
//}
<file_sep>//
// CoursesContetntViewController.swift
// Study Flash
//
// Created by <NAME> on 5/13/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CoursesDetailViewController: UIViewController {
private var myTableView: UITableView!
private var myBottomView: UIView!
private var screenSize: CGRect = UIScreen.main.bounds
var isTodayCourseFinished = UserDefaults.standard.bool(forKey: "isTodayCourseFinished")
override func viewDidLoad() {
super.viewDidLoad()
// temp use
guard courseManager.selectedCourseIndex != nil else {return}
setupBottomView()
setupTableView()
setupNavigationBar()
// update number of question left
courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.totalIncompletedQuestion = courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.questionLeft()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
isTodayCourseFinished = UserDefaults.standard.bool(forKey: "isTodayCourseFinished")
myTableView.reloadData()
setupBottomView()
}
}
extension CoursesDetailViewController: UITableViewDelegate, UITableViewDataSource {
private func setupTableView() {
myTableView = UITableView(frame: .zero)
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.register(UINib(nibName: "CoursesDetailHeaderCell", bundle: nil).self, forCellReuseIdentifier: "HeaderCell")
myTableView.dataSource = self
myTableView.delegate = self
myTableView.separatorStyle = .none
myTableView.allowsSelection = false
myTableView.bounces = false
self.view.addSubview(myTableView)
//set constraint
myTableView.translatesAutoresizingMaskIntoConstraints = false
myTableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true // need to change
myTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
myTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
myTableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -myBottomView.frame.size.height).isActive = true
}
//header section ----------
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 300
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! CoursesDetailHeaderCell
//update the course completion
// print(courseManager.allCourses[courseManager.selectedCourseIndex!])
// header.numberOfQuestion = courseManager.allCourses[courseManager.selectedCourseIndex!].numberOfQuestion
header.courseCompletionRateLabel.text = String(courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.calculateCompletionRate()) + "%" //put in xib
return header
}
//Content Section ----------
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courseManager.allCourses[courseManager.selectedCourseIndex ?? 0].courseChapter.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
cell.textLabel!.text = courseManager.allCourses[courseManager.selectedCourseIndex ?? 0].courseChapter[indexPath.row].title
return cell
}
}
extension CoursesDetailViewController {
private func setupBottomView() {
//hide tabbar
self.tabBarController?.tabBar.isHidden = true
myBottomView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 150))
myBottomView.backgroundColor = .white
self.view.addSubview(myBottomView)
let myComment = UILabel()
myComment.font = .systemFont(ofSize: 14)
myComment.attributedText = modifyCommentText()
myComment.textAlignment = .center
myComment.backgroundColor = .white
myComment.lineBreakMode = .byWordWrapping
myComment.numberOfLines = 3
myComment.sizeToFit()
let myButton = BottomNormalButton()
if courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.state == .todayNotCompleted {
myButton.backgroundColor = UIColor.primaryThemeColor
let titleName = (courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.calculateCompletionRate() == 0) ? "Start New Study Session" : "Continue Study Session"
myButton.setTitle(titleName, for: .normal)
} else {
myButton.backgroundColor = UIColor.lightGray
myButton.setTitle("Done for Today", for: .normal)
}
myButton.addTarget(self, action: #selector(handleContinueStudySession), for: .touchUpInside)
myBottomView.addSubview(myButton)
myBottomView.addSubview(myComment)
//set bottomView constraint
myBottomView.translatesAutoresizingMaskIntoConstraints = false
myBottomView.heightAnchor.constraint(equalToConstant: 150).isActive = true
myBottomView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
myBottomView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
myBottomView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
//button constraint on button to stackView
myButton.translatesAutoresizingMaskIntoConstraints = false
myButton.heightAnchor.constraint(equalToConstant: myButton.height).isActive = true
myButton.leadingAnchor.constraint(equalTo: myBottomView.leadingAnchor).isActive = true
myButton.trailingAnchor.constraint(equalTo: myBottomView.trailingAnchor).isActive = true
myButton.bottomAnchor.constraint(equalTo: myBottomView.bottomAnchor).isActive = true
//Comment Constraint
myComment.translatesAutoresizingMaskIntoConstraints = false
myComment.centerXAnchor.constraint(equalTo: myBottomView.centerXAnchor).isActive = true
myComment.bottomAnchor.constraint(equalTo: myButton.topAnchor, constant: -10).isActive = true
}
@objc private func handleContinueStudySession(sender: UIButton!) {
sender.flash()
if courseManager.allCourses[courseManager.selectedCourseIndex].courseProgress.state == .todayNotCompleted {
actionAfterCourseConfirmed()
performSegue(withIdentifier: "startQuiz", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "startQuiz" {
if let destinationViewController = segue.destination as? UINavigationController {
if let quizViewController = destinationViewController.viewControllers.first as? QuestionsTopViewController {
// Pass data to Quiz View Controller if needed
}
}
}
}
func actionAfterCourseConfirmed() {
//Confirm course selected after starting the course
//save to persistence memory
UserDefaults.standard.set(true, forKey: "isCourseSelected")
UserDefaults.standard.set(courseManager.selectedCourse?.courseId, forKey: "lastSelectedCourseId")
UserDefaults.standard.synchronize()
}
func modifyCommentText() -> NSMutableAttributedString {
// var questionLeft = courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.questionLeft()
//MARK:- temp use
var questionLeft = 10
questionLeft = questionLeft / 3
var boldQuestionNo = ""
var normalText: String!
var normalText2: String!
if questionLeft != 0 {
normalText = "Only "
boldQuestionNo = "\(questionLeft) questions left "
normalText2 = "for today's plan.\n Keep it going!"
} else {
normalText = ""
boldQuestionNo = "No question left "
normalText2 = ""
}
let normalString = NSMutableAttributedString(string:normalText)
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)]
let attributedString = NSMutableAttributedString(string:boldQuestionNo, attributes:attrs)
normalString.append(attributedString)
let normalString2 = NSMutableAttributedString(string: normalText2)
normalString.append(normalString2)
return normalString
}
}
extension CoursesDetailViewController {
func setupNavigationBar() {
let navigationItem = self.navigationItem
navigationItem.title = courseManager.selectedCourse?.courseTitle
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
let helpButton = UIButton(type: .custom)
helpButton.setImage(UIImage(named: "ChartButton.png"), for: .normal)
helpButton.addTarget(self, action: #selector(studyProfileButton_clicked), for: .touchUpInside)
helpButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
helpButton.tintColor = .primaryThemeColor
helpButton.contentMode = .scaleAspectFill
let rightHelpButton = UIBarButtonItem(customView: helpButton)
rightHelpButton.customView?.translatesAutoresizingMaskIntoConstraints = false
rightHelpButton.customView?.heightAnchor.constraint(equalToConstant: 30).isActive = true
rightHelpButton.customView?.widthAnchor.constraint(equalToConstant: 30).isActive = true
navigationItem.rightBarButtonItem = rightHelpButton
}
@objc func studyProfileButton_clicked (_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "showStudyProfile", sender: self)
}
}
<file_sep>//
// CourseManager.swift
// Study Flash
//
// Created by <NAME> on 6/1/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
let courseManager = CourseManager.sharedInstance
private var _SingletonSharedInstance = CourseManager()
class CourseManager {
public class var sharedInstance : CourseManager {
return _SingletonSharedInstance
}
var allCourses = [Course]()
var courseViewModels = [CourseViewModel]()
var courseListFromJSON = [CourseInfo]()
var selectedCourse: Course?
var selectedCourseIndex: Int!
//the place you fetch the courses
func addCourses() {
courseListFromJSON = self.fetchDataFromJSON(filename: "cisco")!
importDataFromJSON()
}
func importDataFromJSON() {
//initizte courseProgress
var courseProgress = CourseProgress()
for index in 0 ... courseListFromJSON.count - 1 {
var sumOfQuestions = 0
for chapterIndex in 0 ... courseListFromJSON[index].chapters.count - 1 {
if let questions = courseListFromJSON[index].chapters[chapterIndex].questions {
sumOfQuestions += questions.count
}
}
courseProgress.completion.totalQuestion = sumOfQuestions
allCourses.append(Course(courseId: courseListFromJSON[index].id,
courseTitle: courseListFromJSON[index].title,
courseSubtitle: courseListFromJSON[index].subtitle,
courseChapter: courseListFromJSON[index].chapters,
courseProgress: courseProgress))
}
}
func transformCourseToCourseViewModels() {
courseViewModels = allCourses.map({return CourseViewModel(course: $0)})
}
func resetAll() {
UserDefaults.standard.set(false, forKey: "isCourseSelected")
UserDefaults.standard.set(false, forKey: "isTodayCourseFinished")
UserDefaults.standard.synchronize()
//reset the data in courseManager
courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress = CourseProgress()
}
func calculateConfidenceLevel(correctNo: Int, totalQuestion: Int) -> Double {
return Double(correctNo * 100 / totalQuestion)
}
}
extension CourseManager {
//MARK: -load course from JSON
private func fetchDataFromJSON(filename fileName: String) -> [CourseInfo]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(CourseData.self, from: data)
return jsonData.courses
} catch {
print("Failed to fetch courses:\(error)")
}
}
return nil
}
}
<file_sep>//
// NavigationBarViewController.swift
// Study Flash
//
// Created by <NAME> on 5/13/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CustomQuestionNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBarAppearance()
}
func setupNavigationBarAppearance(){
let navigationBar = self.navigationBar
navigationBar.barTintColor = .white
navigationBar.tintColor = .lightGray
navigationBar.isTranslucent = false
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "Helvetica-Bold", size: 20)!, NSAttributedString.Key.foregroundColor: UIColor.gray]
}
}
<file_sep>//
// TopicViewController.swift
// Study Flash
//
// Created by <NAME> on 5/10/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class MainCourseListController: UIViewController {
private var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
configueTableView()
setupCourseManager()
stateManager.updateState()
navigateAccordingToState_FirstLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateCourseList()
stateManager.updateState()
navigateAccordingToState_ViewWillAppear()
//unhide tabBar
self.tabBarController?.tabBar.isHidden = false
}
func navigateAccordingToState_FirstLoad() {
if stateManager.state == .courseSelected {
courseManager.selectedCourseIndex = UserDefaults.standard.integer(forKey: "lastSelectedCourseId")
//safeguard
guard courseManager.selectedCourseIndex >= 0 else {return}
performSegue(withIdentifier: "backToCourseDetail", sender: self)
courseManager.allCourses[courseManager.selectedCourseIndex].courseProgress.state = .todayNotCompleted
}
}
func navigateAccordingToState_ViewWillAppear() {
if stateManager.state == .beginNewCourse {
UserDefaults.standard.set(false, forKey: "isBeginNewCourse")
UserDefaults.standard.synchronize()
performSegue(withIdentifier: "backToCourseDetail", sender: self)
}
}
}
extension MainCourseListController: UITableViewDelegate, UITableViewDataSource {
private func configueTableView() {
myTableView = UITableView()
myTableView.register(UINib(nibName: "CoursesTableViewCell", bundle: nil).self, forCellReuseIdentifier: "CoursesTableCell")
myTableView.register(UINib(nibName: "CoursesTableViewFooterCell", bundle: nil).self, forCellReuseIdentifier: "FooterCell")
myTableView.dataSource = self
myTableView.delegate = self
// Eliminate the line
myTableView.separatorStyle = UITableViewCell.SeparatorStyle.none
// Reverse TableView
myTableView.transform = CGAffineTransform(rotationAngle: -(CGFloat)(Double.pi))
self.view.addSubview(myTableView)
//set constraint
myTableView.translatesAutoresizingMaskIntoConstraints = false
myTableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
myTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
myTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
myTableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courseManager.allCourses.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 140
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CoursesTableCell", for: indexPath) as! CoursesTableViewCell
// MVVM
cell.courseViewModel = courseManager.courseViewModels[indexPath.row]
// Reverse TableViewCell
cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi));
return cell
}
// setupFooter
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = tableView.dequeueReusableCell(withIdentifier: "FooterCell") as! CoursesTableViewFooterCell
footer.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
return footer
}
// Course Selected
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCourse = courseManager.allCourses[indexPath.row]
// save selected course data into global
courseManager.selectedCourse = selectedCourse
courseManager.selectedCourseIndex = indexPath.row
// passing course detail to next viewController
if courseManager.selectedCourse?.courseProgress.state == .notStart {
performSegue(withIdentifier: "startNewCourse", sender: self)
} else {
performSegue(withIdentifier: "showCourseDetails", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard myTableView.indexPathForSelectedRow != nil else {return}
// Deselecting animation
myTableView.deselectRow(at: myTableView.indexPathForSelectedRow!, animated: true)
}
}
extension MainCourseListController: UINavigationBarDelegate {
// MARK:- Navigation Bar
func setupNavigationBar() {
guard let navigationBar = self.navigationController?.navigationBar else {return}
let navigationItem = UINavigationItem()
navigationItem.title = "Courses"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
navigationBar.setItems([navigationItem], animated: false)
}
func updateNavigationBar() {
let navigationItem = self.navigationItem
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}
extension MainCourseListController {
func setupCourseManager() {
if courseManager.allCourses.isEmpty {
courseManager.addCourses()
}
}
func updateCourseList() {
courseManager.transformCourseToCourseViewModels()
myTableView.reloadData()
}
}
<file_sep>//
// QuestionsTableViewController.swift
// Study Flash
//
// Created by <NAME> on 5/15/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class QuestionsTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
weak var quizManager: QuizManager?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.bounces = false
tableView.register(UINib(nibName: "QuestionHeaderTableViewCell", bundle: nil).self, forCellReuseIdentifier: "QuestionCell")
constraintsForQuestionsView()
}
func reloadData(withQuizManager manager: QuizManager) {
self.quizManager = manager
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// guard the last question
guard let currentQuestion = quizManager?.getCurrentQuestion() else {
return 0
}
// TODO: remove forceunrapping
return currentQuestion.answers.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 230
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "QuestionCell") as? QuestionHeaderTableViewCell
if let currentQuestion = quizManager?.getCurrentQuestion() {
headerCell?.questionLabel.text = currentQuestion.question
}
return headerCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
// TODO: remove forceunrapping
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuestionTableViewCell
if let currentQuestion = quizManager?.getCurrentQuestion() {
let answerIndex = indexPath.row
if answerIndex >= 0 {
cell.questionLabel.text = currentQuestion.answers[answerIndex].body
cell.updateView()
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// We need the quiz manager for this to work properly
guard let quizManager = quizManager else {
tableView.deselectRow(at: indexPath, animated: false)
return
}
// Check if the answer was already selected
if quizManager.isAnswerAtIndexSelected(answerIndex: indexPath.row) {
// case: it was already selected
// Remove the answer index and deselect the row
quizManager.setAnswerSelection(forAnswerIndex: indexPath.row, select: false)
tableView.deselectRow(at: indexPath, animated: false)
if let cell = self.tableView.cellForRow(at: indexPath) as? QuestionTableViewCell {
cell.answerState = .NotSelected
}
} else {
// Select the answer
quizManager.setAnswerSelection(forAnswerIndex: indexPath.row, select: true)
if let cell = self.tableView.cellForRow(at: indexPath) as? QuestionTableViewCell {
cell.answerState = .Selected
}
}
}
func constraintsForQuestionsView() {
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
}
}
// MARK: - Quiz
extension QuestionsTableViewController {
func showAnswerResult() {
guard let currentQuestion = quizManager?.getCurrentQuestion(), let quizManager = quizManager else {
return
}
// TODO: remove forceunrapping
// Iterate through all answers and change the state
var allAnswersCorrect = true
for i in 0..<currentQuestion.answers.count {
if let cell = tableView.cellForRow(at: IndexPath(row: i, section: 0)) as? QuestionTableViewCell {
let answerState = quizManager.getAnswerState(forAnswerAtIndex: i)
// Only if all states returned are either correctly answered OR notselected:
// User has 100% answered the given question correctly
if answerState == .CorrectlyAnswered || answerState == .NotSelected {
// All fine!
} else {
// Incorrect answer
allAnswersCorrect = false
}
cell.answerState = answerState
}
}
if allAnswersCorrect {
quizManager.increaseScore(byAmount: 1)
}
}
}
<file_sep>//
// courseViewModel.swift
// Study Flash
//
// Created by <NAME> on 15/8/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
struct CourseViewModel {
let courseTitle: String
let courseSubtitle: String?
let courseState: String
let courseStateTextColor: UIColor
let courseCompletion: Double
// Dependency Injection
init(course: Course) {
self.courseTitle = course.courseTitle
self.courseSubtitle = course.courseSubtitle
self.courseCompletion = course.courseProgress.completion.calculateCompletionRate()
if course.courseProgress.state == .notStart {
self.courseState = "New Course!"
self.courseStateTextColor = .primaryThemeColor
} else {
self.courseState = String(courseCompletion) + "% Completed"
self.courseStateTextColor = .darkGray
}
}
}
<file_sep>//
// Topics.swift
// Study Flash
//
// Created by <NAME> on 5/11/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
var courseList = [Course]()
enum CourseState {
case notStart
case todayNotCompleted
case todayCompleted
case allCompleted
}
struct Course {
var courseId: Int
var courseTitle: String
var courseSubtitle: String?
var courseChapter: [Chapter]
var courseProgress: CourseProgress
}
struct CourseProgress {
var state: CourseState
var dateOfExam: Date!
var confidenceLevel: Double
var completion = CourseCompletion()
init() {
state = .notStart
confidenceLevel = 0.0
}
}
struct CourseCompletion {
var totalQuestion: Int
var totalCompletedQuestion: Int
var totalIncompletedQuestion: Int
var completionRate: Double?
// var todayCompletedQuestion: Int
init() {
self.totalQuestion = 1
self.totalCompletedQuestion = 0
self.totalIncompletedQuestion = totalQuestion - totalCompletedQuestion
self.completionRate = 0.0
}
func questionLeft() -> Int {
return totalQuestion - totalCompletedQuestion
}
func calculateCompletionRate() -> Double {
guard totalQuestion >= 1 else {return 0.0}
return Double(totalCompletedQuestion * 100 / totalQuestion)
}
}
<file_sep>//
// SignUpViewController.swift
// Study Flash
//
// Created by <NAME> on 31/10/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController {
let persistenceManager: PersistenceManager
// MARK: -Dependency Injection - Init
init?(coder: NSCoder, persistenceManager: PersistenceManager) {
self.persistenceManager = persistenceManager
super.init(coder: coder)
}
required init?(coder: NSCoder) {
fatalError("you must with a Persistance Maanager")
}
// MARK: - Outlets
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
// MARK: - Outlet Action
@IBAction func endEditingUsername(_ sender: Any) {
username = usernameTextField.text
}
@IBAction func endEditingEmail(_ sender: Any) {
guard let email = emailTextField.text else {return}
do {
try self.email = Email(email)
print("Valid Email")
} catch EvaluateError.isEmpty {
print("it is empty")
} catch EvaluateError.isNotValidEmailLength {
print("Not valid length")
} catch EvaluateError.isNotValidEmailAddress {
print("Not valid Email Address")
} catch {
print("someerror")
}
}
@IBAction func endEditPassword(_ sender: Any) {
password = passwordTextField.text
}
//MARK: - variable
var username: String?
var email: Email?
var password: String?
var users = [User]()
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
// createUser()
getUser()
}
//MARK: - CoreData
func printUsers() {
users.forEach({print($0.username)})
}
func createUser() {
let user = User(context: persistenceManager.context)
user.username = "david"
user.email = "<EMAIL>"
user.password = "123"
persistenceManager.save()
}
func getUser() {
let users = persistenceManager.fetch(User.self)
self.users = users
printUsers()
let deadline = DispatchTime.now() + .seconds(5)
DispatchQueue.main.asyncAfter(deadline: deadline, execute: deleteUser)
}
func updateUser() {
let firstUser = users.first!
firstUser.username += " - Updated"
persistenceManager.save()
printUsers()
}
func deleteUser() {
if let firstUser = users.first {
persistenceManager.delete(firstUser)
}
printUsers()
}
//MARK: - Functions
func setUpUI() {
passwordTextField.isSecureTextEntry = true
confirmPasswordTextField.isSecureTextEntry = true
}
func validateAllInput() -> Bool {
if isUsernameValidated() && isPasswordValidated() && isEmailValidated() {
return true
} else {
return false
}
}
func isUsernameValidated() -> Bool {
//check whether the username is existed in database
return true
}
func isPasswordValidated() -> Bool {
if passwordTextField.text == confirmPasswordTextField.text {
return true
} else {
print("Alert: Passwords are not the same")
return false
}
}
func isEmailValidated() -> Bool {
if email != nil {
return true
} else {
return false
}
}
func createAccount() {
guard
let username = username,
let email = email,
let password = <PASSWORD> else {return}
// let user = User(name: username, email: email, password: <PASSWORD>)
// print(user)
sendDataToDatabase()
}
func sendDataToDatabase() {
//send user data to database
}
@IBAction func tappedOnSubmitButton(_ sender: Any) {
// Force End Editing to check
emailTextField.endEditing(true)
print(username, email, password)
guard validateAllInput() == true else { return }
createAccount()
print("Account Created!")
dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// CoursesDetailHeaderCell.swift
// Study Flash
//
// Created by <NAME> on 5/14/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CoursesDetailHeaderCell: UITableViewCell {
@IBOutlet weak var courseCompletionRateLabel: UILabel!
@IBOutlet weak var courseCompletionLabel: UILabel!
@IBOutlet weak var titleDescription: UILabel!
@IBOutlet weak var detailDescription: UILabel!
let numberOfQuestion = courseManager.allCourses[courseManager.selectedCourseIndex].courseProgress.completion.totalQuestion
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = .white
courseCompletionRateLabel.textColor = .primaryThemeColor
setupDetailDescription(numberOfQuestion: numberOfQuestion)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setupDetailDescription(numberOfQuestion: Int) {
let normalText = "Your study plan of today includes "
let normalString = NSMutableAttributedString(string:normalText)
let boldQuestionNo = "\(numberOfQuestion) questions " // need to be changed
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)]
let attributedString = NSMutableAttributedString(string:boldQuestionNo, attributes:attrs)
normalString.append(attributedString)
let normalText2 = "about the following topics:"
let normalString2 = NSMutableAttributedString(string: normalText2)
normalString.append(normalString2)
detailDescription.attributedText = normalString
}
}
<file_sep>//
// CourseDetailWithScheduleViewController.swift
// Study Flash
//
// Created by 李宇恒 on 13/6/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import Foundation
class CourseDetailWithScheduleViewController: UIViewController {
private var screenSize: CGRect = UIScreen.main.bounds
var isTodayCourseFinished = UserDefaults.standard.bool(forKey: "isTodayCourseFinished")
var dayCount = 1
var streakCount = 0
// var questionsCount = 30
// var numberOfQuestion = courseManager.allCourses[courseManager.selectedCourseIndex!].numberOfQuestion
// var myArray: NSArray = ["Hardware Basics","Router Essentials","Router Configuration"]
var weekArray = [String]()
let calendar = Calendar.current
var today = Date()
let examDate = courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.dateOfExam
let examDateComponents = DateComponents(year: 2019, month: 6, day: 30)
let startDateComponents = DateComponents(year: 2019, month: 6, day: 15)
var todayDaysCountFromStartDay = 0
var pastStatus = [0: true, 1: false, 2: true, 3: true, 4: false, 5: true, 6: true, 7: true, 8: false, 9: true, 10: false, 11: true, 12: false, 13: true, 14: true, 15: true, 16: true, 17: true, 18: true, 19: true, 20: true]
weak var studyDayLabel: UILabel!
weak var collectionView: UICollectionView!
weak var streakLabel: UILabel!
weak var todayLabel: UILabel!
weak var descriptionLabel: UILabel!
weak var tableView: UITableView!
weak var promoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let myWeekdayModel = WeekdayModel()
let weekdayArray = myWeekdayModel.getWeekdayArray(startDateComponents, examDateComponents: examDateComponents)
weekArray += weekdayArray
let daysCountFromStartDay = myWeekdayModel.getTodayDaysCountFromStartDay(startDateComponents)
todayDaysCountFromStartDay = daysCountFromStartDay
let studyDayLabel = UILabel(frame: .zero)
studyDayLabel.text = "Study Day \(dayCount)"
studyDayLabel.font = .boldSystemFont(ofSize: 44)
studyDayLabel.textColor = .black
studyDayLabel.textAlignment = .left
studyDayLabel.translatesAutoresizingMaskIntoConstraints = false
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
// self.view.addSubview(collectionView)
self.collectionView = collectionView
let streakLabel = UILabel(frame: .zero)
// streakLabel.text = "Great job, you are on a \(streakCount) day streak! 😎"
streakLabel.font = .systemFont(ofSize: 18)
streakLabel.textColor = .black
streakLabel.textAlignment = .center
let normalText = "Great job, you are on a "
let boldText = "\(streakCount) day"
let normalText2 = " streak! 😎"
let attributedString = NSMutableAttributedString(string: normalText)
let attributedString2 = NSMutableAttributedString(string: normalText2)
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)]
let boldString = NSMutableAttributedString(string: boldText, attributes:attrs)
attributedString.append(boldString)
attributedString.append(attributedString2)
streakLabel.attributedText = attributedString
streakLabel.translatesAutoresizingMaskIntoConstraints = false
let todayLabel = UILabel(frame: .zero)
todayLabel.text = "Today"
todayLabel.font = .systemFont(ofSize: 23)
todayLabel.textColor = .black
todayLabel.textAlignment = .left
todayLabel.translatesAutoresizingMaskIntoConstraints = false
let descriptionLabel = UILabel(frame: .zero)
descriptionLabel.text = "Your study plan for today includes a total of \(courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.totalQuestion) questions from the following chapters:"
descriptionLabel.font = .systemFont(ofSize: 17)
descriptionLabel.textColor = .black
descriptionLabel.textAlignment = .left
descriptionLabel.numberOfLines = 0
descriptionLabel.lineBreakMode = .byWordWrapping
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
let tableView = UITableView(frame: .zero)
tableView.translatesAutoresizingMaskIntoConstraints = false
self.tableView = tableView
let promoLabel = UILabel(frame: .zero)
promoLabel.text = "Start studying now to continue your streak!"
promoLabel.font = .boldSystemFont(ofSize: 17)
promoLabel.textColor = .black
promoLabel.textAlignment = .left
promoLabel.numberOfLines = 0
promoLabel.lineBreakMode = .byWordWrapping
promoLabel.translatesAutoresizingMaskIntoConstraints = false
// let myButton = UIButton()
// myButton.tintColor = .white
// var titleName = ""
//
// if isTodayCourseFinished {
// myButton.backgroundColor = UIColor.lightGray
// titleName = "Done for today!"
// } else {
// myButton.backgroundColor = UIColor.purpleThemeColor
// titleName = (courseManager.allCourses[courseManager.selectedCourseIndex!].CourseCompletionInPercentage() == 0) ? "Start New Study Session" : "Continue Study Session"
// }
//
// myButton.frame = .zero
// myButton.setTitle(titleName, for: .normal)
// myButton.titleLabel?.lineBreakMode = .byWordWrapping
// myButton.titleLabel?.textAlignment = .center
// myButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
// myButton.titleEdgeInsets = UIEdgeInsets(top: -10,left: -10,bottom: 20,right: -10)
// myButton.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
// myButton.addTarget(self, action: #selector(handleContinueStudySession), for: .touchUpInside)
// myButton.translatesAutoresizingMaskIntoConstraints = false
// self.view.addSubview(myButton)
let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
stackView.axis = NSLayoutConstraint.Axis.vertical
// stackView.alignment = .top
// stackView.spacing = 10
stackView.isLayoutMarginsRelativeArrangement = true
stackView.addArrangedSubview(studyDayLabel)
stackView.addArrangedSubview(collectionView)
stackView.addArrangedSubview(streakLabel)
stackView.addArrangedSubview(todayLabel)
stackView.addArrangedSubview(descriptionLabel)
stackView.addArrangedSubview(tableView)
stackView.addArrangedSubview(promoLabel)
// stackView.setCustomSpacing(100, after: stackView.subviews[2])
// stackView.setCustomSpacing(20, after: stackView.subviews[4])
// stackView.setCustomSpacing(40, after: stackView.subviews[5])
// stackView.setCustomSpacing(10, after: stackView.subviews[0])
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)
NSLayoutConstraint.activate([
studyDayLabel.topAnchor.constraint(equalTo: stackView.topAnchor, constant: 40),
studyDayLabel.bottomAnchor.constraint(equalTo: collectionView.topAnchor, constant: -15),
studyDayLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
collectionView.heightAnchor.constraint(equalToConstant: 70),
collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: streakLabel.topAnchor, constant: -20),
// streakLabel.topAnchor.constraint(equalTo: collectionView.bottomAnchor, constant: 30),
streakLabel.bottomAnchor.constraint(lessThanOrEqualTo: todayLabel.topAnchor, constant: -30),
todayLabel.topAnchor.constraint(greaterThanOrEqualTo: streakLabel.bottomAnchor, constant: 50),
todayLabel.bottomAnchor.constraint(equalTo: descriptionLabel.topAnchor, constant: -10),
descriptionLabel.bottomAnchor.constraint(equalTo: tableView.topAnchor, constant: -30),
tableView.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 20),
tableView.heightAnchor.constraint(equalToConstant: 170),
tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
tableView.bottomAnchor.constraint(equalTo: promoLabel.topAnchor, constant: -30),
promoLabel.topAnchor.constraint(equalTo: tableView.bottomAnchor, constant: 40),
promoLabel.bottomAnchor.constraint(lessThanOrEqualToSystemSpacingBelow: stackView.bottomAnchor, multiplier: -30),
// myButton.heightAnchor.constraint(equalToConstant: 90),
// myButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
// myButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
// myButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
// stackView.heightAnchor.constraint(equalToConstant: 600),
stackView.topAnchor.constraint(equalTo: self.view.topAnchor),
// stackView.bottomAnchor.constraint(lessThanOrEqualTo: myButton.topAnchor, constant: -15),
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
// stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15),
stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15)
])
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
self.collectionView.collectionViewLayout = layout
self.collectionView.backgroundColor = .white
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.register(MyCell.self, forCellWithReuseIdentifier: "MyCell")
// self.collectionView.isPagingEnabled = true
// self.collectionView.isScrollEnabled = true
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyTableCell")
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.allowsSelection = false
self.tableView.separatorStyle = .none
// let myWeekdayModel = WeekdayModel()
// let weekdayArray = myWeekdayModel.getWeekdayArray(DateComponents(year: 2019, month: 6, day: 1), examDateComponents: DateComponents(year: 2019, month: 6, day: 30))
// setupBottomView()
setupNavigationBar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
isTodayCourseFinished = UserDefaults.standard.bool(forKey: "isTodayCourseFinished")
tableView.reloadData()
setupBottomView()
}
}
extension CourseDetailWithScheduleViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return weekArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCell
cell.textLabel.text = weekArray[indexPath.row]
if indexPath.row == todayDaysCountFromStartDay {
cell.textLabel.font = .boldSystemFont(ofSize: 20)
cell.textLabel.textColor = .black
cell.statusImage.image = UIImage(named: "Today")
} else if indexPath.row < todayDaysCountFromStartDay && pastStatus[indexPath.row] == true {
cell.textLabel.font = .systemFont(ofSize: 20)
cell.textLabel.textColor = .gray
cell.statusImage.image = UIImage(named: "Done")
} else if indexPath.row < todayDaysCountFromStartDay && pastStatus[indexPath.row] == false {
cell.textLabel.font = .systemFont(ofSize: 20)
cell.textLabel.textColor = .gray
cell.statusImage.image = UIImage(named: "Missed")
} else {
cell.textLabel.font = .systemFont(ofSize: 20)
cell.textLabel.textColor = .gray
cell.statusImage.image = UIImage(named: "Future")
}
return cell
}
}
extension CourseDetailWithScheduleViewController: UICollectionViewDelegate {
private func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
let cell : UICollectionViewCell = collectionView.cellForItem(at: indexPath as IndexPath)!
cell.backgroundColor = .green
}
}
extension CourseDetailWithScheduleViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 30, height: 60)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
}
}
extension CourseDetailWithScheduleViewController: UITableViewDelegate, UITableViewDataSource {
// func numberOfSections(in tableView: UITableView) -> Int {
// return 1
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courseManager.allCourses[courseManager.selectedCourseIndex ?? 0].courseChapter.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableCell", for: indexPath as IndexPath)
cell.textLabel!.text = courseManager.allCourses[courseManager.selectedCourseIndex ?? 0].courseChapter[indexPath.row].title
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
return cell
}
}
extension CourseDetailWithScheduleViewController {
private func setupBottomView() {
let myButton = UIButton()
myButton.tintColor = .white
var titleName = ""
if isTodayCourseFinished {
myButton.backgroundColor = UIColor.lightGray
titleName = "Done for today!"
} else {
myButton.backgroundColor = UIColor.primaryThemeColor
// titleName = (courseManager.allCourses[courseManager.selectedCourseIndex!].CourseCompletionInPercentage() == 0) ? "Start New Study Session" : "Continue Study Session"
}
myButton.frame = .zero
myButton.setTitle(titleName, for: .normal)
myButton.titleLabel?.lineBreakMode = .byWordWrapping
myButton.titleLabel?.textAlignment = .center
myButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
myButton.titleEdgeInsets = UIEdgeInsets(top: -10,left: -10,bottom: 20,right: -10)
myButton.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
myButton.addTarget(self, action: #selector(handleContinueStudySession), for: .touchUpInside)
myButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(myButton)
NSLayoutConstraint.activate([
// studyDayLabel.topAnchor.constraint(equalTo: stackView.topAnchor, constant: 40),
// studyDayLabel.bottomAnchor.constraint(equalTo: collectionView.topAnchor, constant: -15),
// studyDayLabel.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
// collectionView.heightAnchor.constraint(equalToConstant: 70),
// collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
// collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
// collectionView.bottomAnchor.constraint(equalTo: streakLabel.topAnchor, constant: -20),
// // streakLabel.topAnchor.constraint(equalTo: collectionView.bottomAnchor, constant: 30),
// streakLabel.bottomAnchor.constraint(lessThanOrEqualTo: todayLabel.topAnchor, constant: -30),
// todayLabel.topAnchor.constraint(greaterThanOrEqualTo: streakLabel.bottomAnchor, constant: 50),
// todayLabel.bottomAnchor.constraint(equalTo: descriptionLabel.topAnchor, constant: -10),
// descriptionLabel.bottomAnchor.constraint(equalTo: tableView.topAnchor, constant: -30),
// tableView.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 20),
// tableView.heightAnchor.constraint(equalToConstant: 170),
// tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
// tableView.bottomAnchor.constraint(equalTo: promoLabel.topAnchor, constant: -30),
// promoLabel.topAnchor.constraint(equalTo: tableView.bottomAnchor, constant: 40),
// promoLabel.bottomAnchor.constraint(lessThanOrEqualToSystemSpacingBelow: stackView.bottomAnchor, multiplier: -30),
myButton.heightAnchor.constraint(equalToConstant: 90),
myButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
myButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
myButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
// stackView.heightAnchor.constraint(equalToConstant: 600),
// stackView.topAnchor.constraint(equalTo: self.view.topAnchor),
// stackView.bottomAnchor.constraint(lessThanOrEqualTo: myButton.topAnchor, constant: -15)
// stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
// // stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
// stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15),
// stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15)
])
}
@objc private func handleContinueStudySession(sender: UIButton!) {
sender.flash()
if !isTodayCourseFinished {
confirmSelectedCourse()
performSegue(withIdentifier: "startQuiz", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "startQuiz" {
if let destinationViewController = segue.destination as? UINavigationController {
if let quizViewController = destinationViewController.viewControllers.first as? QuestionsTopViewController {
// Pass data to Quiz View Controller if needed
}
}
}
}
func confirmSelectedCourse() {
//Confirm course selected after starting the course
//save to persistence memory
UserDefaults.standard.set(true, forKey: "isCourseSelected")
UserDefaults.standard.set(courseManager.selectedCourse?.courseId, forKey: "lastSelectedCourseId")
UserDefaults.standard.synchronize()
}
}
extension CourseDetailWithScheduleViewController {
func setupNavigationBar() {
let navigationItem = self.navigationItem
navigationItem.title = courseManager.selectedCourse?.courseTitle
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
let helpButton = UIButton(type: .custom)
helpButton.setImage(UIImage(named: "ChartButton.png"), for: .normal)
helpButton.addTarget(self, action: #selector(studyProfileButton_clicked), for: .touchUpInside)
helpButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
helpButton.tintColor = .primaryThemeColor
helpButton.contentMode = .scaleAspectFill
let rightHelpButton = UIBarButtonItem(customView: helpButton)
rightHelpButton.customView?.translatesAutoresizingMaskIntoConstraints = false
rightHelpButton.customView?.heightAnchor.constraint(equalToConstant: 30).isActive = true
rightHelpButton.customView?.widthAnchor.constraint(equalToConstant: 30).isActive = true
navigationItem.rightBarButtonItem = rightHelpButton
}
@objc func studyProfileButton_clicked (_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "showStudyProfile", sender: self)
}
}
<file_sep>//
// AccountViewController.swift
// Study Flash
//
// Created by <NAME> on 29/9/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class AccountViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
self.navigationItem.setHidesBackButton(true, animated:true)
}
@IBAction func tappedOn_LogoutButton(_ sender: Any) {
stateManager.logState = .loggedOut
navigationController?.popViewController(animated: false)
}
}
<file_sep>//
// CustomBottomButton.swift
// Study Flash
//
// Created by <NAME> on 5/30/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class BottomNormalButton: UIButton {
required init() {
super.init(frame: .zero)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
self.backgroundColor = UIColor.primaryThemeColor
self.tintColor = .white
self.titleLabel?.lineBreakMode = .byWordWrapping
self.titleLabel?.textAlignment = .center
self.titleLabel?.font = .boldSystemFont(ofSize: 16)
self.titleEdgeInsets = UIEdgeInsets(top: -10,left: -10,bottom: self.titleEdgeInsetBottom,right: -10)
self.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
}
}
class BottomDisableButton: UIButton {
required init() {
super.init(frame: .zero)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
self.backgroundColor = UIColor.lightGray
self.tintColor = .white
self.titleLabel?.lineBreakMode = .byWordWrapping
self.titleLabel?.textAlignment = .center
self.titleLabel?.font = .boldSystemFont(ofSize: 16)
self.titleEdgeInsets = UIEdgeInsets(top: -10,left: -10,bottom: self.titleEdgeInsetBottom,right: -10)
self.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
}
}
<file_sep>//
// QuestionsTopViewController.swift
// Study Flash
//
// Created by <NAME> on 5/7/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
enum QuestionState {
case Unchecked
case Checked
}
class QuestionsTopViewController: UIViewController {
var timerLabel: UILabel!
var timeLabel: UILabel!
var numberOfCards: UILabel!
var cardsLeft: UILabel!
var bottomButton: UIButton!
// Questions
private var questionsViewController: QuestionsTableViewController?
// Question State
private var questionState = QuestionState.Unchecked
// Creating top container where all the labels will be placed
var topContainerView: UIView!
var quizManager = QuizManager()
var timerCounter: Int = 0
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
createTopView()
createBottomView()
constraintsForBottomView()
setupQuizManager()
setupNavigationBar()
// Start quiz timer
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimeLabel), userInfo: nil, repeats: true)
}
//MARK: - Navigation
@objc func handleContinueButtonPressed() {
// Depends on status "check or not check"
if questionState == .Checked {
showNextQuestion()
questionsViewController?.tableView.allowsMultipleSelection = true
bottomButton.setTitle("Check", for: .normal)
bottomButton.backgroundColor = .lightGray
questionState = .Unchecked
} else {
// Did the user select any answer?
if !quizManager.anyAnswerSelected() {
// No answer selected, do nothing
return
}
// Highlight the correct answers
questionsViewController?.showAnswerResult()
questionsViewController?.tableView.allowsSelection = false
bottomButton.setTitle("Continue", for: .normal)
bottomButton.backgroundColor = .primaryThemeColor
questionState = .Checked
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "middleViewController" {
if let destinationViewController = segue.destination as? QuestionsTableViewController {
self.questionsViewController = destinationViewController
}
} else if segue.identifier == "showCourseResult" {
if let destinationViewController = segue.destination as? CourseResultViewController {
destinationViewController.gameScore = quizManager.getGameScore()
}
}
}
}
// MARK: - Quiz Stuff
extension QuestionsTopViewController {
private func setupQuizManager() {
quizManager = QuizManager()
quizManager.prepareQuestions()
showNextQuestion()
}
private func showNextQuestion() {
if quizManager.lastQuestionWasReached() {
showQuizResultScreen()
} else {
quizManager.advanceToNextQuestion()
self.reloadQuestionData()
}
}
private func reloadQuestionData() {
// Get the current question and make the question table view controller reload
questionsViewController?.reloadData(withQuizManager: quizManager)
// Also reload the question counter
self.reloadQuestionCounter()
}
private func reloadQuestionCounter() {
numberOfCards.text = "\(quizManager.getCurrentQuestionNumberToDisplay())/\(quizManager.getTotalAmountOfQuestionsToDisplay())"
}
private func showQuizResultScreen() {
timer?.invalidate()
performSegue(withIdentifier: "showCourseResult", sender: self)
}
}
// MARK: Build UI
extension QuestionsTopViewController {
func createTopView () {
topContainerView = UIView()
view.addSubview(topContainerView)
topContainerView.translatesAutoresizingMaskIntoConstraints = false
topContainerView.heightAnchor.constraint(equalToConstant: 80).isActive = true
topContainerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
topContainerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
topContainerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
timerLabel = UILabel()
timerLabel.text = NSLocalizedString("00:00:00", comment: "The time left to study")
timerLabel.font = UIFont.boldSystemFont(ofSize: 20)
timeLabel = UILabel()
timeLabel.text = NSLocalizedString("TIME", comment: "Time label")
timeLabel.textColor = .gray
timeLabel.font = UIFont.boldSystemFont(ofSize: 12)
let myStackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
myStackView.axis = .vertical
myStackView.distribution = .equalSpacing
myStackView.alignment = .leading
myStackView.spacing = 3
myStackView.addArrangedSubview(timerLabel)
myStackView.addArrangedSubview(timeLabel)
self.view.addSubview(myStackView)
myStackView.translatesAutoresizingMaskIntoConstraints = false
myStackView.leadingAnchor.constraint(equalTo: topContainerView.leadingAnchor, constant: 25).isActive = true
myStackView.bottomAnchor.constraint(equalTo: topContainerView.bottomAnchor, constant: -10).isActive = true
numberOfCards = UILabel()
numberOfCards.text = ""
numberOfCards.font = UIFont.boldSystemFont(ofSize: 20)
cardsLeft = UILabel()
cardsLeft.text = NSLocalizedString("QUESTION", comment: "LEFT label")
cardsLeft.textColor = .gray
cardsLeft.font = UIFont.boldSystemFont(ofSize: 12)
let myStackView2 = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
myStackView2.axis = .vertical
myStackView2.distribution = .equalSpacing
myStackView2.alignment = .trailing
myStackView2.spacing = 3
myStackView2.addArrangedSubview(numberOfCards)
myStackView2.addArrangedSubview(cardsLeft)
self.view.addSubview(myStackView2)
myStackView2.translatesAutoresizingMaskIntoConstraints = false
myStackView2.trailingAnchor.constraint(equalTo: topContainerView.trailingAnchor, constant: -25).isActive = true
myStackView2.bottomAnchor.constraint(equalTo: topContainerView.bottomAnchor, constant: -10).isActive = true
}
func createBottomView() {
bottomButton = UIButton()
bottomButton.backgroundColor = UIColor.lightGray
bottomButton.tintColor = .white
bottomButton.setTitle("Check", for: .normal)
bottomButton.titleLabel?.lineBreakMode = .byWordWrapping
bottomButton.titleLabel?.textAlignment = .center
bottomButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
bottomButton.titleEdgeInsets = UIEdgeInsets(top: -10, left: -10, bottom: bottomButton.titleEdgeInsetBottom, right: -10)
bottomButton.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
bottomButton.addTarget(self, action: #selector(handleContinueButtonPressed), for: .touchUpInside)
view.addSubview(bottomButton)
}
func constraintsForBottomView() {
bottomButton.translatesAutoresizingMaskIntoConstraints = false
bottomButton.heightAnchor.constraint(equalToConstant: bottomButton.height).isActive = true
bottomButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
bottomButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
bottomButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
func setupNavigationBar() {
let navigationItem = self.navigationItem
navigationItem.title = "Let's Go Study"
// navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
let exitButton = UIButton(type: .custom)
exitButton.setImage(UIImage(named: "CloseButton.png"), for: .normal)
exitButton.addTarget(self, action: #selector(handleExitButton), for: .touchUpInside)
exitButton.frame = .zero
exitButton.tintColor = .white
exitButton.contentMode = .scaleAspectFill
let rightExitButton = UIBarButtonItem(customView: exitButton)
rightExitButton.customView?.translatesAutoresizingMaskIntoConstraints = false
rightExitButton.customView?.heightAnchor.constraint(equalToConstant: 30).isActive = true
rightExitButton.customView?.widthAnchor.constraint(equalToConstant: 30).isActive = true
navigationItem.rightBarButtonItem = rightExitButton
}
@objc func handleExitButton (_ sender: UIBarButtonItem) {
if let navController = self.navigationController {
navController.presentingViewController?.dismiss(animated: true, completion: {
})
}
}
}
// MARK: - Timer
extension QuestionsTopViewController {
@objc func updateTimeLabel() {
timerCounter += 1
timerLabel.text = timeString(time: TimeInterval(timerCounter))
quizManager.increaseTime(byAmount: 1)
}
func timeString(time:TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
}
<file_sep>//
// UINavigationBarExtension.swift
// Study Flash
//
// Created by <NAME> on 5/30/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UIViewController {
func hideNavigationBar(){
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
func showNavigationBar() {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
}
<file_sep>//
// CourseDetailCollectionViewCell.swift
// Study Flash
//
// Created by 李宇恒 on 13/6/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class MyCell: UICollectionViewCell {
weak var textLabel: UILabel!
weak var statusImage: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
let textLabel = UILabel(frame: .zero)
textLabel.textAlignment = .center
// textLabel.font = .systemFont(ofSize: 20)
// textLabel.textColor = .gray
textLabel.translatesAutoresizingMaskIntoConstraints = false
self.textLabel = textLabel
// let statusImage = UIImageView(image: UIImage(named: "Correct"))
let statusImage = UIImageView()
statusImage.translatesAutoresizingMaskIntoConstraints = false
self.statusImage = statusImage
let stackView = UIStackView()
stackView.axis = NSLayoutConstraint.Axis.vertical
// stackView.spacing = 16.0
stackView.distribution = .equalSpacing
stackView.alignment = .center
stackView.isLayoutMarginsRelativeArrangement = true
stackView.addArrangedSubview(textLabel)
stackView.addArrangedSubview(statusImage)
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
NSLayoutConstraint.activate([
textLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor),
// textLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor),
// textLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor),
// textLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor),
statusImage.topAnchor.constraint(equalTo: textLabel.bottomAnchor),
stackView.leftAnchor.constraint(equalTo: self.leftAnchor),
stackView.rightAnchor.constraint(equalTo: self.rightAnchor),
stackView.heightAnchor.constraint(equalTo: self.heightAnchor),
stackView.widthAnchor.constraint(equalTo: self.widthAnchor),
stackView.centerXAnchor.constraint(equalTo: centerXAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("Interface Builder is not supported!")
}
override func awakeFromNib() {
super.awakeFromNib()
fatalError("Interface Builder is not supported!")
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
<file_sep>//
// QuizManager.swift
// Study Flash
//
// Created by <NAME> on 31/05/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class QuizManager {
// Save all questions here
private var allQuestions = [Question]()
// Save the game state here
private var gameScore: GameScore?
// Save information related to the current status of the quiz here
private var currentQuestionIndex = -1
private lazy var currentlySelectedAnswerIndices: [Int] = {
return [Int]()
}()
func importQuestionFromCourseManager() {
//TODO: chapter should be changed
if let questions = courseManager.courseListFromJSON[courseManager.selectedCourseIndex!].chapters[0].questions {
allQuestions = questions
}
}
// MARK: - Set up quiz data
func prepareQuestions() {
// TODO: What if this fails? Catch error
importQuestionFromCourseManager()
gameScore = GameScore(time: 0, totalQuestions: allQuestions.count, correctQuestions: 0)
}
// MARK: - Current quiz state
func getTotalAmountOfQuestionsToDisplay() -> Int {
return allQuestions.count
}
func getCurrentQuestionNumberToDisplay() -> Int {
return currentQuestionIndex + 1
}
func lastQuestionWasReached() -> Bool {
return currentQuestionIndex == allQuestions.count - 1
}
func getGameScore() -> GameScore? {
return gameScore
}
func anyAnswerSelected() -> Bool {
return currentlySelectedAnswerIndices.count > 0
}
// MARK: Questions
func getCurrentQuestion() -> Question? {
guard currentQuestionIndex >= 0, currentQuestionIndex < allQuestions.count else {
return nil
}
return allQuestions[currentQuestionIndex]
}
func advanceToNextQuestion() {
// Increase counter to advance to the next question
currentQuestionIndex += 1
// Reset selected answers
currentlySelectedAnswerIndices.removeAll()
}
func increaseScore(byAmount amount: Int) {
gameScore?.correctQuestions += amount
}
func increaseTime(byAmount amount: Int) {
gameScore?.time += amount
}
// MARK: - Answers
func isAnswerAtIndexSelected(answerIndex: Int) -> Bool {
return currentlySelectedAnswerIndices.contains(answerIndex)
}
func setAnswerSelection(forAnswerIndex index: Int, select: Bool) {
if select {
// If not already selected, select the answer now
// That means, we add the answer index to the selected answers array
if !isAnswerAtIndexSelected(answerIndex: index) {
currentlySelectedAnswerIndices.append(index)
}
} else {
// Deselect the answer
// Just filter by answerIndex and remove the answer with the given index
currentlySelectedAnswerIndices.removeAll { (answerIndex) -> Bool in
return answerIndex == index
}
}
}
func getAnswerState(forAnswerAtIndex index: Int) -> QuestionAnswerState {
// Check which status the answer should be in
// First, check if answer was correct or incorrect
if let currentQuestion = getCurrentQuestion() {
if currentQuestion.answers[index].isCorrect {
// Did the user select it?
if currentlySelectedAnswerIndices.contains(index) {
// Answer correct AND user selected it!
return .CorrectlyAnswered
} else {
// Answer correct, but user did not select it
return .CorrectButNotSelected
}
} else {
// Did the user select it?
if currentlySelectedAnswerIndices.contains(index) {
// Answer incorrecct AND user selected it!
return .IncorrectlyAnswered
} else {
// Answer incorrect, but user did not select it
return .NotSelected
}
}
} else {
return .NotSelected
}
}
// MARK: Save / load progress
private func saveProgress(forQuestion: Question, answeredCorrectly correct: Bool) {
// Save the question answer
}
}
// MARK: Loading questions
extension QuizManager {
// private func loadJson(filename fileName: String) -> [Question]? {
// if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
// do {
// let data = try Data(contentsOf: url)
// let decoder = JSONDecoder()
// let jsonData = try decoder.decode(Questions.self, from: data)
// return jsonData.questions
//
// } catch {
// print("error:\(error)")
// }
// }
// return nil
// }
}
struct GameScore {
var time: Int
var totalQuestions: Int
var correctQuestions: Int = 0
}
enum QuestionAnswerState {
case NotSelected
case Selected
case CorrectlyAnswered
case IncorrectlyAnswered
case CorrectButNotSelected
}
<file_sep>//
// TopicsTableViewCell.swift
// Study Flash
//
// Created by <NAME> on 5/11/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CoursesTableViewCell: UITableViewCell {
@IBOutlet weak var courseTitle: UILabel!
@IBOutlet weak var courseTopic: UILabel!
@IBOutlet weak var courseState: UILabel!
@IBOutlet weak var grayLine: UIView!
var courseCompletion: Double?
var courseViewModel: CourseViewModel! {
didSet {
courseTitle?.text = courseViewModel.courseTitle
courseTopic?.text = courseViewModel.courseSubtitle
courseState?.text = courseViewModel.courseState
courseState?.textColor = courseViewModel.courseStateTextColor
}
}
override func awakeFromNib() {
//orginal formatting
courseTitle.textColor = .primaryThemeColor
grayLine.backgroundColor = .gray
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
<file_sep>//
// CourseResultViewController.swift
// Study Flash
//
// Created by <NAME> on 5/29/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CourseResultViewController: UIViewController {
var gameScore: GameScore?
let myButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
setupNavigationBar()
setupBottomButton()
setupBottomView()
setupUpperView()
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//
// let destination = segue.destination as! MainCourseListController
// destination.isTodayCourseFinished = true
UserDefaults.standard.set(false, forKey: "isCourseSelected")
UserDefaults.standard.synchronize()
}
}
extension CourseResultViewController {
func setupBottomButton() {
myButton.backgroundColor = UIColor.primaryThemeColor
myButton.tintColor = .white
myButton.setTitle("End Study Session", for: .normal)
myButton.titleLabel?.lineBreakMode = .byWordWrapping
myButton.titleLabel?.textAlignment = .center
myButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
myButton.titleEdgeInsets = UIEdgeInsets(top: -10,left: -10,bottom: myButton.titleEdgeInsetBottom, right: -10)
myButton.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(myButton)
//constraint
myButton.translatesAutoresizingMaskIntoConstraints = false
myButton.heightAnchor.constraint(equalToConstant: myButton.height).isActive = true
myButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
myButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
myButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
@objc private func buttonAction(sender: UIButton!) {
sender.flash()
if let navController = self.navigationController {
updateProgress()
navController.presentingViewController?.dismiss(animated: true, completion: {
//
})
}
}
func updateProgress() {
courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.state = .todayCompleted
//TODO: - totalQuestion should not be 0
if gameScore!.totalQuestions != 0 {
courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.totalCompletedQuestion = gameScore!.totalQuestions
//confidence level
let confidenceLevel = courseManager.calculateConfidenceLevel(correctNo: gameScore!.correctQuestions, totalQuestion: gameScore!.totalQuestions)
courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.confidenceLevel = confidenceLevel
}
UserDefaults.standard.set(true, forKey: "isTodayCourseFinished")
UserDefaults.standard.synchronize()
}
func setupBottomView() {
guard let gameScore = gameScore else {
return
}
let myTitle = UILabel()
let myComment = UILabel()
myTitle.font = .boldSystemFont(ofSize: 22)
myTitle.text = "Congratulations!"
myTitle.textAlignment = .left
myComment.font = .systemFont(ofSize: 14)
myComment.text = "Great job, you answered all questions of today's study plan - keep rocking!"
myComment.textAlignment = .left
myComment.lineBreakMode = .byWordWrapping
myComment.numberOfLines = 3
let myStackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
myStackView.axis = .vertical
myStackView.distribution = .equalSpacing
myStackView.alignment = .leading
myStackView.spacing = 5.0
myStackView.addArrangedSubview(myTitle)
myStackView.addArrangedSubview(myComment)
let myTimeTaken = UILabel()
let myTimeTakenLabel = UILabel()
myTimeTaken.font = .boldSystemFont(ofSize: 22)
myTimeTaken.text = timeString(time: TimeInterval(gameScore.time))
myTimeTaken.textAlignment = .left
myTimeTakenLabel.font = .boldSystemFont(ofSize: 12)
myTimeTakenLabel.textColor = .gray
myTimeTakenLabel.text = "TIME TAKEN"
myTimeTakenLabel.textAlignment = .left
let myStackView2 = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
myStackView2.axis = .vertical
myStackView2.distribution = .equalSpacing
myStackView2.alignment = .leading
myStackView2.spacing = 2.0
myStackView2.addArrangedSubview(myTimeTaken)
myStackView2.addArrangedSubview(myTimeTakenLabel)
// self.view.addSubview(myStackView2)
//
// myStackView2.translatesAutoresizingMaskIntoConstraints = false
// myStackView2.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
// myStackView2.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
// myStackView2.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -150).isActive = true
let myResult = UILabel()
let myResultLabel = UILabel()
myResult.font = .boldSystemFont(ofSize: 22)
myResult.text = "\(gameScore.correctQuestions) / \(gameScore.totalQuestions)"
myResult.textAlignment = .left
myResultLabel.font = .boldSystemFont(ofSize: 12)
myResultLabel.textColor = .gray
myResultLabel.text = "CORRECT ANSWERS"
myResultLabel.textAlignment = .left
let myStackView3 = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
myStackView3.axis = .vertical
myStackView3.distribution = .equalSpacing
myStackView3.alignment = .leading
myStackView3.spacing = 2.0
myStackView3.addArrangedSubview(myResult)
myStackView3.addArrangedSubview(myResultLabel)
// self.view.addSubview(myStackView3)
//
// myStackView3.translatesAutoresizingMaskIntoConstraints = false
// myStackView3.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
// myStackView3.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
// myStackView3.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -100).isActive = true
let myTotalStackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
myTotalStackView.axis = .vertical
myTotalStackView.distribution = .equalSpacing
myTotalStackView.alignment = .leading
myTotalStackView.spacing = 30.0
myTotalStackView.addArrangedSubview(myStackView)
myTotalStackView.addArrangedSubview(myStackView2)
myTotalStackView.addArrangedSubview(myStackView3)
self.view.addSubview(myTotalStackView)
myTotalStackView.translatesAutoresizingMaskIntoConstraints = false
myTotalStackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
myTotalStackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
myTotalStackView.bottomAnchor.constraint(equalTo: myButton.topAnchor, constant: -40).isActive = true
}
func setupUpperView() {
let imageName = "Celebration.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 250, height: 250)
self.view.addSubview(imageView)
//constraints
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true
}
// MARK: - Helper
func timeString(time:TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
}
extension CourseResultViewController {
func setupNavigationBar() {
let navigationItem = self.navigationItem
navigationItem.title = "Result"
let helpButton = UIButton(type: .custom)
helpButton.setImage(UIImage(named: "HelpButton.png"), for: .normal)
helpButton.addTarget(self, action: #selector(studyProfileButton_clicked), for: .touchUpInside)
helpButton.contentMode = .scaleAspectFit
let rightHelpButton = UIBarButtonItem(customView: helpButton)
navigationItem.rightBarButtonItem = rightHelpButton
}
@objc func studyProfileButton_clicked (_ sender: UIBarButtonItem) {
}
}
<file_sep>//
// OnboardingPage1.swift
// Study Flash
//
// Created by <NAME> on 5/24/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class OnboardingPage2: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
let imageOfOnboarding = UIImageView(image: UIImage(named: "OnboardingImage2"))
imageOfOnboarding.setOnboardingImage()
let titleOfOnboarding = UILabel()
titleOfOnboarding.setOnboardingTitleFormat()
titleOfOnboarding.text = "Study Faster"
let descriptionOfOnboarding = UILabel()
descriptionOfOnboarding.setOnboardingDescription()
descriptionOfOnboarding.text = "Algorithm based revision schedulling helps you memorize better with less time."
let stackView = UIStackView()
stackView.setOnboardingStackView()
stackView.addArrangedSubview(imageOfOnboarding)
stackView.addArrangedSubview(titleOfOnboarding)
stackView.addArrangedSubview(descriptionOfOnboarding)
stackView.setCustomSpacing(40, after: stackView.subviews[0])
stackView.setCustomSpacing(20, after: stackView.subviews[1])
addSubview(stackView)
//adding constraint
imageOfOnboarding.widthAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
imageOfOnboarding.heightAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
//Anchor
titleOfOnboarding.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
descriptionOfOnboarding.leftAnchor.constraint(equalTo: stackView.leftAnchor, constant: 20).isActive = true
descriptionOfOnboarding.rightAnchor.constraint(equalTo: stackView.rightAnchor, constant: -20).isActive = true
descriptionOfOnboarding.widthAnchor.constraint(equalToConstant: 340).isActive = true
stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
stackView.topAnchor.constraint(greaterThanOrEqualTo: self.topAnchor, constant: 100).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>//
// UIButtonExtension.swift
// Study Flash
//
// Created by <NAME> on 5/15/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UIButton {
var height: CGFloat {
if detectDeviceModel() == 0 {
return 60
} else {
return 90
}
}
var titleEdgeInsetBottom: CGFloat {
if detectDeviceModel() == 0 {
return -10
} else {
return 20
}
}
func setupButton() {
}
func flash() {
let flash = CABasicAnimation(keyPath: "opacity")
flash.duration = 0.3
flash.fromValue = 0.5
flash.toValue = 0.1
flash.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
flash.autoreverses = true
flash.repeatCount = 1
layer.add(flash, forKey: nil)
}
}
<file_sep>//
// UserDefault.swift
// Study Flash
//
// Created by <NAME> on 16/8/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct Defaults {
static let (nameKey, addressKey) = ("name", "address")
static let userSessionKey = "com.save.usersession"
struct Model {
var name: String
var address: String
init(_ json: [String: String]) {
self.name = json[nameKey] ?? ""
self.address = json[addressKey] ?? ""
}
}
static func save(_ name: String, with address: String){
UserDefaults.standard.set([nameKey: name, addressKey: address], forKey: userSessionKey)
}
static func getNameAndAddress()-> Model {
return Model((UserDefaults.standard.value(forKey: userSessionKey) as? [String: String]) ?? [:])
}
static func clearUserData(){
UserDefaults.standard.removeObject(forKey: userSessionKey)
}
}
<file_sep>//
// File.swift
// Study Flash
//
// Created by <NAME> on 23/10/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct Email {
private var string: String
init(_ string: String) throws {
try Validations.email(string)
self.string = string
}
func address() -> String {
return string
}
}
//struct User {
// let name: String
// let email: Email
// let password: String
//}
<file_sep>//
// CourseDetailCalendarModel.swift
// Study Flash
//
// Created by 李宇恒 on 13/6/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
public class WeekdayModel {
public func getTodayDaysCountFromStartDay(_ startDateComponents: DateComponents) -> Int {
let calendar = Calendar.current
let today = Date()
let startDate = calendar.date(from: startDateComponents)
return calendar.dateComponents([.day], from: startDate!, to: today).day!
}
public func getWeekdayArray(_ startDateComponents: DateComponents, examDateComponents: DateComponents) -> [String] {
let calendar = Calendar.current
let examDate = calendar.date(from: examDateComponents)
let startDate = calendar.date(from: startDateComponents)
let studyDaysCount = calendar.dateComponents([.day], from: startDate!, to: examDate!).day
let weekdayOfStartDay = calendar.component(.weekday, from: startDate!)
let studyDaysRange = 0...studyDaysCount!
var weekdayArrays = [String]()
for i in studyDaysRange {
let x = weekdayOfStartDay + i
let y = weekdayNameFrom(weekdayNumber: x)
weekdayArrays.append(y)
}
return weekdayArrays
}
private func weekdayNameFrom(weekdayNumber: Int) -> String {
let calendar = Calendar.current
let dayIndex = ((weekdayNumber - 1) + (calendar.firstWeekday - 1)) % 7
return calendar.veryShortWeekdaySymbols[dayIndex]
}
}
<file_sep>//
// BeginNewCourseHeaderCell.swift
// Study Flash
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class BeginNewCourseHeaderCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = .white
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// BeginNewCourseViewController.swift
// Study Flash
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class BeginNewCourseViewController: UIViewController {
private var myTableView: UITableView!
private var myBottomView: UIView!
private var examDateTextField: UITextField!
private let myButton = BottomDisableButton()
let datePicker = UIDatePicker()
let toolbar = UIToolbar()
var userSetTheDate = false {
didSet {
myButton.backgroundColor = .primaryThemeColor
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupBottomView()
setupTableView()
}
}
extension BeginNewCourseViewController: UITableViewDelegate, UITableViewDataSource {
private func setupTableView() {
myTableView = UITableView(frame: .zero)
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.register(UINib(nibName: "BeginNewCourseHeaderCell", bundle: nil).self, forCellReuseIdentifier: "HeaderCell")
myTableView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
myTableView.dataSource = self
myTableView.delegate = self
//enilminate thhe line
myTableView.tableFooterView = UIView()
myTableView.bounces = false
myTableView.allowsSelection = false
myTableView.separatorStyle = .none
myTableView.showsVerticalScrollIndicator = false
self.view.addSubview(myTableView)
//set constraint
myTableView.translatesAutoresizingMaskIntoConstraints = false
myTableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 44).isActive = true
myTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
myTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
myTableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -myBottomView.frame.size.height - 10).isActive = true
}
//header section ----------
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 220
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! BeginNewCourseHeaderCell
// header.courseCompletionRateLabel.text = String(courseList[selectedCourseIndex].courseCompletion!) + "%" //put in xib
return header
}
//Content Section ----------
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courseManager.allCourses[courseManager.selectedCourseIndex!].courseChapter.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
cell.textLabel!.text =
courseManager.allCourses[courseManager.selectedCourseIndex!].courseChapter[indexPath.row].title
cell.textLabel!.font = .systemFont(ofSize: 14)
return cell
}
}
extension BeginNewCourseViewController {
//MARK:- BottomView
func setupBottomView() {
myBottomView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 250))
myBottomView.backgroundColor = .white
self.view.addSubview(myBottomView)
//set bottomView constraint
myBottomView.translatesAutoresizingMaskIntoConstraints = false
myBottomView.heightAnchor.constraint(equalToConstant: 250).isActive = true
myBottomView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
myBottomView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
myBottomView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
//Button
myButton.setTitle("Create Plan", for: .normal)
myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
myBottomView.addSubview(myButton)
//button constraint on button to stackView
myButton.translatesAutoresizingMaskIntoConstraints = false
myButton.heightAnchor.constraint(equalToConstant: myButton.height).isActive = true
myButton.leadingAnchor.constraint(equalTo: myBottomView.leadingAnchor).isActive = true
myButton.trailingAnchor.constraint(equalTo: myBottomView.trailingAnchor).isActive = true
myButton.bottomAnchor.constraint(equalTo: myBottomView.bottomAnchor).isActive = true
//Comment
let myComment = UILabel()
myComment.font = .systemFont(ofSize: 15)
myComment.attributedText = modifyCommentText()
myComment.textAlignment = .left
myComment.backgroundColor = .white
myComment.lineBreakMode = .byWordWrapping
myComment.numberOfLines = 3
//MARK:- DatePicker
examDateTextField = TextField()
configureDatePicker()
examDateTextField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
examDateTextField.textAlignment = .center
examDateTextField.font = .boldSystemFont(ofSize: 16)
examDateTextField.layer.borderWidth = 0.5
examDateTextField.layer.borderColor = UIColor.primaryThemeColor.cgColor
examDateTextField.layer.cornerRadius = 5
examDateTextField.text = "Select Exam Date"
examDateTextField.textColor = .primaryThemeColor
examDateTextField.delegate = self
examDateTextField.inputView = datePicker
examDateTextField.inputAccessoryView = toolbar
let totalQuestionLabel = UILabel()
totalQuestionLabel.font = .boldSystemFont(ofSize: 18)
totalQuestionLabel.textColor = .primaryThemeColor
totalQuestionLabel.text = "Total: \(courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.completion.totalQuestion) questions"
totalQuestionLabel.textAlignment = .center
totalQuestionLabel.backgroundColor = .white
let myStackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 320, height: 300))
myStackView.axis = .vertical
myStackView.distribution = .equalSpacing
myStackView.alignment = .center
myStackView.spacing = 15.0
myStackView.addArrangedSubview(totalQuestionLabel)
myStackView.addArrangedSubview(myComment)
myStackView.addArrangedSubview(examDateTextField)
myBottomView.addSubview(myStackView)
//set constraint on stackView to bottomView
myStackView.translatesAutoresizingMaskIntoConstraints = false
myStackView.leadingAnchor.constraint(equalTo: myBottomView.leadingAnchor, constant: 20).isActive = true
myStackView.trailingAnchor.constraint(equalTo: myBottomView.trailingAnchor, constant: -20).isActive = true
myStackView.centerXAnchor.constraint(equalTo: myBottomView.centerXAnchor).isActive = true
myStackView.bottomAnchor.constraint(equalTo: myButton.topAnchor, constant: -25).isActive = true
//Comment Constraint
totalQuestionLabel.translatesAutoresizingMaskIntoConstraints = false
totalQuestionLabel.widthAnchor.constraint(equalTo: myStackView.widthAnchor).isActive = true
myComment.translatesAutoresizingMaskIntoConstraints = false
myComment.widthAnchor.constraint(equalTo: myStackView.widthAnchor).isActive = true
}
func showAlert() {
let alertController = UIAlertController(title: "Please select Exam Date", message: "for creating a customized study plan", preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
@objc private func buttonAction(sender: UIButton!) {
sender.flash()
guard userSetTheDate == true else {return showAlert()}
actionAfterCourseSelected()
UserDefaults.standard.set(true, forKey: "isBeginNewCourse")
UserDefaults.standard.synchronize()
self.dismiss(animated: true, completion: nil)
}
func actionAfterCourseSelected() {
//Confirm course selected after starting the course
courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.state = .todayNotCompleted
//save to persistence memory
UserDefaults.standard.set(true, forKey: "isCourseSelected")
UserDefaults.standard.set(courseManager.selectedCourse?.courseId, forKey: "lastSelectedCourseId")
UserDefaults.standard.synchronize()
}
func modifyCommentText() -> NSMutableAttributedString {
let normalText = "In order to create a personalized and efficient study plan for you, please specify the date of your exam: "
let normalString = NSMutableAttributedString(string:normalText)
let boldQuestionNo = ""
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)]
let attributedString = NSMutableAttributedString(string:boldQuestionNo, attributes:attrs)
normalString.append(attributedString)
let normalText2 = ""
let normalString2 = NSMutableAttributedString(string: normalText2)
normalString.append(normalString2)
return normalString
}
}
//MARK: --Textfield Configuration
extension BeginNewCourseViewController: UITextFieldDelegate {
func configureDatePicker() {
//Formate Date
datePicker.datePickerMode = .date
datePicker.backgroundColor = .white
datePicker.locale = Locale(identifier: "en_GB")
datePicker.minimumDate = Date()
datePicker.tintColor = .primaryThemeColor
//ToolBar
let doneButton = UIBarButtonItem(title: "Select", style: .plain, target: self, action: #selector(doneDatePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker))
toolbar.setItems([cancelButton,spaceButton,doneButton], animated: false)
toolbar.sizeToFit()
toolbar.backgroundColor = .white
toolbar.tintColor = .primaryThemeColor
}
@objc func doneDatePicker(){
let formatter = DateFormatter()
formatter.dateFormat = "d MMM yyyy"
examDateTextField.text = formatter.string(from: datePicker.date)
userSetTheDate = true
let dateTimestamp = datePicker.date
courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.dateOfExam = dateTimestamp
self.view.endEditing(true)
}
@objc func cancelDatePicker(){
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension BeginNewCourseViewController {
func setupNavigationBar() {
let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.size.height, height:44))
navigationBar.barTintColor = .white
navigationBar.tintColor = .lightGray
navigationBar.isTranslucent = false
navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "Helvetica-Bold", size: 20)!, NSAttributedString.Key.foregroundColor: UIColor.gray]
self.view.addSubview(navigationBar)
navigationBar.translatesAutoresizingMaskIntoConstraints = false
navigationBar.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
navigationBar.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
navigationBar.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
let navItem = UINavigationItem(title: courseManager.selectedCourse!.courseTitle)
let exitButton = UIButton(type: .custom)
exitButton.setImage(UIImage(named: "CloseButton.png"), for: .normal)
exitButton.addTarget(self, action: #selector(handleExitButton), for: .touchUpInside)
exitButton.frame = .zero
exitButton.tintColor = .white
exitButton.contentMode = .scaleAspectFill
let rightExitButton = UIBarButtonItem(customView: exitButton)
rightExitButton.customView?.translatesAutoresizingMaskIntoConstraints = false
rightExitButton.customView?.heightAnchor.constraint(equalToConstant: 30).isActive = true
rightExitButton.customView?.widthAnchor.constraint(equalToConstant: 30).isActive = true
navItem.rightBarButtonItem = rightExitButton
navigationBar.setItems([navItem], animated: false)
}
@objc func handleExitButton (_ sender: UIBarButtonItem) {
//save exam date
self.dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// UIColorExtension.swift
// Study Flash
//
// Created by <NAME> on 5/15/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
extension UIColor {
static let primaryThemeColor = UIColor(red: 87/255,
green: 95/255,
blue: 207/255,
alpha: 1.00)
static let secondaryThemeColor = UIColor(red: 245/255,
green: 59/255,
blue: 87/255,
alpha: 1.00) //#F53B57
static let rightAnswerGreenColor = UIColor(red: 5/255,
green: 196/255,
blue: 107/255,
alpha: 1.00)
static let wrongAnswerRedColor = UIColor(red: 245/255,
green: 59/255,
blue: 87/255,
alpha: 1.00)
}
<file_sep>//
// Validation.swift
// Study Flash
//
// Created by <NAME> on 23/10/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
enum EvaluateError: Error {
case isEmpty
case isNotValidEmailAddress
case isNotValidEmailLength
}
struct Validations {
private static let emailRegEx = "(?:[a-zA-Z0-9!#$%\\&‘*+/=?\\^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%\\&'*+/=?\\^_`{|}"
+ "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
+ "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
+ "z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
+ "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
+ "9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
+ "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
static func email(_ string: String) throws {
if string.isEmpty == true {
throw EvaluateError.isEmpty
}
if isValid(input: string,
regEx: emailRegEx,
predicateFormat: "SELF MATCHES[c] %@") == false {
throw EvaluateError.isNotValidEmailAddress
}
if maxLength(emailAddress: string) == false {
throw EvaluateError.isNotValidEmailLength
}
}
private static func isValid(input: String, regEx: String, predicateFormat: String) -> Bool {
return NSPredicate(format: predicateFormat, regEx).evaluate(with: input)
}
private static func maxLength(emailAddress: String) -> Bool {
// 64 chars before domain and total 80. '@' key is part of the domain.
guard emailAddress.count <= 80 else {
return false
}
guard let domainKey = emailAddress.firstIndex(of: "@") else { return false }
return emailAddress[..<domainKey].count <= 64
}
}
<file_sep>//
// CoursesTableViewHeaderCell.swift
// Study Flash
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CoursesTableViewFooterCell: UITableViewCell {
@IBOutlet weak var grayLine: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = nil
grayLine.backgroundColor = .gray
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// OnboardingConstraint.swift
// Study Flash
//
// Created by <NAME> on 12/8/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
extension UILabel {
func setOnboardingTitleFormat() {
self.frame = .zero
self.font = UIFont(name: "AvenirNext-Bold", size: 19)
self.textColor = .black
self.textAlignment = .center
self.translatesAutoresizingMaskIntoConstraints = false
}
func setOnboardingDescription() {
self.frame = .zero
self.font = UIFont(name: "AvenirNext-Medium", size: 17)
self.textColor = .black
self.textAlignment = .center
self.numberOfLines = 0
self.lineBreakMode = .byWordWrapping
self.sizeToFit()
self.translatesAutoresizingMaskIntoConstraints = false
}
func setOnboardingTitleConstraints() {
}
func setOnboardingDescriptionConstraints() {
}
}
extension UIStackView {
func setOnboardingStackView() {
self.axis = NSLayoutConstraint.Axis.vertical
self.alignment = .center
self.isLayoutMarginsRelativeArrangement = true
self.translatesAutoresizingMaskIntoConstraints = false
}
}
extension UIView {
func setOnboardingImage() {
self.contentMode = .scaleAspectFit
}
func setOnboardingImageConstraints() {
}
}
<file_sep>//
// StudyProfile.swift
// Study Flash
//
// Created by <NAME> on 6/1/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class StudyProfileViewController: UIViewController, TKRadarChartDelegate, TKRadarChartDataSource {
@IBOutlet weak var dateOfExam: UILabel!
@IBOutlet weak var dayLeft: UILabel!
@IBOutlet weak var confidenceLevel: UILabel!
let myButton = UIButton()
private var chart: TKRadarChart!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
setupNavigationBar()
setupButton()
showExamDate()
showDayLeft()
showConfidenceLevel()
setupTKChart()
}
func setupTKChart() {
let width = view.bounds.width - 40
chart = TKRadarChart(frame: CGRect(x: 0, y: 0, width: width, height: width))
chart.configuration.radius = width / 3
chart.dataSource = self
chart.delegate = self
chart.center = view.center
chart.reloadData()
view.addSubview(chart)
// chart.translatesAutoresizingMaskIntoConstraints = false
// chart.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
// chart.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
// chart.bottomAnchor.constraint(equalTo: myButton.topAnchor, constant: -20).isActive = true
}
func numberOfStepForRadarChart(_ radarChart: TKRadarChart) -> Int {
return 5
}
func numberOfRowForRadarChart(_ radarChart: TKRadarChart) -> Int {
return 5
//courseManager.selectedCourse!.courseChapter.count
}
func numberOfSectionForRadarChart(_ radarChart: TKRadarChart) -> Int {
return 1
}
func titleOfRowForRadarChart(_ radarChart: TKRadarChart, row: Int) -> String {
return "Chapter\(row + 1)"
}
func valueOfSectionForRadarChart(withRow row: Int, section: Int) -> CGFloat {
if row == 0 {
return CGFloat(courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.confidenceLevel / 100 * 5)
} else {
return 1
}
}
func colorOfLineForRadarChart(_ radarChart: TKRadarChart) -> UIColor {
return UIColor.primaryThemeColor
}
func colorOfFillStepForRadarChart(_ radarChart: TKRadarChart, step: Int) -> UIColor {
switch step {
case 1:
return UIColor.white
case 2:
return UIColor.white
case 3:
return UIColor.white
case 4:
return UIColor.white
default:
return UIColor.white
}
}
func colorOfSectionFillForRadarChart(_ radarChart: TKRadarChart, section: Int) -> UIColor {
if section == 0 {
return UIColor(red:1, green:0.867, blue:0.012, alpha:0.4)
} else {
return UIColor(red:0, green:0.788, blue:0.543, alpha:0.4)
}
}
func colorOfSectionBorderForRadarChart(_ radarChart: TKRadarChart, section: Int) -> UIColor {
if section == 0 {
return UIColor(red:1, green:0.867, blue:0.012, alpha:1)
} else {
return UIColor(red:0, green:0.788, blue:0.543, alpha:1)
}
}
func fontOfTitleForRadarChart(_ radarChart: TKRadarChart) -> UIFont {
return UIFont.systemFont(ofSize: 13)
}
}
extension StudyProfileViewController {
private func showExamDate() {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM, yyyy "
dateOfExam.text = formatter.string(from: courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.dateOfExam)
}
private func showDayLeft() {
let secondLeft = courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.dateOfExam.timeIntervalSince(Date())
let dayLeft: Int = Int((secondLeft / (60 * 60 * 24)).rounded(.up))
self.dayLeft.text = String(dayLeft)
}
private func showConfidenceLevel() {
self.confidenceLevel.text = "\(courseManager.allCourses[courseManager.selectedCourseIndex!].courseProgress.confidenceLevel)%"
}
func setupTopView() {
}
func setupMidView() {
}
func setupBottomView() {
}
func setupButton() {
myButton.backgroundColor = UIColor.secondaryThemeColor
myButton.frame = .zero
myButton.tintColor = .white
myButton.layer.cornerRadius = 8
myButton.setTitle("Reset Course", for: .normal)
myButton.titleEdgeInsets = UIEdgeInsets(top: -10,left: -10,bottom: -10,right: -10)
myButton.contentEdgeInsets = UIEdgeInsets(top: 10,left: 30,bottom: 10,right: 30)
myButton.titleLabel?.lineBreakMode = .byWordWrapping
myButton.titleLabel?.textAlignment = .center
myButton.titleLabel?.font = .systemFont(ofSize: 16)
// startButton.titleLabel?.font = UIFont(name: "AvenirNext-Medium", size: 19)
myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(myButton)
myButton.translatesAutoresizingMaskIntoConstraints = false
myButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
myButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -40).isActive = true
}
@objc func buttonAction(sender: UIButton) {
sender.flash()
showAlert()
}
private func showAlert() {
let alert = UIAlertController(title: "Confirm to reset?", message: "Reset the plan will clear all you progress", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Continue to reset", style: UIAlertAction.Style.destructive, handler: { action in
self.resetPlan()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
private func resetPlan() {
print("resetPlan")
//reset all the progress, including Exam date, completion, confidence,
//.......
courseManager.resetAll()
let mainCourseListController = self.navigationController?.viewControllers[0] as! UIViewController
self.navigationController?.popToViewController(mainCourseListController, animated: false)
//popup for reset complete
let alert = UIAlertController(title: "Course Reset Completed", message: nil, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func setupNavigationBar() {
let navigationItem = self.navigationItem
navigationItem.title = "Study Board"
}
}
<file_sep>////
//// CourseData.swift
//// Study Flash
////
//// Created by <NAME> on 6/13/19.
//// Copyright © 2019 <NAME>. All rights reserved.
////
//
//For importing
struct CourseData: Codable {
var courses: [CourseInfo]
}
struct CourseInfo: Codable {
var id: Int
var title: String
var subtitle: String
var chapters: [Chapter]
}
struct Chapter: Codable {
var id: Int
var title: String
var questions: [Question]?
}
struct Question: Codable {
var id: Int
var question: String
var answers: [Answer]
var explanation: String
}
struct Answer: Codable {
var id: Int
var body: String
var isCorrect: Bool
}
<file_sep>//
// OnboardingViewController.swift
// Study Flash
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class OnboardingViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, CustomCollectionViewCellDelegate {
let numberOfOnboardingScreen = 4
var pageControl = UIPageControl()
override func viewDidLoad() {
super.viewDidLoad()
configurePageControl()
setupLayout()
}
//Configuring CollectionView
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfOnboardingScreen
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch indexPath.item {
case 0:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "page1", for: indexPath)
return cell
case 1:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "page2", for: indexPath)
return cell
case 2:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "page3", for: indexPath)
return cell
case 3:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "page4", for: indexPath) as! OnboardingPage4
cell.delegate = self
return cell
default:
break
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
private func setupLayout() {
guard let collectionView = collectionView else {return}
collectionView.register(OnboardingPage1.self, forCellWithReuseIdentifier: "page1")
collectionView.register(OnboardingPage2.self, forCellWithReuseIdentifier: "page2")
collectionView.register(OnboardingPage3.self, forCellWithReuseIdentifier: "page3")
collectionView.register(OnboardingPage4.self, forCellWithReuseIdentifier: "page4")
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
collectionView.backgroundColor = .white
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
}
//pageControl
func configurePageControl(){
pageControl = UIPageControl(frame: CGRect(x: 0, y: UIScreen.main.bounds.maxY - 180 , width: UIScreen.main.bounds.width, height: 50)) //add constrain later
pageControl.numberOfPages = 4
pageControl.currentPage = 0
pageControl.tintColor = .black
pageControl.pageIndicatorTintColor = .lightGray
pageControl.currentPageIndicatorTintColor = .primaryThemeColor
self.view.addSubview(pageControl)
}
//moving indicator
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
}
override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
}
//MARK: - MyCustomCellDelegator Methods
func presentNewViewController(myData dataobject: AnyObject) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyBoard.instantiateViewController(withIdentifier: "TabBarController")
mainViewController.modalTransitionStyle = .crossDissolve
mainViewController.modalPresentationStyle = .fullScreen
UserDefaults.standard.set(true, forKey: "isOnboardingFinish")
UserDefaults.standard.synchronize()
self.present(mainViewController, animated: true, completion: nil)
}
}
protocol CustomCollectionViewCellDelegate {
func presentNewViewController(myData dataobject: AnyObject)
}
<file_sep>//
// UIDevice.swift
// Study Flash
//
// Created by <NAME> on 12/8/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
func detectDeviceModel() -> Int {
if UIDevice().userInterfaceIdiom == .phone {
switch UIScreen.main.nativeBounds.height {
case 1136, 1334, 1920, 2208:
return 0
case 2436, 2688, 1792:
return 1
default:
return 2
}
}
return 3
}
<file_sep>//
// extension.swift
// Study Flash
//
// Created by <NAME> on 5/13/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
//Not using anyway
extension UINavigationBar {
func hideBottomHairline() {
self.hairlineImageView?.isHidden = true
}
func showBottomHairline() {
self.hairlineImageView?.isHidden = false
}
}
extension UIToolbar {
func hideBottomHairline() {
self.hairlineImageView?.isHidden = true
}
func showBottomHairline() {
self.hairlineImageView?.isHidden = false
}
}
extension UIView {
fileprivate var hairlineImageView: UIImageView? {
return hairlineImageView(in: self)
}
fileprivate func hairlineImageView(in view: UIView) -> UIImageView? {
if let imageView = view as? UIImageView, imageView.bounds.height <= 1.0 {
return imageView
}
for subview in view.subviews {
if let imageView = self.hairlineImageView(in: subview) { return imageView }
}
return nil
}
}
extension UIStackView {
func addBackground(color: UIColor) {
let subView = UIView(frame: bounds)
subView.backgroundColor = color
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subView, at: 0)
}
}
extension UIView {
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: width)
self.layer.addSublayer(border)
}
func addRightBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
self.layer.addSublayer(border)
}
func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
self.layer.addSublayer(border)
}
func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
self.layer.addSublayer(border)
}
}
<file_sep>//
// QuestionTableViewCell.swift
// Study Flash
//
// Created by <NAME> on 5/15/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class QuestionTableViewCell: UITableViewCell {
var answerState: QuestionAnswerState = .NotSelected {
didSet {
self.updateView()
}
}
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var checkBox: UIImageView!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(false, animated: true)
checkBox.image = selected ? UIImage(named: "Selected.png") : UIImage(named: "NotSelectedGray.png")
self.backgroundColor = selected ? .primaryThemeColor : .clear
self.questionLabel.textColor = selected ? .white : .black
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
}
override func prepareForReuse() {
super.prepareForReuse()
answerState = .NotSelected
}
func updateView() {
// Change row appearance based on state
switch answerState {
case .NotSelected:
self.backgroundColor = .clear
self.questionLabel.textColor = .black
checkBox.image = UIImage(named: "NotSelectedGray.png")
case .Selected:
self.backgroundColor = .primaryThemeColor
self.questionLabel.textColor = .white
checkBox.image = UIImage(named: "Selected.png")
case .IncorrectlyAnswered:
self.backgroundColor = .wrongAnswerRedColor
self.questionLabel.textColor = .white
checkBox.image = UIImage(named: "Incorrect.png")
case .CorrectlyAnswered:
self.backgroundColor = .rightAnswerGreenColor
self.questionLabel.textColor = .white
checkBox.image = UIImage(named: "Selected.png")
case .CorrectButNotSelected:
self.backgroundColor = .rightAnswerGreenColor
self.questionLabel.textColor = .white
checkBox.image = UIImage(named: "NotSelectedWhite.png")
}
}
}
<file_sep>//
// Algorithm.swift
// Study Flash
//
// Created by 李宇恒 on 13/6/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
enum Stages {
case revision(daysRevision: Int)
case simulation(daysSimulation: Double)
}
class Algorithm {
public func getSchedule(forQuestions allQuestions: [Int], totalDays: Double) -> [[Int]] {
let questionsCount = allQuestions.count //how many questions in question bank
let daysLeft = totalDays //must be larger than 1
//Return how many days for simulation
let daysSimulation = defineDaysSimulation(daysLeft).rounded()
//Return how many days for revision
let daysRevision = Int(daysLeft - daysSimulation)
// print("days for revision:",daysRevision)
var recallTime = 0 //how many times that the same question appear
//Calculate the repetition frequency
switch daysRevision {
case 0..<3:
recallTime = 1
case 3..<7:
recallTime = 2
case 7..<14:
recallTime = 3
case 14..<26:
recallTime = 4
default:
recallTime = 5
}
// print("recall time:",recallTime)
//Return number of group
let groupOfQuestion = grouppingQuestions(daysRevision)
// print("number of groups:",groupOfQuestion)
//The range of group
let groupRange = 0 ..< groupOfQuestion
var questionId = 0
var groupInQuestions = [Int]()
//Create items based on quantity of questions
groupInQuestions = Array(repeating: 0, count: questionsCount)
//Assign group for all the questions
while questionId < questionsCount {
for g in groupRange {
if questionId >= questionsCount {
continue
}
groupInQuestions[questionId] += g
questionId += 1
}
}
var groupInDay = [[Int]]()
let dayRange = 0..<daysRevision
//Create arrays based on number of revision days
for _ in dayRange {
groupInDay.append([])
}
var repetition = 0 //x-th time that the question displayed
var r = repetitionMode(repetition: repetition)
//Assign group in each day
while repetition < recallTime {
for g in groupRange {
groupInDay[g+r] += [g]
}
repetition += 1
r = repetitionMode(repetition: repetition)
}
//Put questionId in each group
var questionsInGroup = [[Int]]()
for _ in groupRange {
questionsInGroup.append([])
}
var value = 0
while value < groupOfQuestion {
for (i, group) in groupInQuestions.enumerated() {
if group == value {
questionsInGroup[value].append(i)
}
}
value += 1
}
//Put questionId in everyday
var questionIdInDay = [[Int]]()
for _ in dayRange {
questionIdInDay.append([])
}
var initialValue = 0
while initialValue < groupOfQuestion {
for (i, day) in groupInDay.enumerated() {
if day.contains(initialValue) {
questionIdInDay[i] += questionsInGroup[initialValue]
}
}
initialValue += 1
}
return questionIdInDay
}
//Return which day to revise based on spaced repetition
private func repetitionMode(repetition: Int) -> Int {
if repetition == 0 {
return 0
} else if repetition == 1 {
return 1
} else if repetition == 2 {
return 4
} else if repetition == 3 {
return 10
} else {
return 18
}
}
//Calculate how many groups for questions
private func grouppingQuestions(_ daysRevision: Int) -> Int {
if daysRevision < 3 {
return daysRevision
} else if daysRevision < 7 {
return daysRevision - 1
} else if daysRevision < 14 {
return daysRevision - 4
} else if daysRevision < 26 {
return daysRevision - 10
} else {
return daysRevision - 18
}
}
//Calculate how many days for simulation
private func defineDaysSimulation(_ daysLeft: Double) -> Double {
if daysLeft > 7.0 {
return (daysLeft/7.0)
} else {
return 1.0
}
}
}
<file_sep>//
// OnboardingPage1.swift
// Study Flash
//
// Created by <NAME> on 5/24/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class OnboardingPage4: UICollectionViewCell {
var delegate: CustomCollectionViewCellDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
let imageOfOnboarding = UIImageView(image: UIImage(named: "OnboardingImage4"))
imageOfOnboarding.setOnboardingImage()
let titleOfOnboarding = UILabel()
titleOfOnboarding.setOnboardingTitleFormat()
titleOfOnboarding.text = "Performance Analysis"
let descriptionOfOnboarding = UILabel()
descriptionOfOnboarding.setOnboardingDescription()
descriptionOfOnboarding.text = "Review results to know your strengths and weaknesses."
let stackView = UIStackView()
stackView.setOnboardingStackView()
stackView.addArrangedSubview(imageOfOnboarding)
stackView.addArrangedSubview(titleOfOnboarding)
stackView.addArrangedSubview(descriptionOfOnboarding)
stackView.setCustomSpacing(40, after: stackView.subviews[0])
stackView.setCustomSpacing(20, after: stackView.subviews[1])
let startButton = UIButton()
startButton.backgroundColor = UIColor.primaryThemeColor
startButton.frame = .zero
startButton.tintColor = .white
startButton.setTitle("Let's start", for: .normal)
startButton.titleLabel?.lineBreakMode = .byWordWrapping
startButton.titleLabel?.textAlignment = .center
startButton.titleLabel?.font = .boldSystemFont(ofSize: 16)
startButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
startButton.titleEdgeInsets = UIEdgeInsets(top: -10,left: -10,bottom: startButton.titleEdgeInsetBottom, right: -10)
startButton.contentEdgeInsets = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10)
startButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
addSubview(startButton)
//adding constraint
imageOfOnboarding.widthAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
imageOfOnboarding.heightAnchor.constraint(lessThanOrEqualToConstant: 200).isActive = true
//Anchor
titleOfOnboarding.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
descriptionOfOnboarding.leftAnchor.constraint(equalTo: stackView.leftAnchor, constant: 20).isActive = true
descriptionOfOnboarding.rightAnchor.constraint(equalTo: stackView.rightAnchor, constant: -20).isActive = true
descriptionOfOnboarding.widthAnchor.constraint(equalToConstant: 340).isActive = true
stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
stackView.topAnchor.constraint(greaterThanOrEqualTo: self.topAnchor, constant: 100).isActive = true
startButton.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
startButton.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
startButton.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
startButton.heightAnchor.constraint(equalToConstant: startButton.height).isActive = true
}
@objc private func buttonAction(sender: UIButton!) {
sender.flash()
let mydata = "Anydata you want to send to the next controller"
if (self.delegate != nil) {
self.delegate.presentNewViewController(myData: mydata as AnyObject)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>//
// LoginViewController.swift
// Study Flash
//
// Created by <NAME> on 29/9/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
stateManager.logState = .loggedOut
checkLogState()
self.navigationItem.title = "Profile"
}
private func checkLogState() {
// Check sign in or not
if stateManager.logState == .loggedIn {
performSegue(withIdentifier: "goToProfilePage", sender: self)
}
}
@IBAction func tappedOnSignUpButton(_ sender: Any) {
guard let vc = storyboard?.instantiateViewController(identifier: "SignUpViewController",
creator: {coder in
return SignUpViewController(coder: coder, persistenceManager: PersistenceManager.shared)
}) else {
fatalError("Failed to load SignupView Controller from storyboard")
}
self.present(vc, animated: true, completion: nil)
}
}
| 9c1004eb8267eea01e23eec0508d384a59e84dbd | [
"Swift"
] | 41 | Swift | alexxcheung/StudyFlashV2 | aa72e00d5b0e678295d3b1c707b5e3a4b0d03b73 | e30c1b41266228f4c2dccb33e03ffde44b0c0c3a |
refs/heads/master | <file_sep>#include "kalman_filter.h"
#include "tools.h"
#include <iostream>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;
KalmanFilter::KalmanFilter() {}
KalmanFilter::~KalmanFilter() {}
void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in,
MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) {
x_ = x_in;
P_ = P_in;
F_ = F_in;
H_ = H_in;
R_ = R_in;
Q_ = Q_in;
}
void KalmanFilter::Predict() {
/**
TODO:
* predict the state
*/
x_ = F_ * x_;
MatrixXd Ft_ = F_.transpose();
P_ = F_ * P_ * Ft_ + Q_;
}
void KalmanFilter::Update(const VectorXd &z) {
/**
TODO:
* update the state by using Kalman Filter equations
*/
VectorXd z_pred = H_ * x_;
VectorXd y = z - z_pred;
MatrixXd Ht = H_.transpose();
MatrixXd S = H_ * P_ * Ht + R_;
MatrixXd Si = S.inverse();
MatrixXd K = P_ * Ht * Si;
//new state
cout << "what is y value " << y << endl;
x_ = x_ + (K * y);
long x_size = x_.size();
MatrixXd I;
I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_) * P_;
}
void KalmanFilter::UpdateEKF(const VectorXd &z) {
/**
TODO:
* update the state by using Extended Kalman Filter equations
* z = raw_measurement input(ro,phi,ro dot)
*/
Tools tools;
//cartesian to polar
VectorXd h_ = tools.CalculateHX(x_);
VectorXd y = z - h_;
if (y(1)>M_PI){
y(1) -= 2*M_PI;
}
if (y(1)<-M_PI){
y(1) += 2*M_PI;
}
MatrixXd H_ = tools.CalculateJacobian(x_);
MatrixXd Ht = H_.transpose();
MatrixXd S = H_ * P_ * Ht + R_;
MatrixXd Si = S.inverse();
MatrixXd K = P_ * Ht * Si;
//new state
cout << "what is y value " << y << endl;
cout << "what is K value " << K << endl;
cout << "what is S value " << S << endl;
cout << "what is H_ value " << H_ << endl;
cout << "what is P_ value " << P_ << endl;
x_ = x_ + (K * y);
long x_size = x_.size();
MatrixXd I;
I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_) * P_;
}
<file_sep># Extended Kalman Filter Project Starter Code
Self-Driving Car Engineer Nanodegree Program_JAY
---
## Dependencies
* cmake >= 3.5
* All OSes: [click here for installation instructions](https://cmake.org/install/)
* make >= 4.1
* Linux: make is installed by default on most Linux distros
* Mac: [install Xcode command line tools to get make](https://developer.apple.com/xcode/features/)
* Windows: [Click here for installation instructions](http://gnuwin32.sourceforge.net/packages/make.htm)
* gcc/g++ >= 5.4
* Linux: gcc / g++ is installed by default on most Linux distros
* Mac: same deal as make - [install Xcode command line tools]((https://developer.apple.com/xcode/features/)
* Windows: recommend using [MinGW](http://www.mingw.org/)
## Basic Build Instructions
1. Clone this repo.
2. Make a build directory: `mkdir build && cd build`
3. Compile: 'cd /Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/src'
then, `cmake .. && make`
<!-- * On windows, you may need to run: `cmake .. -G "Unix Makefiles" && make` -->
4. Run it: `./src /Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/data/sample-laser-radar-measurement-data-1.txt /Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/data/output.txt`.
## Achieved RSME:
Accuracy - RMSE:
0.0651649
0.0605378
0.54319
0.544191
5. Test with a simulator
* /Users/Jay/anaconda/envs/yourNewEnvironment/bin/python /Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/kalman-tracker.py /Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/data/src
6. Run simulator
7. Save record data in the directory below (where the input data saved, /Users/Jay/Desktop/Udacity/Self_driving_Car/CarND-Extended-Kalman-Filter/src/)
8. Simulator press run. then, Kalman filter tracking dot will be appeared on the simulator
9. Modify C++ code if kalman filter is not correctly tracking.
## Main point
- Angle normalisation ( -M_PI <= phi range <= M_PI )
- Prevent division by zero
## Submission Video
https://www.youtube.com/watch?v=yaOqSoC7j8I
<file_sep># The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
"/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/FusionEKF.cpp" "/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/data/CMakeFiles/src.dir/FusionEKF.cpp.o"
"/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/kalman_filter.cpp" "/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/data/CMakeFiles/src.dir/kalman_filter.cpp.o"
"/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/main.cpp" "/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/data/CMakeFiles/src.dir/main.cpp.o"
"/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/tools.cpp" "/Users/JAY/Desktop/Udacity/Self_Driving_Car/CarND-Extended-Kalman-Filter-P6/data/CMakeFiles/src.dir/tools.cpp.o"
)
set(CMAKE_CXX_COMPILER_ID "AppleClang")
# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
| dad9047ccbb155ce588b2a4cf4d7c3de68e6851b | [
"Markdown",
"CMake",
"C++"
] | 3 | C++ | youngkil9999/Self-Driving-P6-Extended-Kalman-Filter | 79fadaa8c24f2bc550c61671e53710023dbe5847 | 3585a16f300d57c4fab802dad343130ede90c3d4 |
refs/heads/master | <file_sep>package uam.com.br.aps_application;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class GeraisActivity extends AppCompatActivity {
private Button botaoPreco, botaoAlimentacao, botaoLocalizacao;
private TextView txtVisual;
private ImageView imagemVoltar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gerais);
botaoPreco = findViewById(R.id.btnPreco);
botaoAlimentacao = findViewById(R.id.btnFood);
botaoLocalizacao = findViewById(R.id.btnLocalizacao);
imagemVoltar = findViewById(R.id.imgVoltar);
txtVisual = findViewById(R.id.txtVisual);
Intent intent = getIntent();
String mensagem = intent.getStringExtra("Local");
txtVisual.setText(mensagem);
}
}
<file_sep># APS_Application
Projeto de desenvolvimento móvel.
| 844531f46f0f2a014aa32b1a6b17c3a4bbe92e05 | [
"Markdown",
"Java"
] | 2 | Java | igorpompeo/APS_Application | 217d5362c32db102dc3399534ca4ff7e165bc194 | c8869f1eda01e7c043baf5a0bdf99584515fdde1 |
refs/heads/master | <file_sep><?php
namespace Kirby\Image;
use PHPUnit\Framework\TestCase;
class DimensionsTest extends TestCase
{
public function testDimensions()
{
$dimensions = new Dimensions(1200, 768);
$this->assertEquals(1200, $dimensions->width());
$this->assertEquals(768, $dimensions->height());
}
public function testRatio()
{
$dimensions = new Dimensions(1200, 768);
$this->assertEquals(1.5625, $dimensions->ratio());
$dimensions = new Dimensions(768, 1200);
$this->assertEquals(0.64, $dimensions->ratio());
$dimensions = new Dimensions(0, 0);
$this->assertEquals(0, $dimensions->ratio());
}
public function testFit()
{
// zero dimensions
$dimensions = new Dimensions(0, 0);
$dimensions->fit(500);
$this->assertEquals(500, $dimensions->width());
$this->assertEquals(500, $dimensions->height());
// wider than tall
$dimensions = new Dimensions(1200, 768);
$dimensions->fit(500);
$this->assertEquals(500, $dimensions->width());
$this->assertEquals(320, $dimensions->height());
// taller than wide
$dimensions = new Dimensions(768, 1200);
$dimensions->fit(500);
$this->assertEquals(320, $dimensions->width());
$this->assertEquals(500, $dimensions->height());
// width = height but bigger than box
$dimensions = new Dimensions(1200, 1200);
$dimensions->fit(500);
$this->assertEquals(500, $dimensions->width());
$this->assertEquals(500, $dimensions->height());
// smaller than new size
$dimensions = new Dimensions(300, 200);
$dimensions->fit(500);
$this->assertEquals(300, $dimensions->width());
$this->assertEquals(200, $dimensions->height());
}
public function testFitForce()
{
// wider than tall
$dimensions = new Dimensions(1200, 768);
$dimensions->fit(2000, true);
$this->assertEquals(2000, $dimensions->width());
$this->assertEquals(1280, $dimensions->height());
// taller than wide
$dimensions = new Dimensions(768, 1200);
$dimensions->fit(2000, true);
$this->assertEquals(1280, $dimensions->width());
$this->assertEquals(2000, $dimensions->height());
}
public function testFitWidth()
{
$dimensions = new Dimensions(1200, 768);
$dimensions->fitWidth(0);
$this->assertEquals(1200, $dimensions->width());
$this->assertEquals(768, $dimensions->height());
$dimensions = new Dimensions(1200, 768);
$dimensions->fitWidth(500);
$this->assertEquals(500, $dimensions->width());
$this->assertEquals(320, $dimensions->height());
// no upscale
$dimensions = new Dimensions(1200, 768);
$dimensions->fitWidth(2000);
$this->assertEquals(1200, $dimensions->width());
$this->assertEquals(768, $dimensions->height());
// force upscale
$dimensions = new Dimensions(1200, 768);
$dimensions->fitWidth(2000, true);
$this->assertEquals(2000, $dimensions->width());
$this->assertEquals(1280, $dimensions->height());
}
public function testFitHeight()
{
$dimensions = new Dimensions(1200, 768);
$dimensions->fitHeight(0);
$this->assertEquals(1200, $dimensions->width());
$this->assertEquals(768, $dimensions->height());
$dimensions = new Dimensions(1200, 768);
$dimensions->fitHeight(500);
$this->assertEquals(781, $dimensions->width());
$this->assertEquals(500, $dimensions->height());
// no upscale
$dimensions = new Dimensions(1200, 768);
$dimensions->fitHeight(2000);
$this->assertEquals(1200, $dimensions->width());
$this->assertEquals(768, $dimensions->height());
// force upscale
$dimensions = new Dimensions(1200, 768);
$dimensions->fitHeight(2000, true);
$this->assertEquals(3125, $dimensions->width());
$this->assertEquals(2000, $dimensions->height());
}
public function testFitWidthAndHeight()
{
$dimensions = new Dimensions(1200, 768);
$dimensions->fitWidthAndHeight(1000, 500);
$this->assertEquals(781, $dimensions->width());
$this->assertEquals(500, $dimensions->height());
$dimensions = new Dimensions(768, 1200);
$dimensions->fitWidthAndHeight(500, 1000);
$this->assertEquals(500, $dimensions->width());
$this->assertEquals(781, $dimensions->height());
}
public function testResize()
{
$dimensions = new Dimensions(1200, 768);
$dimensions->resize(2000, 800, true);
$this->assertEquals(1250, $dimensions->width());
$this->assertEquals(800, $dimensions->height());
}
public function testCrop()
{
$dimensions = new Dimensions(1200, 768);
$dimensions->crop(1000, 500);
$this->assertEquals(1000, $dimensions->width());
$this->assertEquals(500, $dimensions->height());
$dimensions = new Dimensions(1200, 768);
$dimensions->crop(500);
$this->assertEquals(500, $dimensions->width());
$this->assertEquals(500, $dimensions->height());
}
public function testOrientation()
{
$dimensions = new Dimensions(1200, 768);
$this->assertEquals('landscape', $dimensions->orientation());
$dimensions = new Dimensions(768, 1200);
$this->assertEquals('portrait', $dimensions->orientation());
$dimensions = new Dimensions(1200, 1200);
$this->assertEquals('square', $dimensions->orientation());
$this->assertTrue($dimensions->square());
$dimensions = new Dimensions(0, 0);
$this->assertFalse($dimensions->orientation());
}
public function testArray()
{
$dimensions = new Dimensions(1200, 768);
$array = [
'width' => 1200,
'height' => 768,
'ratio' => 1.5625,
'orientation' => 'landscape'
];
$this->assertEquals($array, $dimensions->toArray());
$this->assertEquals($array, $dimensions->__debuginfo());
}
public function testString()
{
$dimensions = new Dimensions(1200, 768);
$this->assertEquals('1200 × 768', (string)$dimensions);
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class IteratorTest extends TestCase
{
public function testKey()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
]);
$this->assertEquals('one', $iterator->key());
}
public function testKeys()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei'
]);
$this->assertEquals([
'one',
'two',
'three'
], $iterator->keys());
}
public function testCurrent()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
]);
$this->assertEquals('eins', $iterator->current());
}
public function testPrevNext()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei'
]);
$this->assertEquals('eins', $iterator->current());
$iterator->next();
$this->assertEquals('zwei', $iterator->current());
$iterator->next();
$this->assertEquals('drei', $iterator->current());
$iterator->prev();
$this->assertEquals('zwei', $iterator->current());
$iterator->prev();
$this->assertEquals('eins', $iterator->current());
}
public function testRewind()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei'
]);
$iterator->next();
$iterator->next();
$this->assertEquals('drei', $iterator->current());
$iterator->rewind();
$this->assertEquals('eins', $iterator->current());
}
public function testValid()
{
$iterator = new Iterator([]);
$this->assertFalse($iterator->valid());
$iterator = new Iterator(['one' => 'eins']);
$this->assertTrue($iterator->valid());
}
public function testCount()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei'
]);
$this->assertEquals(3, $iterator->count());
$iterator = new Iterator(['one' => 'eins']);
$this->assertEquals(1, $iterator->count());
$iterator = new Iterator([]);
$this->assertEquals(0, $iterator->count());
}
public function testIndexOf()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei'
]);
$this->assertEquals(0, $iterator->indexOf('eins'));
$this->assertEquals(1, $iterator->indexOf('zwei'));
$this->assertEquals(2, $iterator->indexOf('drei'));
}
public function testKeyOf()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei'
]);
$this->assertEquals('one', $iterator->keyOf('eins'));
$this->assertEquals('two', $iterator->keyOf('zwei'));
$this->assertEquals('three', $iterator->keyOf('drei'));
}
public function testHas()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertTrue($iterator->has('one'));
$this->assertTrue($iterator->has('two'));
$this->assertFalse($iterator->has('three'));
}
public function testIsset()
{
$iterator = new Iterator([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertTrue(isset($iterator->one));
$this->assertTrue(isset($iterator->two));
$this->assertFalse(isset($iterator->three));
}
public function testDebuginfo()
{
$array = [
'one' => 'eins',
'two' => 'zwei'
];
$iterator = new Iterator($array);
$this->assertEquals($array, $iterator->__debuginfo());
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class CollectionConverterTest extends TestCase
{
public function testToArray()
{
$array = [
'one' => 'eins',
'two' => 'zwei'
];
$collection = new Collection($array);
$this->assertEquals($array, $collection->toArray());
}
public function testToArrayMap()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals([
'one' => 'einsy',
'two' => 'zweiy'
], $collection->toArray(function ($item) {
return $item . 'y';
}));
}
public function testToJson()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('{"one":"eins","two":"zwei"}', $collection->toJson());
}
public function testToString()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$string = 'one<br />two';
$this->assertEquals($string, $collection->toString());
$this->assertEquals($string, (string)$collection);
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class MockObject
{
protected $value;
public function __construct(string $value)
{
$this->value = $value;
}
public function __toString() {
return (string)$this->value;
}
}
class CollectionSorterTest extends TestCase
{
public function testSortBy()
{
$collection = new Collection([
[
'name' => 'Bastian',
'role' => 'developer',
'color' => 'red'
],
[
'name' => 'Nico',
'role' => 'developer',
'color' => 'green'
],
[
'name' => 'nico',
'role' => 'support',
'color' => 'blue'
],
[
'name' => 'Sonja',
'role' => 'support',
'color' => 'red'
]
]);
$sorted = $collection->sortBy('name', 'asc');
$this->assertEquals('Bastian', $sorted->nth(0)['name']);
$this->assertEquals('green', $sorted->nth(1)['color']);
$this->assertEquals('blue', $sorted->nth(2)['color']);
$this->assertEquals('Sonja', $sorted->nth(3)['name']);
$sorted = $collection->sortBy('name', 'desc');
$this->assertEquals('Bastian', $sorted->last()['name']);
$this->assertEquals('Sonja', $sorted->first()['name']);
$sorted = $collection->sortBy('name', 'asc', 'color', SORT_ASC);
$this->assertEquals('blue', $sorted->nth(1)['color']);
$this->assertEquals('green', $sorted->nth(2)['color']);
$sorted = $collection->sortBy('name', 'asc', 'color', SORT_DESC);
$this->assertEquals('green', $sorted->nth(1)['color']);
$this->assertEquals('blue', $sorted->nth(2)['color']);
}
public function testSortByFlags()
{
$collection = new Collection([
['name' => 'img12.png'],
['name' => 'img10.png'],
['name' => 'img2.png'],
['name' => 'img1.png']
]);
$sorted = $collection->sortBy('name', 'asc', SORT_REGULAR);
$this->assertEquals('img1.png', $sorted->nth(0)['name']);
$this->assertEquals('img10.png', $sorted->nth(1)['name']);
$this->assertEquals('img12.png', $sorted->nth(2)['name']);
$this->assertEquals('img2.png', $sorted->nth(3)['name']);
$sorted = $collection->sortBy('name', SORT_NATURAL);
$this->assertEquals('img1.png', $sorted->nth(0)['name']);
$this->assertEquals('img2.png', $sorted->nth(1)['name']);
$this->assertEquals('img10.png', $sorted->nth(2)['name']);
$this->assertEquals('img12.png', $sorted->nth(3)['name']);
$sorted = $collection->sortBy('name', SORT_NATURAL, 'desc');
$this->assertEquals('img12.png', $sorted->nth(0)['name']);
$this->assertEquals('img10.png', $sorted->nth(1)['name']);
$this->assertEquals('img2.png', $sorted->nth(2)['name']);
$this->assertEquals('img1.png', $sorted->nth(3)['name']);
}
public function testSortCases()
{
$collection = new Collection([
['name' => 'a'],
['name' => 'c'],
['name' => 'A'],
['name' => 'b']
]);
$sorted = $collection->sortBy('name', 'asc');
$this->assertEquals('A', $sorted->nth(0)['name']);
$this->assertEquals('a', $sorted->nth(1)['name']);
$this->assertEquals('b', $sorted->nth(2)['name']);
$this->assertEquals('c', $sorted->nth(3)['name']);
}
public function testSortIntegers()
{
$collection = new Collection([
['number' => 12],
['number' => 1],
['number' => 10],
['number' => 2]
]);
$sorted = $collection->sortBy('number', 'asc');
$this->assertEquals(1, $sorted->nth(0)['number']);
$this->assertEquals(2, $sorted->nth(1)['number']);
$this->assertEquals(10, $sorted->nth(2)['number']);
$this->assertEquals(12, $sorted->nth(3)['number']);
}
public function testSortByZeros()
{
$collection = new Collection([
[
'title' => '1',
'number' => 0
],
[
'title' => '2',
'number' => 0
],
[
'title' => '3',
'number' => 0
],
[
'title' => '4',
'number' => 0
]
]);
$sorted = $collection->sortBy('number', 'asc');
$this->assertEquals('1', $sorted->nth(0)['title']);
$this->assertEquals('2', $sorted->nth(1)['title']);
$this->assertEquals('3', $sorted->nth(2)['title']);
$this->assertEquals('4', $sorted->nth(3)['title']);
}
public function testSortByCallable()
{
$collection = new Collection([
[
'title' => 'Second Article',
'date' => '2019-10-01 10:04',
'tags' => 'test'
],
[
'title' => 'First Article',
'date' => '2018-31-12 00:00',
'tags' => 'test'
],
[
'title' => 'Third Article',
'date' => '01.10.2019 10:05',
'tags' => 'test'
]
]);
$sorted = $collection->sortBy(function ($value) {
$this->assertEquals('test', $value['tags']);
return strtotime($value['date']);
}, 'asc');
$this->assertEquals('First Article', $sorted->nth(0)['title']);
$this->assertEquals('Second Article', $sorted->nth(1)['title']);
$this->assertEquals('Third Article', $sorted->nth(2)['title']);
$sorted = $collection->sortBy(function ($value) {
$this->assertEquals('test', $value['tags']);
return strtotime($value['date']);
}, 'desc');
$this->assertEquals('Third Article', $sorted->nth(0)['title']);
$this->assertEquals('Second Article', $sorted->nth(1)['title']);
$this->assertEquals('First Article', $sorted->nth(2)['title']);
}
public function testSortByEmpty()
{
$collection = new Collection();
$this->assertEquals($collection, $collection->sortBy());
}
public function testSortObjects()
{
$bastian = new MockObject('Bastian');
$nico = new MockObject('Nico');
$sonja = new MockObject('Sonja');
$collection = new Collection([
['name' => $nico],
['name' => $bastian],
['name' => $sonja]
]);
$sorted = $collection->sortBy('name', 'asc');
$this->assertEquals($bastian, $sorted->nth(0)['name']);
$this->assertEquals($nico, $sorted->nth(1)['name']);
$this->assertEquals($sonja, $sorted->nth(2)['name']);
}
public function testFlip()
{
$collection = new Collection([
['name' => 'img12.png'],
['name' => 'img10.png'],
['name' => 'img2.png']
]);
$sorted = $collection->sortBy('name', 'asc');
$this->assertEquals('img12.png', $collection->first(0)['name']);
$this->assertEquals('img10.png', $collection->nth(1)['name']);
$this->assertEquals('img2.png', $collection->nth(2)['name']);
$flipped = $collection->flip();
$this->assertEquals('img2.png', $flipped->nth(0)['name']);
$this->assertEquals('img10.png', $flipped->nth(1)['name']);
$this->assertEquals('img12.png', $flipped->nth(2)['name']);
}
public function testShuffle()
{
$collection = new Collection([
['name' => 'img12.png'],
['name' => 'img10.png'],
['name' => 'img2.png']
]);
$shuffled = $collection->shuffle();
$this->assertEquals(3, $shuffled->count());
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class ObjTest extends TestCase
{
public function test__call()
{
$obj = new Obj([
'foo' => 'bar'
]);
$this->assertEquals('bar', $obj->foo());
}
public function test__get()
{
$obj = new Obj();
$this->assertNull($obj->foo);
}
public function testToArray()
{
$obj = new Obj($expected = [
'foo' => 'bar'
]);
$this->assertEquals($expected, $obj->toArray());
}
public function testToArrayWithChild()
{
$parent = new Obj([
'child' => new Obj([
'foo' => 'bar'
])
]);
$expected = [
'child' => [
'foo' => 'bar'
]
];
$this->assertEquals($expected, $parent->toArray());
}
public function testToJson()
{
$obj = new Obj($expected = [
'foo' => 'bar'
]);
$this->assertEquals(json_encode($expected), $obj->toJson());
}
public function test__debuginfo()
{
$obj = new Obj($expected = [
'foo' => 'bar'
]);
$this->assertEquals($expected, $obj->__debuginfo());
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class CollectionNavigatorTest extends TestCase
{
public function testFirstLast()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier'
]);
$this->assertEquals('eins', $collection->first());
$this->assertEquals('vier', $collection->last());
}
public function testNth()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier'
]);
$this->assertEquals('eins', $collection->nth(0));
$this->assertEquals('zwei', $collection->nth(1));
$this->assertEquals('drei', $collection->nth(2));
$this->assertEquals('vier', $collection->nth(3));
}
}
<file_sep><?php
namespace Kirby\Cms;
class SiteContentTest extends TestCase
{
public function testDefaultContent()
{
$site = new Site();
$this->assertInstanceOf(Content::class, $site->content());
}
public function testContent()
{
$content = [
'text' => 'lorem ipsum'
];
$site = new Site([
'content' => $content
]);
$this->assertEquals($content, $site->content()->toArray());
$this->assertEquals('lorem ipsum', $site->text()->value());
}
/**
* @expectedException TypeError
*/
public function testInvalidContent()
{
$site = new Site([
'content' => 'content'
]);
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Cms\Page;
use Kirby\Form\Field;
class InfoFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('info');
$this->assertEquals('info', $field->type());
$this->assertEquals('info', $field->name());
$this->assertEquals(null, $field->value());
$this->assertEquals(null, $field->label());
$this->assertEquals(null, $field->text());
$this->assertFalse($field->save());
}
public function testText()
{
// simple text
$field = new Field('info', [
'text' => 'test'
]);
$this->assertEquals('<p>test</p>', $field->text());
// translated text
$field = new Field('info', [
'text' => [
'en' => 'en',
'de' => 'de'
]
]);
$this->assertEquals('<p>en</p>', $field->text());
// text template
$field = new Field('info', [
'text' => '{{ page.title }}',
'model' => new Page([
'slug' => 'test',
'content' => [
'title' => 'Test'
]
])
]);
$this->assertEquals('<p>Test</p>', $field->text());
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
class HiddenFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('hidden');
$this->assertEquals('hidden', $field->type());
$this->assertEquals('hidden', $field->name());
$this->assertEquals(null, $field->value());
$this->assertTrue($field->save());
}
}
<file_sep><?php
namespace Kirby\Form;
use Kirby\Cms\App;
use Kirby\Data\Yaml;
use PHPUnit\Framework\TestCase;
class FormTest extends TestCase
{
public function testDataWithoutFields()
{
$form = new Form([
'fields' => [],
'values' => $values = [
'a' => 'A',
'b' => 'B'
]
]);
$this->assertEquals($values, $form->data());
}
public function testValuesWithoutFields()
{
$form = new Form([
'fields' => [],
'values' => $values = [
'a' => 'A',
'b' => 'B'
]
]);
$this->assertEquals($values, $form->values());
}
public function testDataFromNestedFields()
{
new App([
'roots' => [
'index' => '/dev/null'
]
]);
$form = new Form([
'fields' => [
'structure' => [
'type' => 'structure',
'fields' => [
'tags' => [
'type' => 'tags'
]
]
]
],
'values' => $values = [
'structure' => [
[
'tags' => 'a, b'
]
]
]
]);
$expected = [
'structure' => [
[
'tags' => 'a, b'
]
]
];
$this->assertEquals($expected, $form->data());
}
public function testInvalidFieldType()
{
new App([
'roots' => [
'index' => '/dev/null'
]
]);
$form = new Form([
'fields' => [
'test' => [
'type' => 'does-not-exist'
]
]
]);
$field = $form->fields()->first();
$this->assertEquals('info', $field->type());
$this->assertEquals('negative', $field->theme());
$this->assertEquals('Error in "test" field', $field->label());
$this->assertEquals('<p>The field type "does-not-exist" does not exist</p>', $field->text());
}
public function testFieldOrder()
{
new App([
'roots' => [
'index' => '/dev/null'
]
]);
$form = new Form([
'fields' => [
'a' => [
'type' => 'text'
],
'b' => [
'type' => 'text'
]
],
'values' => [
'c' => 'C',
'b' => 'B',
'a' => 'A',
],
'input' => [
'b' => 'B modified'
]
]);
$this->assertTrue(['a' => 'A', 'b' => 'B modified', 'c' => 'C'] === $form->values());
$this->assertTrue(['a' => 'A', 'b' => 'B modified', 'c' => 'C'] === $form->data());
}
public function testStrictMode()
{
new App([
'roots' => [
'index' => '/dev/null'
]
]);
$form = new Form([
'fields' => [
'a' => [
'type' => 'text'
],
'b' => [
'type' => 'text'
]
],
'values' => [
'b' => 'B',
'a' => 'A'
],
'input' => [
'c' => 'C'
],
'strict' => true
]);
$this->assertTrue(['a' => 'A', 'b' => 'B'] === $form->values());
$this->assertTrue(['a' => 'A', 'b' => 'B'] === $form->data());
}
}
<file_sep><?php
namespace Kirby\Cms;
class UserMethodsTest extends TestCase
{
public function setUp()
{
// make sure field methods are loaded
new App([
'roots' => [
'index' => '/dev/null'
]
]);
}
public function testId()
{
$user = new User([
'id' => 'test',
'email' => '<EMAIL>'
]);
$this->assertEquals('test', $user->id());
}
public function testLanguage()
{
$user = new User([
'email' => '<EMAIL>',
'language' => 'en',
]);
$this->assertEquals('en', $user->language());
}
public function testDefaultLanguage()
{
$user = new User([
'email' => '<EMAIL>',
]);
$this->assertEquals('en', $user->language());
}
public function testRole()
{
$kirby = new App([
'roles' => [
['name' => 'editor', 'title' => 'Editor']
]
]);
$user = new User([
'email' => '<EMAIL>',
'role' => 'editor',
'kirby' => $kirby
]);
$this->assertEquals('editor', $user->role()->name());
}
public function testDefaultRole()
{
$user = new User([
'email' => '<EMAIL>',
]);
$this->assertEquals('nobody', $user->role()->name());
}
}
<file_sep># Kirby
[](https://travis-ci.com/k-next/kirby)
[](https://coveralls.io/github/k-next/kirby?branch=master)
## Feature suggestions
If you want to suggest features or enhancements for Kirby, please use our Ideas repository:
https://github.com/k-next/ideas/issues
## Bug reports
Please post all bug reports in our issue tracker:
https://github.com/k-next/kirby/issues
## Installation
```
composer install
```
## Commands
### Archiving and zipping
To zip the current version and remove all unnecessary files, run the following script:
```
composer run-script zip
```
### Build
To create a current build, run the following script:
```
composer run-script build
```
This will run the following steps:
#### Panel
1. `npm i`
2. `npm run build`
#### Kirby
1. `composer run-script zip`
A `dist.zip` will be saved afterwards in the kirby directory and can be distributed and placed in all kits. This file is ignored by default and should never be added to the repository.
<file_sep><?php
namespace Kirby\Toolkit;
class ComponentTest extends TestCase
{
public function tearDown()
{
Component::$types = [];
Component::$mixins = [];
}
public function testProp()
{
Component::$types = [
'test' => [
'props' => [
'prop' => function ($prop) {
return $prop;
}
]
]
];
$component = new Component('test', ['prop' => 'prop value']);
$this->assertEquals('prop value', $component->prop());
$this->assertEquals('prop value', $component->prop);
}
public function testPropWithDefaultValue()
{
Component::$types = [
'test' => [
'props' => [
'prop' => function ($prop = 'default value') {
return $prop;
}
]
]
];
$component = new Component('test');
$this->assertEquals('default value', $component->prop());
$this->assertEquals('default value', $component->prop);
}
public function testPropWithFixedValue()
{
Component::$types = [
'test' => [
'props' => [
'prop' => 'test'
]
]
];
$component = new Component('test');
$this->assertEquals('test', $component->prop());
$this->assertEquals('test', $component->prop);
}
public function testAttrs()
{
Component::$types = [
'test' => []
];
$component = new Component('test', ['foo' => 'bar']);
$this->assertEquals('bar', $component->foo());
$this->assertEquals('bar', $component->foo);
}
public function testComputed()
{
Component::$types = [
'test' => [
'computed' => [
'prop' => function () {
return 'computed prop';
}
]
]
];
$component = new Component('test');
$this->assertEquals('computed prop', $component->prop());
$this->assertEquals('computed prop', $component->prop);
}
public function testComputedFromProp()
{
Component::$types = [
'test' => [
'props' => [
'prop' => function ($prop) {
return $prop;
}
],
'computed' => [
'prop' => function () {
return 'computed: ' . $this->prop;
}
]
]
];
$component = new Component('test', ['prop' => 'prop value']);
$this->assertEquals('computed: prop value', $component->prop());
}
public function testMethod()
{
Component::$types = [
'test' => [
'methods' => [
'say' => function () {
return 'hello world';
}
]
]
];
$component = new Component('test');
$this->assertEquals('hello world', $component->say());
}
public function testPropsInMethods()
{
Component::$types = [
'test' => [
'props' => [
'message' => function ($message) {
return $message;
}
],
'methods' => [
'say' => function () {
return $this->message;
}
]
]
];
$component = new Component('test', ['message' => 'hello world']);
$this->assertEquals('hello world', $component->say());
}
public function testComputedPropsInMethods()
{
Component::$types = [
'test' => [
'props' => [
'message' => function ($message) {
return $message;
}
],
'computed' => [
'message' => function () {
return strtoupper($this->message);
},
],
'methods' => [
'say' => function () {
return $this->message;
}
]
]
];
$component = new Component('test', ['message' => 'hello world']);
$this->assertEquals('HELLO WORLD', $component->say());
}
public function testToArray()
{
Component::$types = [
'test' => [
'props' => [
'message' => function ($message) {
return $message;
}
],
'computed' => [
'message' => function () {
return strtoupper($this->message);
},
],
'methods' => [
'say' => function () {
return $this->message;
}
]
]
];
$component = new Component('test', ['message' => 'hello world']);
$this->assertEquals(['message' => 'HELLO WORLD'], $component->toArray());
}
public function testCustomToArray()
{
Component::$types = [
'test' => [
'toArray' => function () {
return [
'foo' => 'bar'
];
}
]
];
$component = new Component('test');
$this->assertEquals(['foo' => 'bar'], $component->toArray());
}
/**
* @expectedException Kirby\Exception\InvalidArgumentException
* @expectedExceptionMessage Undefined component type: test
*
*/
public function testInvalidType()
{
$component = new Component('test');
}
public function testMixins()
{
Component::$mixins = [
'test' => [
'computed' => [
'message' => function () {
return strtoupper($this->message);
}
]
]
];
Component::$types = [
'test' => [
'mixins' => ['test'],
'props' => [
'message' => function ($message) {
return $message;
}
]
]
];
$component = new Component('test', ['message' => 'hello world']);
$this->assertEquals('HELLO WORLD', $component->message());
$this->assertEquals('HELLO WORLD', $component->message);
}
}
<file_sep><?php
namespace Kirby\Cms;
class RolesTest extends TestCase
{
public function testFactory()
{
$roles = Roles::factory([
[
'name' => 'editor',
'title' => 'Editor'
]
]);
$this->assertInstanceOf(Roles::class, $roles);
// should contain the editor role from fixtures and the default admin role
$this->assertCount(2, $roles);
$this->assertEquals('admin', $roles->first()->name());
$this->assertEquals('editor', $roles->last()->name());
}
public function testLoad()
{
$roles = Roles::load(__DIR__ . '/fixtures/blueprints/users');
$this->assertInstanceOf(Roles::class, $roles);
// should contain the editor role from fixtures and the default admin role
$this->assertCount(2, $roles);
$this->assertEquals('admin', $roles->first()->name());
$this->assertEquals('editor', $roles->last()->name());
}
public function testLoadFromPlugins()
{
$app = new App([
'blueprints' => [
'users/admin' => [
'name' => 'admin',
'title' => 'Admin'
],
'users/editor' => [
'name' => 'editor',
'title' => 'Editor'
],
]
]);
$roles = Roles::load();
$this->assertCount(2, $roles);
$this->assertEquals('admin', $roles->first()->name());
$this->assertEquals('editor', $roles->last()->name());
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
class LineFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('line');
$this->assertEquals('line', $field->type());
$this->assertEquals('line', $field->name());
$this->assertFalse($field->save());
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
class RadioFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('radio');
$this->assertEquals('radio', $field->type());
$this->assertEquals('radio', $field->name());
$this->assertEquals(null, $field->value());
$this->assertEquals(null, $field->icon());
$this->assertEquals([], $field->options());
$this->assertTrue($field->save());
}
public function valueInputProvider()
{
return [
['a', 'a'],
['b', 'b'],
['c', 'c'],
['d', '']
];
}
/**
* @dataProvider valueInputProvider
*/
public function testValue($input, $expected)
{
$field = new Field('radio', [
'options' => [
'a',
'b',
'c'
],
'value' => $input
]);
$this->assertTrue($expected === $field->value());
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class UserPermissionsTest extends TestCase
{
public function actionProvider()
{
return [
['create'],
['changeEmail'],
['changeLanguage'],
['changeName'],
['changePassword'],
['changeRole'],
['delete'],
['update'],
];
}
/**
* @dataProvider actionProvider
*/
public function testWithAdmin($action)
{
$kirby = new App([
'roots' => [
'index' => '/dev/null'
]
]);
$kirby->impersonate('kirby');
$user = new User(['email' => '<EMAIL>']);
$perms = $user->permissions();
$this->assertTrue($perms->can($action));
}
/**
* @dataProvider actionProvider
*/
public function testWithNobody($action)
{
$kirby = new App([
'roots' => [
'index' => '/dev/null'
]
]);
$user = new User(['email' => '<EMAIL>']);
$perms = $user->permissions();
$this->assertFalse($perms->can($action));
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class CollectionFinderTest extends TestCase
{
public function testFindBy()
{
$collection = new Collection([
[
'name' => 'Bastian',
'email' => '<EMAIL>'
],
[
'name' => 'Nico',
'email' => '<EMAIL>'
]
]);
$this->assertEquals([
'name' => 'Bastian',
'email' => '<EMAIL>'
], $collection->findBy('email', '<EMAIL>'));
}
public function testFindKey()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('zwei', $collection->find('two'));
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class SitePermissionsTest extends TestCase
{
public function actionProvider()
{
return [
['changeTitle'],
['update'],
];
}
/**
* @dataProvider actionProvider
*/
public function testWithAdmin($action)
{
$kirby = new App([
'roots' => [
'index' => '/dev/null'
]
]);
$kirby->impersonate('kirby');
$site = new Site;
$perms = $site->permissions();
$this->assertTrue($perms->can($action));
}
/**
* @dataProvider actionProvider
*/
public function testWithNobody($action)
{
$kirby = new App([
'roots' => [
'index' => '/dev/null'
]
]);
$site = new Site;
$perms = $site->permissions();
$this->assertFalse($perms->can($action));
}
}
<file_sep><?php
namespace Kirby\Cms;
class SiteFilesTest extends TestCase
{
public function testDefaultFiles()
{
$site = new Site();
$this->assertInstanceOf(Files::class, $site->files());
}
/**
* @expectedException TypeError
*/
public function testInvalidFiles()
{
$site = new Site([
'files' => 'files'
]);
}
public function testFiles()
{
$site = new Site([
'files' => []
]);
$this->assertInstanceOf(Files::class, $site->files());
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class AppLanguagesTest extends TestCase
{
public function testLanguages()
{
$app = new App([
'languages' => [
[
'code' => 'en',
'name' => 'English',
'default' => true
],
[
'code' => 'de',
'name' => 'Deutsch'
]
]
]);
$this->assertTrue($app->multilang());
$this->assertCount(2, $app->languages());
$this->assertEquals('en', $app->languageCode());
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
class EmailFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('email');
$this->assertEquals('email', $field->type());
$this->assertEquals('email', $field->name());
$this->assertEquals(null, $field->value());
$this->assertEquals('email', $field->icon());
$this->assertEquals('<EMAIL>', $field->placeholder());
$this->assertEquals(null, $field->counter());
$this->assertEquals('email', $field->autocomplete());
$this->assertTrue($field->save());
}
public function testEmailValidation()
{
$field = new Field('email', [
'value' => '<EMAIL>'
]);
$this->assertTrue($field->isValid());
$field = new Field('email', [
'value' => 'mail[at]getkirby.com'
]);
$this->assertFalse($field->isValid());
}
public function testMinLength()
{
$field = new Field('email', [
'value' => '<EMAIL>',
'minlength' => 14
]);
$this->assertFalse($field->isValid());
$this->assertArrayHasKey('minlength', $field->errors());
}
public function testMaxLength()
{
$field = new Field('email', [
'value' => '<EMAIL>',
'maxlength' => 12
]);
$this->assertFalse($field->isValid());
$this->assertArrayHasKey('maxlength', $field->errors());
}
}
<file_sep><?php
namespace Kirby\Cache;
use PHPUnit\Framework\TestCase;
class ValueTest extends TestCase
{
public function testSetup()
{
$value = new Value('foo');
$this->assertEquals('foo', $value->value());
$this->assertEquals(time(), $value->created());
$this->assertEquals(time() + (2628000 * 60), $value->expires());
}
public function testSetupCustomDuration()
{
$value = new Value('foo', 100);
$this->assertEquals(time() + (100 * 60), $value->expires());
}
}
<file_sep><?php
namespace Kirby\Image;
use PHPUnit\Framework\TestCase;
class CameraTest extends TestCase
{
protected function _exif()
{
return [
'Make' => 'Kirby Kamera Inc.',
'Model' => 'Deluxe Snap 3000'
];
}
public function testSetup()
{
$exif = $this->_exif();
$camera = new Camera($exif);
$this->assertEquals($exif['Make'], $camera->make());
$this->assertEquals($exif['Model'], $camera->model());
}
public function testToArray()
{
$exif = $this->_exif();
$camera = new Camera($exif);
$this->assertEquals(array_change_key_case($exif), $camera->toArray());
$this->assertEquals(array_change_key_case($exif), $camera->__debuginfo());
}
public function testToString()
{
$exif = $this->_exif();
$camera = new Camera($exif);
$this->assertEquals('Kirby Kamera Inc. Deluxe Snap 3000', (string)$camera);
}
}
<file_sep><?php
namespace Kirby\Http;
use PHPUnit\Framework\TestCase;
class ParamsTest extends TestCase
{
public function testConstructWithArray()
{
$params = new Params([
'a' => 'value-a',
'b' => 'value-b'
]);
$this->assertEquals('value-a', $params->a);
$this->assertEquals('value-b', $params->b);
}
public function testConstructWithString()
{
$params = new Params('a:value-a/b:value-b');
$this->assertEquals('value-a', $params->a);
$this->assertEquals('value-b', $params->b);
}
public function testConstructWithEmptyValue()
{
$params = new Params('a:/b:');
$this->assertEquals(null, $params->a);
$this->assertEquals(null, $params->b);
}
public function testToString()
{
$params = new Params([
'a' => 'value-a',
'b' => 'value-b'
]);
$this->assertEquals('a:value-a/b:value-b', $params->toString());
}
public function testToStringWithLeadingSlash()
{
$params = new Params([
'a' => 'value-a',
'b' => 'value-b'
]);
$this->assertEquals('/a:value-a/b:value-b', $params->toString(true));
}
public function testToStringWithTrailingSlash()
{
$params = new Params([
'a' => 'value-a',
'b' => 'value-b'
]);
$this->assertEquals('a:value-a/b:value-b/', $params->toString(false, true));
}
public function testToStringWithWindowsSeparator()
{
Params::$separator = ';';
$params = new Params([
'a' => 'value-a',
'b' => 'value-b'
]);
$this->assertEquals('a;value-a/b;value-b/', $params->toString(false, true));
Params::$separator = null;
}
public function testUnsetParam()
{
$params = new Params(['foo' => 'bar']);
$params->foo = null;
$this->assertEquals('', $params->toString());
}
}
<file_sep><?php
namespace Kirby\Form;
use Kirby\Cms\App;
use Kirby\Data\Yaml;
use PHPUnit\Framework\TestCase;
class OptionsTest extends TestCase
{
public function testPages()
{
$app = new App([
'site' => [
'children' => [
[
'slug' => 'a',
'content' => [
'title' => 'Page A'
]
],
[
'slug' => 'b'
],
]
]
]);
$result = Options::query('site.children');
$expected = [
[
'text' => 'Page A',
'value' => 'a'
],
[
'text' => 'b',
'value' => 'b'
]
];
$this->assertEquals($expected, $result);
}
public function testUsers()
{
$app = new App([
'users' => [
[
'email' => '<EMAIL>',
'name' => 'Admin'
],
[
'email' => '<EMAIL>',
]
]
]);
$result = Options::query('users');
$expected = [
[
'text' => 'Admin',
'value' => '<EMAIL>'
],
[
'text' => '<EMAIL>',
'value' => '<EMAIL>'
]
];
$this->assertEquals($expected, $result);
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class CollectionMutatorTest extends TestCase
{
public function testData()
{
$collection = new Collection();
$this->assertEquals([], $collection->data());
$collection->data([
'three' => 'drei'
]);
$this->assertEquals([
'three' => 'drei'
], $collection->data());
$collection->data([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals([
'one' => 'eins',
'two' => 'zwei'
], $collection->data());
}
public function testEmpty()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals([
'one' => 'eins',
'two' => 'zwei'
], $collection->data());
$this->assertEquals([], $collection->empty()->data());
}
public function testSet()
{
$collection = new Collection();
$this->assertEquals(null, $collection->one);
$this->assertEquals(null, $collection->two);
$collection->one = 'eins';
$this->assertEquals('eins', $collection->one);
$collection->set('two', 'zwei');
$this->assertEquals('zwei', $collection->two);
$collection->set([
'three' => 'drei'
]);
$this->assertEquals('drei', $collection->three);
}
public function testAppend()
{
$collection = new Collection([
'one' => 'eins'
]);
$this->assertEquals('eins', $collection->last());
$collection->append('two', 'zwei');
$this->assertEquals('zwei', $collection->last());
}
public function testPrepend()
{
$collection = new Collection([
'one' => 'eins'
]);
$this->assertEquals('eins', $collection->first());
$collection->prepend('zero', 'null');
$this->assertEquals('null', $collection->zero());
}
public function testExtend()
{
$collection = new Collection([
'one' => 'eins'
]);
$result = $collection->extend([
'two' => 'zwei'
]);
$this->assertEquals('eins', $result->one());
$this->assertEquals('zwei', $result->two());
}
public function testRemove()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('zwei', $collection->two());
$collection->remove('two');
$this->assertEquals(null, $collection->two());
}
public function testUnset()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('zwei', $collection->two());
unset($collection->two);
$this->assertEquals(null, $collection->two());
}
public function testMap()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('zwei', $collection->two());
$collection->map(function ($item) {
return $item . '-ish';
});
$this->assertEquals('zwei-ish', $collection->two());
}
public function testPluck()
{
$collection = new Collection([
[
'username' => 'homer',
],
[
'username' => 'marge',
]
]);
$this->assertEquals(['homer', 'marge'], $collection->pluck('username'));
}
public function testPluckAndSplit()
{
$collection = new Collection([
[
'simpsons' => '<NAME>',
],
[
'simpsons' => '<NAME>',
]
]);
$expected = [
'homer', 'marge', 'maggie', 'bart', 'lisa'
];
$this->assertEquals($expected, $collection->pluck('simpsons', ', '));
}
public function testPluckUnique()
{
$collection = new Collection([
[
'user' => 'homer',
],
[
'user' => 'homer',
],
[
'user' => 'marge',
]
]);
$expected = ['homer', 'marge'];
$this->assertEquals($expected, $collection->pluck('user', null, true));
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class CollectionPaginatorTest extends TestCase
{
public function testSlice()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier',
'five' => 'fünf'
]);
$this->assertEquals('drei', $collection->slice(2)->first());
$this->assertEquals('vier', $collection->slice(2, 2)->last());
}
public function testSliceNotReally()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier',
'five' => 'fünf'
]);
$this->assertEquals($collection, $collection->slice());
}
public function testLimit()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier',
'five' => 'fünf'
]);
$this->assertEquals('drei', $collection->limit(3)->last());
$this->assertEquals('fünf', $collection->limit(99)->last());
}
public function testOffset()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier',
'five' => 'fünf'
]);
$this->assertEquals('drei', $collection->offset(2)->first());
$this->assertEquals('vier', $collection->offset(3)->first());
$this->assertEquals(null, $collection->offset(99)->first());
}
public function testPaginate()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier',
'five' => 'fünf'
]);
$this->assertEquals('eins', $collection->paginate(2)->first());
$this->assertEquals('drei', $collection->paginate(2, 2)->first());
$this->assertEquals('eins', $collection->paginate([
'foo' => 'bar'
])->first());
$this->assertEquals('fünf', $collection->paginate([
'limit' => 2,
'page' => 3
])->first());
$this->assertEquals(3, $collection->pagination()->page());
}
public function testChunk()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei',
'three' => 'drei',
'four' => 'vier',
'five' => 'fünf'
]);
$this->assertEquals(3, $collection->chunk(2)->count());
$this->assertEquals('eins', $collection->chunk(2)->first()->first());
$this->assertEquals('fünf', $collection->chunk(2)->last()->first());
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class ContentTranslationTest extends TestCase
{
public function testParentAndCode()
{
$page = new Page([
'slug' => 'test'
]);
$translation = new ContentTranslation([
'parent' => $page,
'code' => 'de'
]);
$this->assertEquals($page, $translation->parent());
$this->assertEquals('de', $translation->code());
}
public function testContentAndSlug()
{
$page = new Page([
'slug' => 'test'
]);
$translation = new ContentTranslation([
'parent' => $page,
'code' => 'de',
'slug' => 'test',
'content' => $content = [
'title' => 'test'
]
]);
$this->assertEquals('test', $translation->slug());
$this->assertEquals($content, $translation->content());
}
public function testContentFile()
{
$app = new App([
'roots' => [
'content' => '/content',
]
]);
$page = new Page([
'slug' => 'test',
'template' => 'project'
]);
$translation = new ContentTranslation([
'parent' => $page,
'code' => 'de',
]);
$this->assertEquals('/content/test/project.de.txt', $translation->contentFile());
}
}
<file_sep><?php
namespace Kirby\Http;
use PHPUnit\Framework\TestCase;
class CookieTest extends TestCase
{
public function testKey()
{
$this->assertEquals('KirbyHttpCookieKey', Cookie::$key);
Cookie::$key = 'KirbyToolkitCookieKey';
$this->assertEquals('KirbyToolkitCookieKey', Cookie::$key);
}
public function testLifetime()
{
$this->assertEquals(12345678901, Cookie::lifetime(12345678901));
$this->assertEquals((600 + time()), Cookie::lifetime(10));
$this->assertEquals(0, Cookie::lifetime(-10));
}
public function testSet()
{
Cookie::set('foo', 'bar');
$this->assertEquals('703a07dc4edca348cb92d9fcb7da1b3931de0a85+bar', $_COOKIE['foo']);
}
public function testForever()
{
Cookie::forever('forever', 'bar');
$this->assertEquals('703a07dc4edca348cb92d9fcb7da1b3931de0a85+bar', $_COOKIE['forever']);
$this->assertTrue(Cookie::exists('forever'));
}
public function testRemove()
{
$this->assertTrue(Cookie::remove('forever'));
$this->assertFalse(isset($_COOKIE['forever']));
$this->assertFalse(Cookie::remove('none'));
}
public function testExists()
{
$this->assertTrue(Cookie::exists('foo'));
$this->assertFalse(Cookie::exists('new'));
}
public function testGet()
{
$this->assertEquals('bar', Cookie::get('foo'));
$this->assertEquals('some amazing default', Cookie::get('does_not_exist', 'some amazing default'));
$this->assertEquals($_COOKIE, Cookie::get());
}
public function testParse()
{
// valid
$_COOKIE['foo'] = '703a07dc4edca348cb92d9fcb7da1b3931de0a85+bar';
$this->assertEquals('bar', Cookie::get('foo'));
// no value
$_COOKIE['foo'] = '21fdd6d0d6f5b4ac8109e5f2d0c3f0f7e8e89492+';
$this->assertEquals('', Cookie::get('foo'));
$_COOKIE['foo'] = '703a07dc4edca348cb92d9fcb7da1b3931de0a85+bar';
$this->assertEquals('bar', Cookie::get('foo'));
// value with a plus sign
$_COOKIE['foo'] = '9c8c403efa31d4e4598d75e9c394b48255b65154+bar+baz';
$this->assertEquals('bar+baz', Cookie::get('foo'));
// separator missing
$_COOKIE['foo'] = '703a07dc4edca348cb92d9fcb7da1b3931de0a85';
$this->assertEquals(null, Cookie::get('foo'));
$_COOKIE['foo'] = '703a07dc4edca348cb92d9fcb7da1b3931de0a85+bar';
$this->assertEquals('bar', Cookie::get('foo'));
// no hash
$_COOKIE['foo'] = '+bar';
$this->assertEquals(null, Cookie::get('foo'));
$_COOKIE['foo'] = '703a07dc4edca348cb92d9fcb7da1b3931de0a85+bar';
$this->assertEquals('bar', Cookie::get('foo'));
// wrong hash
$_COOKIE['foo'] = '040df854f89c9f9ca3490fb950c91ad9aa304c97+bar';
$this->assertEquals(null, Cookie::get('foo'));
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class SiteBlueprintTest extends TestCase
{
public function testOptions()
{
$blueprint = new SiteBlueprint([
'model' => new Site
]);
$expected = [
'changeTitle' => null,
'update' => null,
];
$this->assertEquals($expected, $blueprint->options());
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class UserBlueprintTest extends TestCase
{
public function testOptions()
{
$blueprint = new UserBlueprint([
'model' => new User(['email' => '<EMAIL>'])
]);
$expected = [
'create' => null,
'changeEmail' => null,
'changeLanguage' => null,
'changeName' => null,
'changePassword' => <PASSWORD>,
'changeRole' => null,
'delete' => null,
'update' => null,
];
$this->assertEquals($expected, $blueprint->options());
}
}
<file_sep><?php
namespace Kirby\Cms;
class FileSiblingsTest extends TestCase
{
protected function collection()
{
return [
['filename' => 'cover.jpg', 'template' => 'cover'],
['filename' => 'gallery-1.jpg', 'template' => 'gallery'],
['filename' => 'gallery-2.jpg', 'template' => 'gallery'],
['filename' => 'gallery-3.jpg', 'template' => 'gallery']
];
}
protected function files()
{
return (new Page([
'slug' => 'test',
'files' => $this->collection(),
]))->files();
}
public function testHasNext()
{
$collection = $this->files();
$this->assertTrue($collection->first()->hasNext());
$this->assertFalse($collection->last()->hasNext());
}
public function testHasPrev()
{
$collection = $this->files();
$this->assertTrue($collection->last()->hasPrev());
$this->assertFalse($collection->first()->hasPrev());
}
public function testIndexOf()
{
$collection = $this->files();
$this->assertEquals(0, $collection->first()->indexOf());
$this->assertEquals(1, $collection->nth(1)->indexOf());
$this->assertEquals(3, $collection->last()->indexOf());
}
public function testIsFirst()
{
$collection = $this->files();
$this->assertTrue($collection->first()->isFirst());
$this->assertFalse($collection->last()->isFirst());
}
public function testIsLast()
{
$collection = $this->files();
$this->assertTrue($collection->last()->isLast());
$this->assertFalse($collection->first()->isLast());
}
public function testIsNth()
{
$collection = $this->files();
$this->assertTrue($collection->first()->isNth(0));
$this->assertTrue($collection->nth(1)->isNth(1));
$this->assertTrue($collection->last()->isNth($collection->count() - 1));
}
public function testNext()
{
$collection = $this->files();
$this->assertEquals($collection->first()->next(), $collection->nth(1));
}
public function testNextAll()
{
$collection = $this->files();
$first = $collection->first();
$this->assertCount(3, $first->nextAll());
$this->assertEquals($first->nextAll()->first(), $collection->nth(1));
$this->assertEquals($first->nextAll()->last(), $collection->nth(3));
}
public function testPrev()
{
$collection = $this->files();
$this->assertEquals($collection->last()->prev(), $collection->nth(2));
}
public function testPrevAll()
{
$collection = $this->files();
$last = $collection->last();
$this->assertCount(3, $last->prevAll());
$this->assertEquals($last->prevAll()->first(), $collection->nth(0));
$this->assertEquals($last->prevAll()->last(), $collection->nth(2));
}
public function testSiblings()
{
$files = $this->files();
$file = $files->nth(1);
$siblings = $files->not($file);
$this->assertEquals($files, $file->siblings());
$this->assertEquals($siblings, $file->siblings(false));
}
public function testTemplateSiblings()
{
$page = new Page([
'slug' => 'test',
'files' => [
[
'filename' => 'a.jpg',
'template' => 'gallery'
],
[
'filename' => 'b.jpg',
'template' => 'cover'
],
[
'filename' => 'c.jpg',
'template' => 'gallery'
],
[
'filename' => 'd.jpg',
'template' => 'gallery'
]
]
]);
$files = $page->files();
$siblings = $files->first()->templateSiblings();
$this->assertTrue($siblings->has('test/a.jpg'));
$this->assertTrue($siblings->has('test/c.jpg'));
$this->assertTrue($siblings->has('test/d.jpg'));
$this->assertFalse($siblings->has('test/b.jpg'));
$siblings = $files->first()->templateSiblings(false);
$this->assertTrue($siblings->has('test/c.jpg'));
$this->assertTrue($siblings->has('test/d.jpg'));
$this->assertFalse($siblings->has('test/a.jpg'));
$this->assertFalse($siblings->has('test/b.jpg'));
}
}
<file_sep><?php
class WithDotPage extends Page {}
<file_sep><?php
namespace Kirby\Toolkit;
use PHPUnit\Framework\TestCase;
class XmlTest extends TestCase
{
protected $string;
protected function setUp()
{
$this->string = 'Süper Önencœded ßtring';
}
public function testCreateParse()
{
$xml = Xml::create($data = [
'simpson' => [
[
'name' => 'Homer',
'@attributes' => [
'type' => 'father'
]
],
[
'name' => 'Marge',
'@attributes' => [
'type' => 'mother'
]
]
]
], 'simpsons');
$output = Xml::parse($xml);
$this->assertEquals($output, $data);
}
public function testEncodeDecode()
{
$expected = 'Süper Önencœded ßtring';
$this->assertEquals($expected, Xml::encode($this->string));
$this->assertEquals($this->string, Xml::decode($expected));
}
public function testEntities()
{
$this->assertTrue(is_array(Xml::entities()));
}
public function testTag()
{
$tag = Xml::tag('name', 'content');
$this->assertEquals('<name>content</name>', $tag);
}
public function testTagWithAttributes()
{
$tag = Xml::tag('name', 'content', ['foo' => 'bar']);
$this->assertEquals('<name foo="bar">content</name>', $tag);
}
public function testTagWithCdata()
{
$tag = Xml::tag('name', $this->string, ['foo' => 'bar']);
$this->assertEquals('<name foo="bar"><![CDATA[' . Xml::encode($this->string) . ']]></name>', $tag);
}
public function valueProvider()
{
return [
[1, 1],
[true, 'true'],
[false, 'false'],
[null, null],
['', null],
['<![CDATA[test]]>', '<![CDATA[test]]>'],
['test', 'test'],
['töst', '<![CDATA[töst]]>']
];
}
/**
* @dataProvider valueProvider
*/
public function testValue($input, $expected)
{
$this->assertEquals($expected, Xml::value($input));
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class CollectionGetterTest extends TestCase
{
public function testGetMagic()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('eins', $collection->one);
$this->assertEquals('eins', $collection->ONE);
$this->assertEquals(null, $collection->three);
}
public function testGet()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('eins', $collection->get('one'));
$this->assertEquals(null, $collection->get('three'));
$this->assertEquals('default', $collection->get('three', 'default'));
}
public function testMagicMethods()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('eins', $collection->one());
$this->assertEquals('zwei', $collection->two());
$this->assertEquals(null, $collection->three());
}
public function testGetAttribute()
{
$collection = new Collection([
'one' => 'eins',
'two' => 'zwei'
]);
$this->assertEquals('eins', $collection->getAttribute($collection->toArray(), 'one'));
$this->assertEquals(null, $collection->getAttribute($collection->toArray(), 'three'));
$this->assertEquals('zwei', $collection->getAttribute($collection, 'two'));
$this->assertEquals(null, $collection->getAttribute($collection, 'three'));
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
class HeadlineFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('headline');
$this->assertEquals('headline', $field->type());
$this->assertEquals('headline', $field->name());
$this->assertEquals(null, $field->value());
$this->assertEquals(null, $field->label());
$this->assertFalse($field->save());
$this->assertTrue($field->numbered());
}
public function testNumbered()
{
$field = new Field('headline', [
'numbered' => true
]);
$this->assertTrue($field->numbered());
$field = new Field('headline', [
'numbered' => false
]);
$this->assertFalse($field->numbered());
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
class MultiselectFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('multiselect');
$this->assertEquals('multiselect', $field->type());
$this->assertEquals('multiselect', $field->name());
$this->assertEquals([], $field->value());
$this->assertEquals([], $field->default());
$this->assertEquals([], $field->options());
$this->assertEquals(null, $field->min());
$this->assertEquals(null, $field->max());
$this->assertEquals(',', $field->separator());
$this->assertEquals(null, $field->icon());
$this->assertEquals(null, $field->counter());
$this->assertTrue($field->search());
$this->assertFalse($field->sort());
$this->assertTrue($field->save());
}
public function testMin()
{
$field = new Field('multiselect', [
'value' => 'a',
'options' => ['a', 'b', 'c'],
'min' => 2
]);
$this->assertFalse($field->isValid());
$this->assertArrayHasKey('min', $field->errors());
}
public function testMax()
{
$field = new Field('multiselect', [
'value' => 'a, b',
'options' => ['a', 'b', 'c'],
'max' => 1
]);
$this->assertFalse($field->isValid());
$this->assertArrayHasKey('max', $field->errors());
}
}
<file_sep><?php
namespace Kirby\Cms;
class SiteChildrenTest extends TestCase
{
public function testDefaultChildren()
{
$site = new Site();
$this->assertInstanceOf(Pages::class, $site->children());
}
/**
* @expectedException TypeError
*/
public function testInvalidChildren()
{
$site = new Site([
'children' => 'children'
]);
}
public function testPages()
{
$site = new Site([
'children' => []
]);
$this->assertInstanceOf(Pages::class, $site->children());
}
}
<file_sep><?php
namespace Kirby\Cms;
use ReflectionClass;
class ControllerTestCase extends TestCase
{
public $controller = null;
public function controller(Page $page = null)
{
return $this->kirby()->controller($this->controllerName(), [
'kirby' => $this->kirby(),
'site' => $this->site(),
'pages' => $this->site()->children(),
'page' => $page ?? $this->page()
]);
}
public function controllerRoot(): string
{
return $this->kirby()->root('controllers') . '/' . $this->controllerName() . '.php';
}
public function controllerName(): string
{
if ($this->controller !== null) {
return $this->controller;
}
$reflect = new ReflectionClass($this);
$className = $reflect->getShortName();
return strtolower(str_replace('ControllerTest', '', $className));
}
public function testControllerExists()
{
$this->assertFileExists($this->controllerRoot());
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class LanguageTest extends TestCase
{
public function testCode()
{
$language = new Language([
'code' => 'en'
]);
$this->assertEquals('en', $language->code());
}
public function testDefaultDefault()
{
$language = new Language([
'code' => 'en'
]);
$this->assertFalse($language->isDefault());
}
public function testDefaultIsTrue()
{
$language = new Language([
'code' => 'en',
'default' => true
]);
$this->assertTrue($language->isDefault());
}
public function testDefaultIsFalse()
{
$language = new Language([
'code' => 'en',
'default' => false
]);
$this->assertFalse($language->isDefault());
}
public function testDirection()
{
$language = new Language([
'code' => 'en',
'direction' => 'rtl'
]);
$this->assertEquals('rtl', $language->direction());
$language = new Language([
'code' => 'en',
'direction' => 'ltr'
]);
$this->assertEquals('ltr', $language->direction());
$language = new Language([
'code' => 'en',
'direction' => 'invalid'
]);
$this->assertEquals('ltr', $language->direction());
}
public function testLocale()
{
$language = new Language([
'code' => 'en',
'locale' => 'en_US'
]);
$this->assertEquals('en_US', $language->locale());
}
public function testLocaleDefault()
{
$language = new Language([
'code' => 'en',
]);
$this->assertEquals('en', $language->locale());
}
public function testName()
{
$language = new Language([
'code' => 'en',
'name' => 'English'
]);
$this->assertEquals('English', $language->name());
}
public function testNameDefault()
{
$language = new Language([
'code' => 'en',
]);
$this->assertEquals('en', $language->name());
}
public function testUrlWithRelativeValue()
{
$language = new Language([
'code' => 'en',
'url' => 'super'
]);
$this->assertEquals('/super', $language->url());
}
public function testUrlWithAbsoluteValue()
{
$language = new Language([
'code' => 'en',
'url' => 'https://en.getkirby.com'
]);
$this->assertEquals('https://en.getkirby.com', $language->url());
}
public function testUrlWithDash()
{
$language = new Language([
'code' => 'en',
'url' => '/'
]);
$this->assertEquals('/', $language->url());
}
public function testUrlDefault()
{
$language = new Language([
'code' => 'en',
]);
$this->assertEquals('/en', $language->url());
}
}
<file_sep><?php
namespace Kirby\Toolkit;
use PHPUnit\Framework\TestCase;
class ObjFacade extends Facade
{
public static function instance()
{
return new Obj([
'test' => 'Test'
]);
}
}
class FacadeTest extends TestCase
{
public function testCall()
{
$this->assertEquals('Test', ObjFacade::test());
}
}
<file_sep><?php
use Kirby\Toolkit\A;
return [
'props' => [
/**
* Unset inherited props
*/
'after' => null,
'before' => null,
'autofocus' => null,
'icon' => null,
'placeholder' => null,
/**
* Sets the file(s), which are selected by default when a new page is created
*/
'default' => function ($default = null) {
return $default;
},
/**
* Changes the layout of the selected files. Available layouts: list, cards
*/
'layout' => function (string $layout = 'list') {
return $layout;
},
/**
* Minimum number of required files
*/
'min' => function (int $min = null) {
return $min;
},
/**
* Maximum number of allowed files
*/
'max' => function (int $max = null) {
return $max;
},
/**
* If false, only a single file can be selected
*/
'multiple' => function (bool $multiple = true) {
return $multiple;
},
/**
* Optional query for the parent page that will be used to fetch the files. (i.e site.find("media"))
*/
'parent' => function (string $parent = null) {
return $parent;
},
/**
* Layout size for cards
*/
'size' => function (string $size = null) {
return $size;
},
'value' => function ($value = null) {
return $value;
}
],
'computed' => [
'parentModel' => function () {
if (is_string($this->parent) === true && $model = $this->model()->query($this->parent, 'Kirby\Cms\Model')) {
return $model;
}
return $this->model();
},
'parent' => function () {
return $this->parentModel->apiUrl(true);
},
'default' => function () {
return $this->toFiles($this->default);
},
'value' => function () {
return $this->toFiles($this->value);
},
],
'methods' => [
'toFiles' => function ($value = null) {
$files = [];
$kirby = kirby();
foreach (Yaml::decode($value) as $id) {
if (is_array($id) === true) {
$id = $id['filename'] ?? null;
}
if ($id !== null && ($file = $this->parentModel->file($id))) {
$files[] = [
'filename' => $file->filename(),
'link' => $file->panelUrl(true),
'id' => $file->id(),
'url' => $file->url(),
'thumb' => $file->isResizable() ? $file->resize(512)->url() : null,
'type' => $file->type(),
];
}
}
return $files;
}
],
'save' => function ($value = null) {
return A::pluck($value, 'filename');
},
'validations' => [
'max',
'min'
]
];
<file_sep><?php
namespace Kirby\Toolkit;
class TplTest extends TestCase
{
public function testLoadWithGoodTemplate()
{
$tpl = Tpl::load(__DIR__ . '/fixtures/tpl/good.php', ['name' => 'Peter']);
$this->assertEquals('Hello Peter', $tpl);
}
/**
* @expectedException Error
*/
public function testLoadWithBadTemplate()
{
$tpl = Tpl::load(__DIR__ . '/fixtures/tpl/bad.php');
}
}
<file_sep><?php
namespace Kirby\Cms;
use PHPUnit\Framework\TestCase;
class FilePermissionsTest extends TestCase
{
public function actionProvider()
{
return [
['changeName'],
['create'],
['delete'],
['replace'],
['update']
];
}
/**
* @dataProvider actionProvider
*/
public function testWithAdmin($action)
{
$kirby = new App([
'roots' => [
'index' => '/dev/null'
]
]);
$kirby->impersonate('kirby');
$file = new File(['filename' => 'test.jpg']);
$perms = $file->permissions();
$this->assertTrue($perms->can($action));
}
/**
* @dataProvider actionProvider
*/
public function testWithNobody($action)
{
$kirby = new App([
'roots' => [
'index' => '/dev/null'
]
]);
$file = new File(['filename' => 'test.jpg']);
$perms = $file->permissions();
$this->assertFalse($perms->can($action));
}
}
<file_sep><?php
namespace Kirby\Cms;
class SitePagesTest extends TestCase
{
public function testErrorPage()
{
$site = new Site([
'children' => [
['slug' => 'error']
]
]);
$this->assertIsPage($site->errorPage(), 'error');
}
public function testHomePage()
{
$site = new Site([
'children' => [
['slug' => 'home']
]
]);
$this->assertIsPage($site->homePage(), 'home');
}
public function testPage()
{
$site = new Site([
'page' => $page = new Page(['slug' => 'test'])
]);
$this->assertIsPage($site->page(), $page);
}
public function testDefaultPageWithChildren()
{
$site = new Site([
'children' => [
['slug' => 'home']
]
]);
$this->assertIsPage($site->page(), 'home');
}
public function testPageWithPathAndChildren()
{
$site = new Site([
'children' => [
['slug' => 'test']
]
]);
$this->assertIsPage($site->page('test'), 'test');
}
public function testVisitWithPageObject()
{
$site = new Site();
$page = $site->visit(new Page(['slug' => 'test']));
$this->assertIsPage($site->page(), 'test');
$this->assertIsPage($site->page(), $page);
}
public function testVisitWithId()
{
$site = new Site([
'children' => [
['slug' => 'test']
]
]);
$page = $site->visit('test');
$this->assertIsPage($site->page(), 'test');
$this->assertIsPage($site->page(), $page);
}
}
<file_sep><?php
namespace Kirby\Cms;
class ArticlePage extends Page
{
public function test()
{
return $this->id();
}
}
class PageModelTest extends TestCase
{
public function setUp()
{
parent::setUp();
Page::$models = [
'article' => ArticlePage::class
];
}
public function testPageModelWithTemplate()
{
$page = Page::factory([
'slug' => 'test',
'model' => 'article',
]);
$this->assertInstanceOf(ArticlePage::class, $page);
$this->assertEquals('test', $page->test());
}
public function testMissingPageModel()
{
$page = Page::factory([
'slug' => 'test',
'model' => 'project',
]);
$this->assertInstanceOf(Page::class, $page);
$this->assertFalse(method_exists($page, 'test'));
}
}
<file_sep><?php
namespace Kirby\Http;
use PHPUnit\Framework\TestCase;
use Kirby\Http\Request\Query;
use Kirby\Http\Request\Body;
use Kirby\Http\Request\Files;
class RequestTest extends TestCase
{
public function testCustomProps()
{
$file = [
'name' => 'test.txt',
'tmp_name' => '/tmp/abc',
'size' => 123,
'error' => 0
];
$request = new Request([
'method' => 'POST',
'body' => ['a' => 'a'],
'query' => ['b' => 'b'],
'files' => ['upload' => $file]
]);
$this->assertTrue($request->is('POST'));
$this->assertEquals('a', $request->body()->get('a'));
$this->assertEquals('b', $request->query()->get('b'));
$this->assertEquals($file, $request->file('upload'));
}
public function testData()
{
$request = new Request([
'body' => ['a' => 'a'],
'query' => ['b' => 'b'],
]);
$this->assertEquals(['a' => 'a', 'b' => 'b'], $request->data());
$this->assertEquals('a', $request->get('a'));
$this->assertEquals('b', $request->get('b'));
$this->assertEquals(null, $request->get('c'));
}
public function test__debuginfo()
{
$request = new Request();
$info = $request->__debuginfo();
$this->assertArrayHasKey('body', $info);
$this->assertArrayHasKey('query', $info);
$this->assertArrayHasKey('files', $info);
$this->assertArrayHasKey('method', $info);
$this->assertArrayHasKey('url', $info);
}
public function testMethod()
{
$request = new Request();
$this->assertInstanceOf(Query::class, $request->query());
$this->assertInstanceOf(Body::class, $request->body());
$this->assertInstanceOf(Files::class, $request->files());
}
public function testQuery()
{
$request = new Request();
$this->assertInstanceOf('Kirby\Http\Request\Query', $request->query());
}
public function testBody()
{
$request = new Request();
$this->assertInstanceOf('Kirby\Http\Request\Body', $request->body());
}
public function testFiles()
{
$request = new Request();
$this->assertInstanceOf('Kirby\Http\Request\Files', $request->files());
}
public function testFile()
{
$request = new Request();
$this->assertNull($request->file('test'));
}
public function testIs()
{
$request = new Request();
$this->assertTrue($request->is('GET'));
}
public function testIsWithLowerCaseInput()
{
$request = new Request();
$this->assertTrue($request->is('get'));
}
public function testUrl()
{
$request = new Request();
$this->assertInstanceOf(Uri::class, $request->url());
}
public function testUrlUpdates()
{
$request = new Request();
$uriBefore = $request->url();
$clone = $request->url([
'host' => 'getkirby.com',
'path' => 'yay',
'query' => ['foo' => 'bar']
]);
$uriAfter = $request->url();
$this->assertNotEquals($uriBefore, $clone);
$this->assertEquals($uriBefore, $uriAfter);
$this->assertEquals('http://getkirby.com/yay?foo=bar', $clone->toString());
}
}
<file_sep>(function(t) {
function e(e) {
for (
var i, o, r = e[0], l = e[1], u = e[2], p = 0, f = [];
p < r.length;
p++
)
(o = r[p]), s[o] && f.push(s[o][0]), (s[o] = 0);
for (i in l) Object.prototype.hasOwnProperty.call(l, i) && (t[i] = l[i]);
c && c(e);
while (f.length) f.shift()();
return a.push.apply(a, u || []), n();
}
function n() {
for (var t, e = 0; e < a.length; e++) {
for (var n = a[e], i = !0, r = 1; r < n.length; r++) {
var l = n[r];
0 !== s[l] && (i = !1);
}
i && (a.splice(e--, 1), (t = o((o.s = n[0]))));
}
return t;
}
var i = {},
s = { app: 0 },
a = [];
function o(e) {
if (i[e]) return i[e].exports;
var n = (i[e] = { i: e, l: !1, exports: {} });
return t[e].call(n.exports, n, n.exports, o), (n.l = !0), n.exports;
}
(o.m = t),
(o.c = i),
(o.d = function(t, e, n) {
o.o(t, e) || Object.defineProperty(t, e, { enumerable: !0, get: n });
}),
(o.r = function(t) {
"undefined" !== typeof Symbol &&
Symbol.toStringTag &&
Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }),
Object.defineProperty(t, "__esModule", { value: !0 });
}),
(o.t = function(t, e) {
if ((1 & e && (t = o(t)), 8 & e)) return t;
if (4 & e && "object" === typeof t && t && t.__esModule) return t;
var n = Object.create(null);
if (
(o.r(n),
Object.defineProperty(n, "default", { enumerable: !0, value: t }),
2 & e && "string" != typeof t)
)
for (var i in t)
o.d(
n,
i,
function(e) {
return t[e];
}.bind(null, i)
);
return n;
}),
(o.n = function(t) {
var e =
t && t.__esModule
? function() {
return t["default"];
}
: function() {
return t;
};
return o.d(e, "a", e), e;
}),
(o.o = function(t, e) {
return Object.prototype.hasOwnProperty.call(t, e);
}),
(o.p = "/");
var r = (window["webpackJsonp"] = window["webpackJsonp"] || []),
l = r.push.bind(r);
(r.push = e), (r = r.slice());
for (var u = 0; u < r.length; u++) e(r[u]);
var c = l;
a.push([0, "chunk-vendors"]), n();
})({
0: function(t, e, n) {
t.exports = n("56d7");
},
"0301": function(t, e, n) {},
"0812": function(t, e, n) {},
"08b6": function(t, e, n) {},
"08ec": function(t, e, n) {},
"0a66": function(t, e, n) {},
"0cdc": function(t, e, n) {},
"0dac": function(t, e, n) {
"use strict";
var i = n("1100"),
s = n.n(i);
s.a;
},
"0eae": function(t, e, n) {
"use strict";
var i = n("d6f2"),
s = n.n(i);
s.a;
},
1100: function(t, e, n) {},
1182: function(t, e, n) {
"use strict";
var i = n("9ee7"),
s = n.n(i);
s.a;
},
"12fb": function(t, e, n) {
"use strict";
var i = n("ec72"),
s = n.n(i);
s.a;
},
"146c": function(t, e, n) {
"use strict";
var i = n("f5e3"),
s = n.n(i);
s.a;
},
"14d6": function(t, e, n) {},
"18dd": function(t, e, n) {
"use strict";
var i = n("34a7"),
s = n.n(i);
s.a;
},
"196d": function(t, e, n) {
"use strict";
var i = n("891e"),
s = n.n(i);
s.a;
},
"1c0c": function(t, e, n) {},
"1e3b": function(t, e, n) {
"use strict";
var i = n("8ae6"),
s = n.n(i);
s.a;
},
"200b": function(t, e, n) {},
"202d": function(t, e, n) {
"use strict";
var i = n("ca3a"),
s = n.n(i);
s.a;
},
2114: function(t, e, n) {},
"24c1": function(t, e, n) {
"use strict";
var i = n("7075"),
s = n.n(i);
s.a;
},
2607: function(t, e, n) {
"use strict";
var i = n("3c99"),
s = n.n(i);
s.a;
},
2666: function(t, e, n) {
"use strict";
var i = n("75ae"),
s = n.n(i);
s.a;
},
"28f4": function(t, e, n) {},
"2c67": function(t, e, n) {
"use strict";
var i = n("14d6"),
s = n.n(i);
s.a;
},
3218: function(t, e, n) {},
3460: function(t, e, n) {
"use strict";
var i = n("3eee"),
s = n.n(i);
s.a;
},
"34a7": function(t, e, n) {},
"35ad": function(t, e, n) {
"use strict";
var i = n("fff9"),
s = n.n(i);
s.a;
},
3610: function(t, e, n) {},
3755: function(t, e, n) {},
"38ee": function(t, e, n) {
"use strict";
var i = n("08b6"),
s = n.n(i);
s.a;
},
"3a66": function(t, e, n) {
"use strict";
var i = n("9ae6"),
s = n.n(i);
s.a;
},
"3acb": function(t, e, n) {
"use strict";
var i = n("6b96"),
s = n.n(i);
s.a;
},
"3b9a": function(t, e, n) {},
"3c0c": function(t, e, n) {
"use strict";
var i = n("8b1d"),
s = n.n(i);
s.a;
},
"3c80": function(t, e, n) {},
"3c99": function(t, e, n) {},
"3c9d": function(t, e, n) {},
"3e93": function(t, e, n) {
"use strict";
var i = n("7428"),
s = n.n(i);
s.a;
},
"3eee": function(t, e, n) {},
"3f08": function(t, e, n) {
"use strict";
var i = n("bbbf"),
s = n.n(i);
s.a;
},
"414d": function(t, e, n) {
"use strict";
var i = n("5714"),
s = n.n(i);
s.a;
},
4150: function(t, e, n) {},
4333: function(t, e, n) {
"use strict";
var i = n("58e5"),
s = n.n(i);
s.a;
},
4496: function(t, e, n) {
"use strict";
var i = n("3b9a"),
s = n.n(i);
s.a;
},
4752: function(t, e, n) {
"use strict";
var i = n("1c0c"),
s = n.n(i);
s.a;
},
"4a37": function(t, e, n) {
"use strict";
var i = n("0a66"),
s = n.n(i);
s.a;
},
"4b75": function(t, e, n) {
"use strict";
var i = n("dccd"),
s = n.n(i);
s.a;
},
"4c3f": function(t, e, n) {
"use strict";
var i = n("b8aa"),
s = n.n(i);
s.a;
},
"4cb2": function(t, e, n) {
"use strict";
var i = n("e697"),
s = n.n(i);
s.a;
},
"4cc7": function(t, e, n) {
"use strict";
var i = n("6af3"),
s = n.n(i);
s.a;
},
"4e2b": function(t, e, n) {
"use strict";
var i = n("5f4f"),
s = n.n(i);
s.a;
},
5369: function(t, e, n) {
"use strict";
var i = n("0301"),
s = n.n(i);
s.a;
},
5439: function(t, e, n) {},
"56d7": function(t, e, n) {
"use strict";
n.r(e);
n("cadf"), n("551c"), n("097d");
var i = n("a026"),
s = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.$store.state.system.info.isBroken
? n("div", { staticClass: "k-panel" }, [
n(
"main",
{ staticClass: "k-panel-view" },
[
n("k-error-view", [
t.debug
? n("p", [
t._v(t._s(t.$store.state.system.info.error) + " 😭")
])
: n("p", [t._v("The panel cannot connect to the API 😭")])
])
],
1
)
])
: n(
"div",
{
staticClass: "k-panel",
attrs: {
"data-dragging": t.$store.state.drag,
"data-loading": t.$store.state.isLoading,
"data-topbar": t.inside,
"data-dialog": t.$store.state.dialog
}
},
[
t.inside
? n(
"div",
{ staticClass: "k-panel-header" },
[
n("k-topbar", {
on: {
register: function(e) {
t.$refs.registration.open();
}
}
}),
t.$store.state.search
? n(
"k-search",
t._b({}, "k-search", t.$store.state.search, !1)
)
: t._e()
],
1
)
: t._e(),
n(
"main",
{ staticClass: "k-panel-view" },
[n("router-view")],
1
),
t.inside ? n("k-form-buttons") : t._e(),
n("k-error-dialog"),
t.offline
? n("div", { staticClass: "k-offline-warning" }, [
n("p", [t._v("The panel is currently offline")])
])
: t._e(),
n("k-registration", { ref: "registration" })
],
1
);
},
a = [],
o = (n("386d"),
function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{
staticClass: "k-search",
attrs: { role: "search" },
on: { click: t.close }
},
[
n(
"div",
{
staticClass: "k-search-box",
on: {
click: function(t) {
t.stopPropagation();
}
}
},
[
n(
"div",
{ staticClass: "k-search-input" },
[
n("input", {
directives: [
{
name: "model",
rawName: "v-model",
value: t.q,
expression: "q"
}
],
ref: "input",
attrs: {
placeholder: t.$t("search") + " …",
"aria-label": "$t('search')",
type: "text"
},
domProps: { value: t.q },
on: {
keydown: [
function(e) {
return "button" in e ||
!t._k(e.keyCode, "down", 40, e.key, [
"Down",
"ArrowDown"
])
? (e.preventDefault(), t.down(e))
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "up", 38, e.key, [
"Up",
"ArrowUp"
])
? (e.preventDefault(), t.up(e))
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "tab", 9, e.key, "Tab")
? (e.preventDefault(), t.tab(e))
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "enter", 13, e.key, "Enter")
? t.enter(e)
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "esc", 27, e.key, [
"Esc",
"Escape"
])
? t.close(e)
: null;
}
],
input: function(e) {
e.target.composing || (t.q = e.target.value);
}
}
}),
n("k-button", {
attrs: { tooltip: t.$t("close"), icon: "cancel" },
on: { click: t.close }
})
],
1
),
n(
"ul",
t._l(t.pages, function(e, i) {
return n(
"li",
{
key: e.id,
attrs: { "data-selected": t.selected === i },
on: {
mouseover: function(e) {
t.selected = i;
}
}
},
[
n(
"k-link",
{
attrs: { to: t.$api.pages.link(e.id) },
on: {
click: function(e) {
t.click(i);
}
}
},
[
n("strong", [t._v(t._s(e.title))]),
n("small", [t._v(t._s(e.id))])
]
)
],
1
);
}),
0
)
]
)
]
);
}),
r = [],
l = (n("b54a"),
function(t, e) {
var n = null;
return function() {
var i = this,
s = arguments;
clearTimeout(n),
(n = setTimeout(function() {
t.apply(i, s);
}, e));
};
}),
u = n("be94"),
c = window.panel || {},
p = {
assets: "@/assets",
api: "/api",
site: "http://sandbox.test",
url: "/",
debug: !0,
translation: "en",
search: { limit: 10 }
},
f = Object(u["a"])({}, p, c),
d = {
data: function() {
return { pages: [], q: null, selected: -1 };
},
watch: {
q: l(function(t) {
this.search(t);
}, 200)
},
mounted: function() {
var t = this;
this.$nextTick(function() {
t.$refs.input.focus();
});
},
methods: {
open: function(t) {
t.preventDefault(), this.$store.dispatch("search", !0);
},
click: function(t) {
(this.selected = t), this.tab();
},
close: function() {
this.$store.dispatch("search", !1);
},
down: function() {
this.selected < this.pages.length - 1 && this.selected++;
},
enter: function() {
var t = this.pages[this.selected] || this.pages[0];
t && this.navigate(t);
},
navigate: function(t) {
this.$router.push(this.$api.pages.link(t.id)), this.close();
},
search: function(t) {
var e = this;
this.$api
.get("site/search", { q: t, limit: f.search.limit })
.then(function(t) {
(e.pages = t.data), (e.selected = -1);
})
.catch(function() {
(e.pages = []), (e.selected = -1);
});
},
tab: function() {
var t = this.pages[this.selected];
t && this.navigate(t);
},
up: function() {
this.selected >= 0 && this.selected--;
}
}
},
h = d,
m = (n("4cb2"), n("2877")),
g = Object(m["a"])(h, o, r, !1, null, null, null);
g.options.__file = "Search.vue";
var v = g.exports,
b = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("license.register"), size: "medium" },
on: { submit: t.submit }
},
[
n("k-form", {
attrs: { fields: t.fields, novalidate: !0 },
on: { submit: t.submit },
model: {
value: t.registration,
callback: function(e) {
t.registration = e;
},
expression: "registration"
}
})
],
1
);
},
k = [],
_ = {
methods: {
open: function() {
this.$refs.dialog.open(), this.$emit("open");
},
close: function() {
this.$refs.dialog.close(), this.$emit("close");
},
success: function(t) {
this.$refs.dialog.close(),
t.route && this.$router.push(t.route),
t.message &&
this.$store.dispatch("notification/success", t.message),
t.event && this.$events.$emit(t.event),
this.$emit("success");
}
}
},
$ = {
mixins: [_],
data: function() {
return { registration: { license: null, email: null } };
},
computed: {
fields: function() {
return {
license: {
label: this.$t("license.register.label"),
type: "text",
required: !0,
counter: !1,
placeholder: "K3-",
help: this.$t("license.register.help")
},
email: {
label: this.$t("email"),
type: "email",
required: !0,
counter: !1
}
};
}
},
methods: {
submit: function() {
var t = this;
this.$api.system
.register(this.registration)
.then(function() {
t.$store.dispatch("system/register", t.registration.license),
t.success({ message: t.$t("license.register.success") });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
y = $,
x = Object(m["a"])(y, b, k, !1, null, null, null);
x.options.__file = "RegistrationDialog.vue";
var w = x.exports,
S = {
name: "App",
components: { "k-registration": w, "k-search": v },
data: function() {
return { offline: !1, dragging: !1, debug: f.debug };
},
computed: {
inside: function() {
return !this.$route.meta.outside && this.$store.state.user.current;
}
},
created: function() {
this.$events.$on("offline", this.isOffline),
this.$events.$on("online", this.isOnline),
this.$events.$on("keydown.cmd.shift.f", this.search),
this.$events.$on("drop", this.drop);
},
destroyed: function() {
this.$events.$off("offline", this.isOffline),
this.$events.$off("online", this.isOnline),
this.$events.$off("keydown.cmd.shift.f", this.search),
this.$events.$off("drop", this.drop);
},
methods: {
drop: function() {
this.$store.dispatch("drag", null);
},
isOnline: function() {
this.offline = !1;
},
isOffline: function() {
!1 === this.$store.state.system.info.isLocal && (this.offline = !0);
},
search: function(t) {
t.preventDefault(), this.$store.dispatch("search", !0);
}
}
},
O = S,
C = (n("5c0b"), Object(m["a"])(O, s, a, !1, null, null, null));
C.options.__file = "App.vue";
var E = C.exports,
j = n("1dce"),
T = n.n(j),
I = n("1516"),
L = n.n(I);
n("6762"), n("2fdb");
function A(t) {
var e = String(t);
return e.charAt(0).toLowerCase() + e.substr(1);
}
var q = {
install: function(t) {
t.prototype.$events = new t({
data: function() {
return { entered: null };
},
created: function() {
window.addEventListener("online", this.online),
window.addEventListener("offline", this.offline),
window.addEventListener("dragenter", this.dragenter, !1),
window.addEventListener("dragover", this.prevent, !1),
window.addEventListener("dragexit", this.prevent, !1),
window.addEventListener("dragleave", this.dragleave, !1),
window.addEventListener("drop", this.drop, !1),
window.addEventListener("keydown", this.keydown, !1),
window.addEventListener("keyup", this.keyup, !1),
document.addEventListener("click", this.click, !1);
},
destroyed: function() {
window.removeEventListener("online", this.online),
window.removeEventListener("offline", this.offline),
window.removeEventListener("dragenter", this.dragenter, !1),
window.removeEventListener("dragover", this.prevent, !1),
window.removeEventListener("dragexit", this.prevent, !1),
window.removeEventListener("dragleave", this.dragleave, !1),
window.removeEventListener("drop", this.drop, !1),
window.removeEventListener("keydown", this.keydown, !1),
window.removeEventListener("keyup", this.keyup, !1),
document.removeEventListener("click", this.click, !1);
},
methods: {
click: function(t) {
this.$emit("click", t);
},
drop: function(t) {
this.prevent(t), this.$emit("drop", t);
},
dragenter: function(t) {
(this.entered = t.target),
this.prevent(t),
this.$emit("dragenter", t);
},
dragleave: function(t) {
this.prevent(t),
this.entered === t.target && this.$emit("dragleave", t);
},
keydown: function(t) {
var e = ["keydown"];
(t.metaKey || t.ctrlKey) && e.push("cmd"),
!0 === t.altKey && e.push("alt"),
!0 === t.shiftKey && e.push("shift");
var n = A(t.key),
i = {
escape: "esc",
arrowUp: "up",
arrowDown: "down",
arrowLeft: "left",
arrowRight: "right"
};
i[n] && (n = i[n]),
!1 === ["alt", "control", "shift", "meta"].includes(n) &&
e.push(n),
this.$emit(e.join("."), t),
this.$emit("keydown", t);
},
keyup: function(t) {
this.$emit("keyup", t);
},
online: function(t) {
this.$emit("online", t);
},
offline: function(t) {
this.$emit("offline", t);
},
prevent: function(t) {
t.stopPropagation(), t.preventDefault();
}
}
});
}
},
N = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("div", { staticClass: "k-bar" }, [
t.$slots.left
? n(
"div",
{
staticClass: "k-bar-slot",
attrs: { "data-position": "left" }
},
[t._t("left")],
2
)
: t._e(),
t.$slots.center
? n(
"div",
{
staticClass: "k-bar-slot",
attrs: { "data-position": "center" }
},
[t._t("center")],
2
)
: t._e(),
t.$slots.right
? n(
"div",
{
staticClass: "k-bar-slot",
attrs: { "data-position": "right" }
},
[t._t("right")],
2
)
: t._e()
]);
},
P = [],
B = (n("0dac"), {}),
D = Object(m["a"])(B, N, P, !1, null, null, null);
D.options.__file = "Bar.vue";
var F = D.exports,
R = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
t._g(
{ staticClass: "k-box", attrs: { "data-theme": t.theme } },
t.$listeners
),
[
t._t("default", [
n("k-text", { domProps: { innerHTML: t._s(t.text) } })
])
],
2
);
},
M = [],
z = { props: { theme: String, text: String } },
U = z,
V = (n("3460"), Object(m["a"])(U, R, M, !1, null, null, null));
V.options.__file = "Box.vue";
var H = V.exports,
K = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
t.component,
t._g(
{
directives: [{ name: "tab", rawName: "v-tab" }],
ref: "button",
tag: "component",
staticClass: "k-button",
attrs: {
"aria-current": t.current,
autofocus: t.autofocus,
id: t.id,
disabled: t.disabled,
"data-tabbed": t.tabbed,
"data-theme": t.theme,
"data-responsive": t.responsive,
role: t.role,
tabindex: t.tabindex,
target: t.target,
title: t.tooltip,
to: t.link,
type: t.link ? null : t.type
}
},
t.$listeners
),
[
t.image || t.icon
? n(
"figure",
{ staticClass: "k-button-figure" },
[
t.image
? n("img", {
attrs: { src: t.imageUrl, alt: t.tooltip || "" }
})
: n("k-icon", { attrs: { type: t.icon, alt: t.tooltip } })
],
1
)
: t._e(),
t.$slots.default
? n(
"span",
{ staticClass: "k-button-text" },
[t._t("default")],
2
)
: t._e()
]
);
},
G = [],
Y = n("53ca"),
W = (n("c5f6"),
{
inheritAttrs: !1,
props: {
autofocus: Boolean,
current: [String, Boolean],
disabled: Boolean,
icon: String,
id: [String, Number],
image: [String, Object],
link: String,
responsive: Boolean,
role: String,
target: String,
tabindex: String,
theme: String,
tooltip: String,
type: { type: String, default: "button" }
},
data: function() {
return { tabbed: !1 };
},
computed: {
component: function() {
return this.link ? "k-link" : "button";
},
imageUrl: function() {
return this.image
? "object" === Object(Y["a"])(this.image)
? this.image.url
: this.image
: null;
}
},
methods: {
focus: function() {
this.$refs.button.focus();
},
tab: function() {
this.focus(), (this.tabbed = !0);
},
untab: function() {
this.tabbed = !1;
}
}
}),
J = W,
X = (n("bd6e"), Object(m["a"])(J, K, G, !1, null, null, null));
X.options.__file = "Button.vue";
var Q = X.exports,
Z = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-button-group" },
[t._t("default")],
2
);
},
tt = [],
et = (n("2c67"), {}),
nt = Object(m["a"])(et, Z, tt, !1, null, null, null);
nt.options.__file = "ButtonGroup.vue";
var it = nt.exports,
st = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("div", { staticClass: "k-calendar-input" }, [
n(
"nav",
[
n("k-button", {
attrs: { icon: "angle-left" },
on: { click: t.prev }
}),
n(
"span",
{ staticClass: "k-calendar-selects" },
[
n("k-select-input", {
attrs: {
options: t.months,
disabled: t.disabled,
empty: !1,
required: !0
},
model: {
value: t.month,
callback: function(e) {
t.month = t._n(e);
},
expression: "month"
}
}),
n("k-select-input", {
attrs: {
options: t.years,
disabled: t.disabled,
empty: !1,
required: !0
},
model: {
value: t.year,
callback: function(e) {
t.year = t._n(e);
},
expression: "year"
}
})
],
1
),
n("k-button", {
attrs: { icon: "angle-right" },
on: { click: t.next }
})
],
1
),
n("table", { staticClass: "k-calendar-table" }, [
n("thead", [
n(
"tr",
t._l(t.weekdays, function(e) {
return n("th", { key: "weekday_" + e }, [t._v(t._s(e))]);
}),
0
)
]),
n(
"tbody",
t._l(t.numberOfWeeks, function(e) {
return n(
"tr",
{ key: "week_" + e },
t._l(t.days(e), function(e, i) {
return n(
"td",
{
key: "day_" + i,
staticClass: "k-calendar-day",
attrs: {
"aria-current": !!t.isToday(e) && "date",
"aria-selected": !!t.isCurrent(e) && "date"
}
},
[
e
? n(
"k-button",
{
on: {
click: function(n) {
t.select(e);
}
}
},
[t._v(t._s(e))]
)
: t._e()
],
1
);
}),
0
);
}),
0
),
n("tfoot", [
n("tr", [
n(
"td",
{ staticClass: "k-calendar-today", attrs: { colspan: "7" } },
[
n(
"k-button",
{
on: {
click: function(e) {
t.go("today");
}
}
},
[t._v(t._s(t.$t("today")))]
)
],
1
)
])
])
])
]);
},
at = [],
ot = (n("ac6a"), n("5a0c")),
rt = n.n(ot),
lt = function(t, e) {
t = String(t);
var n = "";
e = (e || 2) - t.length;
while (n.length < e) n += "0";
return n + t;
},
ut = {
props: { value: String, disabled: Boolean },
data: function() {
var t = this.value ? rt()(this.value) : rt()();
return {
day: t.date(),
month: t.month(),
year: t.year(),
today: rt()(),
current: t
};
},
computed: {
date: function() {
return rt()(
""
.concat(this.year, "-")
.concat(this.month + 1, "-")
.concat(this.day)
);
},
numberOfDays: function() {
return this.date.daysInMonth();
},
numberOfWeeks: function() {
return Math.ceil((this.numberOfDays + this.firstWeekday - 1) / 7);
},
firstWeekday: function() {
var t = this.date
.clone()
.startOf("month")
.day();
return t > 0 ? t : 7;
},
weekdays: function() {
return [
this.$t("days.mon"),
this.$t("days.tue"),
this.$t("days.wed"),
this.$t("days.thu"),
this.$t("days.fri"),
this.$t("days.sat"),
this.$t("days.sun")
];
},
monthnames: function() {
return [
this.$t("months.january"),
this.$t("months.february"),
this.$t("months.march"),
this.$t("months.april"),
this.$t("months.may"),
this.$t("months.june"),
this.$t("months.july"),
this.$t("months.august"),
this.$t("months.september"),
this.$t("months.october"),
this.$t("months.november"),
this.$t("months.december")
];
},
months: function() {
var t = [];
return (
this.monthnames.forEach(function(e, n) {
t.push({ value: n, text: e });
}),
t
);
},
years: function() {
for (var t = [], e = this.year - 10; e <= this.year + 10; e++)
t.push({ value: e, text: lt(e) });
return t;
}
},
watch: {
value: function(t) {
var e = rt()(t);
(this.day = e.date()),
(this.month = e.month()),
(this.year = e.year()),
(this.current = e);
}
},
methods: {
days: function(t) {
for (var e = [], n = 7 * (t - 1) + 1, i = n; i < n + 7; i++) {
var s = i - (this.firstWeekday - 1);
s <= 0 || s > this.numberOfDays ? e.push("") : e.push(s);
}
return e;
},
next: function() {
var t = this.date.clone().add(1, "month");
this.set(t);
},
isToday: function(t) {
return (
this.month === this.today.month() &&
this.year === this.today.year() &&
t === this.today.date()
);
},
isCurrent: function(t) {
return (
this.month === this.current.month() &&
this.year === this.current.year() &&
t === this.current.date()
);
},
prev: function() {
var t = this.date.clone().subtract(1, "month");
this.set(t);
},
go: function(t, e) {
"today" === t &&
((t = this.today.year()), (e = this.today.month())),
(this.year = t),
(this.month = e);
},
set: function(t) {
(this.day = t.date()),
(this.month = t.month()),
(this.year = t.year());
},
select: function(t) {
t && (this.day = t);
var e = rt()(
new Date(
this.year,
this.month,
this.day,
this.current.hour(),
this.current.minute()
)
);
this.$emit("input", e.toISOString());
}
}
},
ct = ut,
pt = (n("4c3f"), Object(m["a"])(ct, st, at, !1, null, null, null));
pt.options.__file = "Calendar.vue";
var ft = pt.exports,
dt = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"figure",
t._g({ staticClass: "k-card" }, t.$listeners),
[
t.sortable
? n("k-icon", {
staticClass: "k-sort-handle",
attrs: { type: "sort" }
})
: t._e(),
n(
t.wrapper,
{ tag: "component", attrs: { to: t.link, target: t.target } },
[
t.image && t.image.url
? n("k-image", {
staticClass: "k-card-image",
attrs: {
src: t.image.url,
ratio: t.image.ratio || "3/2",
back: t.image.back || "black",
cover: t.image.cover
}
})
: n(
"span",
{
staticClass: "k-card-icon",
style: "padding-bottom:" + t.ratioPadding
},
[n("k-icon", t._b({}, "k-icon", t.icon, !1))],
1
),
n("figcaption", { staticClass: "k-card-content" }, [
n(
"span",
{
staticClass: "k-card-text",
attrs: { "data-noinfo": !t.info }
},
[t._v(t._s(t.text))]
),
t.info
? n("span", {
staticClass: "k-card-info",
domProps: { innerHTML: t._s(t.info) }
})
: t._e()
])
],
1
),
n(
"nav",
{ staticClass: "k-card-options" },
[
t.flag
? n(
"k-button",
t._b(
{
staticClass: "k-card-options-button",
on: { click: t.flag.click }
},
"k-button",
t.flag,
!1
)
)
: t._e(),
t._t("options", [
t.options
? n("k-button", {
staticClass: "k-card-options-button",
attrs: { tooltip: t.$t("options"), icon: "dots" },
on: {
click: function(e) {
e.stopPropagation(), t.$refs.dropdown.toggle();
}
}
})
: t._e(),
n("k-dropdown-content", {
ref: "dropdown",
staticClass: "k-card-options-dropdown",
attrs: { options: t.options, align: "right" },
on: {
action: function(e) {
t.$emit("action", e);
}
}
})
])
],
2
)
],
1
);
},
ht = [],
mt = (n("28a5"),
function(t) {
t = t || "3/2";
var e = t.split("/");
if (2 !== e.length) return "100%";
var n = Number(e[0]),
i = Number(e[1]),
s = 100 / n * i;
return s + "%";
}),
gt = {
inheritAttrs: !1,
props: {
flag: Object,
icon: {
type: Object,
default: function() {
return { type: "file", back: "black" };
}
},
image: Object,
info: String,
link: String,
options: [Array, Function],
sortable: Boolean,
target: String,
text: String
},
computed: {
wrapper: function() {
return this.link ? "k-link" : "div";
},
ratioPadding: function() {
return this.icon && this.icon.ratio
? mt(this.icon.ratio)
: mt("3/2");
}
}
},
vt = gt,
bt = (n("5369"), Object(m["a"])(vt, dt, ht, !1, null, null, null));
bt.options.__file = "Card.vue";
var kt = bt.exports,
_t = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-cards" },
[
t._t(
"default",
t._l(t.cards, function(e, i) {
return n(
"k-card",
t._g(t._b({ key: i }, "k-card", e, !1), t.$listeners)
);
})
)
],
2
);
},
$t = [],
yt = { props: { cards: Array } },
xt = yt,
wt = (n("2666"), Object(m["a"])(xt, _t, $t, !1, null, null, null));
wt.options.__file = "Cards.vue";
var St = wt.exports,
Ot = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-collection", attrs: { "data-layout": t.layout } },
[
n(
"k-draggable",
{
attrs: {
list: t.items,
options: t.dragOptions,
element: t.elements.list,
"data-size": t.size
},
on: {
start: t.onStart,
change: function(e) {
t.$emit("change", e);
},
end: t.onEnd
}
},
t._l(t.items, function(e, i) {
return n(
t.elements.item,
t._b(
{
key: i,
tag: "component",
class: { "k-draggable-item": e.sortable },
on: {
action: function(n) {
t.$emit("action", e, n);
},
dragstart: function(n) {
t.onDragStart(n, e.dragText);
}
}
},
"component",
e,
!1
)
);
}),
1
),
!1 !== t.pagination && !0 !== t.paginationOptions.hide
? n(
"k-pagination",
t._b(
{
on: {
paginate: function(e) {
t.$emit("paginate", e);
}
}
},
"k-pagination",
t.paginationOptions,
!1
)
)
: t._e()
],
1
);
},
Ct = [],
Et = {
props: {
items: {
type: [Array, Object],
default: function() {
return [];
}
},
layout: { type: String, default: "list" },
size: String,
sortable: Boolean,
pagination: {
type: [Boolean, Object],
default: function() {
return !1;
}
}
},
data: function() {
return { list: this.items };
},
computed: {
dragOptions: function() {
return {
sort: this.sortable,
forceFallback: !0,
fallbackClass: "sortable-fallback",
fallbackOnBody: !0,
scroll: document.querySelector(".k-panel-view"),
filter: ".disabled",
disabled: !1 === this.sortable,
draggable: ".k-draggable-item",
handle: ".k-sort-handle"
};
},
elements: function() {
var t = {
cards: { list: "k-cards", item: "k-card" },
list: { list: "k-list", item: "k-list-item" }
};
return t[this.layout] ? t[this.layout] : t["list"];
},
paginationOptions: function() {
var t =
"object" !== Object(Y["a"])(this.pagination)
? {}
: this.pagination;
return Object(u["a"])(
{
limit: 10,
align: "center",
details: !0,
keys: !1,
total: 0,
hide: !1
},
t
);
}
},
watch: {
items: function() {
this.list = this.items;
},
$props: function() {
this.$forceUpdate();
}
},
over: null,
methods: {
onEnd: function() {
this.over && this.over.removeAttribute("data-over"),
this.$emit("sort", this.items),
this.$store.dispatch("drag", null);
},
onDragStart: function(t, e) {
this.$store.dispatch("drag", { type: "text", data: e });
},
onStart: function() {
this.$store.dispatch("drag", { type: "item" });
}
}
},
jt = Et,
Tt = Object(m["a"])(jt, Ot, Ct, !1, null, null, null);
Tt.options.__file = "Collection.vue";
var It = Tt.exports,
Lt = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-column", attrs: { "data-width": t.width } },
[t._t("default")],
2
);
},
At = [],
qt = { name: "KirbyColumn", props: { width: String } },
Nt = qt,
Pt = (n("5e3a"), Object(m["a"])(Nt, Lt, At, !1, null, null, null));
Pt.options.__file = "Column.vue";
var Bt = Pt.exports,
Dt = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"span",
{ staticClass: "k-counter", attrs: { "data-invalid": !t.valid } },
[
n("span", [t._v(t._s(t.count))]),
t.min && t.max
? n("span", { staticClass: "k-counter-rules" }, [
t._v("(" + t._s(t.min) + "–" + t._s(t.max) + ")")
])
: t.min
? n("span", { staticClass: "k-counter-rules" }, [
t._v("≥ " + t._s(t.min))
])
: t.max
? n("span", { staticClass: "k-counter-rules" }, [
t._v("≤ " + t._s(t.max))
])
: t._e()
]
);
},
Ft = [],
Rt = {
props: {
count: Number,
min: Number,
max: Number,
required: { type: Boolean, default: !1 }
},
computed: {
valid: function() {
return (
(!1 === this.required && 0 === this.count) ||
((!0 !== this.required || 0 !== this.count) &&
(!(this.min && this.count < this.min) &&
!(this.max && this.count > this.max)))
);
}
}
},
Mt = Rt,
zt = (n("5f5b"), Object(m["a"])(Mt, Dt, Ft, !1, null, null, null));
zt.options.__file = "Counter.vue";
var Ut = zt.exports,
Vt = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.isOpen
? n("div", { staticClass: "k-dialog", on: { click: t.cancel } }, [
n(
"div",
{
staticClass: "k-dialog-box",
attrs: { "data-size": t.size },
on: {
click: function(t) {
t.stopPropagation();
}
}
},
[
t.notification
? n(
"div",
{
staticClass: "k-dialog-notification",
attrs: { "data-theme": t.notification.type }
},
[
n("p", [t._v(t._s(t.notification.message))]),
n("k-button", {
attrs: { icon: "cancel" },
on: {
click: function(e) {
t.notification = null;
}
}
})
],
1
)
: t._e(),
n(
"div",
{ staticClass: "k-dialog-body" },
[t._t("default")],
2
),
n(
"footer",
{ staticClass: "k-dialog-footer" },
[
t._t("footer", [
n(
"k-button-group",
[
n(
"k-button",
{
staticClass: "k-dialog-button-cancel",
attrs: { icon: "cancel" },
on: { click: t.cancel }
},
[
t._v(
"\n " +
t._s(t.$t("cancel")) +
"\n "
)
]
),
n(
"k-button",
{
staticClass: "k-dialog-button-submit",
attrs: { icon: t.icon, theme: t.theme },
on: { click: t.submit }
},
[
t._v(
"\n " +
t._s(t.button || t.$t("confirm")) +
"\n "
)
]
)
],
1
)
])
],
2
)
]
)
])
: t._e();
},
Ht = [],
Kt = {
props: {
button: { type: String, default: "Ok" },
icon: { type: String, default: "check" },
size: String,
theme: String,
visible: Boolean
},
data: function() {
return { notification: null, isOpen: this.visible, scrollTop: 0 };
},
mounted: function() {
!0 === this.isOpen && this.$emit("open");
},
methods: {
storeScrollPosition: function() {
var t = document.querySelector(".k-panel-view");
t && t.scrollTop
? (this.scrollTop = t.scrollTop)
: (this.scrollTop = 0);
},
restoreScrollPosition: function() {
var t = document.querySelector(".k-panel-view");
t && t.scrollTop && (t.scrollTop = this.scrollTop);
},
open: function() {
var t = this;
this.storeScrollPosition(),
this.$store.dispatch("dialog", !0),
(this.notification = null),
(this.isOpen = !0),
this.$emit("open"),
this.$events.$on("keydown.esc", this.close),
this.$nextTick(function() {
t.$el &&
(t.focus(),
document.body.addEventListener(
"focus",
function(e) {
!1 === t.$el.contains(e.target) && t.focus();
},
!0
));
});
},
close: function() {
(this.notification = null),
(this.isOpen = !1),
this.$emit("close"),
this.$events.$off("keydown.esc", this.close),
this.$store.dispatch("dialog", null),
this.restoreScrollPosition();
},
cancel: function() {
this.$emit("cancel"), this.close();
},
focus: function() {
if (this.$el && this.$el.querySelector) {
var t = this.$el.querySelector(
"[autofocus], [data-autofocus], input, textarea, select, .k-dialog-button-submit"
);
if (
(t || (t = this.$el.querySelector(".k-dialog-button-cancel")),
t)
)
return void t.focus();
}
},
error: function(t) {
this.notification = { message: t, type: "error" };
},
submit: function() {
this.$emit("submit");
},
success: function(t) {
this.notification = { message: t, type: "success" };
}
}
},
Gt = Kt,
Yt = (n("4752"), Object(m["a"])(Gt, Vt, Ht, !1, null, null, null));
Yt.options.__file = "Dialog.vue";
var Wt = Yt.exports,
Jt = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"span",
{
staticClass: "k-dropdown",
on: {
click: function(t) {
t.stopPropagation();
}
}
},
[t._t("default")],
2
);
},
Xt = [],
Qt = (n("df30"), {}),
Zt = Object(m["a"])(Qt, Jt, Xt, !1, null, null, null);
Zt.options.__file = "Dropdown.vue";
var te = Zt.exports,
ee = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.isOpen
? n(
"div",
{
staticClass: "k-dropdown-content",
attrs: { "data-align": t.align }
},
[
t._t(
"default",
t._l(t.items, function(e, i) {
return n(
"k-dropdown-item",
t._b(
{
key: t._uid + "-item-" + i,
ref: t._uid + "-item-" + i,
refInFor: !0,
on: {
click: function(n) {
t.$emit("action", e.click);
}
}
},
"k-dropdown-item",
e,
!1
),
[t._v("\n " + t._s(e.text) + "\n ")]
);
})
)
],
2
)
: t._e();
},
ne = [],
ie = null,
se = {
props: { options: [Array, Function], align: String },
data: function() {
return { items: [], current: -1, isOpen: !1 };
},
methods: {
fetchOptions: function(t) {
if (!this.options) return t(this.items);
"string" === typeof this.options
? fetch(this.options)
.then(function(t) {
return t.json();
})
.then(function(e) {
return t(e);
})
: "function" === typeof this.options
? this.options(t)
: Array.isArray(this.options) && t(this.options);
},
open: function() {
var t = this;
this.reset(),
ie && ie !== this && ie.close(),
this.fetchOptions(function(e) {
t.$events.$on("keydown", t.navigate),
t.$events.$on("click", t.close),
(t.items = e),
(t.isOpen = !0),
t.$emit("open"),
(ie = t);
});
},
reset: function() {
(this.current = -1),
this.$events.$off("keydown", this.navigate),
this.$events.$off("click", this.close);
},
close: function() {
this.reset(), (this.isOpen = ie = !1), this.$emit("close");
},
toggle: function() {
this.isOpen ? this.close() : this.open();
},
focus: function(t) {
(t = t || 0),
this.$children[t] &&
this.$children[t].focus &&
((this.current = t), this.$children[t].focus());
},
navigate: function(t) {
switch (t.code) {
case "Escape":
case "ArrowLeft":
this.close(), this.$emit("leave", t.code);
break;
case "ArrowUp":
t.preventDefault(),
this.current > 0
? (this.current--, this.focus(this.current))
: (this.close(), this.$emit("leave", t.code));
break;
case "ArrowDown":
t.preventDefault(),
this.current < this.$children.length - 1 &&
(this.current++, this.focus(this.current));
break;
}
}
}
},
ae = se,
oe = (n("f32d"), Object(m["a"])(ae, ee, ne, !1, null, null, null));
oe.options.__file = "DropdownContent.vue";
var re = oe.exports,
le = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-button",
t._g(
t._b(
{ ref: "button", staticClass: "k-dropdown-item" },
"k-button",
t.$props,
!1
),
t.listeners
),
[t._t("default")],
2
);
},
ue = [],
ce = {
inheritAttrs: !1,
props: {
disabled: Boolean,
icon: String,
image: [String, Object],
link: String,
target: String,
theme: String,
upload: String,
current: [String, Boolean]
},
data: function() {
var t = this;
return {
listeners: Object(u["a"])({}, this.$listeners, {
click: function(e) {
t.$parent.close(), t.$emit("click", e);
}
})
};
},
methods: {
focus: function() {
this.$refs.button.focus();
},
tab: function() {
this.$refs.button.tab();
}
}
},
pe = ce,
fe = (n("b8aa9"), Object(m["a"])(pe, le, ue, !1, null, null, null));
fe.options.__file = "DropdownItem.vue";
var de = fe.exports,
he = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
t._g(
{ staticClass: "k-empty", attrs: { "data-layout": t.layout } },
t.$listeners
),
[
n("k-icon", { attrs: { type: t.icon } }),
n("p", [t._t("default")], 2)
],
1
);
},
me = [],
ge = {
props: {
text: String,
icon: String,
layout: { type: String, default: "list" }
}
},
ve = ge,
be = (n("fa25"), Object(m["a"])(ve, he, me, !1, null, null, null));
be.options.__file = "Empty.vue";
var ke,
_e,
$e = be.exports,
ye = {
data: function() {
return { error: null };
},
errorCaptured: function(t) {
return (this.error = t), !1;
},
render: function(t) {
return this.error
? this.$slots.error
? this.$slots.error[0]
: this.$scopedSlots.error
? this.$scopedSlots.error({ error: this.error })
: t(
"k-box",
{ attrs: { theme: "negative" } },
this.error.message || this.error
)
: this.$slots.default[0];
}
},
xe = ye,
we = Object(m["a"])(xe, ke, _e, !1, null, null, null);
we.options.__file = "ErrorBoundary.vue";
var Se = we.exports,
Oe = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-grid", attrs: { "data-gutter": t.gutter } },
[t._t("default")],
2
);
},
Ce = [],
Ee = { props: { gutter: String } },
je = Ee,
Te = (n("fbb8"), Object(m["a"])(je, Oe, Ce, !1, null, null, null));
Te.options.__file = "Grid.vue";
var Ie = Te.exports,
Le = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"header",
{ staticClass: "k-header", attrs: { "data-editable": t.editable } },
[
n(
"k-headline",
{ attrs: { tag: "h1", size: "huge" } },
[
t.editable && t.$listeners.edit
? n(
"span",
{
staticClass: "k-headline-editable",
on: {
click: function(e) {
t.$emit("edit");
}
}
},
[
t._t("default"),
n("k-icon", { attrs: { type: "edit" } })
],
2
)
: t._t("default")
],
2
),
t.$slots.left || t.$slots.right
? n(
"k-bar",
[
t._t("left", null, { slot: "left" }),
t._t("right", null, { slot: "right" })
],
2
)
: t._e(),
t.tabs && t.tabs.length > 1
? n(
"div",
{ staticClass: "k-header-tabs" },
[
n(
"nav",
[
t._l(t.visibleTabs, function(e, i) {
return n(
"k-button",
{
key: t.$route.fullPath + "-tab-" + i,
staticClass: "k-tab-button",
attrs: {
link: "#" + e.name,
current:
t.currentTab && t.currentTab.name === e.name,
icon: e.icon,
tooltip: e.label
}
},
[t._v("\n " + t._s(e.label) + "\n ")]
);
}),
t.invisibleTabs.length
? n(
"k-button",
{
staticClass:
"k-tab-button k-tabs-dropdown-button",
attrs: { icon: "dots" },
on: {
click: function(e) {
e.stopPropagation(), t.$refs.more.toggle();
}
}
},
[
t._v(
"\n " + t._s(t.$t("more")) + "\n "
)
]
)
: t._e()
],
2
),
t.invisibleTabs.length
? n(
"k-dropdown-content",
{
ref: "more",
staticClass: "k-tabs-dropdown",
attrs: { align: "right" }
},
t._l(t.invisibleTabs, function(e, i) {
return n(
"k-dropdown-item",
{
key: "more-" + i,
attrs: {
link: "#" + e.name,
current:
t.currentTab &&
t.currentTab.name === e.name,
icon: e.icon,
tooltip: e.label
}
},
[t._v("\n " + t._s(e.label) + "\n ")]
);
}),
1
)
: t._e()
],
1
)
: t._e()
],
1
);
},
Ae = [],
qe = {
props: { editable: Boolean, tabs: Array, tab: Object },
data: function() {
return {
size: null,
currentTab: this.tab,
visibleTabs: this.tabs,
invisibleTabs: []
};
},
watch: {
tab: function() {
this.currentTab = this.tab;
},
tabs: function(t) {
(this.visibleTabs = t), (this.invisibleTabs = []), this.resize(!0);
}
},
created: function() {
window.addEventListener("resize", this.resize);
},
destroyed: function() {
window.removeEventListener("resize", this.resize);
},
methods: {
resize: function(t) {
if (this.tabs && !(this.tabs.length <= 1)) {
if (this.tabs.length <= 3)
return (
(this.visibleTabs = this.tabs), void (this.invisibleTabs = [])
);
if (window.innerWidth >= 700) {
if ("large" === this.size && !t) return;
(this.visibleTabs = this.tabs),
(this.invisibleTabs = []),
(this.size = "large");
} else {
if ("small" === this.size && !t) return;
(this.visibleTabs = this.tabs.slice(0, 2)),
(this.invisibleTabs = this.tabs.slice(2)),
(this.size = "small");
}
}
}
}
},
Ne = qe,
Pe = (n("b42a"), Object(m["a"])(Ne, Le, Ae, !1, null, null, null));
Pe.options.__file = "Header.vue";
var Be = Pe.exports,
De = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
t.tag,
t._g(
{
tag: "component",
staticClass: "k-headline",
attrs: { "data-theme": t.theme, "data-size": t.size }
},
t.$listeners
),
[
t.link
? n("k-link", { attrs: { to: t.link } }, [t._t("default")], 2)
: t._t("default")
],
2
);
},
Fe = [],
Re = {
props: {
link: String,
size: { type: String },
tag: { type: String, default: "h2" },
theme: { type: String }
}
},
Me = Re,
ze = (n("b83b"), Object(m["a"])(Me, De, Fe, !1, null, null, null));
ze.options.__file = "Headline.vue";
var Ue = ze.exports,
Ve = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"span",
{
staticClass: "k-icon",
attrs: {
"aria-label": t.alt,
role: t.alt ? "img" : null,
"aria-hidden": !t.alt,
"data-back": t.back,
"data-size": t.size
}
},
[
t.emoji
? n("span", { staticClass: "k-icon-emoji" }, [t._v(t._s(t.type))])
: n(
"svg",
{
style: { color: t.color },
attrs: { viewBox: "0 0 16 16" }
},
[n("use", { attrs: { "xlink:href": "#icon-" + t.type } })]
)
]
);
},
He = [],
Ke = {
props: {
alt: String,
color: String,
back: String,
emoji: Boolean,
size: String,
type: String
}
},
Ge = Ke,
Ye = (n("4496"), Object(m["a"])(Ge, Ve, He, !1, null, null, null));
Ye.options.__file = "Icon.vue";
var We = Ye.exports,
Je = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"figure",
t._g(
{
staticClass: "k-image",
attrs: {
"data-ratio": t.ratio,
"data-back": t.back,
"data-cover": t.cover
}
},
t.$listeners
),
[
n(
"span",
{ style: "padding-bottom:" + t.ratioPadding },
[
t.loaded
? n("img", {
key: t.src,
attrs: { alt: t.alt || "", src: t.src },
on: {
dragstart: function(t) {
t.preventDefault();
}
}
})
: t._e(),
t.loaded || t.error
? t._e()
: n("k-loader", {
attrs: { position: "center", theme: "light" }
}),
!t.loaded && t.error
? n("k-icon", {
staticClass: "k-image-error",
attrs: { type: "cancel" }
})
: t._e()
],
1
),
t.caption
? n("figcaption", { domProps: { innerHTML: t._s(t.caption) } })
: t._e()
]
);
},
Xe = [],
Qe = {
props: {
src: String,
alt: String,
ratio: String,
back: String,
caption: String,
cover: Boolean
},
data: function() {
return {
loaded: { type: Boolean, default: !1 },
error: { type: Boolean, default: !1 }
};
},
computed: {
ratioPadding: function() {
return mt(this.ratio || "1/1");
}
},
created: function() {
var t = this,
e = new Image();
(e.onload = function() {
(t.loaded = !0), t.$emit("load");
}),
(e.onerror = function() {
(t.error = !0), t.$emit("error");
}),
(e.src = this.src);
}
},
Ze = Qe,
tn = (n("791b"), Object(m["a"])(Ze, Je, Xe, !1, null, null, null));
tn.options.__file = "Image.vue";
var en = tn.exports,
nn = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.to && !t.disabled
? n(
"a",
t._g(
{
ref: "link",
staticClass: "k-link",
attrs: {
disabled: t.disabled,
href: t.href,
rel: t.relAttr,
tabindex: t.tabindex,
target: t.target,
title: t.title
}
},
t.listeners
),
[t._t("default")],
2
)
: n(
"span",
{
staticClass: "k-link",
attrs: { title: t.title, "data-disabled": "" }
},
[t._t("default")],
2
);
},
sn = [],
an = {
props: {
disabled: Boolean,
rel: String,
tabindex: String,
target: String,
title: String,
to: String
},
data: function() {
return {
relAttr:
"_blank" === this.target ? "noreferrer noopener" : this.rel,
listeners: Object(u["a"])({}, this.$listeners, {
click: this.onClick
})
};
},
computed: {
href: function() {
return void 0 !== this.$route && "/" === this.to[0]
? (this.$router.options.url || "") + this.to
: this.to;
}
},
methods: {
isRoutable: function(t) {
return (
void 0 !== this.$route &&
(!(t.metaKey || t.altKey || t.ctrlKey || t.shiftKey) &&
(!t.defaultPrevented &&
((void 0 === t.button || 0 === t.button) && !this.target)))
);
},
onClick: function(t) {
if (!0 === this.disabled) return t.preventDefault(), !1;
this.isRoutable(t) &&
(t.preventDefault(), this.$router.push(this.to)),
this.$emit("click", t);
},
focus: function() {
this.$refs.link.focus();
}
}
},
on = an,
rn = Object(m["a"])(on, nn, sn, !1, null, null, null);
rn.options.__file = "Link.vue";
var ln = rn.exports,
un = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"ul",
{ staticClass: "k-list" },
[
t._t(
"default",
t._l(t.items, function(e, i) {
return n(
"k-list-item",
t._g(t._b({ key: i }, "k-list-item", e, !1), t.$listeners)
);
})
)
],
2
);
},
cn = [],
pn = { props: { items: Array } },
fn = pn,
dn = (n("8e2d"), Object(m["a"])(fn, un, cn, !1, null, null, null));
dn.options.__file = "List.vue";
var hn = dn.exports,
mn = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
t.element,
t._g({ tag: "component", staticClass: "k-list-item" }, t.$listeners),
[
t.sortable
? n("k-icon", {
staticClass: "k-sort-handle",
attrs: { type: "sort" }
})
: t._e(),
n(
"k-link",
{
directives: [{ name: "tab", rawName: "v-tab" }],
staticClass: "k-list-item-content",
attrs: { to: t.link, target: t.target }
},
[
n(
"figure",
{ staticClass: "k-list-item-image" },
[
t.image && t.image.url
? n("k-image", {
attrs: {
src: t.image.url,
back: t.image.back || "pattern",
cover: t.image.cover
}
})
: n("k-icon", t._b({}, "k-icon", t.icon, !1))
],
1
),
n("figcaption", { staticClass: "k-list-item-text" }, [
n("em", [t._v(t._s(t.text))]),
t.info
? n("small", { domProps: { innerHTML: t._s(t.info) } })
: t._e()
])
]
),
n(
"div",
{ staticClass: "k-list-item-options" },
[
t._t("options", [
t.flag
? n(
"k-button",
t._b(
{ on: { click: t.flag.click } },
"k-button",
t.flag,
!1
)
)
: t._e(),
t.options
? n("k-button", {
staticClass: "k-list-item-toggle",
attrs: {
tooltip: t.$t("options"),
icon: "dots",
alt: "Options"
},
on: {
click: function(e) {
e.stopPropagation(), t.$refs.options.toggle();
}
}
})
: t._e(),
n("k-dropdown-content", {
ref: "options",
attrs: { options: t.options, align: "right" },
on: {
action: function(e) {
t.$emit("action", e);
}
}
})
])
],
2
)
],
1
);
},
gn = [],
vn = {
inheritAttrs: !1,
props: {
element: { type: String, default: "li" },
image: Object,
icon: {
type: Object,
default: function() {
return { type: "file", back: "black" };
}
},
sortable: Boolean,
text: String,
target: String,
info: String,
link: String,
flag: Object,
options: [Array, Function]
}
},
bn = vn,
kn = (n("6022"), Object(m["a"])(bn, mn, gn, !1, null, null, null));
kn.options.__file = "ListItem.vue";
var _n = kn.exports,
$n = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.show
? n(
"k-button-group",
{ staticClass: "k-pagination", attrs: { "data-align": t.align } },
[
n("k-button", {
attrs: {
disabled: !t.hasPrev,
tooltip: t.prevLabel,
icon: "angle-left"
},
on: { click: t.prev }
}),
t.details
? [
t.dropdown
? [
n(
"k-dropdown",
[
n(
"k-button",
{
attrs: { disabled: !t.hasPages },
on: {
click: function(e) {
t.$refs.dropdown.toggle();
}
}
},
[
t.total > 1
? [t._v(t._s(t.detailsText))]
: t._e(),
t._v(t._s(t.total) + "\n ")
],
2
),
n(
"k-dropdown-content",
{
ref: "dropdown",
staticClass: "k-pagination-selector",
on: {
open: function(e) {
t.$nextTick(function() {
return t.$refs.page.focus();
});
}
}
},
[
n("div", [
n(
"label",
{
attrs: { for: "k-pagination-input" }
},
[t._v(t._s(t.pageLabel))]
),
n("input", {
ref: "page",
attrs: {
id: "k-pagination-input",
min: 1,
max: t.pages,
type: "number"
},
domProps: { value: t.currentPage },
on: {
focus: function(t) {
t.target.select();
},
input: function(e) {
t.goTo(e.target.value);
}
}
})
])
]
)
],
1
)
]
: [
n(
"span",
[
t.total > 1
? [t._v(t._s(t.detailsText))]
: t._e(),
t._v(t._s(t.total))
],
2
)
]
]
: t._e(),
n("k-button", {
attrs: {
disabled: !t.hasNext,
tooltip: t.nextLabel,
icon: "angle-right"
},
on: { click: t.next }
})
],
2
)
: t._e();
},
yn = [],
xn = {
props: {
align: { type: String, default: "left" },
details: { type: Boolean, default: !1 },
dropdown: { type: Boolean, default: !0 },
validate: {
type: Function,
default: function() {
return Promise.resolve();
}
},
page: { type: Number, default: 1 },
total: { type: Number, default: 0 },
limit: { type: Number, default: 10 },
keys: { type: Boolean, default: !1 },
pageLabel: { type: String, default: "Page" },
prevLabel: {
type: String,
default: function() {
return this.$t("prev");
}
},
nextLabel: {
type: String,
default: function() {
return this.$t("next");
}
}
},
data: function() {
return { currentPage: this.page };
},
computed: {
show: function() {
return this.pages > 1;
},
start: function() {
return (this.currentPage - 1) * this.limit + 1;
},
end: function() {
var t = this.start - 1 + this.limit;
return t > this.total ? this.total : t;
},
detailsText: function() {
return 1 === this.limit
? this.start + " / "
: this.start + "-" + this.end + " / ";
},
pages: function() {
return Math.ceil(this.total / this.limit);
},
hasPrev: function() {
return this.start > 1;
},
hasNext: function() {
return this.end < this.total;
},
hasPages: function() {
return this.total > this.limit;
},
offset: function() {
return this.start - 1;
}
},
watch: {
page: function(t) {
this.currentPage = t;
}
},
created: function() {
!0 === this.keys &&
window.addEventListener("keydown", this.navigate, !1);
},
destroyed: function() {
window.removeEventListener("keydown", this.navigate, !1);
},
methods: {
goTo: function(t) {
var e = this;
this.validate(t)
.then(function() {
t < 1 && (t = 1),
t > e.pages && (t = e.pages),
(e.currentPage = t),
e.$emit("paginate", {
page: parseInt(e.currentPage),
start: e.start,
end: e.end,
limit: e.limit,
offset: e.offset
});
})
.catch(function() {});
},
prev: function() {
this.goTo(this.currentPage - 1);
},
next: function() {
this.goTo(this.currentPage + 1);
},
navigate: function(t) {
switch (t.code) {
case "ArrowLeft":
this.prev();
break;
case "ArrowRight":
this.next();
break;
}
}
}
},
wn = xn,
Sn = (n("3acb"), Object(m["a"])(wn, $n, yn, !1, null, null, null));
Sn.options.__file = "Pagination.vue";
var On = Sn.exports,
Cn = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-button-group",
{ staticClass: "k-prev-next" },
[
n(
"k-button",
t._b({ attrs: { icon: "angle-left" } }, "k-button", t.prev, !1)
),
n(
"k-button",
t._b({ attrs: { icon: "angle-right" } }, "k-button", t.next, !1)
)
],
1
);
},
En = [],
jn = {
props: {
prev: {
type: Object,
default: function() {
return { disabled: !0, link: "#" };
}
},
next: {
type: Object,
default: function() {
return { disabled: !0, link: "#" };
}
}
}
},
Tn = jn,
In = (n("2607"), Object(m["a"])(Tn, Cn, En, !1, null, null, null));
In.options.__file = "PrevNext.vue";
var Ln = In.exports,
An = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"progress",
{
staticClass: "k-progress",
attrs: { max: "100" },
domProps: { value: t.state }
},
[t._v("\n " + t._s(t.state) + "%\n")]
);
},
qn = [],
Nn = {
props: { value: { type: Number, default: 0 } },
data: function() {
return { state: this.value };
},
methods: {
set: function(t) {
this.state = t;
}
}
},
Pn = Nn,
Bn = (n("8be2"), Object(m["a"])(Pn, An, qn, !1, null, null, null));
Bn.options.__file = "Progress.vue";
var Dn = Bn.exports,
Fn = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"span",
{
ref: "button",
staticClass: "k-tag",
attrs: { "data-size": t.size, tabindex: "0" },
on: {
keydown: function(e) {
return "button" in e ||
!t._k(e.keyCode, "delete", [8, 46], e.key, [
"Backspace",
"Delete",
"Del"
])
? (e.preventDefault(), t.remove(e))
: null;
}
}
},
[
n("span", { staticClass: "k-tag-text" }, [t._t("default")], 2),
t.removable
? n(
"span",
{ staticClass: "k-tag-toggle", on: { click: t.remove } },
[t._v("×")]
)
: t._e()
]
);
},
Rn = [],
Mn = {
props: { removable: Boolean, size: String },
methods: {
remove: function() {
this.removable && this.$emit("remove");
},
focus: function() {
this.$refs.button.focus();
}
}
},
zn = Mn,
Un = (n("a361"), Object(m["a"])(zn, Fn, Rn, !1, null, null, null));
Un.options.__file = "Tag.vue";
var Vn = Un.exports,
Hn = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{
staticClass: "k-text",
attrs: {
"data-align": t.align,
"data-size": t.size,
"data-theme": t.theme
}
},
[t._t("default")],
2
);
},
Kn = [],
Gn = { props: { align: String, size: String, theme: String } },
Yn = Gn,
Wn = (n("dea4"), Object(m["a"])(Yn, Hn, Kn, !1, null, null, null));
Wn.options.__file = "Text.vue";
var Jn = Wn.exports,
Xn = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-view", attrs: { "data-align": t.align } },
[t._t("default")],
2
);
},
Qn = [],
Zn = { props: { align: String } },
ti = Zn,
ei = (n("4cc7"), Object(m["a"])(ti, Xn, Qn, !1, null, null, null));
ei.options.__file = "View.vue";
var ni = ei.exports,
ii = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dropdown",
{ staticClass: "k-autocomplete" },
[
t._t("default"),
n(
"k-dropdown-content",
t._g({ ref: "dropdown", attrs: { autofocus: !0 } }, t.$listeners),
t._l(t.matches, function(e, i) {
return n(
"k-dropdown-item",
t._b(
{
key: i,
on: {
click: function(n) {
t.onSelect(e);
},
keydown: [
function(n) {
if (
!("button" in n) &&
t._k(n.keyCode, "tab", 9, n.key, "Tab")
)
return null;
n.preventDefault(), t.onSelect(e);
},
function(n) {
if (
!("button" in n) &&
t._k(n.keyCode, "enter", 13, n.key, "Enter")
)
return null;
n.preventDefault(), t.onSelect(e);
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "left", 37, e.key, [
"Left",
"ArrowLeft"
])
? "button" in e && 0 !== e.button
? null
: (e.preventDefault(), t.close(e))
: null;
},
function(e) {
return "button" in e ||
!t._k(
e.keyCode,
"backspace",
void 0,
e.key,
void 0
)
? (e.preventDefault(), t.close(e))
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "delete", [8, 46], e.key, [
"Backspace",
"Delete",
"Del"
])
? (e.preventDefault(), t.close(e))
: null;
}
]
}
},
"k-dropdown-item",
e,
!1
),
[t._v("\n " + t._s(e.text) + "\n ")]
);
}),
1
),
t._v("\n " + t._s(t.query) + "\n")
],
2
);
},
si = [],
ai = (n("4917"),
n("3b2b"),
{
props: {
limit: 10,
skip: {
type: Array,
default: function() {
return [];
}
},
options: Array,
query: String
},
data: function() {
return { matches: [], selected: { text: null } };
},
methods: {
close: function() {
this.$refs.dropdown.close();
},
onSelect: function(t) {
this.$refs.dropdown.close(), this.$emit("select", t);
},
search: function(t) {
var e = this;
if (!(t.length < 1) && -1 === this.skip.indexOf(t)) {
var n = new RegExp(t, "ig");
(this.matches = this.options
.filter(function(t) {
return (
!!t.text &&
(-1 === e.skip.indexOf(t.text) && null !== t.text.match(n))
);
})
.slice(0, this.limit)),
this.$emit("search", t, this.matches),
this.$refs.dropdown.open();
}
}
}
}),
oi = ai,
ri = (n("3f08"), Object(m["a"])(oi, ii, si, !1, null, null, null));
ri.options.__file = "Autocomplete.vue";
var li = ri.exports,
ui = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"form",
{
ref: "form",
staticClass: "k-form",
attrs: { method: "POST", autocomplete: "off", novalidate: "" },
on: {
submit: function(e) {
return e.preventDefault(), t.onSubmit(e);
}
}
},
[
t._t("header"),
t._t("default", [
n(
"k-fieldset",
t._g(
{
ref: "fields",
attrs: {
disabled: t.disabled,
fields: t.fields,
novalidate: t.novalidate
},
model: {
value: t.value,
callback: function(e) {
t.value = e;
},
expression: "value"
}
},
t.listeners
)
)
]),
t._t("footer"),
n("input", {
ref: "submitter",
staticClass: "k-form-submitter",
attrs: { type: "submit" }
})
],
2
);
},
ci = [],
pi = {
props: {
disabled: Boolean,
config: Object,
fields: {
type: [Array, Object],
default: function() {
return {};
}
},
novalidate: { type: Boolean, default: !1 },
value: {
type: Object,
default: function() {
return {};
}
}
},
data: function() {
return {
errors: {},
listeners: Object(u["a"])({}, this.$listeners, {
submit: this.onSubmit
})
};
},
methods: {
focus: function(t) {
this.$refs.fields &&
this.$refs.fields.focus &&
this.$refs.fields.focus(t);
},
onSubmit: function() {
this.$emit("submit", this.value);
},
submit: function() {
this.$refs.submitter.click();
}
}
},
fi = pi,
di = (n("8633"), Object(m["a"])(fi, ui, ci, !1, null, null, null));
di.options.__file = "Form.vue";
var hi = di.exports,
mi = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{
class: "k-field k-field-name-" + t.name,
attrs: { "data-disabled": t.disabled },
on: {
focusin: function(e) {
t.$emit("focus", e);
},
focusout: function(e) {
t.$emit("blur", e);
}
}
},
[
t._t("header", [
n(
"header",
{ staticClass: "k-field-header" },
[
t._t("label", [
n(
"label",
{ staticClass: "k-field-label", attrs: { for: t.input } },
[
t._v(t._s(t.labelText) + " "),
t.required
? n(
"abbr",
{ attrs: { title: "This field is required" } },
[t._v("*")]
)
: t._e()
]
)
]),
t._t("options"),
t._t("counter", [
t.counter
? n(
"k-counter",
t._b(
{
staticClass: "k-field-counter",
attrs: { required: t.required }
},
"k-counter",
t.counter,
!1
)
)
: t._e()
])
],
2
)
]),
t._t("default"),
t._t("footer", [
t.help || t.$slots.help
? n(
"footer",
{ staticClass: "k-field-footer" },
[
t._t("help", [
t.help
? n("k-text", {
staticClass: "k-field-help",
attrs: { theme: "help" },
domProps: { innerHTML: t._s(t.help) }
})
: t._e()
])
],
2
)
: t._e()
])
],
2
);
},
gi = [],
vi = {
inheritAttrs: !1,
props: {
counter: [Boolean, Object],
disabled: Boolean,
endpoints: Object,
help: String,
input: [String, Number],
label: String,
name: [String, Number],
required: Boolean,
type: String
},
computed: {
labelText: function() {
return this.label || " ";
}
}
},
bi = vi,
ki = (n("fa44"), Object(m["a"])(bi, mi, gi, !1, null, null, null));
ki.options.__file = "Field.vue";
var _i = ki.exports,
$i = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"fieldset",
{ staticClass: "k-fieldset" },
[
n(
"k-grid",
t._l(t.fields, function(e, i) {
return "hidden" !== e.type
? n(
"k-column",
{ key: e.signature, attrs: { width: e.width } },
[
n(
"k-error-boundary",
[
t.hasFieldType(e.type)
? n(
"k-" + e.type + "-field",
t._b(
{
ref: i,
refInFor: !0,
tag: "component",
attrs: {
name: i,
novalidate: t.novalidate,
disabled: t.disabled || e.disabled
},
on: {
input: function(n) {
t.$emit("input", t.value, e, i);
},
focus: function(n) {
t.$emit("focus", n, e, i);
},
invalid: function(n, s) {
return t.onInvalid(n, s, e, i);
},
submit: function(n) {
t.$emit("submit", n, e, i);
}
},
model: {
value: t.value[i],
callback: function(e) {
t.$set(t.value, i, e);
},
expression: "value[fieldName]"
}
},
"component",
e,
!1
)
)
: n(
"k-box",
{ attrs: { theme: "negative" } },
[
n("k-text", { attrs: { size: "small" } }, [
t._v("\n The field type "),
n("strong", [t._v('"' + t._s(i) + '"')]),
t._v(" does not exist\n ")
])
],
1
)
],
1
)
],
1
)
: t._e();
}),
1
)
],
1
);
},
yi = [],
xi = (n("456d"),
n("7f7f"),
{
props: {
config: Object,
disabled: Boolean,
fields: {
type: [Array, Object],
default: function() {
return [];
}
},
novalidate: { type: Boolean, default: !1 },
value: {
type: Object,
default: function() {
return {};
}
}
},
data: function() {
return { errors: {} };
},
methods: {
focus: function(t) {
if (t)
this.hasField(t) &&
"function" === typeof this.$refs[t][0].focus &&
this.$refs[t][0].focus();
else {
var e = Object.keys(this.$refs)[0];
this.focus(e);
}
},
hasFieldType: function(t) {
return i["a"].options.components["k-" + t + "-field"];
},
hasField: function(t) {
return this.$refs[t] && this.$refs[t][0];
},
onInvalid: function(t, e, n, i) {
(this.errors[i] = e), this.$emit("invalid", this.errors);
},
hasErrors: function() {
return Object.keys(this.errors).length;
}
}
}),
wi = xi,
Si = (n("f986"), Object(m["a"])(wi, $i, yi, !1, null, null, null));
Si.options.__file = "Fieldset.vue";
var Oi = Si.exports,
Ci = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{
staticClass: "k-input",
attrs: {
"data-disabled": t.disabled,
"data-invalid": !t.novalidate && t.isInvalid,
"data-theme": t.theme,
"data-type": t.type
}
},
[
t.$slots.before || t.before
? n(
"span",
{ staticClass: "k-input-before", on: { click: t.focus } },
[t._t("before", [t._v(t._s(t.before))])],
2
)
: t._e(),
n(
"span",
{
staticClass: "k-input-element",
on: {
click: function(e) {
return e.stopPropagation(), t.focus(e);
}
}
},
[
t._t("default", [
n(
"k-" + t.type + "-input",
t._g(
t._b(
{
ref: "input",
tag: "component",
attrs: { value: t.value }
},
"component",
t.inputProps,
!1
),
t.listeners
)
)
])
],
2
),
t.$slots.after || t.after
? n(
"span",
{ staticClass: "k-input-after", on: { click: t.focus } },
[t._t("after", [t._v(t._s(t.after))])],
2
)
: t._e(),
t.$slots.icon || t.icon
? n(
"span",
{ staticClass: "k-input-icon", on: { click: t.focus } },
[t._t("icon", [n("k-icon", { attrs: { type: t.icon } })])],
2
)
: t._e()
]
);
},
Ei = [],
ji = {
inheritAttrs: !1,
props: {
after: String,
before: String,
disabled: Boolean,
type: String,
icon: [String, Boolean],
invalid: Boolean,
theme: String,
novalidate: { type: Boolean, default: !1 },
value: { type: [String, Boolean, Number, Object, Array] }
},
data: function() {
var t = this;
return {
isInvalid: this.invalid,
listeners: Object(u["a"])({}, this.$listeners, {
invalid: function(e, n) {
(t.isInvalid = e), t.$emit("invalid", e, n);
}
}),
inputProps: Object(u["a"])({}, this.$props, this.$attrs)
};
},
methods: {
blur: function(t) {
t.relatedTarget &&
!1 === this.$el.contains(t.relatedTarget) &&
this.$refs.input.blur &&
this.$refs.input.blur();
},
focus: function(t) {
if (t && t.target && "INPUT" === t.target.tagName) t.target.focus();
else if (this.$refs.input.focus) this.$refs.input.focus();
else {
var e = this.$el.querySelector("input, select, textarea");
e && e.focus();
}
}
}
},
Ti = ji,
Ii = (n("a2a8"), Object(m["a"])(Ti, Ci, Ei, !1, null, null, null));
Ii.options.__file = "Input.vue";
var Li = Ii.exports,
Ai = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-upload" },
[
n("input", {
ref: "input",
attrs: {
accept: t.options.accept,
multiple: t.options.multiple,
"aria-hidden": "true",
type: "file",
tabindex: "-1"
},
on: { change: t.select }
}),
n(
"k-dialog",
{ ref: "dialog", attrs: { size: "medium" } },
[
t.errors.length > 0
? [
n("k-headline", [t._v(t._s(t.$t("upload.errors")))]),
n(
"ul",
{ staticClass: "k-upload-error-list" },
t._l(t.errors, function(e, i) {
return n("li", { key: "error-" + i }, [
n("p", { staticClass: "k-upload-error-filename" }, [
t._v(t._s(e.file.name))
]),
n("p", { staticClass: "k-upload-error-message" }, [
t._v(t._s(e.message))
])
]);
}),
0
)
]
: [
n("k-headline", [t._v(t._s(t.$t("upload.progress")))]),
n(
"ul",
{ staticClass: "k-upload-list" },
t._l(t.files, function(e, i) {
return n(
"li",
{ key: "file-" + i },
[
n("k-progress", { ref: e.name, refInFor: !0 }),
n(
"p",
{ staticClass: "k-upload-list-filename" },
[t._v(t._s(e.name))]
),
n("p", [t._v(t._s(t.errors[e.name]))])
],
1
);
}),
0
)
],
n(
"template",
{ slot: "footer" },
[
t.errors.length > 0
? [
n(
"k-button-group",
[
n(
"k-button",
{
attrs: { icon: "check" },
on: {
click: function(e) {
t.$refs.dialog.close();
}
}
},
[
t._v(
"\n " +
t._s(t.$t("confirm")) +
"\n "
)
]
)
],
1
)
]
: t._e()
],
2
)
],
2
)
],
1
);
},
qi = [],
Ni = n("2909"),
Pi = (n("f751"),
function(t, e) {
var n = {
url: "/",
field: "file",
method: "POST",
accept: "text",
attributes: {},
complete: function() {},
error: function() {},
success: function() {},
progress: function() {}
},
i = Object.assign(n, e),
s = new FormData();
s.append(i.field, t),
i.attributes &&
Object.keys(i.attributes).forEach(function(t) {
s.append(t, i.attributes[t]);
});
var a = new XMLHttpRequest(),
o = function(e) {
if (e.lengthComputable && i.progress) {
var n = Math.max(0, Math.min(100, e.loaded / e.total * 100));
i.progress(a, t, Math.ceil(n));
}
};
a.addEventListener("loadstart", o),
a.addEventListener("progress", o),
a.addEventListener("load", function(e) {
var n = null;
try {
n = JSON.parse(e.target.response);
} catch (s) {
n = {
status: "error",
message: "The file could not be uploaded"
};
}
n.status && "error" === n.status
? i.error(a, t, n)
: (i.success(a, t, n), i.progress(a, t, 100));
}),
a.addEventListener("error", function(e) {
var n = JSON.parse(e.target.response);
i.error(a, t, n), i.progress(a, t, 100);
}),
a.open("POST", i.url, !0),
i.headers &&
Object.keys(i.headers).forEach(function(t) {
var e = i.headers[t];
a.setRequestHeader(t, e);
}),
a.send(s);
}),
Bi = {
props: {
url: { type: String },
accept: { type: String, default: "*" },
attributes: { type: Object },
multiple: { type: Boolean, default: !0 },
max: { type: Number }
},
data: function() {
return {
options: this.$props,
completed: {},
errors: [],
files: [],
total: 0
};
},
methods: {
open: function(t) {
var e = this;
this.params(t),
setTimeout(function() {
e.$refs.input.click();
}, 1);
},
params: function(t) {
this.options = Object.assign({}, this.$props, t);
},
select: function(t) {
this.upload(t.target.files);
},
drop: function(t, e) {
this.params(e), this.upload(t);
},
upload: function(t) {
var e = this;
this.$refs.dialog.open(),
(this.files = Object(Ni["a"])(t)),
(this.completed = {}),
(this.errors = []),
(this.hasErrors = !1),
this.options.max &&
(this.files = this.files.slice(0, this.options.max)),
(this.total = this.files.length),
this.files.forEach(function(t) {
Pi(t, {
url: e.options.url,
attributes: e.options.attributes,
headers: { "X-CSRF": window.panel.csrf },
progress: function(t, n, i) {
e.$refs[n.name] &&
e.$refs[n.name][0] &&
e.$refs[n.name][0].set(i);
},
success: function(t, n) {
e.complete(n);
},
error: function(t, n, i) {
e.errors.push({ file: n, message: i.message }),
e.complete(n, i.message);
}
});
});
},
complete: function(t) {
var e = this;
if (
((this.completed[t.name] = !0),
Object.keys(this.completed).length == this.total)
) {
if (((this.$refs.input.value = ""), this.errors.length > 0))
return (
this.$forceUpdate(), void this.$emit("error", this.files)
);
setTimeout(function() {
e.$refs.dialog.close(), e.$emit("success", e.files);
}, 250);
}
}
}
},
Di = Bi,
Fi = (n("4a37"), Object(m["a"])(Di, Ai, qi, !1, null, null, null));
Fi.options.__file = "Upload.vue";
var Ri = Fi.exports,
Mi = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("label", { staticClass: "k-checkbox-input" }, [
n(
"input",
t._g(
{
ref: "input",
staticClass: "k-checkbox-input-native",
attrs: { disabled: t.disabled, id: t.id, type: "checkbox" },
domProps: { checked: t.value }
},
t.listeners
)
),
n(
"span",
{
staticClass: "k-checkbox-input-icon",
attrs: { "aria-hidden": "true" }
},
[
n(
"svg",
{
attrs: {
width: "12",
height: "10",
viewBox: "0 0 12 10",
xmlns: "http://www.w3.org/2000/svg"
}
},
[
n("path", {
attrs: {
d: "M1 5l3.3 3L11 1",
"stroke-width": "2",
fill: "none",
"fill-rule": "evenodd"
}
})
]
)
]
),
n("span", {
staticClass: "k-checkbox-input-label",
domProps: { innerHTML: t._s(t.label) }
})
]);
},
zi = [],
Ui = n("b5ae"),
Vi = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
disabled: Boolean,
id: [Number, String],
label: String,
required: Boolean,
value: Boolean
},
data: function() {
var t = this;
return {
listeners: Object(u["a"])({}, this.$listeners, {
change: function(e) {
return t.onChange(e.target.checked);
}
})
};
},
watch: {
value: function() {
this.onInvalid();
}
},
mounted: function() {
this.onInvalid(), this.$props.autofocus && this.focus();
},
methods: {
focus: function() {
this.$refs.input.focus();
},
onChange: function(t) {
this.$emit("input", t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
select: function() {
this.$refs.input.focus();
}
},
validations: function() {
return { value: { required: !this.required || Ui["required"] } };
}
},
Hi = Vi,
Ki = (n("38ee"), Object(m["a"])(Hi, Mi, zi, !1, null, null, null));
Ki.options.__file = "CheckboxInput.vue";
var Gi = Ki.exports,
Yi = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"ul",
{
staticClass: "k-checkboxes-input",
style: "--columns:" + t.columns
},
t._l(t.options, function(e, i) {
return n(
"li",
{ key: i },
[
n("k-checkbox-input", {
attrs: {
id: t.id + "-" + i,
label: e.text,
value: -1 !== t.selected.indexOf(e.value)
},
on: {
input: function(n) {
t.onInput(e.value, n);
}
}
})
],
1
);
}),
0
);
},
Wi = [],
Ji = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
columns: Number,
disabled: Boolean,
id: {
type: [Number, String],
default: function() {
return this._uid;
}
},
max: Number,
min: Number,
options: Array,
required: Boolean,
value: {
type: Array,
default: function() {
return [];
}
}
},
data: function() {
return { selected: this.valueToArray(this.value) };
},
watch: {
value: function(t) {
this.selected = this.valueToArray(t);
},
selected: function() {
this.onInvalid();
}
},
mounted: function() {
this.onInvalid(), this.$props.autofocus && this.focus();
},
methods: {
focus: function() {
this.$el.querySelector("input").focus();
},
onInput: function(t, e) {
if (!0 === e) this.selected.push(t);
else {
var n = this.selected.indexOf(t);
-1 !== n && this.selected.splice(n, 1);
}
this.$emit("input", this.selected);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
select: function() {
this.focus();
},
valueToArray: function(t) {
return Array.isArray(t) ? t : String(t).split(",");
}
},
validations: function() {
return {
selected: {
required: !this.required || Ui["required"],
min: !this.min || Object(Ui["minLength"])(this.min),
max: !this.max || Object(Ui["maxLength"])(this.max)
}
};
}
},
Xi = Ji,
Qi = Object(m["a"])(Xi, Yi, Wi, !1, null, null, null);
Qi.options.__file = "CheckboxesInput.vue";
var Zi = Qi.exports,
ts = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-date-input" },
[
n("k-select-input", {
ref: "years",
attrs: {
"aria-label": t.$t("year"),
options: t.years,
disabled: t.disabled,
required: t.required,
value: t.year,
placeholder: "––––",
empty: "––––"
},
on: { input: t.setYear, invalid: t.onInvalid }
}),
n("span", { staticClass: "k-date-input-separator" }, [t._v("-")]),
n("k-select-input", {
ref: "months",
attrs: {
"aria-label": t.$t("month"),
options: t.months,
disabled: t.disabled,
required: t.required,
value: t.month,
empty: "––",
placeholder: "––"
},
on: { input: t.setMonth, invalid: t.onInvalid }
}),
n("span", { staticClass: "k-date-input-separator" }, [t._v("-")]),
n("k-select-input", {
ref: "days",
attrs: {
"aria-label": t.$t("day"),
autofocus: t.autofocus,
id: t.id,
options: t.days,
disabled: t.disabled,
required: t.required,
value: t.day,
placeholder: "––",
empty: "––"
},
on: { input: t.setDay, invalid: t.onInvalid }
})
],
1
);
},
es = [],
ns = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
disabled: Boolean,
id: [String, Number],
max: String,
min: String,
required: Boolean,
value: String
},
data: function() {
return {
date: rt()(this.value),
minDate: this.calculate(this.min, "min"),
maxDate: this.calculate(this.max, "max")
};
},
computed: {
day: function() {
return isNaN(this.date.date()) ? "" : this.date.date();
},
days: function() {
return this.options(1, this.date.daysInMonth() || 31, "days");
},
month: function() {
return isNaN(this.date.date()) ? "" : this.date.month() + 1;
},
months: function() {
return this.options(1, 12, "months");
},
year: function() {
return isNaN(this.date.year()) ? "" : this.date.year();
},
years: function() {
var t = this.date.isBefore(this.minDate)
? this.date.year()
: this.minDate.year(),
e = this.date.isAfter(this.maxDate)
? this.date.year()
: this.maxDate.year();
return this.options(t, e);
}
},
watch: {
value: function(t) {
this.date = rt()(t);
}
},
methods: {
calculate: function(t, e) {
var n = {
min: { run: "subtract", take: "startOf" },
max: { run: "add", take: "endOf" }
}[e],
i = t ? rt()(t) : null;
return (
(i && !1 !== i.isValid()) ||
(i = rt()()
[n.run](10, "year")
[n.take]("year")),
i
);
},
focus: function() {
this.$refs.years.focus();
},
onInput: function() {
!1 !== this.date.isValid()
? this.$emit("input", this.date.toISOString())
: this.$emit("input", "");
},
onInvalid: function(t, e) {
this.$emit("invalid", t, e);
},
options: function(t, e) {
for (var n = [], i = t; i <= e; i++)
n.push({ value: i, text: lt(i) });
return n;
},
set: function(t, e) {
if ("" === e || null === e || !1 === e || -1 === e)
return this.setInvalid(), void this.onInput();
if (!1 === this.date.isValid())
return this.setInitialDate(t, e), void this.onInput();
var n = this.date,
i = this.date.date();
(this.date = this.date.set(t, parseInt(e))),
"month" === t &&
this.date.date() !== i &&
(this.date = n
.set("date", 1)
.set("month", e)
.endOf("month")),
this.onInput();
},
setInvalid: function() {
this.date = rt()("invalid");
},
setInitialDate: function(t, e) {
var n = rt()();
return (
(this.date = rt()().set(t, parseInt(e))),
"date" === t &&
n.month() !== this.date.month() &&
(this.date = n.endOf("month")),
this.date
);
},
setDay: function(t) {
this.set("date", t);
},
setMonth: function(t) {
this.set("month", t - 1);
},
setYear: function(t) {
this.set("year", t);
}
}
},
is = ns,
ss = (n("196d"), Object(m["a"])(is, ts, es, !1, null, null, null));
ss.options.__file = "DateInput.vue";
var as = ss.exports,
os = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-datetime-input" },
[
n("k-date-input", {
ref: "dateInput",
attrs: {
autofocus: t.autofocus,
required: t.required,
id: t.id,
disabled: t.disabled,
value: t.dateValue
},
on: { input: t.setDate }
}),
n(
"k-time-input",
t._b(
{
ref: "timeInput",
attrs: {
required: t.required,
disabled: t.disabled,
value: t.timeValue
},
on: { input: t.setTime }
},
"k-time-input",
t.timeOptions,
!1
)
)
],
1
);
},
rs = [],
ls = {
inheritAttrs: !1,
props: Object(u["a"])({}, as.props, {
time: {
type: [Boolean, Object],
default: function() {
return {};
}
},
value: String
}),
data: function() {
return {
dateValue: this.parseDate(this.value),
timeValue: this.parseTime(this.value),
timeOptions: this.setTimeOptions()
};
},
watch: {
value: function(t) {
(this.dateValue = this.parseDate(t)),
(this.timeValue = this.parseTime(t)),
this.onInvalid();
}
},
mounted: function() {
this.onInvalid();
},
methods: {
focus: function() {
this.$refs.dateInput.focus();
},
onInput: function() {
if (this.timeValue && this.dateValue) {
var t = this.dateValue + "T" + this.timeValue + ":00";
this.$emit("input", t);
} else this.$emit("input", "");
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
parseDate: function(t) {
var e = rt()(t);
return e.isValid() ? e.format("YYYY-MM-DD") : null;
},
parseTime: function(t) {
var e = rt()(t);
return e.isValid() ? e.format("HH:mm") : null;
},
setDate: function(t) {
t && !this.timeValue && (this.timeValue = rt()().format("HH:mm")),
t
? (this.dateValue = this.parseDate(t))
: ((this.dateValue = null), (this.timeValue = null)),
this.onInput();
},
setTime: function(t) {
t &&
!this.dateValue &&
(this.dateValue = rt()().format("YYYY-MM-DD")),
t
? (this.timeValue = t)
: ((this.dateValue = null), (this.timeValue = null)),
this.onInput();
},
setTimeOptions: function() {
return !0 === this.time ? {} : this.time;
}
},
validations: function() {
return { value: { required: !this.required || Ui["required"] } };
}
},
us = ls,
cs = (n("988f"), Object(m["a"])(us, os, rs, !1, null, null, null));
cs.options.__file = "DateTimeInput.vue";
var ps = cs.exports,
fs = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"input",
t._g(
t._b(
{ ref: "input", staticClass: "k-text-input" },
"input",
{
autocomplete: t.autocomplete,
autofocus: t.autofocus,
disabled: t.disabled,
id: t.id,
minlength: t.minlength,
name: t.name,
pattern: t.pattern,
placeholder: t.placeholder,
required: t.required,
spellcheck: t.spellcheck,
type: t.type,
value: t.value
},
!1
),
t.listeners
)
);
},
ds = [],
hs = {
inheritAttrs: !1,
class: "k-text-input",
props: {
autocomplete: { type: [Boolean, String], default: "off" },
autofocus: Boolean,
disabled: Boolean,
id: [Number, String],
maxlength: Number,
minlength: Number,
name: [Number, String],
pattern: String,
placeholder: String,
preselect: Boolean,
required: Boolean,
spellcheck: { type: [Boolean, String], default: "off" },
type: { type: String, default: "text" },
value: String
},
data: function() {
var t = this;
return {
listeners: Object(u["a"])({}, this.$listeners, {
input: function(e) {
return t.onInput(e.target.value);
}
})
};
},
watch: {
value: function() {
this.onInvalid();
}
},
mounted: function() {
this.onInvalid(),
this.$props.autofocus && this.focus(),
this.$props.preselect && this.select();
},
methods: {
focus: function() {
this.$refs.input.focus();
},
onInput: function(t) {
this.$emit("input", t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
select: function() {
this.$refs.input.select();
}
},
validations: function() {
return {
value: {
required: !this.required || Ui["required"],
minLength:
!this.minlength || Object(Ui["minLength"])(this.minlength),
maxLength:
!this.maxlength || Object(Ui["maxLength"])(this.maxlength),
email: "email" !== this.type || Ui["email"],
url: "url" !== this.type || Ui["url"]
}
};
}
},
ms = hs,
gs = (n("1182"), Object(m["a"])(ms, fs, ds, !1, null, null, null));
gs.options.__file = "TextInput.vue";
var vs,
bs,
ks = gs.exports,
_s = {
extends: ks,
props: Object(u["a"])({}, ks.props, {
autocomplete: { type: String, default: "email" },
placeholder: {
type: String,
default: function() {
return this.$t("email.placeholder");
}
},
type: { type: String, default: "email" }
})
},
$s = _s,
ys = Object(m["a"])($s, vs, bs, !1, null, null, null);
ys.options.__file = "EmailInput.vue";
var xs = ys.exports,
ws = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-draggable",
{
staticClass: "k-multiselect-input",
attrs: {
options: {
disabled: !t.draggable,
forceFallback: !0,
draggable: ".k-tag",
delay: 1
},
"data-layout": t.layout,
element: "k-dropdown"
},
on: { input: t.onInput },
nativeOn: {
click: function(e) {
return t.$refs.dropdown.toggle(e);
}
},
model: {
value: t.state,
callback: function(e) {
t.state = e;
},
expression: "state"
}
},
[
t._l(t.sorted, function(e) {
return n(
"k-tag",
{
key: e.value,
ref: e.value,
refInFor: !0,
attrs: { removable: !0 },
on: {
remove: function(n) {
t.remove(e);
}
},
nativeOn: {
click: function(t) {
t.stopPropagation();
},
keydown: [
function(e) {
return "button" in e ||
!t._k(e.keyCode, "left", 37, e.key, [
"Left",
"ArrowLeft"
])
? "button" in e && 0 !== e.button
? null
: void t.navigate("prev")
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "right", 39, e.key, [
"Right",
"ArrowRight"
])
? "button" in e && 2 !== e.button
? null
: void t.navigate("next")
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "down", 40, e.key, [
"Down",
"ArrowDown"
])
? t.$refs.dropdown.open(e)
: null;
}
]
}
},
[t._v("\n " + t._s(e.text) + "\n ")]
);
}),
n(
"k-dropdown-content",
{
ref: "dropdown",
attrs: { slot: "footer" },
on: {
open: function(e) {
t.$nextTick(function() {
t.$refs.search.focus();
});
},
close: function(e) {
t.q = null;
}
},
slot: "footer"
},
[
t.search
? n(
"k-dropdown-item",
{
staticClass: "k-multiselect-search",
attrs: { icon: "search" }
},
[
n("input", {
directives: [
{
name: "model",
rawName: "v-model",
value: t.q,
expression: "q"
}
],
ref: "search",
domProps: { value: t.q },
on: {
input: function(e) {
e.target.composing || (t.q = e.target.value);
}
}
})
]
)
: t._e(),
n(
"div",
{ staticClass: "k-multiselect-options" },
t._l(t.filtered, function(e) {
return n(
"k-dropdown-item",
{
key: e.value,
class: {
"k-multiselect-option": !0,
selected: t.isSelected(e),
disabled: !t.addable
},
attrs: {
icon: t.isSelected(e) ? "check" : "circle-outline"
},
on: {
click: function(n) {
t.select(e);
}
},
nativeOn: {
keydown: [
function(n) {
if (
!("button" in n) &&
t._k(n.keyCode, "enter", 13, n.key, "Enter")
)
return null;
n.preventDefault(), t.select(e);
},
function(n) {
if (
!("button" in n) &&
t._k(n.keyCode, "space", 32, n.key, [
" ",
"Spacebar"
])
)
return null;
n.preventDefault(), t.select(e);
}
]
}
},
[
n("span", { domProps: { innerHTML: t._s(e.display) } }),
n("span", {
staticClass: "k-multiselect-value",
domProps: { innerHTML: t._s(e.info) }
})
]
);
}),
1
)
],
1
)
],
2
);
},
Ss = [],
Os = (n("20d6"),
n("a481"),
n("55dd"),
{
inheritAttrs: !1,
props: {
disabled: Boolean,
id: [Number, String],
max: Number,
min: Number,
layout: String,
options: {
type: Array,
default: function() {
return [];
}
},
required: Boolean,
search: Boolean,
separator: { type: String, default: "," },
sort: Boolean,
value: {
type: Array,
required: !0,
default: function() {
return [];
}
}
},
data: function() {
return { state: this.value, q: null };
},
computed: {
addable: function() {
return !this.max || this.state.length < this.max;
},
draggable: function() {
return this.state.length > 1 && !this.sort;
},
filtered: function() {
if (null === this.q)
return this.options.map(function(t) {
return Object(
u["a"]
)({}, t, { display: t.text, info: t.value });
});
var t = new RegExp("(".concat(this.q, ")"), "ig");
return this.options
.filter(function(e) {
return e.text.match(t) || e.value.match(t);
})
.map(function(e) {
return Object(
u["a"]
)({}, e, { display: e.text.replace(t, "<b>$1</b>"), info: e.value.replace(t, "<b>$1</b>") });
});
},
sorted: function() {
var t = this;
if (!1 === this.sort) return this.state;
var e = function(e) {
return t.options.findIndex(function(t) {
return t.value === e.value;
});
};
return this.state.sort(function(t, n) {
return e(t) - e(n);
});
}
},
watch: {
value: function(t) {
(this.state = t), this.onInvalid();
}
},
mounted: function() {
this.onInvalid(),
this.$events.$on("click", this.close),
this.$events.$on("keydown.cmd.s", this.close),
this.$events.$on("keydown.esc", this.escape);
},
destroyed: function() {
this.$events.$off("click", this.close),
this.$events.$off("keydown.cmd.s", this.close),
this.$events.$off("keydown.esc", this.escape);
},
methods: {
add: function(t) {
this.addable && (this.state.push(t), this.onInput(this.sorted));
},
blur: function() {
this.close();
},
close: function() {
this.$refs.dropdown.close(), (this.q = null), this.$el.focus();
},
escape: function() {
this.q ? (this.q = null) : this.close();
},
focus: function() {
this.$refs.dropdown.open();
},
index: function(t) {
return this.state.findIndex(function(e) {
return e.value === t.value;
});
},
isSelected: function(t) {
return -1 !== this.index(t);
},
navigate: function(t) {
var e = document.activeElement;
switch (t) {
case "prev":
e && e.previousSibling && e.previousSibling.focus();
break;
case "next":
e && e.nextSibling && e.nextSibling.focus();
break;
}
},
onInput: function(t) {
this.$emit("input", t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
remove: function(t) {
this.state.splice(this.index(t), 1), this.onInput(this.sorted);
},
select: function(t) {
(t = { text: t.text, value: t.value }),
this.isSelected(t) ? this.remove(t) : this.add(t);
}
},
validations: function() {
return {
state: {
required: !this.required || Ui["required"],
minLength: !this.min || Object(Ui["minLength"])(this.min),
maxLength: !this.max || Object(Ui["maxLength"])(this.max)
}
};
}
}),
Cs = Os,
Es = (n("6a0a"), Object(m["a"])(Cs, ws, Ss, !1, null, null, null));
Es.options.__file = "MultiselectInput.vue";
var js = Es.exports,
Ts = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"input",
t._g(
t._b(
{
ref: "input",
staticClass: "k-number-input",
attrs: { type: "number" }
},
"input",
{
autofocus: t.autofocus,
disabled: t.disabled,
id: t.id,
max: t.max,
min: t.min,
name: t.name,
placeholder: t.placeholder,
required: t.required,
step: t.step,
value: t.value
},
!1
),
t.listeners
)
);
},
Is = [],
Ls = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
disabled: Boolean,
id: [Number, String],
max: Number,
min: Number,
name: [Number, String],
placeholder: String,
preselect: Boolean,
required: Boolean,
step: Number,
value: { type: [Number, String], default: null }
},
data: function() {
var t = this;
return {
listeners: Object(u["a"])({}, this.$listeners, {
input: function(e) {
return t.onInput(e.target.value);
}
})
};
},
watch: {
value: function() {
this.onInvalid();
}
},
mounted: function() {
this.onInvalid(),
this.$props.autofocus && this.focus(),
this.$props.preselect && this.select();
},
methods: {
focus: function() {
this.$refs.input.focus();
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
onInput: function(t) {
this.$emit("input", Number(t));
},
select: function() {
this.$refs.input.select();
}
},
validations: function() {
return {
value: {
required: !this.required || Ui["required"],
min: !this.min || Object(Ui["minValue"])(this.min),
max: !this.max || Object(Ui["maxValue"])(this.max)
}
};
}
},
As = Ls,
qs = (n("4b75"), Object(m["a"])(As, Ts, Is, !1, null, null, null));
qs.options.__file = "NumberInput.vue";
var Ns,
Ps,
Bs = qs.exports,
Ds = {
extends: ks,
props: Object(u["a"])({}, ks.props, {
autocomplete: { type: String, default: "new-password" },
type: { type: String, default: "password" }
})
},
Fs = Ds,
Rs = Object(m["a"])(Fs, Ns, Ps, !1, null, null, null);
Rs.options.__file = "PasswordInput.vue";
var Ms = Rs.exports,
zs = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"ul",
{ staticClass: "k-radio-input", style: "--columns:" + t.columns },
t._l(t.options, function(e, i) {
return n(
"li",
{ key: i },
[
n("input", {
staticClass: "k-radio-input-native",
attrs: { id: t.id + "-" + i, name: t.id, type: "radio" },
domProps: { value: e.value, checked: t.value === e.value },
on: {
change: function(n) {
t.onInput(e.value);
}
}
}),
n(
"label",
{ attrs: { for: t.id + "-" + i } },
[
e.info
? [
n("span", { staticClass: "k-radio-input-text" }, [
t._v(t._s(e.text))
]),
n("span", { staticClass: "k-radio-input-info" }, [
t._v(t._s(e.info))
])
]
: [t._v("\n " + t._s(e.text) + "\n ")]
],
2
),
e.icon ? n("k-icon", { attrs: { type: e.icon } }) : t._e()
],
1
);
}),
0
);
},
Us = [],
Vs = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
columns: Number,
disabled: Boolean,
id: {
type: [Number, String],
default: function() {
return this._uid;
}
},
options: Array,
required: Boolean,
value: [String, Number, Boolean]
},
watch: {
value: function() {
this.onInvalid();
}
},
mounted: function() {
this.onInvalid(), this.$props.autofocus && this.focus();
},
methods: {
focus: function() {
this.$el.querySelector("input").focus();
},
onInput: function(t) {
this.$emit("input", t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
select: function() {
this.focus();
}
},
validations: function() {
return { value: { required: !this.required || Ui["required"] } };
}
},
Hs = Vs,
Ks = (n("d11d"), Object(m["a"])(Hs, zs, Us, !1, null, null, null));
Ks.options.__file = "RadioInput.vue";
var Gs = Ks.exports,
Ys = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("label", { staticClass: "k-range-input" }, [
n(
"input",
t._g(
t._b(
{
ref: "input",
staticClass: "k-range-input-native",
style:
"--min: " +
t.min +
"; --max: " +
t.max +
"; --value: " +
t.position,
attrs: { type: "range" }
},
"input",
{
autofocus: t.autofocus,
disabled: t.disabled,
id: t.id,
max: t.max,
min: t.min,
name: t.name,
required: t.required,
step: t.step,
value: t.value
},
!1
),
t.listeners
)
),
t.tooltip
? n("span", { staticClass: "k-range-input-tooltip" }, [
t.tooltip.before
? n("span", { staticClass: "k-range-input-tooltip-before" }, [
t._v(t._s(t.tooltip.before))
])
: t._e(),
n("span", { staticClass: "k-range-input-tooltip-text" }, [
t._v(t._s(t.label))
]),
t.tooltip.after
? n("span", { staticClass: "k-range-input-tooltip-after" }, [
t._v(t._s(t.tooltip.after))
])
: t._e()
])
: t._e()
]);
},
Ws = [],
Js = (n("6b54"),
{
inheritAttrs: !1,
props: {
autofocus: Boolean,
disabled: Boolean,
id: [String, Number],
max: { type: Number, default: 100 },
min: { type: Number, default: 0 },
name: [String, Number],
required: Boolean,
step: { type: Number, default: 1 },
tooltip: {
type: [Boolean, Object],
default: function() {
return { before: null, after: null };
}
},
value: [Number, String]
},
data: function() {
var t = this;
return {
listeners: Object(u["a"])({}, this.$listeners, {
input: function(e) {
return t.onInput(e.target.value);
}
})
};
},
computed: {
label: function() {
return null !== this.value ? this.format(this.value) : "–";
},
center: function() {
var t = (this.max - this.min) / 2 + this.min;
return Math.ceil(t / this.step) * this.step;
},
position: function() {
return null !== this.value ? this.value : this.center;
}
},
watch: {
value: function() {
this.onInvalid();
}
},
mounted: function() {
this.onInvalid(), this.$props.autofocus && this.focus();
},
methods: {
focus: function() {
this.$refs.input.focus();
},
format: function(t) {
var e = document.lang ? document.lang.replace("_", "-") : "en",
n = this.step.toString().split("."),
i = n.length > 1 ? n[1].length : 0;
return new Intl.NumberFormat(e, {
minimumFractionDigits: i
}).format(t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
onInput: function(t) {
this.$emit("input", t);
}
},
validations: function() {
return {
value: {
required: !this.required || Ui["required"],
min: !this.min || Object(Ui["minValue"])(this.min),
max: !this.max || Object(Ui["maxValue"])(this.max)
}
};
}
}),
Xs = Js,
Qs = (n("3c0c"), Object(m["a"])(Xs, Ys, Ws, !1, null, null, null));
Qs.options.__file = "RangeInput.vue";
var Zs = Qs.exports,
ta = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"span",
{
staticClass: "k-select-input",
attrs: {
"data-disabled": t.disabled,
"data-empty": "" === t.selected
}
},
[
n(
"select",
t._g(
{
directives: [
{
name: "model",
rawName: "v-model",
value: t.selected,
expression: "selected"
}
],
ref: "input",
staticClass: "k-select-input-native",
attrs: {
autofocus: t.autofocus,
"aria-label": t.ariaLabel,
disabled: t.disabled,
id: t.id,
name: t.name,
required: t.required
},
on: {
change: function(e) {
var n = Array.prototype.filter
.call(e.target.options, function(t) {
return t.selected;
})
.map(function(t) {
var e = "_value" in t ? t._value : t.value;
return e;
});
t.selected = e.target.multiple ? n : n[0];
}
}
},
t.listeners
),
[
!1 !== t.empty
? n("option", { attrs: { value: "" } }, [t._v(t._s(t.empty))])
: t._e(),
t._l(t.options, function(e) {
return n(
"option",
{
key: e.value,
attrs: { disabled: e.disabled },
domProps: { value: e.value }
},
[t._v("\n " + t._s(e.text) + "\n ")]
);
})
],
2
),
t._v("\n " + t._s(t.label) + "\n")
]
);
},
ea = [],
na = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
ariaLabel: String,
disabled: Boolean,
id: [Number, String],
name: [Number, String],
placeholder: String,
empty: { type: [String, Boolean], default: "—" },
options: {
type: Array,
default: function() {
return [];
}
},
required: Boolean,
value: { type: [String, Number, Boolean], default: "" }
},
data: function() {
var t = this;
return {
selected: this.value,
listeners: Object(u["a"])({}, this.$listeners, {
click: function(e) {
return t.onClick(e);
},
input: function(e) {
return t.onInput(e.target.value);
}
})
};
},
computed: {
label: function() {
var t = this.text(this.selected);
return "" === this.selected || null === this.selected || null === t
? this.placeholder || "—"
: t;
}
},
watch: {
value: function(t) {
(this.selected = t), this.onInvalid();
}
},
mounted: function() {
this.onInvalid(), this.$props.autofocus && this.focus();
},
methods: {
focus: function() {
this.$refs.input.focus();
},
onClick: function(t) {
t.stopPropagation(), this.$emit("click", t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
onInput: function(t) {
(this.selected = t), this.$emit("input", this.selected);
},
select: function() {
this.focus();
},
text: function(t) {
var e = null;
return (
this.options.forEach(function(n) {
n.value == t && (e = n.text);
}),
e
);
}
},
validations: function() {
return { selected: { required: !this.required || Ui["required"] } };
}
},
ia = na,
sa = (n("bd46"), Object(m["a"])(ia, ta, ea, !1, null, null, null));
sa.options.__file = "SelectInput.vue";
var aa = sa.exports,
oa = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-draggable",
{
ref: "box",
staticClass: "k-tags-input",
attrs: { options: t.dragOptions, "data-layout": t.layout },
on: { input: t.onInput },
model: {
value: t.tags,
callback: function(e) {
t.tags = e;
},
expression: "tags"
}
},
[
t._l(t.tags, function(e, i) {
return n(
"k-tag",
{
key: i,
ref: e.value,
refInFor: !0,
attrs: { removable: !0, name: "tag" },
on: {
remove: function(n) {
t.remove(e);
}
},
nativeOn: {
click: function(t) {
t.stopPropagation();
},
blur: function(e) {
t.selectTag(null);
},
focus: function(n) {
t.selectTag(e);
},
keydown: [
function(e) {
return "button" in e ||
!t._k(e.keyCode, "left", 37, e.key, [
"Left",
"ArrowLeft"
])
? "button" in e && 0 !== e.button
? null
: void t.navigate("prev")
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "right", 39, e.key, [
"Right",
"ArrowRight"
])
? "button" in e && 2 !== e.button
? null
: void t.navigate("next")
: null;
}
],
dblclick: function(n) {
t.edit(e);
}
}
},
[t._v("\n " + t._s(e.text) + "\n ")]
);
}),
n(
"span",
{
staticClass: "k-tags-input-element",
attrs: { slot: "footer" },
slot: "footer"
},
[
n(
"k-autocomplete",
{
ref: "autocomplete",
attrs: { options: t.options, skip: t.skip },
on: {
select: t.addTag,
leave: function(e) {
t.$refs.input.focus();
}
}
},
[
n("input", {
directives: [
{
name: "model",
rawName: "v-model.trim",
value: t.newTag,
expression: "newTag",
modifiers: { trim: !0 }
}
],
ref: "input",
attrs: {
autofocus: t.autofocus,
disabled:
t.disabled || (t.max && t.tags.length >= t.max),
id: t.id,
name: t.name,
autocomplete: "off",
type: "text"
},
domProps: { value: t.newTag },
on: {
input: [
function(e) {
e.target.composing ||
(t.newTag = e.target.value.trim());
},
function(e) {
t.type(e.target.value);
}
],
blur: [
t.blurInput,
function(e) {
t.$forceUpdate();
}
],
keydown: [
function(e) {
return ("button" in e ||
!t._k(e.keyCode, "s", void 0, e.key, void 0)) &&
e.metaKey
? t.blurInput(e)
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "left", 37, e.key, [
"Left",
"ArrowLeft"
])
? "button" in e && 0 !== e.button
? null
: t.leaveInput(e)
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "enter", 13, e.key, "Enter")
? t.enter(e)
: null;
},
function(e) {
return "button" in e ||
!t._k(e.keyCode, "tab", 9, e.key, "Tab")
? t.tab(e)
: null;
},
function(e) {
return "button" in e ||
!t._k(
e.keyCode,
"backspace",
void 0,
e.key,
void 0
)
? t.leaveInput(e)
: null;
}
]
}
})
]
)
],
1
)
],
2
);
},
ra = [],
la = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
accept: { type: String, default: "all" },
disabled: Boolean,
icon: { type: [String, Boolean], default: "tag" },
id: [Number, String],
layout: String,
max: Number,
min: Number,
name: [Number, String],
options: {
type: Array,
default: function() {
return [];
}
},
required: Boolean,
separator: { type: String, default: "," },
value: {
type: Array,
default: function() {
return [];
}
}
},
data: function() {
return {
tags: this.prepareTags(this.value),
selected: null,
newTag: null,
tagOptions: this.options.map(function(t) {
return (t.icon = "tag"), t;
})
};
},
computed: {
dragOptions: function() {
return {
delay: 1,
disabled: !this.draggable,
draggable: ".k-tag",
fallbackOnBody: !0,
forceFallback: !0,
scroll: document.querySelector(".k-panel-view")
};
},
draggable: function() {
return this.tags.length > 1;
},
skip: function() {
return this.tags.map(function(t) {
return t.text;
});
}
},
watch: {
value: function(t) {
(this.tags = this.prepareTags(t)), this.onInvalid();
}
},
mounted: function() {
this.onInvalid(), this.$props.autofocus && this.focus();
},
methods: {
addString: function(t) {
t &&
((t = t.trim()),
0 !== t.length && this.addTag({ text: t, value: t }));
},
addTag: function(t) {
this.addTagToIndex(t),
this.$refs.autocomplete.close(),
this.$refs.input.focus();
},
addTagToIndex: function(t) {
if ("options" === this.accept) {
var e = this.options.filter(function(e) {
return e.value === t.value;
})[0];
if (!e) return;
}
-1 === this.index(t) &&
(!this.max || this.tags.length < this.max) &&
(this.tags.push(t), this.onInput(this.tags)),
(this.newTag = null);
},
blurInput: function(t) {
(this.$refs.autocomplete.$el &&
this.$refs.autocomplete.$el.contains(t.relatedTarget)) ||
(this.$refs.input.value.length &&
(this.addTagToIndex(this.$refs.input.value),
this.$refs.autocomplete.close()));
},
edit: function(t) {
(this.newTag = t.text), this.$refs.input.select(), this.remove(t);
},
enter: function(t) {
if (!this.newTag || 0 === this.newTag.length) return !0;
t.preventDefault(), this.addString(this.newTag);
},
focus: function() {
this.$refs.input.focus();
},
get: function(t) {
var e = null,
n = null;
switch (t) {
case "prev":
case "next":
if (!this.selected) return;
(n = this.index(this.selected)),
(e = "prev" === t ? n - 1 : n + 1);
break;
case "first":
e = 0;
break;
case "last":
e = this.tags.length - 1;
break;
default:
e = t;
break;
}
var i = this.tags[e];
if (i) {
var s = this.$refs[i.value];
if (s && s[0]) return { ref: s[0], tag: i, index: e };
}
return !1;
},
index: function(t) {
return this.tags.findIndex(function(e) {
return e.value === t.value;
});
},
onInput: function(t) {
this.$emit("input", t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
leaveInput: function(t) {
0 === t.target.selectionStart &&
t.target.selectionStart === t.target.selectionEnd &&
(this.navigate("last"),
this.$refs.autocomplete.close(),
t.preventDefault(),
t.target.blur());
},
navigate: function(t) {
var e = this.get(t);
e
? (e.ref.focus(), (this.selected = e.tag))
: "next" === t &&
(this.$refs.input.focus(), (this.selected = null));
},
prepareTags: function(t) {
return !1 === Array.isArray(t)
? []
: t.map(function(t) {
return "string" === typeof t ? { text: t, value: t } : t;
});
},
remove: function(t) {
var e = this.get("prev"),
n = this.get("next");
this.tags.splice(this.index(t), 1),
this.onInput(this.tags),
e ? e.ref.focus() : n ? n.ref.focus() : this.$refs.input.focus();
},
select: function() {
this.focus();
},
selectTag: function(t) {
this.selected = t;
},
tab: function(t) {
this.newTag &&
this.newTag.length > 0 &&
(t.preventDefault(), this.addString(this.newTag));
},
type: function(t) {
(this.newTag = t), this.$refs.autocomplete.search(t);
}
},
validations: function() {
return {
tags: {
required: !this.required || Ui["required"],
minLength: !this.min || Object(Ui["minLength"])(this.min),
maxLength: !this.max || Object(Ui["maxLength"])(this.max)
}
};
}
},
ua = la,
ca = (n("eabd"), Object(m["a"])(ua, oa, ra, !1, null, null, null));
ca.options.__file = "TagsInput.vue";
var pa,
fa,
da = ca.exports,
ha = {
extends: ks,
props: Object(u["a"])({}, ks.props, {
autocomplete: { type: String, default: "tel" },
type: { type: String, default: "tel" }
})
},
ma = ha,
ga = Object(m["a"])(ma, pa, fa, !1, null, null, null);
ga.options.__file = "TelInput.vue";
var va = ga.exports,
ba = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{
staticClass: "k-textarea-input",
attrs: { "data-theme": t.theme, "data-over": t.over }
},
[
n(
"div",
{ staticClass: "k-textarea-input-wrapper" },
[
t.buttons
? n("k-toolbar", {
ref: "toolbar",
attrs: { buttons: t.buttons },
on: { command: t.onCommand }
})
: t._e(),
n(
"textarea",
t._b(
{
ref: "input",
staticClass: "k-textarea-input-native",
attrs: { "data-size": t.size },
on: {
focus: t.onFocus,
input: t.onInput,
keydown: [
function(e) {
return ("button" in e ||
!t._k(e.keyCode, "enter", 13, e.key, "Enter")) &&
e.metaKey
? t.onSubmit(e)
: null;
},
function(e) {
return e.metaKey ? t.onShortcut(e) : null;
}
],
dragover: t.onOver,
dragleave: t.onOut,
drop: t.onDrop
}
},
"textarea",
{
autofocus: t.autofocus,
disabled: t.disabled,
id: t.id,
minlength: t.minlength,
name: t.name,
placeholder: t.placeholder,
required: t.required,
spellcheck: t.spellcheck,
value: t.value
},
!1
)
)
],
1
),
n("k-email-dialog", {
ref: "emailDialog",
on: {
cancel: t.cancel,
submit: function(e) {
t.insert(e);
}
}
}),
n("k-link-dialog", {
ref: "linkDialog",
on: {
cancel: t.cancel,
submit: function(e) {
t.insert(e);
}
}
}),
n("k-upload", { ref: "upload" })
],
1
);
},
ka = [],
_a = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("nav", { staticClass: "k-toolbar" }, [
n(
"div",
{ staticClass: "k-toolbar-buttons" },
[
t._l(t.layout, function(e, i) {
return [
e.divider
? [n("span", { key: i, staticClass: "k-toolbar-divider" })]
: e.dropdown
? [
n(
"k-dropdown",
{ key: i },
[
n("k-button", {
key: i,
staticClass: "k-toolbar-button",
attrs: {
icon: e.icon,
tooltip: e.label,
tabindex: "-1"
},
on: {
click: function(e) {
t.$refs[i + "-dropdown"][0].toggle();
}
}
}),
n(
"k-dropdown-content",
{ ref: i + "-dropdown", refInFor: !0 },
t._l(e.dropdown, function(e, i) {
return n(
"k-dropdown-item",
{
key: i,
attrs: { icon: e.icon },
on: {
click: function(n) {
t.command(e.command, e.args);
}
}
},
[
t._v(
"\n " +
t._s(e.label) +
"\n "
)
]
);
}),
1
)
],
1
)
]
: [
n("k-button", {
key: i,
staticClass: "k-toolbar-button",
attrs: {
icon: e.icon,
tooltip: e.label,
tabindex: "-1"
},
on: {
click: function(n) {
t.command(e.command, e.args);
}
}
})
]
];
})
],
2
)
]);
},
$a = [],
ya = function(t) {
this.command("insert", function(e, n) {
var i = [];
return (
n.split("\n").forEach(function(e, n) {
var s = "ol" === t ? n + 1 + "." : "-";
i.push(s + " " + e);
}),
i.join("\n")
);
});
},
xa = {
layout: [
"headlines",
"bold",
"italic",
"|",
"link",
"email",
"code",
"|",
"ul",
"ol"
],
props: { buttons: { type: [Boolean, Array], default: !0 } },
data: function() {
var t = {},
e = {},
n = [],
i = this.commands();
return !1 === this.buttons
? t
: (Array.isArray(this.buttons) && (n = this.buttons),
!0 !== Array.isArray(this.buttons) && (n = this.$options.layout),
n.forEach(function(n, s) {
if ("|" === n) t["divider-" + s] = { divider: !0 };
else if (i[n]) {
var a = i[n];
(t[n] = a), a.shortcut && (e[a.shortcut] = n);
}
}),
{ layout: t, shortcuts: e });
},
methods: {
command: function(t, e) {
"function" === typeof t
? t.apply(this)
: this.$emit("command", t, e);
},
commands: function() {
return {
headlines: {
label: this.$t("toolbar.button.headings"),
icon: "title",
dropdown: {
h1: {
label: this.$t("toolbar.button.heading.1"),
icon: "title",
command: "prepend",
args: "#"
},
h2: {
label: this.$t("toolbar.button.heading.2"),
icon: "title",
command: "prepend",
args: "##"
},
h3: {
label: this.$t("toolbar.button.heading.3"),
icon: "title",
command: "prepend",
args: "###"
}
}
},
bold: {
label: this.$t("toolbar.button.bold"),
icon: "bold",
command: "wrap",
args: "**",
shortcut: "b"
},
italic: {
label: this.$t("toolbar.button.italic"),
icon: "italic",
command: "wrap",
args: "*",
shortcut: "i"
},
link: {
label: this.$t("toolbar.button.link"),
icon: "url",
shortcut: "l",
command: "dialog",
args: "link"
},
email: {
label: this.$t("toolbar.button.email"),
icon: "email",
shortcut: "e",
command: "dialog",
args: "email"
},
code: {
label: this.$t("toolbar.button.code"),
icon: "code",
command: "wrap",
args: "`"
},
ul: {
label: this.$t("toolbar.button.ul"),
icon: "list-bullet",
command: function() {
return ya.apply(this, ["ul"]);
}
},
ol: {
label: this.$t("toolbar.button.ol"),
icon: "list-numbers",
command: function() {
return ya.apply(this, ["ol"]);
}
}
};
},
shortcut: function(t, e) {
if (this.shortcuts[t]) {
var n = this.layout[this.shortcuts[t]];
if (!n) return !1;
e.preventDefault(), this.command(n.command, n.args);
}
}
}
},
wa = xa,
Sa = (n("813c"), Object(m["a"])(wa, _a, $a, !1, null, null, null));
Sa.options.__file = "Toolbar.vue";
var Oa = Sa.exports,
Ca = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("insert") },
on: {
close: t.cancel,
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.value,
callback: function(e) {
t.value = e;
},
expression: "value"
}
})
],
1
);
},
Ea = [],
ja = {
data: function() {
return {
value: { email: null, text: null },
fields: {
email: { label: this.$t("email"), type: "email" },
text: { label: this.$t("link.text"), type: "text" }
}
};
},
computed: {
kirbytext: function() {
return this.$store.state.system.info.kirbytext;
}
},
methods: {
open: function(t, e) {
(this.value.text = e), this.$refs.dialog.open();
},
cancel: function() {
this.$emit("cancel");
},
createKirbytext: function() {
return this.value.text.length > 0
? "(email: "
.concat(this.value.email, " text: ")
.concat(this.value.text, ")")
: "(email: ".concat(this.value.email, ")");
},
createMarkdown: function() {
return this.value.text.length > 0
? "["
.concat(this.value.text, "](mailto:")
.concat(this.value.email, ")")
: "<".concat(this.value.email, ">");
},
submit: function() {
this.$emit(
"submit",
this.kirbytext ? this.createKirbytext() : this.createMarkdown()
),
(this.value = { email: null, text: null }),
this.$refs.dialog.close();
}
}
},
Ta = ja,
Ia = Object(m["a"])(Ta, Ca, Ea, !1, null, null, null);
Ia.options.__file = "EmailDialog.vue";
var La = Ia.exports,
Aa = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("insert") },
on: {
close: t.cancel,
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.value,
callback: function(e) {
t.value = e;
},
expression: "value"
}
})
],
1
);
},
qa = [],
Na = {
data: function() {
return {
value: { url: null, text: null },
fields: {
url: {
label: this.$t("link"),
type: "text",
placeholder: this.$t("url.placeholder"),
icon: "url"
},
text: { label: this.$t("link.text"), type: "text" }
}
};
},
computed: {
kirbytext: function() {
return this.$store.state.system.info.kirbytext;
}
},
methods: {
open: function(t, e) {
(this.value.text = e), this.$refs.dialog.open();
},
cancel: function() {
this.$emit("cancel");
},
createKirbytext: function() {
return this.value.text.length > 0
? "(link: "
.concat(this.value.url, " text: ")
.concat(this.value.text, ")")
: "(link: ".concat(this.value.url, ")");
},
createMarkdown: function() {
return this.value.text.length > 0
? "[".concat(this.value.text, "](").concat(this.value.url, ")")
: "<".concat(this.value.url, ">");
},
submit: function() {
this.$emit(
"submit",
this.kirbytext ? this.createKirbytext() : this.createMarkdown()
),
(this.value = { url: null, text: null }),
this.$refs.dialog.close();
}
}
},
Pa = Na,
Ba = Object(m["a"])(Pa, Aa, qa, !1, null, null, null);
Ba.options.__file = "LinkDialog.vue";
var Da = Ba.exports,
Fa = n("19e9"),
Ra = n.n(Fa),
Ma = {
components: {
"k-toolbar": Oa,
"k-email-dialog": La,
"k-link-dialog": Da
},
inheritAttrs: !1,
props: {
autofocus: Boolean,
buttons: { type: [Boolean, Array], default: !0 },
disabled: Boolean,
id: [Number, String],
name: [Number, String],
maxlength: Number,
minlength: Number,
placeholder: String,
preselect: Boolean,
required: Boolean,
size: String,
spellcheck: { type: [Boolean, String], default: "off" },
theme: String,
value: String
},
data: function() {
return { over: !1 };
},
watch: {
value: function() {
var t = this;
this.onInvalid(),
this.$nextTick(function() {
t.resize();
});
}
},
mounted: function() {
var t = this;
this.$nextTick(function() {
Ra()(t.$refs.input);
}),
this.onInvalid(),
this.$props.autofocus && this.focus(),
this.$props.preselect && this.select();
},
methods: {
cancel: function() {
this.$refs.input.focus();
},
dialog: function(t) {
if (!this.$refs[t + "Dialog"]) throw "Invalid toolbar dialog";
this.$refs[t + "Dialog"].open(this.$refs.input, this.selection());
},
focus: function() {
this.$refs.input.focus();
},
insert: function(t) {
var e = this.$refs.input,
n = e.value;
if (
(e.focus(),
document.execCommand("insertText", !1, t),
e.value === n)
) {
var i =
e.value.slice(0, e.selectionStart) +
t +
e.value.slice(e.selectionEnd);
(e.value = i), this.$emit("input", i);
}
this.resize();
},
prepend: function(t) {
this.insert(t + " " + this.selection());
},
resize: function() {
Ra.a.update(this.$refs.input);
},
onCommand: function(t, e) {
"function" === typeof this[t]
? "function" === typeof e
? this[t](e(this.$refs.input, this.selection()))
: this[t](e)
: window.console.warn(t + " is not a valid command");
},
onDrop: function() {
var t = this.$store.state.drag;
t && "text" === t.type && (this.focus(), this.insert(t.data));
},
onFocus: function(t) {
this.$emit("focus", t);
},
onInput: function(t) {
this.$emit("input", t.target.value);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
onOut: function() {
this.$refs.input.blur(), (this.over = !1);
},
onOver: function(t) {
var e = this.$store.state.drag;
e &&
"text" === e.type &&
((t.dataTransfer.dropEffect = "copy"),
this.focus(),
(this.over = !0));
},
onShortcut: function(t) {
!1 !== this.buttons &&
"Meta" !== t.key &&
this.$refs.toolbar &&
this.$refs.toolbar.shortcut(t.key, t);
},
onSubmit: function(t) {
return this.$emit("submit", t);
},
select: function() {
this.$refs.select();
},
selection: function() {
var t = this.$refs.input,
e = t.selectionStart,
n = t.selectionEnd;
return t.value.substring(e, n);
},
wrap: function(t) {
this.insert(t + this.selection() + t);
}
},
validations: function() {
return {
value: {
required: !this.required || Ui["required"],
minLength:
!this.minlength || Object(Ui["minLength"])(this.minlength),
maxLength:
!this.maxlength || Object(Ui["maxLength"])(this.maxlength)
}
};
}
},
za = Ma,
Ua = (n("f093"), Object(m["a"])(za, ba, ka, !1, null, null, null));
Ua.options.__file = "TextareaInput.vue";
var Va = Ua.exports,
Ha = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-time-input" },
[
n("k-select-input", {
ref: "hour",
attrs: {
id: t.id,
"aria-label": t.$t("hour"),
autofocus: t.autofocus,
options: t.hours,
required: t.required,
disabled: t.disabled,
placeholder: "––",
empty: "––"
},
on: { input: t.setHour, invalid: t.onInvalid },
model: {
value: t.hour,
callback: function(e) {
t.hour = e;
},
expression: "hour"
}
}),
n("span", { staticClass: "k-time-input-separator" }, [t._v(":")]),
n("k-select-input", {
ref: "minute",
attrs: {
"aria-label": t.$t("minutes"),
options: t.minutes,
required: t.required,
disabled: t.disabled,
placeholder: "––",
empty: "––"
},
on: { input: t.setMinute, invalid: t.onInvalid },
model: {
value: t.minute,
callback: function(e) {
t.minute = e;
},
expression: "minute"
}
}),
12 === t.notation
? n("k-select-input", {
ref: "meridiem",
staticClass: "k-time-input-meridiem",
attrs: {
"aria-label": t.$t("meridiem"),
empty: !1,
options: [
{ value: "AM", text: "AM" },
{ value: "PM", text: "PM" }
],
required: t.required,
disabled: t.disabled
},
on: { input: t.onInput },
model: {
value: t.meridiem,
callback: function(e) {
t.meridiem = e;
},
expression: "meridiem"
}
})
: t._e()
],
1
);
},
Ka = [],
Ga = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
disabled: Boolean,
id: [String, Number],
notation: { type: Number, default: 24 },
required: Boolean,
step: { type: Number, default: 5 },
value: { type: String }
},
data: function() {
var t = this.toObject(this.value);
return {
time: this.value,
hour: t.hour,
minute: t.minute,
meridiem: t.meridiem
};
},
computed: {
hours: function() {
return this.options(
24 === this.notation ? 0 : 1,
24 === this.notation ? 23 : 12
);
},
minutes: function() {
return this.options(0, 59, this.step);
}
},
watch: {
value: function(t) {
this.time = t;
},
time: function(t) {
var e = this.toObject(t);
(this.hour = e.hour),
(this.minute = e.minute),
(this.meridiem = e.meridiem);
}
},
methods: {
focus: function() {
this.$refs.hour.focus();
},
setHour: function(t) {
t && !this.minute && (this.minute = 0),
t || (this.minute = null),
this.onInput();
},
setMinute: function(t) {
t && !this.hour && (this.hour = 0),
t || (this.hour = null),
this.onInput();
},
onInput: function() {
if (null !== this.hour && null !== this.minute) {
var t = lt(this.hour || 0),
e = lt(this.minute || 0),
n = this.meridiem || "AM",
i =
24 === this.notation
? "".concat(t, ":").concat(e, ":00")
: ""
.concat(t, ":")
.concat(e, ":00 ")
.concat(n),
s = rt()("2000-01-01 " + i);
this.$emit("input", s.format("HH:mm"));
} else this.$emit("input", "");
},
onInvalid: function(t, e) {
this.$emit("invalid", t, e);
},
options: function(t, e) {
for (
var n =
arguments.length > 2 && void 0 !== arguments[2]
? arguments[2]
: 1,
i = [],
s = t;
s <= e;
s += n
)
i.push({ value: s, text: lt(s) });
return i;
},
reset: function() {
(this.hour = null), (this.minute = null), (this.meridiem = null);
},
round: function(t) {
return Math.floor(t / this.step) * this.step;
},
toObject: function(t) {
var e = rt()("2001-01-01 " + t + ":00");
return !1 === e.isValid()
? { hour: null, minute: null, meridiem: null }
: {
hour: e.format(24 === this.notation ? "H" : "h"),
minute: this.round(e.format("m")),
meridiem: e.format("A")
};
}
}
},
Ya = Ga,
Wa = (n("35ad"), Object(m["a"])(Ya, Ha, Ka, !1, null, null, null));
Wa.options.__file = "TimeInput.vue";
var Ja = Wa.exports,
Xa = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("label", { staticClass: "k-toggle-input" }, [
n(
"input",
t._g(
{
ref: "input",
staticClass: "k-toggle-input-native",
attrs: { disabled: t.disabled, id: t.id, type: "checkbox" },
domProps: { checked: t.value }
},
t.listeners
)
),
n("span", {
staticClass: "k-toggle-input-label",
domProps: { innerHTML: t._s(t.label) }
})
]);
},
Qa = [],
Za = {
inheritAttrs: !1,
props: {
autofocus: Boolean,
disabled: Boolean,
id: [Number, String],
text: {
type: [Array, String],
default: function() {
return ["off", "on"];
}
},
required: Boolean,
value: Boolean
},
data: function() {
var t = this;
return {
listeners: Object(u["a"])({}, this.$listeners, {
change: function(e) {
return t.onInput(e.target.checked);
},
keydown: this.onEnter
})
};
},
computed: {
label: function() {
return Array.isArray(this.text)
? this.value
? this.text[1]
: this.text[0]
: this.text;
}
},
watch: {
value: function() {
this.onInvalid();
}
},
mounted: function() {
this.onInvalid(), this.$props.autofocus && this.focus();
},
methods: {
focus: function() {
this.$refs.input.focus();
},
onEnter: function(t) {
"Enter" === t.key && this.$refs.input.click();
},
onInput: function(t) {
this.$emit("input", t);
},
onInvalid: function() {
this.$emit("invalid", this.$v.$invalid, this.$v);
},
select: function() {
this.$refs.input.focus();
}
},
validations: function() {
return { value: { required: !this.required || Ui["required"] } };
}
},
to = Za,
eo = (n("3a66"), Object(m["a"])(to, Xa, Qa, !1, null, null, null));
eo.options.__file = "ToggleInput.vue";
var no,
io,
so = eo.exports,
ao = {
extends: ks,
props: Object(u["a"])({}, ks.props, {
autocomplete: { type: String, default: "url" },
type: { type: String, default: "url" }
})
},
oo = ao,
ro = Object(m["a"])(oo, no, io, !1, null, null, null);
ro.options.__file = "UrlInput.vue";
var lo = ro.exports,
uo = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{
staticClass: "k-checkboxes-field",
attrs: { counter: t.counterOptions }
},
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
co = [],
po = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, Zi.props, {
counter: { type: Boolean, default: !0 }
}),
computed: {
counterOptions: function() {
return (
null !== this.value &&
!this.disabled &&
!1 !== this.counter && {
count:
this.value && Array.isArray(this.value)
? this.value.length
: 0,
min: this.min,
max: this.max
}
);
}
},
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
fo = po,
ho = Object(m["a"])(fo, uo, co, !1, null, null, null);
ho.options.__file = "CheckboxesField.vue";
var mo = ho.exports,
go = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-date-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{
ref: "input",
attrs: {
id: t._uid,
type: t.inputType,
value: t.date,
theme: "field"
}
},
"k-input",
t.$props,
!1
),
t.listeners
),
[
n(
"template",
{ slot: "icon" },
[
n(
"k-dropdown",
[
n("k-button", {
staticClass: "k-input-icon-button",
attrs: {
icon: t.icon,
tooltip: t.$t("date.select"),
tabindex: "-1"
},
on: {
click: function(e) {
t.$refs.dropdown.toggle();
}
}
}),
n(
"k-dropdown-content",
{ ref: "dropdown", attrs: { align: "right" } },
[
n("k-calendar", {
attrs: { value: t.date },
on: {
input: function(e) {
t.onInput(e), t.$refs.dropdown.close();
}
}
})
],
1
)
],
1
)
],
1
)
],
2
)
],
1
);
},
vo = [],
bo = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, ps.props, {
icon: { type: String, default: "calendar" }
}),
data: function() {
return {
date: this.value,
listeners: Object(u["a"])({}, this.$listeners, {
input: this.onInput
})
};
},
computed: {
inputType: function() {
return !1 === this.time ? "date" : "datetime";
}
},
watch: {
value: function(t) {
this.date = t;
}
},
methods: {
focus: function() {
this.$refs.input.focus();
},
onInput: function(t) {
(this.date = t), this.$emit("input", t);
}
}
},
ko = bo,
_o = Object(m["a"])(ko, go, vo, !1, null, null, null);
_o.options.__file = "DateField.vue";
var $o = _o.exports,
yo = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-email-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
),
[
t.link
? n("k-button", {
staticClass: "k-input-icon-button",
attrs: {
slot: "icon",
icon: t.icon,
link: "mailto:" + t.value,
tooltip: t.$t("open"),
tabindex: "-1",
target: "_blank"
},
slot: "icon"
})
: t._e()
],
1
)
],
1
);
},
xo = [],
wo = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, xs.props, {
link: { type: Boolean, default: !0 },
icon: { type: String, default: "email" }
}),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
So = wo,
Oo = Object(m["a"])(So, yo, xo, !1, null, null, null);
Oo.options.__file = "EmailField.vue";
var Co = Oo.exports,
Eo = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b({ staticClass: "k-files-field" }, "k-field", t.$props, !1),
[
t.more
? n(
"k-button",
{
attrs: { slot: "options", icon: "add" },
on: { click: t.open },
slot: "options"
},
[t._v("\n " + t._s(t.$t("select")) + "\n ")]
)
: t._e(),
t.selected.length
? [
n(
"k-draggable",
{
attrs: {
element: t.elements.list,
list: t.selected,
options: t.dragOptions,
"data-size": t.size
},
on: { start: t.onStart, end: t.onInput }
},
t._l(t.selected, function(e, i) {
return n(
t.elements.item,
{
key: e.filename,
tag: "component",
attrs: {
sortable: !0,
text: e.filename,
link: e.link,
image: e.thumb
? { url: e.thumb, back: "pattern" }
: null,
icon: { type: "file", back: "pattern" }
}
},
[
n("k-button", {
attrs: {
slot: "options",
tooltip: t.$t("remove"),
icon: "remove"
},
on: {
click: function(e) {
t.remove(i);
}
},
slot: "options"
})
],
1
);
}),
1
)
]
: n(
"k-empty",
{
attrs: { layout: t.layout, icon: "image" },
on: { click: t.open }
},
[t._v("\n " + t._s(t.$t("field.files.empty")) + "\n ")]
),
n("k-files-dialog", { ref: "selector", on: { submit: t.select } })
],
2
);
},
jo = [],
To = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, {
layout: String,
max: Number,
multiple: Boolean,
parent: String,
size: String,
value: {
type: Array,
default: function() {
return [];
}
}
}),
data: function() {
return { selected: this.value };
},
computed: {
dragOptions: function() {
return {
forceFallback: !0,
fallbackClass: "sortable-fallback",
fallbackOnBody: !0,
scroll: document.querySelector(".k-panel-view"),
handle: ".k-sort-handle"
};
},
elements: function() {
var t = {
cards: { list: "k-cards", item: "k-card" },
list: { list: "k-list", item: "k-list-item" }
};
return t[this.layout] ? t[this.layout] : t["list"];
},
more: function() {
return !this.max || this.max > this.selected.length;
}
},
watch: {
value: function(t) {
this.selected = t;
}
},
methods: {
open: function() {
this.$refs.selector.open({
max: this.max,
multiple: this.multiple,
parent: this.parent,
selected: this.selected.map(function(t) {
return t.id;
})
});
},
remove: function(t) {
this.selected.splice(t, 1), this.onInput();
},
focus: function() {},
onStart: function() {
this.$store.dispatch("drag", {});
},
onInput: function() {
this.$store.dispatch("drag", null),
this.$emit("input", this.selected);
},
select: function(t) {
(this.selected = t), this.onInput();
}
}
},
Io = To,
Lo = Object(m["a"])(Io, Eo, jo, !1, null, null, null);
Lo.options.__file = "FilesField.vue";
var Ao = Lo.exports,
qo = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-headline",
{
staticClass: "k-headline-field",
attrs: { "data-numbered": t.numbered, size: "large" }
},
[t._v("\n " + t._s(t.label) + "\n")]
);
},
No = [],
Po = { props: { label: String, numbered: Boolean } },
Bo = Po,
Do = (n("7027"), Object(m["a"])(Bo, qo, No, !1, null, null, null));
Do.options.__file = "HeadlineField.vue";
var Fo = Do.exports,
Ro = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-field k-info-field" },
[
n("k-headline", [t._v(t._s(t.label))]),
n(
"k-box",
{ attrs: { theme: t.theme } },
[n("k-text", { domProps: { innerHTML: t._s(t.text) } })],
1
)
],
1
);
},
Mo = [],
zo = {
props: {
label: String,
text: String,
theme: { type: String, default: "info" }
}
},
Uo = zo,
Vo = (n("e104"), Object(m["a"])(Uo, Ro, Mo, !1, null, null, null));
Vo.options.__file = "InfoField.vue";
var Ho = Vo.exports,
Ko = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("hr", { staticClass: "k-line-field" });
},
Go = [],
Yo = (n("4e2b"), {}),
Wo = Object(m["a"])(Yo, Ko, Go, !1, null, null, null);
Wo.options.__file = "LineField.vue";
var Jo = Wo.exports,
Xo = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{
staticClass: "k-multiselect-field",
attrs: { input: t._uid, counter: t.counterOptions },
on: { blur: t.blur }
},
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
Qo = [],
Zo = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, js.props, {
counter: { type: Boolean, default: !0 },
icon: { type: String, default: "angle-down" }
}),
computed: {
counterOptions: function() {
return (
null !== this.value &&
!this.disabled &&
!1 !== this.counter && {
count:
this.value && Array.isArray(this.value)
? this.value.length
: 0,
min: this.min,
max: this.max
}
);
}
},
methods: {
blur: function(t) {
this.$refs.input.blur(t);
},
focus: function() {
this.$refs.input.focus();
}
}
},
tr = Zo,
er = Object(m["a"])(tr, Xo, Qo, !1, null, null, null);
er.options.__file = "MultiselectField.vue";
var nr = er.exports,
ir = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-number-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
sr = [],
ar = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, Bs.props),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
or = ar,
rr = Object(m["a"])(or, ir, sr, !1, null, null, null);
rr.options.__file = "NumberField.vue";
var lr = rr.exports,
ur = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b({ staticClass: "k-pages-field" }, "k-field", t.$props, !1),
[
t.more
? n(
"k-button",
{
attrs: { slot: "options", icon: "add" },
on: { click: t.open },
slot: "options"
},
[t._v("\n " + t._s(t.$t("select")) + "\n ")]
)
: t._e(),
t.selected.length
? [
n(
"k-draggable",
{
attrs: {
element: t.elements.list,
list: t.selected,
options: t.dragOptions
},
on: { start: t.onStart, end: t.onInput }
},
t._l(t.selected, function(e, i) {
return n(
t.elements.item,
{
key: e.id,
tag: "component",
attrs: {
sortable: !0,
text: e.title,
link: t.$api.pages.link(e.id),
icon: { type: "page", back: "black" }
}
},
[
n("k-button", {
attrs: { slot: "options", icon: "remove" },
on: {
click: function(e) {
t.remove(i);
}
},
slot: "options"
})
],
1
);
}),
1
)
]
: n(
"k-empty",
{
attrs: { layout: t.layout, icon: "page" },
on: { click: t.open }
},
[t._v("\n " + t._s(t.$t("field.pages.empty")) + "\n ")]
),
n("k-pages-dialog", { ref: "selector", on: { submit: t.select } })
],
2
);
},
cr = [],
pr = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, {
max: Number,
multiple: Boolean,
value: {
type: Array,
default: function() {
return [];
}
}
}),
data: function() {
return { layout: "list", selected: this.value };
},
computed: {
dragOptions: function() {
return {
forceFallback: !0,
fallbackClass: "sortable-fallback",
fallbackOnBody: !0,
scroll: document.querySelector(".k-panel-view"),
handle: ".k-sort-handle"
};
},
elements: function() {
return { list: "k-list", item: "k-list-item" };
},
more: function() {
return !this.max || this.max > this.selected.length;
}
},
watch: {
value: function(t) {
this.selected = t;
}
},
methods: {
open: function() {
this.$refs.selector.open({
max: this.max,
multiple: this.multiple,
selected: this.selected.map(function(t) {
return t.id;
})
});
},
remove: function(t) {
this.selected.splice(t, 1), this.onInput();
},
focus: function() {},
onStart: function() {
this.$store.dispatch("drag", {});
},
onInput: function() {
this.$store.dispatch("drag", null),
this.$emit("input", this.selected);
},
select: function(t) {
(this.selected = t), this.onInput();
}
}
},
fr = pr,
dr = Object(m["a"])(fr, ur, cr, !1, null, null, null);
dr.options.__file = "PagesField.vue";
var hr = dr.exports,
mr = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{
staticClass: "k-password-field",
attrs: { input: t._uid, counter: t.counterOptions }
},
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
gr = [],
vr = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, Ms.props, {
counter: { type: Boolean, default: !0 },
minlength: { type: Number, default: 8 },
icon: { type: String, default: "key" }
}),
computed: {
counterOptions: function() {
return (
null !== this.value &&
!this.disabled &&
!1 !== this.counter && {
count: this.value ? String(this.value).length : 0,
min: this.minlength,
max: this.maxlength
}
);
}
},
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
br = vr,
kr = Object(m["a"])(br, mr, gr, !1, null, null, null);
kr.options.__file = "PasswordField.vue";
var _r = kr.exports,
$r = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b({ staticClass: "k-radio-field" }, "k-field", t.$props, !1),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
yr = [],
xr = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, Gs.props),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
wr = xr,
Sr = Object(m["a"])(wr, $r, yr, !1, null, null, null);
Sr.options.__file = "RadioField.vue";
var Or = Sr.exports,
Cr = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-range-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
Er = [],
jr = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, Zs.props),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
Tr = jr,
Ir = Object(m["a"])(Tr, Cr, Er, !1, null, null, null);
Ir.options.__file = "RangeField.vue";
var Lr = Ir.exports,
Ar = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-select-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
qr = [],
Nr = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, aa.props, {
icon: { type: String, default: "angle-down" }
}),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
Pr = Nr,
Br = Object(m["a"])(Pr, Ar, qr, !1, null, null, null);
Br.options.__file = "SelectField.vue";
var Dr = Br.exports,
Fr = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{
staticClass: "k-structure-field",
nativeOn: {
click: function(t) {
t.stopPropagation();
}
}
},
"k-field",
t.$props,
!1
),
[
n(
"template",
{ slot: "options" },
[
t.more && null === t.currentIndex
? n(
"k-button",
{
ref: "add",
attrs: { id: t._uid, icon: "add" },
on: { click: t.add }
},
[t._v("\n " + t._s(t.$t("add")) + "\n ")]
)
: t._e()
],
1
),
null !== t.currentIndex
? [
n("div", {
staticClass: "k-structure-backdrop",
on: { click: t.escape }
}),
n(
"section",
{ staticClass: "k-structure-form" },
[
n("k-form", {
ref: "form",
staticClass: "k-structure-form-fields",
attrs: { fields: t.formFields },
on: { input: t.onInput, submit: t.submit },
model: {
value: t.currentModel,
callback: function(e) {
t.currentModel = e;
},
expression: "currentModel"
}
}),
n(
"footer",
{ staticClass: "k-structure-form-buttons" },
[
n(
"k-button",
{
staticClass: "k-structure-form-cancel-button",
attrs: { icon: "cancel" },
on: { click: t.close }
},
[t._v(t._s(t.$t("cancel")))]
),
"new" !== t.currentIndex
? n("k-pagination", {
attrs: {
dropdown: !1,
total: t.items.length,
limit: 1,
page: t.currentIndex + 1,
details: !0,
validate: t.beforePaginate
},
on: { paginate: t.paginate }
})
: t._e(),
n(
"k-button",
{
staticClass: "k-structure-form-submit-button",
attrs: { icon: "check" },
on: { click: t.submit }
},
[
t._v(
t._s(
t.$t(
"new" !== t.currentIndex ? "confirm" : "add"
)
)
)
]
)
],
1
)
],
1
)
]
: 0 === t.items.length
? n(
"k-empty",
{ attrs: { icon: "list-bullet" }, on: { click: t.add } },
[
t._v(
"\n " + t._s(t.$t("field.structure.empty")) + "\n "
)
]
)
: [
n(
"table",
{
staticClass: "k-structure-table",
attrs: { "data-sortable": t.isSortable }
},
[
n("thead", [
n(
"tr",
[
n(
"th",
{ staticClass: "k-structure-table-index" },
[t._v("#")]
),
t._l(t.columns, function(e, i) {
return n(
"th",
{
key: i + "-header",
staticClass: "k-structure-table-column",
attrs: {
"data-width": e.width,
"data-align": e.align
}
},
[
t._v(
"\n " +
t._s(e.label) +
"\n "
)
]
);
}),
n("th")
],
2
)
]),
n(
"k-draggable",
{
attrs: {
"data-disabled": t.disabled,
options: t.dragOptions,
element: "tbody"
},
on: {
input: t.onInput,
choose: t.close,
end: t.onInput
},
model: {
value: t.items,
callback: function(e) {
t.items = e;
},
expression: "items"
}
},
t._l(t.paginatedItems, function(e, i) {
return n(
"tr",
{
key: i,
on: {
click: function(t) {
t.stopPropagation();
}
}
},
[
n(
"td",
{ staticClass: "k-structure-table-index" },
[
t.isSortable
? n("k-button", {
staticClass:
"k-structure-table-handle",
attrs: { icon: "sort" }
})
: t._e(),
n("span", [t._v(t._s(t.indexOf(i)))])
],
1
),
t._l(t.columns, function(s, a) {
return n(
"td",
{
key: a,
staticClass: "k-structure-table-column",
attrs: {
title: s.label,
"data-width": s.width,
"data-align": s.align
},
on: {
click: function(e) {
t.jump(i, a);
}
}
},
[
!1 === t.columnIsEmpty(e[a])
? [
t.previewExists(s.type)
? n(
"k-" +
s.type +
"-field-preview",
{
tag: "component",
attrs: {
value: e[a],
column: s,
field: t.fields[a]
}
}
)
: [
n(
"p",
{
staticClass:
"k-structure-table-text"
},
[
t._v(
"\n " +
t._s(s.before) +
" " +
t._s(
t.displayText(
t.fields[a],
e[a]
) || "–"
) +
" " +
t._s(s.after) +
"\n "
)
]
)
]
]
: t._e()
],
2
);
}),
n(
"td",
{ staticClass: "k-structure-table-option" },
[
n("k-button", {
attrs: {
tooltip: t.$t("remove"),
icon: "remove"
},
on: {
click: function(e) {
t.confirmRemove(i);
}
}
})
],
1
)
],
2
);
}),
0
)
],
1
),
t.limit
? n(
"k-pagination",
t._b(
{ on: { paginate: t.paginateItems } },
"k-pagination",
t.pagination,
!1
)
)
: t._e(),
t.disabled
? t._e()
: n(
"k-dialog",
{
ref: "remove",
attrs: {
button: t.$t("delete"),
theme: "negative"
},
on: { submit: t.remove }
},
[
n("k-text", [
t._v(t._s(t.$t("field.structure.delete.confirm")))
])
],
1
)
]
],
2
);
},
Rr = [],
Mr = (n("8615"),
function(t) {
t = t || {};
var e = t.desc ? -1 : 1,
n = -e,
i = /^0/,
s = /\s+/g,
a = /^\s+|\s+$/g,
o = /[^\x00-\x80]/,
r = /^0x[0-9a-f]+$/i,
l = /(0x[\da-fA-F]+|(^[\+\-]?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?(?=\D|\s|$))|\d+)/g,
u = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
c = t.insensitive
? function(t) {
return p("" + t).replace(a, "");
}
: function(t) {
return ("" + t).replace(a, "");
};
function p(t) {
return t.toLocaleLowerCase ? t.toLocaleLowerCase() : t.toLowerCase();
}
function f(t) {
return t
.replace(l, "\0$1\0")
.replace(/\0$/, "")
.replace(/^\0/, "")
.split("\0");
}
function d(t, e) {
return (
((!t.match(i) || 1 === e) && parseFloat(t)) ||
t.replace(s, " ").replace(a, "") ||
0
);
}
return function(t, i) {
var s = c(t),
a = c(i);
if (!s && !a) return 0;
if (!s && a) return n;
if (s && !a) return e;
var l = f(s),
p = f(a),
h = parseInt(s.match(r), 16) || (1 !== l.length && Date.parse(s)),
m =
parseInt(a.match(r), 16) ||
(h && a.match(u) && Date.parse(a)) ||
null;
if (m) {
if (h < m) return n;
if (h > m) return e;
}
for (
var g = l.length, v = p.length, b = 0, k = Math.max(g, v);
b < k;
b++
) {
var _ = d(l[b] || "", g),
$ = d(p[b] || "", v);
if (isNaN(_) !== isNaN($)) return isNaN(_) ? e : n;
if (o.test(_ + $) && _.localeCompare) {
var y = _.localeCompare($);
if (y > 0) return e;
if (y < 0) return n;
if (b === k - 1) return 0;
} else {
if (_ < $) return n;
if (_ > $) return e;
}
}
return 0;
};
}),
zr = function(t) {
if (void 0 !== t) return JSON.parse(JSON.stringify(t));
};
Array.prototype.sortBy = function(t) {
var e = Mr(),
n = t.split(" "),
i = n[0],
s = n[1] || "asc";
return this.sort(function(t, n) {
var a = String(t[i]).toLowerCase(),
o = String(n[i]).toLowerCase();
return "desc" === s ? e(o, a) : e(a, o);
});
};
var Ur = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, {
columns: Object,
fields: Object,
limit: Number,
max: Number,
min: Number,
sortable: { type: Boolean, default: !0 },
sortBy: String,
value: {
type: Array,
default: function() {
return [];
}
}
}),
data: function() {
return {
items: this.makeItems(this.value),
currentIndex: null,
currentModel: null,
trash: null,
page: 1
};
},
computed: {
dragOptions: function() {
return {
disabled: !this.isSortable,
handle: ".k-structure-table-handle",
forceFallback: !0,
fallbackClass: "sortable-fallback",
fallbackOnBody: !0,
scroll: document.querySelector(".k-panel-view")
};
},
formFields: function() {
var t = this,
e = {};
return (
Object.keys(this.fields).forEach(function(n) {
var i = t.fields[n];
(i.section = t.name),
(i.endpoints = {
field: t.endpoints.field + "+" + n,
section: t.endpoints.section,
model: t.endpoints.model
}),
(e[n] = i);
}),
e
);
},
more: function() {
return (
!0 !== this.disabled &&
!(this.max && this.items.length >= this.max)
);
},
isSortable: function() {
return (
!this.sortBy &&
(!this.limit &&
(!0 !== this.disabled &&
(!(this.items.length <= 1) && !1 !== this.sortable)))
);
},
pagination: function() {
return {
page: this.page,
limit: this.limit,
total: this.items.length,
align: "center",
details: !0
};
},
paginatedItems: function() {
if (!this.limit) return this.items;
var t = this.page - 1,
e = t * this.limit;
return this.items.slice(e, e + this.limit);
}
},
watch: {
value: function(t) {
t != this.items && (this.items = this.makeItems(t));
}
},
methods: {
add: function() {
var t = this;
if (!0 === this.disabled) return !1;
if (null !== this.currentIndex) return this.escape(), !1;
var e = {};
Object.keys(this.fields).forEach(function(n) {
var i = t.fields[n];
i.default && (e[n] = i.default);
}),
(this.currentIndex = "new"),
(this.currentModel = e),
this.createForm();
},
close: function() {
(this.currentIndex = null),
(this.currentModel = null),
this.$events.$off("keydown.esc", this.escape),
this.$events.$off("keydown.cmd.s", this.submit),
this.$store.dispatch("form/unlock");
},
columnIsEmpty: function(t) {
return (
void 0 === t ||
null === t ||
"" === t ||
(("object" === Object(Y["a"])(t) &&
0 === Object.keys(t).length &&
t.constructor === Object) ||
(void 0 !== t.length && 0 === t.length))
);
},
confirmRemove: function(t) {
this.close(), (this.trash = t), this.$refs.remove.open();
},
createForm: function(t) {
var e = this;
this.$events.$on("keydown.esc", this.escape),
this.$events.$on("keydown.cmd.s", this.submit),
this.$store.dispatch("form/lock"),
this.$nextTick(function() {
e.$refs.form && e.$refs.form.focus(t);
});
},
displayText: function(t, e) {
switch (t.type) {
case "user":
return e.email;
case "date":
var n = rt()(e);
return n.isValid() ? n.format("YYYY-MM-DD") : "";
case "tags":
return e
.map(function(t) {
return t.text;
})
.join(", ");
case "checkboxes":
return e
.map(function(e) {
var n = e;
return (
t.options.forEach(function(t) {
t.value === e && (n = t.text);
}),
n
);
})
.join(", ");
case "select":
var i = t.options.filter(function(t) {
return t.value === e;
})[0];
return i ? i.text : null;
}
return "object" === Object(Y["a"])(e) && null !== e ? "…" : e;
},
escape: function() {
var t = this;
if ("new" === this.currentIndex) {
var e = Object.values(this.currentModel),
n = !0;
if (
(e.forEach(function(e) {
!1 === t.columnIsEmpty(e) && (n = !1);
}),
!0 === n)
)
return void this.close();
}
this.submit();
},
focus: function() {
this.$refs.add.focus();
},
indexOf: function(t) {
return this.limit ? (this.page - 1) * this.limit + t + 1 : t + 1;
},
isActive: function(t) {
return this.currentIndex === t;
},
jump: function(t, e) {
this.open(t, e);
},
makeItems: function(t) {
return !1 === Array.isArray(t) ? [] : this.sort(t);
},
onInput: function() {
this.$emit("input", this.items);
},
open: function(t, e) {
(this.currentIndex = t),
(this.currentModel = zr(this.items[t])),
this.createForm(e);
},
beforePaginate: function() {
return this.save(this.currentModel);
},
paginate: function(t) {
this.open(t.offset);
},
paginateItems: function(t) {
this.page = t.page;
},
previewExists: function(t) {
return (
void 0 !==
i["a"].options.components["k-" + t + "-field-preview"] ||
void 0 !== this.$options.components["k-" + t + "-field-preview"]
);
},
remove: function() {
if (null === this.trash) return !1;
this.items.splice(this.trash, 1),
(this.trash = null),
this.$refs.remove.close(),
this.onInput(),
0 === this.paginatedItems.length && this.page > 1 && this.page--,
(this.items = this.sort(this.items));
},
sort: function(t) {
return this.sortBy ? t.sortBy(this.sortBy) : t;
},
save: function() {
var t = this;
return null !== this.currentIndex && void 0 !== this.currentIndex
? this.validate(this.currentModel)
.then(function() {
return (
"new" === t.currentIndex
? t.items.push(t.currentModel)
: (t.items[t.currentIndex] = t.currentModel),
(t.items = t.sort(t.items)),
t.onInput(),
!0
);
})
.catch(function(e) {
throw (t.$store.dispatch("notification/error", {
message: t.$t("error.form.incomplete"),
details: e
}),
e);
})
: Promise.resolve();
},
submit: function() {
this.save()
.then(this.close)
.catch(function() {});
},
validate: function(t) {
return this.$api
.post(this.endpoints.field + "/validate", t)
.then(function(t) {
if (t.length > 0) throw t;
return !0;
});
}
}
},
Vr = Ur,
Hr = (n("68b5"), Object(m["a"])(Vr, Fr, Rr, !1, null, null, null));
Hr.options.__file = "StructureField.vue";
var Kr = Hr.exports,
Gr = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{
staticClass: "k-tags-field",
attrs: { input: t._uid, counter: t.counterOptions }
},
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
Yr = [],
Wr = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, da.props, {
counter: { type: Boolean, default: !0 }
}),
computed: {
counterOptions: function() {
return (
null !== this.value &&
!this.disabled &&
!1 !== this.counter && {
count:
this.value && Array.isArray(this.value)
? this.value.length
: 0,
min: this.min,
max: this.max
}
);
}
},
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
Jr = Wr,
Xr = Object(m["a"])(Jr, Gr, Yr, !1, null, null, null);
Xr.options.__file = "TagsField.vue";
var Qr = Xr.exports,
Zr = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-tel-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
tl = [],
el = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, va.props, {
icon: { type: String, default: "phone" }
}),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
nl = el,
il = Object(m["a"])(nl, Zr, tl, !1, null, null, null);
il.options.__file = "TelField.vue";
var sl = il.exports,
al = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{
staticClass: "k-text-field",
attrs: { input: t._uid, counter: t.counterOptions }
},
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
ol = [],
rl = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, ks.props, {
counter: { type: Boolean, default: !0 }
}),
computed: {
counterOptions: function() {
return (
null !== this.value &&
!this.disabled &&
!1 !== this.counter && {
count: this.value ? String(this.value).length : 0,
min: this.minlength,
max: this.maxlength
}
);
}
},
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
ll = rl,
ul = (n("a89c"), Object(m["a"])(ll, al, ol, !1, null, null, null));
ul.options.__file = "TextField.vue";
var cl = ul.exports,
pl = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{
staticClass: "k-textarea-field",
attrs: { input: t._uid, counter: t.counterOptions }
},
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{
ref: "input",
attrs: { id: t._uid, type: "textarea", theme: "field" }
},
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
fl = [],
dl = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, Va.props, {
counter: { type: Boolean, default: !0 }
}),
computed: {
counterOptions: function() {
return (
null !== this.value &&
!this.disabled &&
!1 !== this.counter && {
count: this.value ? this.value.length : 0,
min: this.minlength,
max: this.maxlength
}
);
}
},
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
hl = dl,
ml = Object(m["a"])(hl, pl, fl, !1, null, null, null);
ml.options.__file = "TextareaField.vue";
var gl = ml.exports,
vl = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-time-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
bl = [],
kl = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, Ja.props, {
icon: { type: String, default: "clock" }
}),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
_l = kl,
$l = Object(m["a"])(_l, vl, bl, !1, null, null, null);
$l.options.__file = "TimeField.vue";
var yl = $l.exports,
xl = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-toggle-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
)
)
],
1
);
},
wl = [],
Sl = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, so.props),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
Ol = Sl,
Cl = Object(m["a"])(Ol, xl, wl, !1, null, null, null);
Cl.options.__file = "ToggleField.vue";
var El = Cl.exports,
jl = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b(
{ staticClass: "k-url-field", attrs: { input: t._uid } },
"k-field",
t.$props,
!1
),
[
n(
"k-input",
t._g(
t._b(
{ ref: "input", attrs: { id: t._uid, theme: "field" } },
"k-input",
t.$props,
!1
),
t.$listeners
),
[
t.link
? n("k-button", {
staticClass: "k-input-icon-button",
attrs: {
slot: "icon",
icon: t.icon,
link: t.value,
tooltip: t.$t("open"),
tabindex: "-1",
target: "_blank"
},
slot: "icon"
})
: t._e()
],
1
)
],
1
);
},
Tl = [],
Il = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, Li.props, lo.props, {
link: { type: Boolean, default: !0 },
icon: { type: String, default: "url" }
}),
methods: {
focus: function() {
this.$refs.input.focus();
}
}
},
Ll = Il,
Al = Object(m["a"])(Ll, jl, Tl, !1, null, null, null);
Al.options.__file = "UrlField.vue";
var ql = Al.exports,
Nl = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-field",
t._b({ staticClass: "k-users-field" }, "k-field", t.$props, !1),
[
t.more
? n(
"k-button",
{
attrs: { slot: "options", icon: "add" },
on: { click: t.open },
slot: "options"
},
[t._v("\n " + t._s(t.$t("select")) + "\n ")]
)
: t._e(),
t.selected.length
? [
n(
"k-draggable",
{
attrs: {
element: t.elements.list,
list: t.selected,
options: t.dragOptions
},
on: { start: t.onStart, end: t.onInput }
},
t._l(t.selected, function(e, i) {
return n(
t.elements.item,
{
key: e.email,
tag: "component",
attrs: {
sortable: !0,
text: e.username,
link: t.$api.users.link(e.id),
image: e.avatar
? {
url: e.avatar.url,
back: "pattern",
cover: !0
}
: null,
icon: { type: "user", back: "black" }
}
},
[
n("k-button", {
attrs: { slot: "options", icon: "remove" },
on: {
click: function(e) {
t.remove(i);
}
},
slot: "options"
})
],
1
);
}),
1
)
]
: n(
"k-empty",
{ attrs: { icon: "users" }, on: { click: t.open } },
[t._v("\n " + t._s(t.$t("field.users.empty")) + "\n ")]
),
n("k-users-dialog", { ref: "selector", on: { submit: t.select } })
],
2
);
},
Pl = [],
Bl = {
inheritAttrs: !1,
props: Object(u["a"])({}, _i.props, {
max: Number,
multiple: Boolean,
value: {
type: Array,
default: function() {
return [];
}
}
}),
data: function() {
return { layout: "list", selected: this.value };
},
computed: {
dragOptions: function() {
return {
forceFallback: !0,
fallbackClass: "sortable-fallback",
fallbackOnBody: !0,
scroll: document.querySelector(".k-panel-view"),
handle: ".k-sort-handle"
};
},
elements: function() {
return { list: "k-list", item: "k-list-item" };
},
more: function() {
return !this.max || this.max > this.selected.length;
}
},
watch: {
value: function(t) {
this.selected = t;
}
},
methods: {
open: function() {
this.$refs.selector.open({
max: this.max,
multiple: this.multiple,
selected: this.selected.map(function(t) {
return t.email;
})
});
},
remove: function(t) {
this.selected.splice(t, 1), this.onInput();
},
focus: function() {},
onStart: function() {
this.$store.dispatch("drag", {});
},
onInput: function() {
this.$store.dispatch("drag", null),
this.$emit("input", this.selected);
},
select: function(t) {
(this.selected = t), this.onInput();
}
}
},
Dl = Bl,
Fl = Object(m["a"])(Dl, Nl, Pl, !1, null, null, null);
Fl.options.__file = "UsersField.vue";
var Rl = Fl.exports,
Ml = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.value
? n(
"ul",
{ staticClass: "k-files-field-preview" },
t._l(t.value, function(t) {
return n(
"li",
{ key: t.url },
[
n(
"k-link",
{
attrs: { title: t.filename, to: t.link },
nativeOn: {
click: function(t) {
t.stopPropagation();
}
}
},
[
n("k-image", { attrs: { src: t.url, back: "pattern" } })
],
1
)
],
1
);
}),
0
)
: t._e();
},
zl = [],
Ul = { props: { value: Array } },
Vl = Ul,
Hl = (n("3e93"), Object(m["a"])(Vl, Ml, zl, !1, null, null, null));
Hl.options.__file = "FilesFieldPreview.vue";
var Kl = Hl.exports,
Gl = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"p",
{ staticClass: "k-url-field-preview" },
[
n(
"k-link",
{
attrs: { to: t.link, target: "_blank" },
nativeOn: {
click: function(t) {
t.stopPropagation();
}
}
},
[t._v(t._s(t.value))]
)
],
1
);
},
Yl = [],
Wl = {
props: { column: Object, value: String },
computed: {
link: function() {
return this.value;
}
}
},
Jl = Wl,
Xl = (n("b61e"), Object(m["a"])(Jl, Gl, Yl, !1, null, null, null));
Xl.options.__file = "UrlFieldPreview.vue";
var Ql,
Zl,
tu = Xl.exports,
eu = {
extends: tu,
computed: {
link: function() {
return "mailto:" + this.value;
}
}
},
nu = eu,
iu = Object(m["a"])(nu, Ql, Zl, !1, null, null, null);
iu.options.__file = "EmailFieldPreview.vue";
var su = iu.exports,
au = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.value
? n(
"ul",
{ staticClass: "k-pages-field-preview" },
t._l(t.value, function(e) {
return n("li", { key: e.id }, [
n(
"figure",
[
n(
"k-link",
{
attrs: { title: e.id, to: t.$api.pages.link(e.id) },
nativeOn: {
click: function(t) {
t.stopPropagation();
}
}
},
[
n("k-icon", {
staticClass: "k-pages-field-preview-image",
attrs: { type: "page", back: "pattern" }
}),
n("figcaption", [
t._v("\n " + t._s(e.title) + "\n ")
])
],
1
)
],
1
)
]);
}),
0
)
: t._e();
},
ou = [],
ru = { props: { value: Array } },
lu = ru,
uu = (n("0eae"), Object(m["a"])(lu, au, ou, !1, null, null, null));
uu.options.__file = "PagesFieldPreview.vue";
var cu = uu.exports,
pu = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.value
? n(
"ul",
{ staticClass: "k-users-field-preview" },
t._l(t.value, function(e) {
return n("li", { key: e.email }, [
n(
"figure",
[
n(
"k-link",
{
attrs: {
title: e.email,
to: t.$api.users.link(e.id)
},
nativeOn: {
click: function(t) {
t.stopPropagation();
}
}
},
[
e.avatar
? n("k-image", {
staticClass: "k-users-field-preview-avatar",
attrs: { src: e.avatar.url, back: "pattern" }
})
: n("k-icon", {
staticClass: "k-users-field-preview-avatar",
attrs: { type: "user", back: "pattern" }
}),
n("figcaption", [
t._v(
"\n " + t._s(e.username) + "\n "
)
])
],
1
)
],
1
)
]);
}),
0
)
: t._e();
},
fu = [],
du = { props: { value: Array } },
hu = du,
mu = (n("77f7"), Object(m["a"])(hu, pu, fu, !1, null, null, null));
mu.options.__file = "UsersFieldPreview.vue";
var gu = mu.exports;
i["a"].use(T.a), i["a"].use(q);
var vu = {
install: function(t) {
t.filter("t", function(t) {
return t;
}),
t.directive("tab", {
inserted: function(t) {
t.addEventListener("keyup", function(e) {
9 === e.keyCode && (t.dataset.tabbed = !0);
}),
t.addEventListener("blur", function() {
delete t.dataset.tabbed;
});
}
}),
t.component("k-bar", F),
t.component("k-box", H),
t.component("k-button", Q),
t.component("k-button-group", it),
t.component("k-calendar", ft),
t.component("k-card", kt),
t.component("k-cards", St),
t.component("k-collection", It),
t.component("k-column", Bt),
t.component("k-counter", Ut),
t.component("k-dialog", Wt),
t.component("k-draggable", L.a),
t.component("k-dropdown", te),
t.component("k-dropdown-content", re),
t.component("k-dropdown-item", de),
t.component("k-empty", $e),
t.component("k-error-boundary", Se),
t.component("k-grid", Ie),
t.component("k-header", Be),
t.component("k-headline", Ue),
t.component("k-icon", We),
t.component("k-image", en),
t.component("k-link", ln),
t.component("k-list", hn),
t.component("k-list-item", _n),
t.component("k-pagination", On),
t.component("k-prev-next", Ln),
t.component("k-progress", Dn),
t.component("k-tag", Vn),
t.component("k-text", Jn),
t.component("k-view", ni),
t.component("k-autocomplete", li),
t.component("k-form", hi),
t.component("k-field", _i),
t.component("k-fieldset", Oi),
t.component("k-input", Li),
t.component("k-upload", Ri),
t.component("k-checkbox-input", Gi),
t.component("k-checkboxes-input", Zi),
t.component("k-date-input", as),
t.component("k-datetime-input", ps),
t.component("k-email-input", xs),
t.component("k-multiselect-input", js),
t.component("k-number-input", Bs),
t.component("k-password-input", Ms),
t.component("k-radio-input", Gs),
t.component("k-range-input", Zs),
t.component("k-select-input", aa),
t.component("k-tags-input", da),
t.component("k-tel-input", va),
t.component("k-text-input", ks),
t.component("k-textarea-input", Va),
t.component("k-time-input", Ja),
t.component("k-toggle-input", so),
t.component("k-url-input", lo),
t.component("k-checkboxes-field", mo),
t.component("k-date-field", $o),
t.component("k-email-field", Co),
t.component("k-files-field", Ao),
t.component("k-headline-field", Fo),
t.component("k-info-field", Ho),
t.component("k-line-field", Jo),
t.component("k-multiselect-field", nr),
t.component("k-number-field", lr),
t.component("k-pages-field", hr),
t.component("k-password-field", _r),
t.component("k-radio-field", Or),
t.component("k-range-field", Lr),
t.component("k-select-field", Dr),
t.component("k-structure-field", Kr),
t.component("k-tags-field", Qr),
t.component("k-text-field", cl),
t.component("k-textarea-field", gl),
t.component("k-tel-field", sl),
t.component("k-time-field", yl),
t.component("k-toggle-field", El),
t.component("k-url-field", ql),
t.component("k-users-field", Rl),
t.component("k-email-field-preview", su),
t.component("k-files-field-preview", Kl),
t.component("k-pages-field-preview", cu),
t.component("k-url-field-preview", tu),
t.component("k-users-field-preview", gu);
}
};
i["a"].use(vu);
var bu,
ku,
_u = {
extends: Wt,
created: function() {
this.$events.$on("keydown.esc", this.close, !1);
},
destroyed: function() {
this.$events.$off("keydown.esc", this.close, !1);
}
},
$u = _u,
yu = Object(m["a"])($u, bu, ku, !1, null, null, null);
yu.options.__file = "Dialog.vue";
var xu = yu.exports,
wu = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.error
? n(
"k-dialog",
{
ref: "dialog",
staticClass: "k-error-dialog",
attrs: { visible: !0 },
on: { close: t.exit, open: t.enter }
},
[
n("k-text", [t._v(t._s(t.error.message))]),
t.error.details && Object.keys(t.error.details).length
? n(
"dl",
{ staticClass: "k-error-details" },
[
t._l(t.error.details, function(e, i) {
return [
n("dt", { key: "detail-label-" + i }, [
t._v(t._s(e.label))
]),
n(
"dd",
{ key: "detail-message-" + i },
[
"object" === typeof e.message
? [
n(
"ul",
t._l(e.message, function(e, i) {
return n("li", { key: i }, [
t._v(
"\n " +
t._s(e) +
"\n "
)
]);
}),
0
)
]
: [
t._v(
"\n " +
t._s(e.message) +
"\n "
)
]
],
2
)
];
})
],
2
)
: t._e(),
n(
"k-button-group",
{ attrs: { slot: "footer" }, slot: "footer" },
[
n(
"k-button",
{ attrs: { icon: "check" }, on: { click: t.close } },
[t._v("\n " + t._s(t.$t("confirm")) + "\n ")]
)
],
1
)
],
1
)
: t._e();
},
Su = [],
Ou = {
mixins: [_],
computed: {
error: function() {
var t = this.$store.state.notification;
return "error" === t.type ? t : null;
}
},
methods: {
enter: function() {
var t = this;
this.$nextTick(function() {
t.$el.querySelector(".k-dialog-footer .k-button").focus();
});
},
exit: function() {
this.$store.dispatch("notification/close");
}
}
},
Cu = Ou,
Eu = (n("7737"), Object(m["a"])(Cu, wu, Su, !1, null, null, null));
Eu.options.__file = "ErrorDialog.vue";
var ju = Eu.exports,
Tu = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("delete"), theme: "negative", icon: "trash" },
on: { submit: t.submit }
},
[
n("k-text", {
domProps: {
innerHTML: t._s(
t.$t("file.delete.confirm", { filename: t.filename })
)
}
})
],
1
);
},
Iu = [],
Lu = {
mixins: [_],
data: function() {
return { id: null, parent: null, filename: null };
},
methods: {
open: function(t, e) {
var n = this;
this.$api.files
.get(t, e)
.then(function(e) {
(n.id = e.id),
(n.filename = e.filename),
(n.parent = t),
n.$refs.dialog.open();
})
.catch(function(t) {
n.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api.files
.delete(this.parent, this.filename)
.then(function() {
t.$store.dispatch("form/remove", "files/" + t.id),
t.$store.dispatch("notification/success", ":)"),
t.$events.$emit("file.delete"),
t.$emit("success"),
t.$refs.dialog.close();
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
Au = Lu,
qu = Object(m["a"])(Au, Tu, Iu, !1, null, null, null);
qu.options.__file = "FileRemoveDialog.vue";
var Nu = qu.exports,
Pu = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("rename"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: {
submit: t.submit,
input: function(e) {
t.file.name = t.sluggify(t.file.name);
}
},
model: {
value: t.file,
callback: function(e) {
t.file = e;
},
expression: "file"
}
})
],
1
);
},
Bu = [],
Du = n("b747"),
Fu = n.n(Du),
Ru = function(t) {
return Fu()(t, { remove: /[$*_+~.,;:()'"`!?§$%\/=#@]/g }).toLowerCase();
},
Mu = {
mixins: [_],
data: function() {
return {
parent: null,
file: { id: null, name: null, filename: null, extension: null }
};
},
computed: {
fields: function() {
return {
name: {
label: this.$t("name"),
type: "text",
required: !0,
icon: "title",
after: "." + this.file.extension,
preselect: !0
}
};
}
},
methods: {
open: function(t, e) {
var n = this;
this.$api.files
.get(t, e, { select: ["id", "filename", "name", "extension"] })
.then(function(e) {
(n.file = e), (n.parent = t), n.$refs.dialog.open();
})
.catch(function(t) {
n.$store.dispatch("notification/error", t);
});
},
sluggify: function(t) {
return Ru(t);
},
submit: function() {
var t = this;
this.$api.files
.rename(this.parent, this.file.filename, this.file.name)
.then(function(e) {
t.$store.dispatch("form/revert", "files/" + t.file.id),
t.$store.dispatch("notification/success", ":)"),
t.$emit("success", e),
t.$events.$emit("file.changeName", e),
t.$refs.dialog.close();
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
zu = Mu,
Uu = Object(m["a"])(zu, Pu, Bu, !1, null, null, null);
Uu.options.__file = "FileRenameDialog.vue";
var Vu = Uu.exports,
Hu = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
staticClass: "k-files-dialog",
attrs: { size: "medium" },
on: {
cancel: function(e) {
t.$emit("cancel");
},
submit: t.submit
}
},
[
t.issue
? [n("k-box", { attrs: { text: t.issue, theme: "negative" } })]
: [
t.files.length
? n(
"k-list",
t._l(t.files, function(e, i) {
return n(
"k-list-item",
{
key: e.filename,
attrs: {
text: e.filename,
image: e.thumb ? { url: e.thumb } : null,
icon: { type: "file", back: "pattern" }
},
on: {
click: function(e) {
t.toggle(i);
}
}
},
[
e.selected
? n("k-button", {
attrs: {
slot: "options",
autofocus: !0,
icon: t.checkedIcon,
tooltip: t.$t("remove"),
theme: "positive"
},
slot: "options"
})
: n("k-button", {
attrs: {
slot: "options",
autofocus: !0,
tooltip: t.$t("select"),
icon: "circle-outline"
},
slot: "options"
})
],
1
);
}),
1
)
: n("k-empty", { attrs: { icon: "image" } }, [
t._v("\n No files to select\n ")
])
]
],
2
);
},
Ku = [],
Gu = {
data: function() {
return {
files: [],
issue: null,
options: { max: null, multiple: !0, parent: null, selected: [] }
};
},
computed: {
multiple: function() {
return !0 === this.options.multiple && 1 !== this.options.max;
},
checkedIcon: function() {
return !0 === this.multiple ? "check" : "circle-filled";
}
},
methods: {
fetch: function() {
var t = this;
return (
(this.files = []),
this.$api
.get(this.options.parent + "/files", {
select: "id, filename, link, type, url, thumbs"
})
.then(function(e) {
var n = t.options.selected || [];
t.files = e.data.map(function(t) {
return (
(t.selected = -1 !== n.indexOf(t.id)),
t.thumbs && t.thumbs.tiny && (t.thumb = t.thumbs.medium),
t
);
});
})
.catch(function(e) {
(t.files = []), (t.issue = e.message);
})
);
},
selected: function() {
return this.files.filter(function(t) {
return t.selected;
});
},
submit: function() {
this.$emit("submit", this.selected()), this.$refs.dialog.close();
},
toggle: function(t) {
if (
(!1 === this.options.multiple &&
(this.files = this.files.map(function(t) {
return (t.selected = !1), t;
})),
this.files[t].selected)
)
this.files[t].selected = !1;
else {
if (
this.options.max &&
this.options.max <= this.selected().length
)
return;
this.files[t].selected = !0;
}
},
open: function(t) {
var e = this;
(this.options = t),
this.fetch().then(function() {
e.$refs.dialog.open();
});
}
}
},
Yu = Gu,
Wu = (n("bf53"), Object(m["a"])(Yu, Hu, Ku, !1, null, null, null));
Wu.options.__file = "FilesDialog.vue";
var Ju = Wu.exports,
Xu = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("language.create"),
notification: t.notification,
theme: "positive",
size: "medium"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields, novalidate: !0 },
on: { submit: t.submit },
model: {
value: t.language,
callback: function(e) {
t.language = e;
},
expression: "language"
}
})
],
1
);
},
Qu = [],
Zu = {
mixins: [_],
data: function() {
return {
notification: null,
language: { name: "", code: "", direction: "ltr" }
};
},
computed: {
fields: function() {
return {
name: {
label: this.$t("language.name"),
type: "text",
required: !0,
icon: "title"
},
code: {
label: this.$t("language.code"),
type: "text",
required: !0,
counter: !1,
icon: "globe",
width: "1/2"
},
direction: {
label: this.$t("language.direction"),
type: "select",
required: !0,
empty: !1,
options: [
{ value: "ltr", text: this.$t("language.direction.ltr") },
{ value: "rtl", text: this.$t("language.direction.rtl") }
],
width: "1/2"
},
locale: {
label: this.$t("language.locale"),
type: "text",
placeholder: "en_US"
}
};
}
},
watch: {
"language.name": function(t) {
this.language.code = Ru(t).substr(0, 2);
},
"language.code": function(t) {
this.language.code = Ru(t);
}
},
methods: {
open: function() {
(this.language = { name: "", code: "", direction: "ltr" }),
this.$refs.dialog.open();
},
submit: function() {
var t = this;
this.$api
.post("languages", this.language)
.then(function() {
t.$store.dispatch("languages/load"),
t.success({
message: t.$t("language.created"),
event: "language.create"
});
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
tc = Zu,
ec = Object(m["a"])(tc, Xu, Qu, !1, null, null, null);
ec.options.__file = "LanguageCreateDialog.vue";
var nc = ec.exports,
ic = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("delete"), theme: "negative", icon: "trash" },
on: { submit: t.submit }
},
[
n("k-text", {
domProps: {
innerHTML: t._s(
t.$t("language.delete.confirm", { name: t.language.name })
)
}
})
],
1
);
},
sc = [],
ac = {
mixins: [_],
data: function() {
return { language: { name: null } };
},
methods: {
open: function(t) {
var e = this;
this.$api
.get("languages/" + t)
.then(function(t) {
(e.language = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api
.delete("languages/" + this.language.code)
.then(function() {
t.$store.dispatch("languages/load"),
t.success({
message: t.$t("language.deleted"),
event: "language.delete"
});
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
oc = ac,
rc = Object(m["a"])(oc, ic, sc, !1, null, null, null);
rc.options.__file = "LanguageRemoveDialog.vue";
var lc = rc.exports,
uc = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("save"),
notification: t.notification,
size: "medium"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.language,
callback: function(e) {
t.language = e;
},
expression: "language"
}
})
],
1
);
},
cc = [],
pc = {
mixins: [nc],
computed: {
fields: function() {
var t = nc.computed.fields.apply(this);
return (t.code.disabled = !0), t;
}
},
methods: {
open: function(t) {
var e = this;
this.$api
.get("languages/" + t)
.then(function(t) {
(e.language = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api
.patch("languages/" + this.language.code, this.language)
.then(function() {
t.$store.dispatch("languages/load"),
t.success({
message: t.$t("language.updated"),
event: "language.update"
});
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
fc = pc,
dc = Object(m["a"])(fc, uc, cc, !1, null, null, null);
dc.options.__file = "LanguageUpdateDialog.vue";
var hc = dc.exports,
mc = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("page.draft.create"),
notification: t.notification,
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields, novalidate: !0 },
on: { submit: t.submit },
model: {
value: t.page,
callback: function(e) {
t.page = e;
},
expression: "page"
}
})
],
1
);
},
gc = [],
vc = {
mixins: [_],
data: function() {
return {
notification: null,
parent: null,
section: null,
templates: [],
page: { title: "", slug: "", template: null }
};
},
computed: {
fields: function() {
return {
title: {
label: this.$t("title"),
type: "text",
required: !0,
icon: "title"
},
slug: {
label: this.$t("slug"),
type: "text",
required: !0,
counter: !1,
icon: "url"
},
template: {
name: "template",
label: this.$t("template"),
type: "select",
disabled: 1 === this.templates.length,
required: !0,
icon: "code",
empty: !1,
options: this.templates
}
};
}
},
watch: {
"page.title": function(t) {
this.page.slug = Ru(t);
}
},
methods: {
open: function(t, e, n) {
var i = this;
(this.parent = t),
(this.section = n),
this.$api
.get(e, { section: n })
.then(function(t) {
(i.templates = t.map(function(t) {
return { value: t.name, text: t.title };
})),
i.templates[0] && (i.page.template = i.templates[0].value),
i.$refs.dialog.open();
})
.catch(function(t) {
i.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
if (0 === this.page.title.length)
return this.$refs.dialog.error("Please enter a title"), !1;
var e = {
template: this.page.template,
slug: this.page.slug,
content: { title: this.page.title }
};
this.$api
.post(this.parent + "/children", e)
.then(function(e) {
t.success({
route: t.$api.pages.link(e.id),
message: ":)",
event: "page.create"
});
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
bc = vc,
kc = Object(m["a"])(bc, mc, gc, !1, null, null, null);
kc.options.__file = "PageCreateDialog.vue";
var _c = kc.exports,
$c = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("delete"),
size: t.hasSubpages ? "medium" : "small",
theme: "negative",
icon: "trash"
},
on: { submit: t.submit }
},
[
t.page.hasChildren || t.page.hasDrafts
? [
n("k-text", {
domProps: {
innerHTML: t._s(
t.$t("page.delete.confirm", { title: t.page.title })
)
}
}),
n(
"div",
{ staticClass: "k-page-remove-warning" },
[
n("k-box", {
attrs: { theme: "negative" },
domProps: {
innerHTML: t._s(t.$t("page.delete.confirm.subpages"))
}
})
],
1
),
t.hasSubpages
? n("k-form", {
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.model,
callback: function(e) {
t.model = e;
},
expression: "model"
}
})
: t._e()
]
: [
n("k-text", {
domProps: {
innerHTML: t._s(
t.$t("page.delete.confirm", { title: t.page.title })
)
},
on: {
keydown: function(e) {
return "button" in e ||
!t._k(e.keyCode, "enter", 13, e.key, "Enter")
? t.submit(e)
: null;
}
}
})
]
],
2
);
},
yc = [],
xc = {
mixins: [_],
data: function() {
return {
page: { title: null, hasChildren: !1, hasDrafts: !1 },
model: { check: null }
};
},
computed: {
hasSubpages: function() {
return this.page.hasChildren || this.page.hasDrafts;
},
fields: function() {
return {
check: {
label: this.$t("page.delete.confirm.title"),
type: "text",
counter: !1
}
};
}
},
methods: {
open: function(t) {
var e = this;
this.$api.pages
.get(t, { select: "id, title, hasChildren, hasDrafts, parent" })
.then(function(t) {
(e.page = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.hasSubpages && this.model.check !== this.page.title
? this.$refs.dialog.error(this.$t("error.page.delete.confirm"))
: this.$api.pages
.delete(this.page.id, { force: !0 })
.then(function() {
t.$store.dispatch("form/remove", "pages/" + t.page.id);
var e = { message: ":)", event: "page.delete" };
t.$route.params.path &&
t.page.id === t.$route.params.path.replace(/\+/g, "/") &&
(t.page.parent
? (e.route = "/pages/" + t.page.parent.id)
: (e.route = "/pages")),
t.success(e);
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
wc = xc,
Sc = (n("12fb"), Object(m["a"])(wc, $c, yc, !1, null, null, null));
Sc.options.__file = "PageRemoveDialog.vue";
var Oc = Sc.exports,
Cc = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("rename"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.page,
callback: function(e) {
t.page = e;
},
expression: "page"
}
})
],
1
);
},
Ec = [],
jc = {
mixins: [_],
data: function() {
return { page: { id: null, title: null } };
},
computed: {
fields: function() {
return {
title: {
label: this.$t("title"),
type: "text",
required: !0,
icon: "title",
preselect: !0
}
};
}
},
methods: {
open: function(t) {
var e = this;
this.$api.pages
.get(t, { select: ["id", "title"] })
.then(function(t) {
(e.page = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
0 !== this.page.title.length
? this.$api.pages
.title(this.page.id, this.page.title)
.then(function() {
t.success({ message: ":)", event: "page.changeTitle" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
})
: this.$refs.dialog.error(
this.$t("error.page.changeTitle.empty")
);
}
}
},
Tc = jc,
Ic = Object(m["a"])(Tc, Cc, Ec, !1, null, null, null);
Ic.options.__file = "PageRenameDialog.vue";
var Lc = Ic.exports,
Ac = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("change"),
size: "medium",
theme: "positive"
},
on: { submit: t.submit }
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.changeStatus },
model: {
value: t.form,
callback: function(e) {
t.form = e;
},
expression: "form"
}
})
],
1
);
},
qc = [],
Nc = {
mixins: [_],
data: function() {
return {
page: { id: null },
isBlocked: !1,
isIncomplete: !1,
form: { status: null, position: null },
states: {}
};
},
computed: {
fields: function() {
var t = this,
e = {
status: {
name: "status",
label: this.$t("page.changeStatus.select"),
type: "radio",
required: !0,
options: Object.keys(this.states).map(function(e) {
return {
value: e,
text: t.states[e].label,
info: t.states[e].text
};
})
}
};
return (
"listed" === this.form.status &&
"default" === this.page.blueprint.num &&
(e.position = {
name: "position",
label: this.$t("page.changeStatus.position"),
type: "select",
empty: !1,
options: this.sortingOptions()
}),
e
);
}
},
methods: {
sortingOptions: function() {
var t = this,
e = [],
n = 0;
return (
this.page.siblings.forEach(function(i) {
if (i.id === t.page.id || i.num < 1) return !1;
n++,
e.push({ value: n, text: n }),
e.push({ value: i.id, text: i.title, disabled: !0 });
}),
e.push({ value: n + 1, text: n + 1 }),
e
);
},
open: function(t) {
var e = this;
this.$api.pages
.get(t, {
select: [
"id",
"status",
"num",
"errors",
"siblings",
"blueprint"
]
})
.then(function(t) {
return !1 === t.blueprint.options.changeStatus
? e.$store.dispatch("notification/error", {
message: e.$t("error.page.changeStatus.permission")
})
: "draft" === t.status && Object.keys(t.errors).length > 0
? e.$store.dispatch("notification/error", {
message: e.$t("error.page.changeStatus.incomplete"),
details: t.errors
})
: ((e.states = t.blueprint.status),
(e.page = t),
(e.form.status = t.status),
(e.form.position = t.num),
void e.$refs.dialog.open());
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
this.$refs.form.submit();
},
changeStatus: function() {
var t = this;
this.$api.pages
.status(this.page.id, this.form.status, this.form.position || 1)
.then(function() {
t.success({ message: ":)", event: "page.changeStatus" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
Pc = Nc,
Bc = Object(m["a"])(Pc, Ac, qc, !1, null, null, null);
Bc.options.__file = "PageStatusDialog.vue";
var Dc = Bc.exports,
Fc = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("change"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.page,
callback: function(e) {
t.page = e;
},
expression: "page"
}
})
],
1
);
},
Rc = [],
Mc = {
mixins: [_],
data: function() {
return { blueprints: [], page: { id: null, template: null } };
},
computed: {
fields: function() {
return {
template: {
label: this.$t("template"),
type: "select",
required: !0,
empty: !1,
options: this.page.blueprints,
icon: "template"
}
};
}
},
methods: {
open: function(t) {
var e = this;
this.$api.pages
.get(t, { select: ["id", "template", "blueprints"] })
.then(function(t) {
if (t.blueprints.length <= 1)
return e.$store.dispatch("notification/error", {
message: e.$t("error.page.changeTemplate.invalid", {
slug: t.id
})
});
(e.page = t),
(e.page.blueprints = e.page.blueprints.map(function(t) {
return { text: t.title, value: t.name };
})),
e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$events.$emit("keydown.cmd.s"),
this.$api.pages
.template(this.page.id, this.page.template)
.then(function() {
t.success({ message: ":)", event: "page.changeTemplate" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
zc = Mc,
Uc = Object(m["a"])(zc, Fc, Rc, !1, null, null, null);
Uc.options.__file = "PageTemplateDialog.vue";
var Vc = Uc.exports,
Hc = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("change"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n(
"k-form",
{ ref: "form", on: { submit: t.submit } },
[
n(
"k-text-field",
t._b(
{
attrs: { value: t.slug },
on: {
input: function(e) {
t.sluggify(e);
}
}
},
"k-text-field",
t.field,
!1
),
[
n(
"k-button",
{
attrs: {
slot: "options",
icon: "wand",
"data-options": ""
},
on: {
click: function(e) {
t.sluggify(t.page.title);
}
},
slot: "options"
},
[
t._v(
"\n " +
t._s(t.$t("page.changeSlug.fromTitle")) +
"\n "
)
]
)
],
1
)
],
1
)
],
1
);
},
Kc = [],
Gc = {
mixins: [_],
data: function() {
return {
slug: null,
url: null,
page: { id: null, parent: null, title: null }
};
},
computed: {
field: function() {
return {
name: "slug",
label: this.$t("slug"),
type: "text",
required: !0,
icon: "url",
help: "/" + this.url,
preselect: !0
};
}
},
methods: {
sluggify: function(t) {
(this.slug = Ru(t)),
this.page.parents
? (this.url = this.page.parents
.map(function(t) {
return t.slug;
})
.concat([this.slug])
.join("/"))
: (this.url = this.slug);
},
open: function(t) {
var e = this;
this.$api.pages
.get(t, { view: "panel" })
.then(function(t) {
(e.page = t), e.sluggify(e.page.slug), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
if (this.slug === this.page.slug)
return (
this.$refs.dialog.close(),
void this.$store.dispatch("notification/success", ":)")
);
0 !== this.slug.length
? this.$api.pages
.slug(this.page.id, this.slug)
.then(function(e) {
t.$store.dispatch("form/revert", "pages/" + t.page.id);
var n = { message: ":)", event: "page.changeSlug" };
t.$route.params.path &&
t.page.id === t.$route.params.path.replace(/\+/g, "/") &&
(n.route = t.$api.pages.link(e.id)),
t.success(n);
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
})
: this.$refs.dialog.error(this.$t("error.page.slug.invalid"));
}
}
},
Yc = Gc,
Wc = Object(m["a"])(Yc, Hc, Kc, !1, null, null, null);
Wc.options.__file = "PageUrlDialog.vue";
var Jc = Wc.exports,
Xc = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
staticClass: "k-pages-dialog",
attrs: { size: "medium" },
on: {
cancel: function(e) {
t.$emit("cancel");
},
submit: t.submit
}
},
[
t.issue
? [n("k-box", { attrs: { text: t.issue, theme: "negative" } })]
: [
n(
"header",
{ staticClass: "k-pages-dialog-navbar" },
[
n("k-button", {
attrs: {
disabled: !t.model.id,
tooltip: t.$t("back"),
icon: "angle-left"
},
on: { click: t.back }
}),
n("k-headline", [t._v(t._s(t.model.title))])
],
1
),
t.pages.length
? n(
"k-list",
t._l(t.pages, function(e) {
return n(
"k-list-item",
{
key: e.id,
attrs: {
text: e.title,
icon: { type: "page", back: "pattern" }
},
on: {
click: function(n) {
t.toggle(e);
}
}
},
[
n(
"template",
{ slot: "options" },
[
t.isSelected(e)
? n("k-button", {
attrs: {
slot: "options",
autofocus: !0,
icon: t.checkedIcon,
tooltip: t.$t("remove"),
theme: "positive"
},
slot: "options"
})
: n("k-button", {
attrs: {
slot: "options",
autofocus: !0,
tooltip: t.$t("select"),
icon: "circle-outline"
},
slot: "options"
}),
n("k-button", {
attrs: {
disabled: !e.hasChildren,
tooltip: t.$t("open"),
icon: "angle-right"
},
on: {
click: function(n) {
n.stopPropagation(), t.go(e);
}
}
})
],
1
)
],
2
);
}),
1
)
: n("k-empty", { attrs: { icon: "page" } }, [
t._v("\n No pages to select\n ")
])
]
],
2
);
},
Qc = [],
Zc = {
data: function() {
return {
model: { title: null, parent: null },
pages: [],
issue: null,
options: { max: null, multiple: !0, parent: null, selected: [] }
};
},
computed: {
multiple: function() {
return !0 === this.options.multiple && 1 !== this.options.max;
},
checkedIcon: function() {
return !0 === this.multiple ? "check" : "circle-filled";
}
},
methods: {
fetch: function() {
var t = this,
e = this.options.parent
? this.$api.pages.url(this.options.parent)
: "site";
return this.$api
.get(e, { view: "selector" })
.then(function(e) {
(t.model = e), (t.pages = e.children);
})
.catch(function(e) {
(t.pages = []), (t.issue = e.message);
});
},
back: function() {
(this.options.parent = this.model.parent
? this.model.parent.id
: null),
this.fetch();
},
submit: function() {
var t = this;
if (0 === this.options.selected.length)
return this.$emit("submit", []), void this.$refs.dialog.close();
this.$api
.post("site/find", this.options.selected)
.then(function(e) {
t.$emit("submit", e.data), t.$refs.dialog.close();
});
},
isSelected: function(t) {
return this.options.selected.includes(t.id);
},
toggle: function(t) {
if (
(!1 === this.options.multiple && (this.options.selected = []),
!1 === this.options.selected.includes(t.id))
) {
if (
this.options.max &&
this.options.max <= this.options.selected.length
)
return;
this.options.selected.push(t.id);
} else
this.options.selected = this.options.selected.filter(function(e) {
return e !== t.id;
});
},
open: function(t) {
var e = this;
(this.options = t),
this.fetch().then(function() {
e.$refs.dialog.open();
});
},
go: function(t) {
(this.options.parent = t.id), this.fetch();
}
}
},
tp = Zc,
ep = (n("ac27"), Object(m["a"])(tp, Xc, Qc, !1, null, null, null));
ep.options.__file = "PagesDialog.vue";
var np,
ip,
sp = ep.exports,
ap = {
extends: Lc,
methods: {
open: function() {
var t = this;
this.$api.site
.get({ select: ["title"] })
.then(function(e) {
(t.page = e), t.$refs.dialog.open();
})
.catch(function(e) {
t.$store.dispatch("notification/error", e);
});
},
submit: function() {
var t = this;
this.$api.site
.title(this.page.title)
.then(function() {
t.$store.dispatch("system/title", t.page.title),
t.success({ message: ":)", event: "site.changeTitle" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
op = ap,
rp = Object(m["a"])(op, np, ip, !1, null, null, null);
rp.options.__file = "SiteRenameDialog.vue";
var lp = rp.exports,
up = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("create"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
},
close: t.reset
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields, novalidate: !0 },
on: { submit: t.create },
model: {
value: t.user,
callback: function(e) {
t.user = e;
},
expression: "user"
}
})
],
1
);
},
cp = [],
pp = {
mixins: [_],
data: function() {
return { user: this.emptyUser(), languages: [], roles: [] };
},
computed: {
fields: function() {
return {
name: { label: this.$t("name"), type: "text", icon: "user" },
email: {
label: this.$t("email"),
type: "email",
icon: "email",
link: !1,
required: !0
},
password: {
label: this.$t("password"),
type: "password",
icon: "key"
},
language: {
label: this.$t("language"),
type: "select",
icon: "globe",
options: this.languages,
required: !0,
empty: !1
},
role: {
label: this.$t("role"),
type: 1 === this.roles.length ? "hidden" : "radio",
required: !0,
options: this.roles
}
};
}
},
methods: {
create: function() {
var t = this;
this.$api.users
.create(this.user)
.then(function() {
t.success({ message: ":)", event: "user.create" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
},
emptyUser: function() {
return {
name: "",
email: "",
password: "",
language: "en",
role: "admin"
};
},
open: function() {
var t = this;
this.$api.roles
.options()
.then(function(e) {
(t.roles = e),
t.$api.translations
.options()
.then(function(e) {
(t.languages = e), t.$refs.dialog.open();
})
.catch(function(e) {
t.$store.dispatch("notification/error", e);
});
})
.catch(function(e) {
t.$store.dispatch("notification/error", e);
});
},
reset: function() {
this.user = this.emptyUser();
}
}
},
fp = pp,
dp = Object(m["a"])(fp, up, cp, !1, null, null, null);
dp.options.__file = "UserCreateDialog.vue";
var hp = dp.exports,
mp = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("change"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.user,
callback: function(e) {
t.user = e;
},
expression: "user"
}
})
],
1
);
},
gp = [],
vp = {
mixins: [_],
data: function() {
return { user: { id: null, email: null } };
},
computed: {
fields: function() {
return {
email: {
label: this.$t("email"),
preselect: !0,
required: !0,
type: "email"
}
};
}
},
methods: {
open: function(t) {
var e = this;
this.$api.users
.get(t, { select: ["id", "email"] })
.then(function(t) {
(e.user = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api.users
.changeEmail(this.user.id, this.user.email)
.then(function(e) {
t.$store.dispatch("form/revert", "users/" + t.user.id);
var n = { message: ":)", event: "user.changeEmail" };
"User" === t.$route.name && (n.route = t.$api.users.link(e.id)),
t.success(n);
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
bp = vp,
kp = Object(m["a"])(bp, mp, gp, !1, null, null, null);
kp.options.__file = "UserEmailDialog.vue";
var _p = kp.exports,
$p = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("change"), theme: "positive", icon: "check" },
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.user,
callback: function(e) {
t.user = e;
},
expression: "user"
}
})
],
1
);
},
yp = [],
xp = {
mixins: [_],
data: function() {
return { user: { language: "en" }, languages: [] };
},
computed: {
fields: function() {
return {
language: {
label: this.$t("language"),
type: "select",
icon: "globe",
options: this.languages,
required: !0,
empty: !1
}
};
}
},
created: function() {
var t = this;
this.$api.translations.options().then(function(e) {
t.languages = e;
});
},
methods: {
open: function(t) {
var e = this;
this.$api.users
.get(t, { view: "compact" })
.then(function(t) {
(e.user = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api.users
.changeLanguage(this.user.id, this.user.language)
.then(function(e) {
(t.user = e),
t.$store.state.user.current.id === t.user.id &&
t.$store.dispatch("user/language", t.user.language),
t.success({ message: ":)", event: "user.changeLanguage" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
wp = xp,
Sp = Object(m["a"])(wp, $p, yp, !1, null, null, null);
Sp.options.__file = "UserLanguageDialog.vue";
var Op = Sp.exports,
Cp = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("change"), theme: "positive", icon: "check" },
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.values,
callback: function(e) {
t.values = e;
},
expression: "values"
}
})
],
1
);
},
Ep = [],
jp = {
mixins: [_],
data: function() {
return {
user: null,
values: { password: null, passwordConfirmation: null }
};
},
computed: {
fields: function() {
return {
password: {
label: this.$t("user.changePassword.new"),
type: "password",
icon: "key"
},
passwordConfirmation: {
label: this.$t("user.changePassword.new.confirm"),
icon: "key",
type: "password"
}
};
}
},
methods: {
open: function(t) {
var e = this;
this.$api.users
.get(t)
.then(function(t) {
(e.user = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
return this.values.password.length < 8
? (this.$refs.dialog.error(
this.$t("error.user.password.invalid")
),
!1)
: this.values.password !== this.values.passwordConfirmation
? (this.$refs.dialog.error(
this.$t("error.user.password.notSame")
),
!1)
: void this.$api.users
.changePassword(this.user.id, this.values.password)
.then(function() {
t.success({
message: ":)",
event: "user.changePassword"
});
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
Tp = jp,
Ip = Object(m["a"])(Tp, Cp, Ep, !1, null, null, null);
Ip.options.__file = "UserPasswordDialog.vue";
var Lp = Ip.exports,
Ap = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: { button: t.$t("delete"), theme: "negative", icon: "trash" },
on: { submit: t.submit }
},
[
n("k-text", {
domProps: {
innerHTML: t._s(
t.$t("user.delete.confirm", { email: t.user.email })
)
}
})
],
1
);
},
qp = [],
Np = {
mixins: [_],
data: function() {
return { user: { email: null } };
},
methods: {
open: function(t) {
var e = this;
this.$api.users
.get(t)
.then(function(t) {
(e.user = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api.users
.delete(this.user.id)
.then(function() {
t.$store.dispatch("form/remove", "users/" + t.user.id),
t.success({ message: ":)", event: "user.delete" }),
"User" === t.$route.name && t.$router.push("/users");
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
Pp = Np,
Bp = Object(m["a"])(Pp, Ap, qp, !1, null, null, null);
Bp.options.__file = "UserRemoveDialog.vue";
var Dp = Bp.exports,
Fp = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("rename"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.user,
callback: function(e) {
t.user = e;
},
expression: "user"
}
})
],
1
);
},
Rp = [],
Mp = {
mixins: [_],
data: function() {
return { user: { id: null, name: null } };
},
computed: {
fields: function() {
return {
name: {
label: this.$t("name"),
type: "text",
icon: "user",
preselect: !0
}
};
}
},
methods: {
open: function(t) {
var e = this;
this.$api.users
.get(t, { select: ["id", "name"] })
.then(function(t) {
(e.user = t), e.$refs.dialog.open();
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api.users
.changeName(this.user.id, this.user.name)
.then(function() {
t.success({ message: ":)", event: "user.changeName" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
zp = Mp,
Up = Object(m["a"])(zp, Fp, Rp, !1, null, null, null);
Up.options.__file = "UserRenameDialog.vue";
var Vp = Up.exports,
Hp = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
attrs: {
button: t.$t("user.changeRole"),
size: "medium",
theme: "positive"
},
on: {
submit: function(e) {
t.$refs.form.submit();
}
}
},
[
n("k-form", {
ref: "form",
attrs: { fields: t.fields },
on: { submit: t.submit },
model: {
value: t.user,
callback: function(e) {
t.user = e;
},
expression: "user"
}
})
],
1
);
},
Kp = [],
Gp = {
mixins: [_],
data: function() {
return { roles: [], user: { id: null, role: "visitor" } };
},
computed: {
fields: function() {
return {
role: {
label: this.$t("user.changeRole.select"),
type: "radio",
required: !0,
options: this.roles
}
};
}
},
methods: {
open: function(t) {
var e = this;
(this.id = t),
this.$api.users
.get(t)
.then(function(t) {
e.$api.roles.options().then(function(n) {
(e.roles = n),
(e.user = t),
(e.user.role = e.user.role.name),
e.$refs.dialog.open();
});
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
},
submit: function() {
var t = this;
this.$api.users
.changeRole(this.user.id, this.user.role)
.then(function() {
t.success({ message: ":)", event: "user.changeRole" });
})
.catch(function(e) {
t.$refs.dialog.error(e.message);
});
}
}
},
Yp = Gp,
Wp = Object(m["a"])(Yp, Hp, Kp, !1, null, null, null);
Wp.options.__file = "UserRoleDialog.vue";
var Jp = Wp.exports,
Xp = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-dialog",
{
ref: "dialog",
staticClass: "k-users-dialog",
attrs: { size: "medium" },
on: {
cancel: function(e) {
t.$emit("cancel");
},
submit: t.submit
}
},
[
t.issue
? [n("k-box", { attrs: { text: t.issue, theme: "negative" } })]
: [
t.users.length
? n(
"k-list",
t._l(t.users, function(e, i) {
return n(
"k-list-item",
{
key: e.email,
attrs: {
text: e.username,
image: e.avatar
? {
url: e.avatar.url,
back: "pattern",
cover: !0
}
: null,
icon: { type: "user", back: "black" }
},
on: {
click: function(e) {
t.toggle(i);
}
}
},
[
e.selected
? n("k-button", {
attrs: {
slot: "options",
autofocus: !0,
icon: t.checkedIcon,
tooltip: t.$t("remove"),
theme: "positive"
},
slot: "options"
})
: n("k-button", {
attrs: {
slot: "options",
autofocus: !0,
tooltip: t.$t("select"),
icon: "circle-outline"
},
slot: "options"
})
],
1
);
}),
1
)
: n("k-empty", { attrs: { icon: "users" } }, [
t._v("\n No users to select\n ")
])
]
],
2
);
},
Qp = [],
Zp = {
data: function() {
return {
users: [],
issue: null,
options: { max: null, multiple: !0, selected: [] }
};
},
computed: {
multiple: function() {
return !0 === this.options.multiple && 1 !== this.options.max;
},
checkedIcon: function() {
return !0 === this.multiple ? "check" : "circle-filled";
}
},
methods: {
fetch: function() {
var t = this;
return (
(this.users = []),
this.$api
.get("users")
.then(function(e) {
var n = t.options.selected || [];
t.users = e.data.map(function(t) {
return (t.selected = -1 !== n.indexOf(t.email)), t;
});
})
.catch(function(e) {
(t.users = []), (t.issue = e.message);
})
);
},
selected: function() {
return this.users.filter(function(t) {
return t.selected;
});
},
submit: function() {
this.$emit("submit", this.selected()), this.$refs.dialog.close();
},
toggle: function(t) {
if (
(!1 === this.options.multiple &&
(this.users = this.users.map(function(t) {
return (t.selected = !1), t;
})),
this.users[t].selected)
)
this.users[t].selected = !1;
else {
if (
this.options.max &&
this.options.max <= this.selected().length
)
return;
this.users[t].selected = !0;
}
},
open: function(t) {
var e = this;
(this.options = t),
this.fetch().then(function() {
e.$refs.dialog.open();
});
}
}
},
tf = Zp,
ef = (n("7568"), Object(m["a"])(tf, Xp, Qp, !1, null, null, null));
ef.options.__file = "UsersDialog.vue";
var nf = ef.exports,
sf = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.hasChanges
? n(
"nav",
{ staticClass: "k-form-buttons" },
[
n(
"k-view",
[
n(
"k-button",
{
staticClass: "k-form-button",
attrs: { icon: "undo" },
on: { click: t.reset }
},
[t._v("\n " + t._s(t.$t("revert")) + "\n ")]
),
n(
"k-button",
{
staticClass: "k-form-button",
attrs: { icon: "check" },
on: { click: t.save }
},
[t._v("\n " + t._s(t.$t("save")) + "\n ")]
)
],
1
)
],
1
)
: t._e();
},
af = [],
of = {
computed: {
hasChanges: function() {
return this.$store.getters["form/hasChanges"](this.id);
},
id: function() {
return this.$store.state.form.current;
}
},
created: function() {
this.$events.$on("keydown.cmd.s", this.save);
},
destroyed: function() {
this.$events.$off("keydown.cmd.s", this.save);
},
methods: {
reset: function() {
this.$store.dispatch("form/revert", this.id);
},
save: function(t) {
var e = this;
return (
!!t &&
(t.preventDefault && t.preventDefault(),
!1 === this.hasChanges ||
void this.$store
.dispatch("form/save", this.id)
.then(function() {
e.$events.$emit("model.update"),
e.$store.dispatch("notification/success", ":)");
})
.catch(function(t) {
403 !== t.code &&
(t.details
? e.$store.dispatch("notification/error", {
message: e.$t("error.form.incomplete"),
details: t.details
})
: e.$store.dispatch("notification/error", {
message: e.$t("error.form.notSaved"),
details: [
{
label: "Exception: " + t.exception,
message: t.message
}
]
}));
}))
);
}
}
},
rf = of,
lf = (n("18dd"), Object(m["a"])(rf, sf, af, !1, null, null, null));
lf.options.__file = "FormButtons.vue";
var uf = lf.exports,
cf = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{
staticClass: "k-dropzone",
attrs: { "data-dragging": t.dragging, "data-over": t.over },
on: {
dragenter: t.onEnter,
dragleave: t.onLeave,
dragover: t.onOver,
drop: t.onDrop
}
},
[t._t("default")],
2
);
},
pf = [],
ff = {
props: {
label: { type: String, default: "Drop to upload" },
disabled: { type: Boolean, default: !1 }
},
data: function() {
return { files: [], dragging: !1, over: !1 };
},
methods: {
cancel: function() {
this.reset();
},
reset: function() {
(this.dragging = !1), (this.over = !1);
},
onDrop: function(t) {
return !0 === this.disabled
? this.reset()
: t.dataTransfer.types
? !1 === t.dataTransfer.types.includes("Files")
? this.reset()
: (this.$events.$emit("dropzone.drop"),
(this.files = t.dataTransfer.files),
this.$emit("drop", this.files),
void this.reset())
: this.reset();
},
onEnter: function(t) {
!1 === this.disabled &&
t.dataTransfer.types &&
t.dataTransfer.types.includes("Files") &&
(this.dragging = !0);
},
onLeave: function() {
this.reset();
},
onOver: function(t) {
!1 === this.disabled &&
t.dataTransfer.types &&
t.dataTransfer.types.includes("Files") &&
((t.dataTransfer.dropEffect = "copy"), (this.over = !0));
}
}
},
df = ff,
hf = (n("414d"), Object(m["a"])(df, cf, pf, !1, null, null, null));
hf.options.__file = "Dropzone.vue";
var mf = hf.exports,
gf = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"div",
{ staticClass: "k-file-preview" },
[
n("k-view", { staticClass: "k-file-preview-layout" }, [
n("div", { staticClass: "k-file-preview-image" }, [
n(
"a",
{
directives: [{ name: "tab", rawName: "v-tab" }],
staticClass: "k-file-preview-image-link",
attrs: {
href: t.file.url,
title: t.$t("open"),
target: "_blank"
}
},
[
t.file.panelImage && t.file.panelImage.url
? n("k-image", {
attrs: { src: t.file.panelImage.url, back: "none" }
})
: t.file.panelIcon
? n("k-icon", {
staticClass: "k-file-preview-icon",
style: { color: t.file.panelIcon.color },
attrs: { type: t.file.panelIcon.type }
})
: t._e()
],
1
)
]),
n("div", { staticClass: "k-file-preview-details" }, [
n("ul", [
n("li", [
n("h3", [t._v(t._s(t.$t("template")))]),
n("p", [t._v(t._s(t.file.template || "—"))])
]),
n("li", [
n("h3", [t._v(t._s(t.$t("mime")))]),
n("p", [t._v(t._s(t.file.mime))])
]),
n("li", [
n("h3", [t._v(t._s(t.$t("url")))]),
n(
"p",
[
n(
"k-link",
{
attrs: {
to: t.file.url,
tabindex: "-1",
target: "_blank"
}
},
[t._v("/" + t._s(t.file.id))]
)
],
1
)
]),
n("li", [
n("h3", [t._v(t._s(t.$t("size")))]),
n("p", [t._v(t._s(t.file.niceSize))])
]),
n("li", [
n("h3", [t._v(t._s(t.$t("dimensions")))]),
t.file.dimensions
? n("p", [
t._v(
t._s(t.file.dimensions.width) +
"×" +
t._s(t.file.dimensions.height) +
" " +
t._s(t.$t("pixel"))
)
])
: n("p", [t._v("—")])
]),
n("li", [
n("h3", [t._v(t._s(t.$t("orientation")))]),
t.file.dimensions
? n("p", [
t._v(
t._s(
t.$t(
"orientation." + t.file.dimensions.orientation
)
)
)
])
: n("p", [t._v("—")])
])
])
])
])
],
1
);
},
vf = [],
bf = { props: { file: Object } },
kf = bf,
_f = (n("696b"), Object(m["a"])(kf, gf, vf, !1, null, null, null));
_f.options.__file = "FilePreview.vue";
var $f = _f.exports,
yf = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return 0 === t.tabs.length
? n("k-box", {
attrs: {
text: "This page has no blueprint setup yet",
theme: "info"
}
})
: t.tab
? n("k-sections", {
attrs: {
parent: t.parent,
blueprint: t.blueprint,
columns: t.tab.columns
},
on: {
submit: function(e) {
t.$emit("submit", e);
}
}
})
: t._e();
},
xf = [],
wf = {
props: { parent: String, blueprint: String, tabs: Array },
data: function() {
return { tab: null };
},
watch: {
$route: function() {
this.open();
},
blueprint: function() {
this.open();
}
},
mounted: function() {
this.open();
},
methods: {
open: function(t) {
if (0 !== this.tabs.length) {
t || (t = this.$route.hash.replace("#", "")),
t || (t = this.tabs[0].name);
var e = null;
this.tabs.forEach(function(n) {
n.name === t && (e = n);
}),
e || (e = this.tabs[0]),
(this.tab = e),
this.$emit("tab", this.tab);
}
}
}
},
Sf = wf,
Of = Object(m["a"])(Sf, yf, xf, !1, null, null, null);
Of.options.__file = "Tabs.vue";
var Cf = Of.exports,
Ef = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.languages.length
? n(
"k-dropdown",
[
n(
"k-button",
{
attrs: { responsive: !0, icon: "globe" },
on: {
click: function(e) {
t.$refs.languages.toggle();
}
}
},
[t._v("\n " + t._s(t.language.name) + "\n ")]
),
t.languages
? n(
"k-dropdown-content",
{ ref: "languages" },
[
n(
"k-dropdown-item",
{
on: {
click: function(e) {
t.change(t.defaultLanguage);
}
}
},
[t._v(t._s(t.defaultLanguage.name))]
),
n("hr"),
t._l(t.languages, function(e) {
return n(
"k-dropdown-item",
{
key: e.code,
on: {
click: function(n) {
t.change(e);
}
}
},
[t._v("\n " + t._s(e.name) + "\n ")]
);
})
],
2
)
: t._e()
],
1
)
: t._e();
},
jf = [],
Tf = {
computed: {
defaultLanguage: function() {
return this.$store.state.languages.default;
},
language: function() {
return this.$store.state.languages.current;
},
languages: function() {
return this.$store.state.languages.all.filter(function(t) {
return !1 === t.default;
});
}
},
methods: {
change: function(t) {
this.$store.dispatch("languages/current", t),
this.$emit("change", t);
}
}
},
If = Tf,
Lf = Object(m["a"])(If, Ef, jf, !1, null, null, null);
Lf.options.__file = "Languages.vue";
var Af = Lf.exports,
qf = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"header",
{ staticClass: "k-topbar" },
[
t.user && t.view
? n("k-view", [
n(
"div",
{ staticClass: "k-topbar-wrapper" },
[
n(
"k-dropdown",
{ staticClass: "k-topbar-menu" },
[
n(
"k-button",
{
staticClass:
"k-topbar-button k-topbar-menu-button",
attrs: { tooltip: t.$t("menu"), icon: "bars" },
on: {
click: function(e) {
t.$refs.menu.toggle();
}
}
},
[n("k-icon", { attrs: { type: "angle-down" } })],
1
),
n(
"k-dropdown-content",
{ ref: "menu", staticClass: "k-topbar-menu" },
[
n(
"ul",
[
t._l(t.views, function(e, i) {
return e.menu
? n(
"li",
{
key: "menu-item-" + i,
attrs: {
"aria-current":
t.$store.state.view === i
}
},
[
n(
"k-dropdown-item",
{
attrs: {
disabled:
!1 ===
t.$permissions.access[i],
icon: e.icon,
link: e.link
}
},
[
t._v(
"\n " +
t._s(t.viewTitle(i, e)) +
"\n "
)
]
)
],
1
)
: t._e();
}),
n("li", [n("hr")]),
n(
"li",
{
attrs: {
"aria-current":
"account" === t.$route.meta.view
}
},
[
n(
"k-dropdown-item",
{
attrs: {
icon: "account",
link: "/account"
}
},
[
t._v(
"\n " +
t._s(t.$t("view.account")) +
"\n "
)
]
)
],
1
),
n("li", [n("hr")]),
n(
"li",
[
n(
"k-dropdown-item",
{
attrs: {
icon: "logout",
link: "/logout"
}
},
[
t._v(
"\n " +
t._s(t.$t("logout")) +
"\n "
)
]
)
],
1
)
],
2
)
]
)
],
1
),
t.view
? n(
"k-link",
{
directives: [{ name: "tab", rawName: "v-tab" }],
staticClass:
"k-topbar-button k-topbar-view-button",
attrs: { to: t.view.link }
},
[
n("k-icon", { attrs: { type: t.view.icon } }),
t._v(" " + t._s(t.breadcrumbTitle) + "\n ")
],
1
)
: t._e(),
t.$store.state.breadcrumb.length > 1
? n(
"k-dropdown",
{ staticClass: "k-topbar-breadcrumb-menu" },
[
n(
"k-button",
{
staticClass: "k-topbar-button",
on: {
click: function(e) {
t.$refs.crumb.toggle();
}
}
},
[
t._v("\n …\n "),
n("k-icon", { attrs: { type: "angle-down" } })
],
1
),
n(
"k-dropdown-content",
{ ref: "crumb" },
[
n(
"k-dropdown-item",
{
attrs: {
icon: t.view.icon,
link: t.view.link
}
},
[
t._v(
"\n " +
t._s(
t.$t(
"view." + t.$store.state.view,
t.view.label
)
) +
"\n "
)
]
),
t._l(t.$store.state.breadcrumb, function(
e,
i
) {
return n(
"k-dropdown-item",
{
key: "crumb-" + i + "-dropdown",
attrs: {
icon: t.view.icon,
link: e.link
}
},
[
t._v(
"\n " +
t._s(e.label) +
"\n "
)
]
);
})
],
2
)
],
1
)
: t._e(),
n(
"nav",
{ staticClass: "k-topbar-crumbs" },
t._l(t.$store.state.breadcrumb, function(e, i) {
return n(
"k-link",
{
directives: [{ name: "tab", rawName: "v-tab" }],
key: "crumb-" + i,
attrs: { to: e.link }
},
[
t._v(
"\n " + t._s(e.label) + "\n "
)
]
);
}),
1
),
n(
"div",
{ staticClass: "k-topbar-signals" },
[
t.notification
? n(
"k-button",
{
staticClass: "k-topbar-notification",
attrs: { theme: "positive" },
on: {
click: function(e) {
t.$store.dispatch("notification/close");
}
}
},
[
t._v(
"\n " +
t._s(t.notification.message) +
"\n "
)
]
)
: t._e(),
n("k-button", {
attrs: { tooltip: t.$t("search"), icon: "search" },
on: {
click: function(e) {
t.$store.dispatch("search", !0);
}
}
})
],
1
)
],
1
)
])
: t._e()
],
1
);
},
Nf = [],
Pf = Object(u["a"])(
{
site: { link: "/site", icon: "page", menu: !0 },
users: { link: "/users", icon: "users", menu: !0 },
settings: { link: "/settings", icon: "settings", menu: !0 },
account: { link: "/account", icon: "users", menu: !1 }
},
window.panel.plugins.views
),
Bf = {
computed: {
breadcrumbTitle: function() {
var t = this.$t(
"view.".concat(this.$store.state.view),
this.view.label
);
return (
("site" === this.$store.state.view &&
this.$store.state.system.info.title) ||
t
);
},
view: function() {
return Pf[this.$store.state.view];
},
views: function() {
return Pf;
},
user: function() {
return this.$store.state.user.current;
},
notification: function() {
return this.$store.state.notification.type &&
"error" !== this.$store.state.notification.type
? this.$store.state.notification
: null;
},
unregistered: function() {
return !this.$store.state.system.info.license;
}
},
methods: {
viewTitle: function(t, e) {
var n = this.$t("view.".concat(t), e.label);
return (
("site" === t && this.$store.state.system.info.breadcrumbTitle) ||
n
);
}
}
},
Df = Bf,
Ff = (n("1e3b"), Object(m["a"])(Df, qf, Nf, !1, null, null, null));
Ff.options.__file = "Topbar.vue";
var Rf = Ff.exports,
Mf = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-grid",
{ staticClass: "k-sections", attrs: { gutter: "large" } },
t._l(t.columns, function(e, i) {
return n(
"k-column",
{ key: t.parent + "-column-" + i, attrs: { width: e.width } },
[
t._l(e.sections, function(e, s) {
return [
t.exists(e.type)
? n(
"k-" + e.type + "-section",
t._b(
{
key:
t.parent +
"-column-" +
i +
"-section-" +
s +
"-" +
t.blueprint,
tag: "component",
class: "k-section k-section-name-" + e.name,
attrs: {
name: e.name,
parent: t.parent,
blueprint: t.blueprint
},
on: {
submit: function(e) {
t.$emit("submit", e);
}
}
},
"component",
e,
!1
)
)
: [
n("k-box", {
key: t.parent + "-column-" + i + "-section-" + s,
attrs: {
text: t.$t("error.section.type.invalid", {
type: e.type
}),
theme: "negative"
}
})
]
];
})
],
2
);
}),
1
);
},
zf = [],
Uf = {
props: { parent: String, blueprint: String, columns: Array },
methods: {
exists: function(t) {
return i["a"].options.components["k-" + t + "-section"];
}
}
},
Vf = Uf,
Hf = (n("6bcd"), Object(m["a"])(Vf, Mf, zf, !1, null, null, null));
Hf.options.__file = "Sections.vue";
var Kf = Hf.exports,
Gf = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"section",
{ staticClass: "k-info-section" },
[
n("k-headline", { staticClass: "k-info-section-headline" }, [
t._v(t._s(t.headline))
]),
n(
"k-box",
{ attrs: { theme: t.theme } },
[n("k-text", { domProps: { innerHTML: t._s(t.text) } })],
1
)
],
1
);
},
Yf = [],
Wf = {
props: { parent: String, blueprint: String, name: String },
methods: {
load: function() {
return this.$api.get(this.parent + "/sections/" + this.name);
}
}
},
Jf = {
mixins: [Wf],
data: function() {
return { headline: null, issue: null, text: null, theme: null };
},
created: function() {
var t = this;
this.load()
.then(function(e) {
(t.headline = e.options.headline),
(t.text = e.options.text),
(t.theme = e.options.theme || "info");
})
.catch(function(e) {
t.issue = e;
});
}
},
Xf = Jf,
Qf = (n("4333"), Object(m["a"])(Xf, Gf, Yf, !1, null, null, null));
Qf.options.__file = "InfoSection.vue";
var Zf = Qf.exports,
td = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return !1 === t.isLoading
? n(
"section",
{ staticClass: "k-pages-section" },
[
n(
"header",
{ staticClass: "k-section-header" },
[
n("k-headline", { attrs: { link: t.options.link } }, [
t._v("\n " + t._s(t.headline) + " "),
t.options.min
? n(
"abbr",
{ attrs: { title: "This section is required" } },
[t._v("*")]
)
: t._e()
]),
t.add
? n(
"k-button-group",
[
n(
"k-button",
{
attrs: { icon: "add" },
on: {
click: function(e) {
t.action(null, "create");
}
}
},
[t._v(t._s(t.$t("add")))]
)
],
1
)
: t._e()
],
1
),
t.error
? [
n(
"k-box",
{ attrs: { theme: "negative" } },
[
n("k-text", { attrs: { size: "small" } }, [
n("strong", [
t._v(
t._s(
t.$t("error.section.notLoaded", {
name: t.name
})
) + ":"
)
]),
t._v("\n " + t._s(t.error) + "\n ")
])
],
1
)
]
: [
t.data.length
? n("k-collection", {
attrs: {
layout: t.options.layout,
items: t.data,
pagination: t.pagination,
sortable: t.options.sortable,
size: t.options.size
},
on: {
change: t.sort,
paginate: t.paginate,
action: t.action
}
})
: n(
"k-empty",
{
attrs: { layout: t.options.layout, icon: "page" },
on: {
click: function(e) {
t.add && t.action(null, "create");
}
}
},
[
t._v(
"\n " +
t._s(t.options.empty || t.$t("pages.empty")) +
"\n "
)
]
),
n("k-page-create-dialog", { ref: "create" }),
n("k-page-rename-dialog", {
ref: "rename",
on: { success: t.update }
}),
n("k-page-url-dialog", {
ref: "url",
on: { success: t.update }
}),
n("k-page-status-dialog", {
ref: "status",
on: { success: t.update }
}),
n("k-page-template-dialog", {
ref: "template",
on: { success: t.update }
}),
n("k-page-remove-dialog", {
ref: "remove",
on: { success: t.update }
})
]
],
2
)
: t._e();
},
ed = [],
nd = {
props: { parent: String, blueprint: String, name: String },
data: function() {
return {
data: [],
error: null,
isLoading: !1,
options: {
empty: null,
headline: null,
layout: "list",
link: null,
max: null,
min: null,
size: null,
sortable: null
},
pagination: { page: null }
};
},
computed: {
headline: function() {
return this.options.headline || " ";
},
language: function() {
return this.$store.state.languages.current;
},
paginationId: function() {
return "kirby$pagination$" + this.parent + "/" + this.name;
}
},
watch: {
language: function() {
this.reload();
}
},
methods: {
items: function(t) {
return t;
},
load: function(t) {
var e = this;
t || (this.isLoading = !0),
null === this.pagination.page &&
(this.pagination.page =
localStorage.getItem(this.paginationId) || 1),
this.$api
.get(this.parent + "/sections/" + this.name, {
page: this.pagination.page
})
.then(function(t) {
(e.isLoading = !1),
(e.options = t.options),
(e.pagination = t.pagination),
(e.data = e.items(t.data));
})
.catch(function(t) {
(e.isLoading = !1), (e.error = t.message);
});
},
paginate: function(t) {
localStorage.setItem(this.paginationId, t.page),
(this.pagination = t),
this.reload();
},
reload: function() {
this.load(!0);
}
}
},
id = {
mixins: [nd],
computed: {
add: function() {
return this.options.add && this.$permissions.pages.create;
}
},
created: function() {
this.load(), this.$events.$on("page.changeStatus", this.reload);
},
destroyed: function() {
this.$events.$off("page.changeStatus", this.reload);
},
methods: {
action: function(t, e) {
var n = this;
switch (e) {
case "create":
this.$refs.create.open(
this.options.link || this.parent,
this.parent + "/children/blueprints",
this.name
);
break;
case "preview":
var i = window.open("", "_blank");
(i.document.write = "..."),
this.$api.pages
.preview(t.id)
.then(function(t) {
i.location.href = t;
})
.catch(function(t) {
n.$store.dispatch("notification/error", t);
});
break;
case "rename":
this.$refs.rename.open(t.id);
break;
case "url":
this.$refs.url.open(t.id);
break;
case "status":
this.$refs.status.open(t.id);
break;
case "template":
this.$refs.template.open(t.id);
break;
case "remove":
this.$refs.remove.open(t.id);
break;
default:
throw new Error("Invalid action");
}
},
items: function(t) {
var e = this;
return t.map(function(t) {
return (
(t.flag = {
class: "k-status-flag k-status-flag-" + t.status,
tooltip: e.$t("page.status"),
icon:
!1 === t.permissions.changeStatus ? "protected" : "circle",
disabled: !1 === t.permissions.changeStatus,
click: function() {
e.action(t, "status");
}
}),
(t.options = function(n) {
e.$api.pages
.options(t.id, "list")
.then(function(t) {
return n(t);
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
}),
(t.sortable = t.permissions.sort && e.options.sortable),
t
);
});
},
sort: function(t) {
var e = this,
n = null;
if ((t.added && (n = "added"), t.moved && (n = "moved"), n)) {
var i = t[n].element,
s = t[n].newIndex + 1 + this.pagination.offset;
this.$api.pages
.status(i.id, "listed", s)
.then(function() {
e.$store.dispatch("notification/success", ":)");
})
.catch(function(t) {
e.$store.dispatch("notification/error", {
message: t.message,
details: t.details
}),
e.reload();
});
}
},
update: function() {
this.reload(), this.$events.$emit("model.update");
}
}
},
sd = id,
ad = Object(m["a"])(sd, td, ed, !1, null, null, null);
ad.options.__file = "PagesSection.vue";
var od = ad.exports,
rd = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return !1 === t.isLoading
? n(
"section",
{ staticClass: "k-files-section" },
[
n(
"header",
{ staticClass: "k-section-header" },
[
n("k-headline", [
t._v("\n " + t._s(t.headline) + " "),
t.options.min
? n(
"abbr",
{ attrs: { title: "This section is required" } },
[t._v("*")]
)
: t._e()
]),
t.add
? n(
"k-button-group",
[
n(
"k-button",
{
attrs: { icon: "upload" },
on: { click: t.upload }
},
[t._v(t._s(t.$t("add")))]
)
],
1
)
: t._e()
],
1
),
t.error
? [
n(
"k-box",
{ attrs: { theme: "negative" } },
[
n("k-text", { attrs: { size: "small" } }, [
n("strong", [
t._v(
t._s(
t.$t("error.section.notLoaded", {
name: t.name
})
) + ":"
)
]),
t._v("\n " + t._s(t.error) + "\n ")
])
],
1
)
]
: [
n(
"k-dropzone",
{
attrs: { disabled: !1 === t.add },
on: { drop: t.drop }
},
[
t.data.length
? n("k-collection", {
attrs: {
items: t.data,
layout: t.options.layout,
pagination: t.pagination,
sortable: t.options.sortable,
size: t.options.size
},
on: {
sort: t.sort,
paginate: t.paginate,
action: t.action
}
})
: n(
"k-empty",
{
attrs: {
layout: t.options.layout,
icon: "image"
},
on: {
click: function(e) {
t.add && t.upload();
}
}
},
[
t._v(
"\n " +
t._s(
t.options.empty || t.$t("files.empty")
) +
"\n "
)
]
)
],
1
),
n("k-file-rename-dialog", {
ref: "rename",
on: { success: t.update }
}),
n("k-file-remove-dialog", {
ref: "remove",
on: { success: t.update }
}),
n("k-upload", {
ref: "upload",
on: { success: t.uploaded, error: t.reload }
})
]
],
2
)
: t._e();
},
ld = [],
ud = {
mixins: [nd],
computed: {
add: function() {
return (
!(
!this.$permissions.files.create || !1 === this.options.upload
) && this.options.upload
);
}
},
created: function() {
this.load(), this.$events.$on("model.update", this.reload);
},
destroyed: function() {
this.$events.$off("model.update", this.reload);
},
methods: {
action: function(t, e) {
switch (e) {
case "edit":
this.$router.push(t.link);
break;
case "download":
window.open(t.url);
break;
case "rename":
this.$refs.rename.open(t.parent, t.filename);
break;
case "replace":
this.replace(t);
break;
case "remove":
this.$refs.remove.open(t.parent, t.filename);
break;
}
},
drop: function(t) {
if (!1 === this.add) return !1;
this.$refs.upload.drop(
t,
Object(u["a"])({}, this.add, { url: f.api + "/" + this.add.api })
);
},
items: function(t) {
var e = this;
return t.map(function(t) {
return (
(t.options = function(n) {
e.$api.files
.options(t.parent, t.filename, "list")
.then(function(t) {
return n(t);
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
}),
(t.sortable = e.options.sortable),
t
);
});
},
replace: function(t) {
this.$refs.upload.open({
url: f.api + "/" + this.$api.files.url(t.parent, t.filename),
accept: t.mime,
multiple: !1
});
},
sort: function(t) {
var e = this;
if (!1 === this.options.sortable) return !1;
(t = t.map(function(t) {
return t.id;
})),
this.$api
.patch(this.parent + "/files/sort", { files: t })
.then(function() {
e.$store.dispatch("notification/success", ":)");
})
.catch(function(t) {
e.reload(),
e.$store.dispatch("notification/error", t.message);
});
},
update: function() {
this.$events.$emit("model.update");
},
upload: function() {
if (!1 === this.add) return !1;
this.$refs.upload.open(
Object(u["a"])({}, this.add, { url: f.api + "/" + this.add.api })
);
},
uploaded: function() {
this.$events.$emit("file.create"),
this.$events.$emit("model.update"),
this.$store.dispatch("notification/success", ":)");
}
}
},
cd = ud,
pd = Object(m["a"])(cd, rd, ld, !1, null, null, null);
pd.options.__file = "FilesSection.vue";
var fd = pd.exports,
dd = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.isLoading
? t._e()
: n(
"section",
{ staticClass: "k-fields-section" },
[
t.issue
? [
n(
"k-headline",
{ staticClass: "k-fields-issue-headline" },
[t._v("Error")]
),
n("k-box", {
attrs: { text: t.issue.message, theme: "negative" }
})
]
: t._e(),
n("k-form", {
attrs: { fields: t.fields, validate: !0, value: t.values },
on: { input: t.input, submit: t.onSubmit }
})
],
2
);
},
hd = [],
md = {
mixins: [Wf],
data: function() {
return { fields: {}, isLoading: !0, issue: null };
},
computed: {
id: function() {
return this.$store.state.form.current;
},
language: function() {
return this.$store.state.languages.current;
},
values: function() {
return this.$store.getters["form/values"](this.id);
}
},
watch: {
$route: function() {
(this.fields = {}), (this.isLoading = !0), (this.issue = null);
},
language: function() {
this.fetch();
}
},
created: function() {
this.fetch();
},
methods: {
input: function(t, e, n) {
this.$store.dispatch("form/update", [this.id, n, t[n]]);
},
fetch: function() {
var t = this;
this.$api
.get(this.parent + "/sections/" + this.name)
.then(function(e) {
(t.fields = e.fields),
Object.keys(t.fields).forEach(function(e) {
(t.fields[e].section = t.name),
(t.fields[e].endpoints = {
field: t.parent + "/fields/" + e,
section: t.parent + "/sections/" + t.name,
model: t.parent
});
}),
(t.isLoading = !1);
})
.catch(function(e) {
(t.issue = e), (t.isLoading = !1);
});
},
onSubmit: function(t) {
this.$events.$emit("keydown.cmd.s", t);
}
}
},
gd = md,
vd = (n("7d5d"), Object(m["a"])(gd, dd, hd, !1, null, null, null));
vd.options.__file = "FieldsSection.vue";
var bd = vd.exports,
kd = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n("k-view", { staticClass: "k-error-view" }, [
n(
"div",
{ staticClass: "k-error-view-content" },
[
n("k-text", [
n(
"p",
[
n("k-icon", {
staticClass: "k-error-view-icon",
attrs: { type: "alert" }
})
],
1
),
n("p", [t._t("default")], 2)
])
],
1
)
]);
},
_d = [],
$d = (n("d221"), {}),
yd = Object(m["a"])($d, kd, _d, !1, null, null, null);
yd.options.__file = "ErrorView.vue";
var xd = yd.exports;
i["a"].component("k-dialog", xu),
i["a"].component("k-error-dialog", ju),
i["a"].component("k-file-rename-dialog", Vu),
i["a"].component("k-file-remove-dialog", Nu),
i["a"].component("k-files-dialog", Ju),
i["a"].component("k-language-create-dialog", nc),
i["a"].component("k-language-remove-dialog", lc),
i["a"].component("k-language-update-dialog", hc),
i["a"].component("k-page-create-dialog", _c),
i["a"].component("k-page-rename-dialog", Lc),
i["a"].component("k-page-remove-dialog", Oc),
i["a"].component("k-page-status-dialog", Dc),
i["a"].component("k-page-template-dialog", Vc),
i["a"].component("k-page-url-dialog", Jc),
i["a"].component("k-pages-dialog", sp),
i["a"].component("k-site-rename-dialog", lp),
i["a"].component("k-user-create-dialog", hp),
i["a"].component("k-user-email-dialog", _p),
i["a"].component("k-user-language-dialog", Op),
i["a"].component("k-user-password-dialog", Lp),
i["a"].component("k-user-remove-dialog", Dp),
i["a"].component("k-user-rename-dialog", Vp),
i["a"].component("k-user-role-dialog", Jp),
i["a"].component("k-users-dialog", nf),
i["a"].component("k-form-buttons", uf),
i["a"].component("k-dropzone", mf),
i["a"].component("k-file-preview", $f),
i["a"].component("k-tabs", Cf),
i["a"].component("k-languages-dropdown", Af),
i["a"].component("k-topbar", Rf),
i["a"].component("k-sections", Kf),
i["a"].component("k-info-section", Zf),
i["a"].component("k-pages-section", od),
i["a"].component("k-files-section", fd),
i["a"].component("k-fields-section", bd),
i["a"].component("k-error-view", xd);
var wd = {
user: function() {
return em.get("auth");
},
login: function(t) {
var e = {
long: t.remember || !1,
email: t.email,
password: <PASSWORD>
};
return em.post("auth/login", e).then(function(t) {
return t.user;
});
},
logout: function() {
return em.post("auth/logout");
}
},
Sd = {
get: function(t, e, n) {
return em.get(this.url(t, e), n).then(function(t) {
return !0 === Array.isArray(t.content) && (t.content = {}), t;
});
},
update: function(t, e, n) {
return em.patch(this.url(t, e), n);
},
rename: function(t, e, n) {
return em.patch(this.url(t, e, "name"), { name: n });
},
url: function(t, e, n) {
var i = t + "/files/" + e;
return n && (i += "/" + n), i;
},
link: function(t, e, n) {
return "/" + this.url(t, e, n);
},
delete: function(t, e) {
return em.delete(this.url(t, e));
},
options: function(t, e, n) {
return em
.get(this.url(t, e), { select: "options" })
.then(function(t) {
var e = t.options,
s = [];
return (
"list" === n &&
s.push({
icon: "open",
text: i["a"].i18n.translate("open"),
click: "download"
}),
s.push({
icon: "title",
text: i["a"].i18n.translate("rename"),
click: "rename",
disabled: !e.changeName
}),
s.push({
icon: "upload",
text: i["a"].i18n.translate("replace"),
click: "replace",
disabled: !e.replace
}),
s.push({
icon: "trash",
text: i["a"].i18n.translate("delete"),
click: "remove",
disabled: !e.delete
}),
s
);
});
},
breadcrumb: function(t, e) {
var n = null,
i = [];
switch (e) {
case "UserFile":
i.push({
label: t.parent.username,
link: em.users.link(t.parent.id)
}),
(n = "users/" + t.parent.id);
break;
case "SiteFile":
n = "site";
break;
case "PageFile":
(i = t.parents.map(function(t) {
return { label: t.title, link: em.pages.link(t.id) };
})),
(n = "pages/" + t.parent.id);
break;
}
return (
i.push({ label: t.filename, link: this.link(n, t.filename) }), i
);
}
},
Od = {
create: function(t, e) {
return null === t || "/" === t
? em.post("site/children", e)
: em.post(this.url(t, "children"), e);
},
url: function(t, e) {
var n = null === t ? "pages" : "pages/" + t.replace(/\//g, "+");
return e && (n += "/" + e), n;
},
link: function(t) {
return "/" + this.url(t);
},
get: function(t, e) {
return em.get(this.url(t), e).then(function(t) {
return !0 === Array.isArray(t.content) && (t.content = {}), t;
});
},
options: function(t) {
var e =
arguments.length > 1 && void 0 !== arguments[1]
? arguments[1]
: "view";
return em.get(this.url(t), { select: "options" }).then(function(t) {
var n = t.options,
s = [];
return (
"list" === e &&
s.push({
click: "preview",
icon: "open",
text: i["a"].i18n.translate("open"),
disabled: !1 === n.preview
}),
s.push({
click: "rename",
icon: "title",
text: i["a"].i18n.translate("rename"),
disabled: !n.changeTitle
}),
s.push({
click: "url",
icon: "url",
text: i["a"].i18n.translate("page.changeSlug"),
disabled: !n.changeSlug
}),
s.push({
click: "status",
icon: "preview",
text: i["a"].i18n.translate("page.changeStatus"),
disabled: !n.changeStatus
}),
s.push({
click: "template",
icon: "template",
text: i["a"].i18n.translate("page.changeTemplate"),
disabled: !n.changeTemplate
}),
s.push({
click: "remove",
icon: "trash",
text: i["a"].i18n.translate("delete"),
disabled: !n.delete
}),
s
);
});
},
preview: function(t) {
return this.get(t, { select: "previewUrl" }).then(function(t) {
return t.previewUrl;
});
},
update: function(t, e) {
return em.patch(this.url(t), e);
},
children: function(t, e) {
return em.post(this.url(t, "children/search"), e);
},
files: function(t, e) {
return em.post(this.url(t, "files/search"), e);
},
delete: function(t, e) {
return em.delete(this.url(t), e);
},
slug: function(t, e) {
return em.patch(this.url(t, "slug"), { slug: e });
},
title: function(t, e) {
return em.patch(this.url(t, "title"), { title: e });
},
template: function(t, e) {
return em.patch(this.url(t, "template"), { template: e });
},
search: function(t, e) {
return t
? em.post(
"pages/" +
t.replace("/", "+") +
"/children/search?select=id,title,hasChildren",
e
)
: em.post("site/children/search?select=id,title,hasChildren", e);
},
status: function(t, e, n) {
return em.patch(this.url(t, "status"), { status: e, position: n });
},
breadcrumb: function(t) {
var e = this,
n =
!(arguments.length > 1 && void 0 !== arguments[1]) ||
arguments[1],
i = t.parents.map(function(t) {
return { label: t.title, link: e.link(t.id) };
});
return (
!0 === n && i.push({ label: t.title, link: this.link(t.id) }), i
);
}
},
Cd = n("2f62"),
Ed = n("3835"),
jd = {
namespaced: !0,
state: { models: {}, current: null, isLocked: !1 },
getters: {
current: function(t) {
return t.current;
},
exists: function(t) {
return function(e) {
return t.models.hasOwnProperty(e);
};
},
hasChanges: function(t, e) {
return function(t) {
return Object.keys(e.model(t).changes).length > 0;
};
},
id: function(t, e, n) {
return function(t) {
return n.languages.current
? t + "/" + n.languages.current.code
: t;
};
},
isCurrent: function(t) {
return function(e) {
return (t.current = e);
};
},
model: function(t, e) {
return function(n) {
return e.exists(n)
? t.models[n]
: { originals: {}, values: {}, changes: {}, api: null };
};
},
originals: function(t, e) {
return function(t) {
return zr(e.model(t).originals);
};
},
values: function(t, e) {
return function(t) {
return zr(e.model(t).values);
};
}
},
mutations: {
CREATE: function(t, e) {
i["a"].set(t.models, e.id, {
api: e.api,
originals: zr(e.content),
values: zr(e.content),
changes: {}
});
},
CURRENT: function(t, e) {
t.current = e;
},
IS_LOCKED: function(t, e) {
t.isLocked = e;
},
REMOVE: function(t, e) {
i["a"].delete(t.models, e),
localStorage.removeItem("kirby$form$" + e);
},
DELETE_CHANGES: function(t, e) {
i["a"].set(t.models[e], "changes", {}),
localStorage.removeItem("kirby$form$" + e);
},
SET_ORIGINALS: function(t, e) {
var n = Object(Ed["a"])(e, 2),
i = n[0],
s = n[1];
t.models[i].originals = zr(s);
},
SET_VALUES: function(t, e) {
var n = Object(Ed["a"])(e, 2),
i = n[0],
s = n[1];
t.models[i].values = zr(s);
},
UPDATE: function(t, e) {
var n = Object(Ed["a"])(e, 3),
s = n[0],
a = n[1],
o = n[2];
(o = zr(o)), i["a"].set(t.models[s].values, a, o);
var r = JSON.stringify(t.models[s].originals[a]),
l = JSON.stringify(o);
r === l
? i["a"].delete(t.models[s].changes, a)
: i["a"].set(t.models[s].changes, a, !0),
localStorage.setItem(
"kirby$form$" + s,
JSON.stringify(t.models[s].values)
);
}
},
actions: {
create: function(t, e) {
t.rootState.languages.current &&
t.rootState.languages.current.code &&
(e.id = t.getters.id(e.id)),
t.commit("CREATE", e),
t.commit("CURRENT", e.id);
var n = localStorage.getItem("kirby$form$" + e.id);
if (n) {
var i = JSON.parse(n);
Object.keys(i).forEach(function(n) {
var s = i[n];
t.commit("UPDATE", [e.id, n, s]);
});
}
},
remove: function(t, e) {
t.commit("REMOVE", e);
},
revert: function(t, e) {
var n = t.getters.model(e);
return em.get(n.api, { select: "content" }).then(function(n) {
t.commit("SET_ORIGINALS", [e, n.content]),
t.commit("SET_VALUES", [e, n.content]),
t.commit("DELETE_CHANGES", e);
});
},
save: function(t, e) {
e = e || t.state.current;
var n = t.getters.model(e);
return (
(!t.getters.isCurrent(e) || !t.state.isLocked) &&
em.patch(n.api, n.values).then(function() {
t.dispatch("revert", e);
})
);
},
lock: function(t) {
t.commit("IS_LOCKED", !0);
},
unlock: function(t) {
t.commit("IS_LOCKED", !1);
},
update: function(t, e) {
var n = Object(Ed["a"])(e, 3),
i = n[0],
s = n[1],
a = n[2];
t.commit("UPDATE", [i, s, a]);
}
}
},
Td = {
namespaced: !0,
state: { all: [], current: null, default: null },
mutations: {
SET_ALL: function(t, e) {
t.all = e.map(function(t) {
return {
code: t.code,
name: t.name,
default: t.default,
direction: t.direction
};
});
},
SET_CURRENT: function(t, e) {
(t.current = e),
e && e.code && localStorage.setItem("kirby$language", e.code);
},
SET_DEFAULT: function(t, e) {
t.default = e;
}
},
actions: {
current: function(t, e) {
t.commit("SET_CURRENT", e);
},
install: function(t, e) {
var n = e.filter(function(t) {
return t.default;
})[0];
t.commit("SET_ALL", e), t.commit("SET_DEFAULT", n);
var i = localStorage.getItem("kirby$language");
if (i) {
var s = e.filter(function(t) {
return t.code === i;
})[0];
if (s) return void t.commit("SET_CURRENT", s);
}
t.commit("SET_CURRENT", n || e[0]);
},
load: function(t) {
return em.get("languages").then(function(e) {
t.dispatch("install", e.data);
});
}
}
},
Id = {
timer: null,
namespaced: !0,
state: { type: null, message: null, details: null, timeout: null },
mutations: {
SET: function(t, e) {
(t.type = e.type),
(t.message = e.message),
(t.details = e.details),
(t.timeout = e.timeout);
},
UNSET: function(t) {
(t.type = null),
(t.message = null),
(t.details = null),
(t.timeout = null);
}
},
actions: {
close: function(t) {
clearTimeout(this.timer), t.commit("UNSET");
},
open: function(t, e) {
t.dispatch("close"),
t.commit("SET", e),
e.timeout &&
(this.timer = setTimeout(function() {
t.dispatch("close");
}, e.timeout));
},
success: function(t, e) {
"string" === typeof e && (e = { message: e }),
t.dispatch(
"open",
Object(u["a"])({ type: "success", timeout: 4e3 }, e)
);
},
error: function(t, e) {
"string" === typeof e && (e = { message: e }),
t.dispatch("open", Object(u["a"])({ type: "error" }, e));
}
}
},
Ld = {
namespaced: !0,
state: { info: { title: null } },
mutations: {
SET_INFO: function(t, e) {
t.info = e;
},
SET_LICENSE: function(t, e) {
t.info.license = e;
},
SET_TITLE: function(t, e) {
t.info.title = e;
}
},
actions: {
title: function(t, e) {
t.commit("SET_TITLE", e);
},
register: function(t, e) {
t.commit("SET_LICENSE", e);
},
load: function(t, e) {
return !e && t.state.info.isReady && t.rootState.user.current
? new Promise(function(e) {
e(t.state.info);
})
: em.system
.info({ view: "panel" })
.then(function(e) {
return (
t.commit(
"SET_INFO",
Object(u["a"])({ isReady: e.isInstalled && e.isOk }, e)
),
t.dispatch("languages/install", e.languages, {
root: !0
}),
t.dispatch("translation/install", e.translation, {
root: !0
}),
t.dispatch("translation/activate", e.translation.id, {
root: !0
}),
t.dispatch("user/current", e.user, { root: !0 }),
t.state.info
);
})
.catch(function(e) {
t.commit("SET_INFO", { isBroken: !0, error: e.message });
});
}
}
},
Ad = {
namespaced: !0,
state: { current: null, installed: [] },
mutations: {
SET_CURRENT: function(t, e) {
t.current = e;
},
INSTALL: function(t, e) {
t.installed[e.id] = e;
}
},
actions: {
load: function(t, e) {
return em.translations.get(e);
},
install: function(t, e) {
t.commit("INSTALL", e), i["a"].i18n.add(e.id, e.data);
},
activate: function(t, e) {
var n = t.state.installed[e];
n
? (i["a"].i18n.set(e),
t.commit("SET_CURRENT", e),
(document.dir = n.direction),
(document.documentElement.lang = e))
: t.dispatch("load", e).then(function(n) {
t.dispatch("install", n), t.dispatch("activate", e);
});
}
}
},
qd = n("8c4f"),
Nd = function(t, e, n) {
Yh.dispatch("system/load").then(function() {
var e = Yh.state.user.current;
if (!e)
return (
Yh.dispatch("user/visit", t.path), Yh.dispatch("user/logout"), !1
);
var s = e.permissions.access;
return !1 === s.panel
? ((window.location.href = f.site), !1)
: !1 === s[t.meta.view]
? (Yh.dispatch("notification/error", {
message: i["a"].i18n.translate("error.access.view")
}),
n("/"))
: void n();
});
},
Pd = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-error-view",
{ staticClass: "k-browser-view" },
[
n("p", [
t._v(
"\n We are really sorry, but your browser does not support\n all features required for the Kirby Panel.\n "
)
]),
!1 === t.hasFetchSupport
? [
n("p", [
n("strong", [t._v("Fetch")]),
n("br"),
t._v(
"\n We use Javascript's new Fetch API. You can find a list of supported browsers for this feature on\n "
),
n("strong", [
n(
"a",
{ attrs: { href: "https://caniuse.com/#feat=fetch" } },
[t._v("caniuse.com")]
)
])
])
]
: t._e(),
!1 === t.hasGridSupport
? [
n("p", [
n("strong", [t._v("CSS Grid")]),
n("br"),
t._v(
"\n We use CSS Grids for all our layouts. You can find a list of supported browsers for this feature on\n "
),
n("strong", [
n(
"a",
{
attrs: { href: "https://caniuse.com/#feat=css-grid" }
},
[t._v("caniuse.com")]
)
])
])
]
: t._e()
],
2
);
},
Bd = [],
Dd = {
grid: function() {
return !(!window.CSS || !window.CSS.supports("display", "grid"));
},
fetch: function() {
return void 0 !== window.fetch;
},
all: function() {
return this.fetch() && this.grid();
}
},
Fd = {
computed: {
hasFetchSupport: function() {
return Dd.fetch();
},
hasGridSupport: function() {
return Dd.grid();
}
},
created: function() {
Dd.all() && this.$router.push("/");
}
},
Rd = Fd,
Md = (n("d6fc"), Object(m["a"])(Rd, Pd, Bd, !1, null, null, null));
Md.options.__file = "BrowserView.vue";
var zd = Md.exports,
Ud = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-error-boundary",
{
key: t.plugin,
scopedSlots: t._u([
{
key: "error",
fn: function(e) {
var i = e.error;
return n("k-error-view", {}, [
t._v("\n " + t._s(i) + "\n ")
]);
}
}
])
},
[n("k-" + t.plugin + "-plugin-view", { tag: "component" })],
1
);
},
Vd = [],
Hd = {
props: { plugin: String },
watch: {
plugin: function() {
this.$store.dispatch("view", this.plugin);
}
},
created: function() {
this.$store.dispatch("view", this.plugin);
}
},
Kd = Hd,
Gd = Object(m["a"])(Kd, Ud, Vd, !1, null, null, null);
Gd.options.__file = "CustomView.vue";
var Yd = Gd.exports,
Wd = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.issue
? n("k-error-view", [t._v("\n " + t._s(t.issue.message) + "\n")])
: n(
"div",
{ staticClass: "k-file-view" },
[
n("k-file-preview", { attrs: { file: t.file } }),
n(
"k-view",
{ staticClass: "k-file-content" },
[
n(
"k-header",
{
attrs: {
editable: t.permissions.changeName,
tabs: t.tabs,
tab: t.tab
},
on: {
edit: function(e) {
t.action("rename");
}
}
},
[
t._v(
"\n\n " + t._s(t.file.filename) + "\n\n "
),
n(
"k-button-group",
{ attrs: { slot: "left" }, slot: "left" },
[
n(
"k-button",
{
attrs: { responsive: !0, icon: "open" },
on: {
click: function(e) {
t.action("download");
}
}
},
[
t._v(
"\n " +
t._s(t.$t("open")) +
"\n "
)
]
),
n(
"k-dropdown",
[
n(
"k-button",
{
attrs: { responsive: !0, icon: "cog" },
on: {
click: function(e) {
t.$refs.settings.toggle();
}
}
},
[
t._v(
"\n " +
t._s(t.$t("settings")) +
"\n "
)
]
),
n("k-dropdown-content", {
ref: "settings",
attrs: { options: t.options },
on: { action: t.action }
})
],
1
),
n("k-languages-dropdown")
],
1
),
t.file.id
? n("k-prev-next", {
attrs: {
slot: "right",
prev: t.prev,
next: t.next
},
slot: "right"
})
: t._e()
],
1
),
t.file.id
? n("k-tabs", {
key: "file-" + t.file.id + "-tabs",
ref: "tabs",
attrs: {
parent: t.$api.files.url(t.path, t.file.filename),
tabs: t.tabs,
blueprint: t.file.blueprint.name
},
on: {
tab: function(e) {
t.tab = e;
}
}
})
: t._e(),
n("k-file-rename-dialog", {
ref: "rename",
on: { success: t.renamed }
}),
n("k-file-remove-dialog", {
ref: "remove",
on: { success: t.deleted }
}),
n("k-upload", {
ref: "upload",
attrs: {
url: t.uploadApi,
accept: t.file.mime,
multiple: !1
},
on: { success: t.uploaded }
})
],
1
)
],
1
);
},
Jd = [],
Xd = {
created: function() {
this.fetch(),
this.$events.$on("keydown.left", this.toPrev),
this.$events.$on("keydown.right", this.toNext);
},
destroyed: function() {
this.$events.$off("keydown.left", this.toPrev),
this.$events.$off("keydown.right", this.toNext);
},
watch: {
$route: function() {
this.fetch();
}
},
methods: {
toPrev: function(t) {
this.prev &&
"body" === t.target.localName &&
this.$router.push(this.prev.link);
},
toNext: function(t) {
this.next &&
"body" === t.target.localName &&
this.$router.push(this.next.link);
}
}
},
Qd = {
mixins: [Xd],
props: {
path: { type: String },
filename: { type: String, required: !0 }
},
data: function() {
return {
name: "",
file: {
id: null,
parent: null,
filename: "",
url: "",
prev: null,
next: null,
panelIcon: null,
panelImage: null,
mime: null,
content: {}
},
permissions: { changeName: !1, delete: !1 },
issue: null,
tabs: [],
tab: null,
options: null
};
},
computed: {
uploadApi: function() {
return f.api + "/" + this.path + "/files/" + this.filename;
},
prev: function() {
if (this.file.prev)
return {
link: this.$api.files.link(this.path, this.file.prev.filename),
tooltip: this.file.prev.filename
};
},
language: function() {
return this.$store.state.languages.current;
},
next: function() {
if (this.file.next)
return {
link: this.$api.files.link(this.path, this.file.next.filename),
tooltip: this.file.next.filename
};
}
},
watch: {
language: function() {
this.fetch();
},
path: function() {
this.fetch();
}
},
methods: {
fetch: function() {
var t = this;
this.$api.files
.get(this.path, this.filename, { view: "panel" })
.then(function(e) {
(t.file = e),
(t.file.next = e.nextWithTemplate),
(t.file.prev = e.prevWithTemplate),
(t.file.url = e.url),
(t.name = e.name),
(t.tabs = e.blueprint.tabs),
(t.permissions = e.options),
(t.options = function(e) {
t.$api.files
.options(t.path, t.file.filename)
.then(function(t) {
e(t);
});
}),
t.$store.dispatch(
"breadcrumb",
t.$api.files.breadcrumb(t.file, t.$route.name)
),
t.$store.dispatch("title", t.filename),
t.$store.dispatch("form/create", {
id: "files/" + e.id,
api: t.$api.files.link(t.path, t.filename),
content: e.content
});
})
.catch(function(e) {
window.console.error(e), (t.issue = e);
});
},
action: function(t) {
switch (t) {
case "download":
window.open(this.file.url);
break;
case "rename":
this.$refs.rename.open(this.path, this.file.filename);
break;
case "replace":
this.$refs.upload.open({
url:
f.api +
"/" +
this.$api.files.url(this.path, this.file.filename),
accept: this.file.mime
});
break;
case "remove":
this.$refs.remove.open(this.path, this.file.filename);
break;
}
},
deleted: function() {
this.path
? this.$router.push("/" + this.path)
: this.$router.push("/site");
},
renamed: function(t) {
this.$router.push(this.$api.files.link(this.path, t.filename));
},
uploaded: function() {
this.fetch(), this.$store.dispatch("notification/success", ":)");
}
}
},
Zd = Qd,
th = Object(m["a"])(Zd, Wd, Jd, !1, null, null, null);
th.options.__file = "FileView.vue";
var eh = th.exports,
nh = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.system
? n(
"k-view",
{
staticClass: "k-installation-view",
attrs: { align: "center" }
},
[
t.system.isOk && !t.system.isInstalled
? n(
"form",
{
on: {
submit: function(e) {
return e.preventDefault(), t.install(e);
}
}
},
[
n("h1", { staticClass: "k-offscreen" }, [
t._v(t._s(t.$t("installation")))
]),
n("k-fieldset", {
attrs: { fields: t.fields, novalidate: !0 },
model: {
value: t.user,
callback: function(e) {
t.user = e;
},
expression: "user"
}
}),
n(
"k-button",
{ attrs: { type: "submit", icon: "check" } },
[t._v(t._s(t.$t("install")))]
)
],
1
)
: t.system.isOk && t.system.isInstalled
? n(
"k-text",
[
n("k-headline", [
t._v(t._s(t.$t("installation.completed")))
]),
n("k-link", { attrs: { to: "/login" } }, [
t._v(t._s(t.$t("login")))
])
],
1
)
: n(
"div",
[
t.system.isInstalled
? t._e()
: n("k-headline", [
t._v(t._s(t.$t("installation.issues.headline")))
]),
n("ul", { staticClass: "k-installation-issues" }, [
!1 === t.requirements.php
? n(
"li",
[
n("k-icon", { attrs: { type: "alert" } }),
n("span", {
domProps: {
innerHTML: t._s(
t.$t("installation.issues.php")
)
}
})
],
1
)
: t._e(),
!1 === t.requirements.server
? n(
"li",
[
n("k-icon", { attrs: { type: "alert" } }),
n("span", {
domProps: {
innerHTML: t._s(
t.$t("installation.issues.server")
)
}
})
],
1
)
: t._e(),
!1 === t.requirements.mbstring
? n(
"li",
[
n("k-icon", { attrs: { type: "alert" } }),
n("span", {
domProps: {
innerHTML: t._s(
t.$t("installation.issues.mbstring")
)
}
})
],
1
)
: t._e(),
!1 === t.requirements.curl
? n(
"li",
[
n("k-icon", { attrs: { type: "alert" } }),
n("span", {
domProps: {
innerHTML: t._s(
t.$t("installation.issues.curl")
)
}
})
],
1
)
: t._e(),
!1 === t.requirements.accounts
? n(
"li",
[
n("k-icon", { attrs: { type: "alert" } }),
n("span", {
domProps: {
innerHTML: t._s(
t.$t("installation.issues.accounts")
)
}
})
],
1
)
: t._e(),
!1 === t.requirements.content
? n(
"li",
[
n("k-icon", { attrs: { type: "alert" } }),
n("span", {
domProps: {
innerHTML: t._s(
t.$t("installation.issues.content")
)
}
})
],
1
)
: t._e(),
!1 === t.requirements.media
? n(
"li",
[
n("k-icon", { attrs: { type: "alert" } }),
n("span", {
domProps: {
innerHTML: t._s(
t.$t("installation.issues.media")
)
}
})
],
1
)
: t._e()
]),
n(
"k-button",
{
attrs: { icon: "refresh" },
on: { click: t.check }
},
[
n("span", {
domProps: { innerHTML: t._s(t.$t("retry")) }
})
]
)
],
1
)
],
1
)
: t._e();
},
ih = [],
sh = {
data: function() {
return {
user: {
name: "",
email: "",
language: "en",
password: "",
role: "admin"
},
languages: [],
system: null
};
},
computed: {
translation: function() {
return this.$store.state.translation.current;
},
requirements: function() {
return this.system ? this.system.requirements : {};
},
fields: function() {
return {
name: {
label: this.$t("name"),
type: "text",
icon: "user",
autofocus: !0
},
email: {
label: this.$t("email"),
type: "email",
link: !1,
required: !0
},
password: {
label: this.$t("password"),
type: "password",
placeholder: this.$t("password") + " …",
required: !0
},
language: {
label: this.$t("language"),
type: "select",
options: this.languages,
icon: "globe",
empty: !1,
required: !0
}
};
}
},
watch: {
translation: function(t) {
this.user.language = t;
},
"user.language": function(t) {
this.$store.dispatch("translation/activate", t);
}
},
created: function() {
this.check();
},
methods: {
install: function() {
var t = this;
this.$api.system
.install(this.user)
.then(function(e) {
t.$store.dispatch("user/current", e),
t.$store.dispatch(
"notification/success",
t.$t("welcome") + "!"
),
t.$router.push("/");
})
.catch(function(e) {
t.$store.dispatch("notification/error", e);
});
},
check: function() {
var t = this;
this.$store.dispatch("system/load", !0).then(function(e) {
!0 === e.isInstalled && e.isReady
? t.$router.push("/login")
: t.$api.translations.options().then(function(n) {
(t.languages = n),
(t.system = e),
t.$store.dispatch("title", t.$t("view.installation"));
});
});
}
}
},
ah = sh,
oh = (n("146c"), Object(m["a"])(ah, nh, ih, !1, null, null, null));
oh.options.__file = "InstallationView.vue";
var rh = oh.exports,
lh = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return n(
"k-view",
{ staticClass: "k-settings-view" },
[
n("k-header", [
t._v("\n " + t._s(t.$t("view.settings")) + "\n ")
]),
n("section", { staticClass: "k-system-info" }, [
n("header", [n("k-headline", [t._v("Kirby")])], 1),
n("ul", { staticClass: "k-system-info-box" }, [
n("li", [
n("dl", [
n("dt", [t._v(t._s(t.$t("license")))]),
n(
"dd",
[
t.license
? [
t._v(
"\n " +
t._s(t.license) +
"\n "
)
]
: n("p", [
n(
"strong",
{ staticClass: "k-system-unregistered" },
[t._v(t._s(t.$t("license.unregistered")))]
)
])
],
2
)
])
]),
n("li", [
n("dl", [
n("dt", [t._v(t._s(t.$t("version")))]),
n("dd", [t._v(t._s(t.$store.state.system.info.version))])
])
])
])
]),
t.multilang
? n(
"section",
{ staticClass: "k-languages" },
[
t.languages.length > 0
? [
n(
"section",
{ staticClass: "k-languages-section" },
[
n(
"header",
[
n("k-headline", [
t._v(t._s(t.$t("languages.default")))
])
],
1
),
n("k-collection", {
attrs: { items: t.defaultLanguage },
on: { action: t.action }
})
],
1
),
n(
"section",
{ staticClass: "k-languages-section" },
[
n(
"header",
[
n("k-headline", [
t._v(t._s(t.$t("languages.secondary")))
]),
n(
"k-button",
{
attrs: { icon: "add" },
on: {
click: function(e) {
t.$refs.create.open();
}
}
},
[t._v(t._s(t.$t("language.create")))]
)
],
1
),
t.translations.length
? n("k-collection", {
attrs: { items: t.translations },
on: { action: t.action }
})
: n(
"k-empty",
{
attrs: { icon: "globe" },
on: {
click: function(e) {
t.$refs.create.open();
}
}
},
[
t._v(
t._s(t.$t("languages.secondary.empty"))
)
]
)
],
1
)
]
: 0 === t.languages.length
? [
n(
"header",
[
n("k-headline", [
t._v(t._s(t.$t("languages")))
]),
n(
"k-button",
{
attrs: { icon: "add" },
on: {
click: function(e) {
t.$refs.create.open();
}
}
},
[t._v(t._s(t.$t("language.create")))]
)
],
1
),
n(
"k-empty",
{
attrs: { icon: "globe" },
on: {
click: function(e) {
t.$refs.create.open();
}
}
},
[t._v(t._s(t.$t("languages.empty")))]
)
]
: t._e(),
n("k-language-create-dialog", {
ref: "create",
on: { success: t.fetch }
}),
n("k-language-update-dialog", {
ref: "update",
on: { success: t.fetch }
}),
n("k-language-remove-dialog", {
ref: "remove",
on: { success: t.fetch }
})
],
2
)
: t._e()
],
1
);
},
uh = [],
ch = {
data: function() {
return { languages: [] };
},
computed: {
defaultLanguage: function() {
return this.languages.filter(function(t) {
return t.default;
});
},
multilang: function() {
return this.$store.state.system.info.multilang;
},
license: function() {
return this.$store.state.system.info.license;
},
translations: function() {
return this.languages.filter(function(t) {
return !1 === t.default;
});
}
},
created: function() {
this.fetch(),
this.$store.dispatch("title", this.$t("view.settings")),
this.$store.dispatch("breadcrumb", []);
},
methods: {
fetch: function() {
var t = this;
!1 !== this.multilang
? this.$api.get("languages").then(function(e) {
t.languages = e.data.map(function(n) {
return {
id: n.code,
default: n.default,
icon: { type: "globe", back: "black" },
text: n.name,
info: n.code,
options: [
{ icon: "edit", text: t.$t("edit"), click: "update" },
{
icon: "trash",
text: t.$t("delete"),
disabled: n.default && 1 !== e.data.length,
click: "remove"
}
]
};
});
})
: (this.languages = []);
},
action: function(t, e) {
switch (e) {
case "update":
this.$refs.update.open(t.id);
break;
case "remove":
this.$refs.remove.open(t.id);
break;
}
}
}
},
ph = ch,
fh = (n("9bd5"), Object(m["a"])(ph, lh, uh, !1, null, null, null));
fh.options.__file = "SettingsView.vue";
var dh = fh.exports,
hh = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.issue
? n("k-error-view", [t._v("\n " + t._s(t.issue.message) + "\n")])
: t.ready
? n(
"k-view",
{ staticClass: "k-login-view", attrs: { align: "center" } },
[
n(
"form",
{
staticClass: "k-login-form",
attrs: { "data-invalid": t.invalid },
on: {
submit: function(e) {
return e.preventDefault(), t.login(e);
}
}
},
[
n("h1", { staticClass: "k-offscreen" }, [
t._v(t._s(t.$t("login")))
]),
n("k-fieldset", {
attrs: { novalidate: !0, fields: t.fields },
model: {
value: t.user,
callback: function(e) {
t.user = e;
},
expression: "user"
}
}),
n(
"div",
{ staticClass: "k-login-buttons" },
[
n(
"span",
{ staticClass: "k-login-checkbox" },
[
n("k-checkbox-input", {
attrs: {
value: t.user.remember,
label: t.$t("login.remember")
},
on: {
input: function(e) {
t.user.remember = e;
}
}
})
],
1
),
n(
"k-button",
{
staticClass: "k-login-button",
attrs: { icon: "check", type: "submit" }
},
[
t._v("\n " + t._s(t.$t("login")) + " "),
t.isLoading ? [t._v("…")] : t._e()
],
2
)
],
1
)
],
1
)
]
)
: t._e();
},
mh = [],
gh = {
data: function() {
return {
ready: !1,
issue: null,
invalid: !1,
isLoading: !1,
user: { email: "", password: "", remember: !1 }
};
},
computed: {
fields: function() {
return {
email: {
autofocus: !0,
label: this.$t("email"),
type: "email",
link: !1
},
password: {
label: this.$t("password"),
type: "password",
minLength: 8,
autocomplete: "<PASSWORD>",
counter: !1
}
};
}
},
created: function() {
var t = this;
this.$store
.dispatch("system/load")
.then(function(e) {
e.isReady || t.$router.push("/installation"),
e.user && e.user.id && t.$router.push("/"),
(t.ready = !0),
t.$store.dispatch("title", t.$t("login"));
})
.catch(function(e) {
t.issue = e;
});
},
methods: {
login: function() {
var t = this;
(this.invalid = !1),
(this.isLoading = !0),
this.$store
.dispatch("user/login", this.user)
.then(function() {
t.$store.dispatch("notification/success", t.$t("welcome")),
(t.isLoading = !1);
})
.catch(function() {
(t.invalid = !0), (t.isLoading = !1);
});
}
}
},
vh = gh,
bh = (n("24c1"), Object(m["a"])(vh, hh, mh, !1, null, null, null));
bh.options.__file = "LoginView.vue";
var kh = bh.exports,
_h = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.issue
? n("k-error-view", [t._v("\n " + t._s(t.issue.message) + "\n")])
: n(
"k-view",
{ staticClass: "k-page-view" },
[
n(
"k-header",
{
attrs: {
tabs: t.tabs,
tab: t.tab,
editable: t.permissions.changeTitle
},
on: {
edit: function(e) {
t.action("rename");
}
}
},
[
t._v("\n " + t._s(t.page.title) + "\n "),
n(
"k-button-group",
{ attrs: { slot: "left" }, slot: "left" },
[
t.permissions.preview && t.page.previewUrl
? n(
"k-button",
{
attrs: {
responsive: !0,
link: t.page.previewUrl,
target: "_blank",
icon: "open"
}
},
[
t._v(
"\n " + t._s(t.$t("open")) + "\n "
)
]
)
: t._e(),
t.status
? n(
"k-button",
{
class: [
"k-status-flag",
"k-status-flag-" + t.page.status
],
attrs: {
disabled: !1 === t.permissions.changeStatus,
icon:
!1 === t.permissions.changeStatus
? "protected"
: "circle",
responsive: !0
},
on: {
click: function(e) {
t.action("status");
}
}
},
[
t._v(
"\n " +
t._s(t.status.label) +
"\n "
)
]
)
: t._e(),
n(
"k-dropdown",
[
n(
"k-button",
{
attrs: { responsive: !0, icon: "cog" },
on: {
click: function(e) {
t.$refs.settings.toggle();
}
}
},
[
t._v(
"\n " +
t._s(t.$t("settings")) +
"\n "
)
]
),
n("k-dropdown-content", {
ref: "settings",
attrs: { options: t.options },
on: { action: t.action }
})
],
1
),
n("k-languages-dropdown")
],
1
),
t.page.id
? n("k-prev-next", {
attrs: { slot: "right", prev: t.prev, next: t.next },
slot: "right"
})
: t._e()
],
1
),
t.page.id
? n("k-tabs", {
key: t.tabsKey,
ref: "tabs",
attrs: {
parent: t.$api.pages.url(t.page.id),
blueprint: t.blueprint,
tabs: t.tabs
},
on: {
tab: function(e) {
t.tab = e;
}
}
})
: t._e(),
n("k-page-rename-dialog", {
ref: "rename",
on: { success: t.update }
}),
n("k-page-url-dialog", {
ref: "url",
on: {
success: function(e) {
t.$emit("model.update");
}
}
}),
n("k-page-status-dialog", {
ref: "status",
on: { success: t.update }
}),
n("k-page-template-dialog", {
ref: "template",
on: { success: t.update }
}),
n("k-page-remove-dialog", { ref: "remove" })
],
1
);
},
$h = [],
yh = {
mixins: [Xd],
props: { path: { type: String, required: !0 } },
data: function() {
return {
page: { title: "", id: null, prev: null, next: null, status: null },
blueprint: null,
preview: !0,
permissions: { changeTitle: !1, changeStatus: !1 },
icon: "page",
issue: null,
tab: null,
tabs: [],
options: null
};
},
computed: {
prev: function() {
if (this.page.prev)
return {
link: this.$api.pages.link(this.page.prev.id),
tooltip: this.page.prev.title
};
},
language: function() {
return this.$store.state.languages.current;
},
next: function() {
if (this.page.next)
return {
link: this.$api.pages.link(this.page.next.id),
tooltip: this.page.next.title
};
},
status: function() {
return null !== this.page.status
? this.page.blueprint.status[this.page.status]
: null;
},
tabsKey: function() {
return "page-" + this.page.id + "-tabs";
}
},
watch: {
language: function() {
this.fetch();
},
path: function() {
this.fetch();
}
},
methods: {
action: function(t) {
var e = this;
switch (t) {
case "preview":
this.$api.pages
.preview(this.page.id)
.then(function(t) {
window.open(t);
})
.catch(function(t) {
e.$store.dispatch("notification/error", t);
});
break;
case "rename":
this.$refs.rename.open(this.page.id);
break;
case "url":
this.$refs.url.open(this.page.id);
break;
case "status":
this.$refs.status.open(this.page.id);
break;
case "template":
this.$refs.template.open(this.page.id);
break;
case "remove":
this.$refs.remove.open(this.page.id);
break;
default:
this.$store.dispatch(
"notification/error",
this.$t("notification.notImplemented")
);
break;
}
},
changeLanguage: function(t) {
this.$store.dispatch("languages/current", t), this.fetch();
},
fetch: function() {
var t = this;
this.$api.pages
.get(this.path, { view: "panel" })
.then(function(e) {
(t.page = e),
(t.blueprint = e.blueprint.name),
(t.permissions = e.options),
(t.tabs = e.blueprint.tabs),
(t.options = function(e) {
t.$api.pages.options(t.page.id).then(function(t) {
e(t);
});
}),
t.$store.dispatch("breadcrumb", t.$api.pages.breadcrumb(e)),
t.$store.dispatch("title", t.page.title),
t.$store.dispatch("form/create", {
id: "pages/" + e.id,
api: t.$api.pages.link(e.id),
content: e.content
});
})
.catch(function(e) {
t.issue = e;
});
},
update: function() {
this.fetch(), this.$emit("model.update");
}
}
},
xh = yh,
wh = (n("202d"), Object(m["a"])(xh, _h, $h, !1, null, null, null));
wh.options.__file = "PageView.vue";
var Sh = wh.exports,
Oh = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.issue
? n("k-error-view", [t._v("\n " + t._s(t.issue.message) + "\n")])
: n(
"k-view",
{ key: "site-view", staticClass: "k-site-view" },
[
n(
"k-header",
{
attrs: {
tabs: t.tabs,
tab: t.tab,
editable: t.permissions.changeTitle
},
on: {
edit: function(e) {
t.action("rename");
}
}
},
[
t._v("\n " + t._s(t.site.title) + "\n "),
n(
"k-button-group",
{ attrs: { slot: "left" }, slot: "left" },
[
n(
"k-button",
{
attrs: { icon: "open" },
on: {
click: function(e) {
t.action("preview");
}
}
},
[t._v("\n " + t._s(t.$t("open")) + "\n ")]
),
n("k-languages-dropdown")
],
1
)
],
1
),
t.site.url
? n("k-tabs", {
ref: "tabs",
attrs: {
tabs: t.tabs,
blueprint: t.site.blueprint.name,
parent: "site"
},
on: {
tab: function(e) {
t.tab = e;
}
}
})
: t._e(),
n("k-site-rename-dialog", {
ref: "rename",
on: { success: t.fetch }
})
],
1
);
},
Ch = [],
Eh = {
data: function() {
return {
site: { title: null, url: null },
issue: null,
tab: null,
tabs: [],
options: null,
permissions: { changeTitle: !0 }
};
},
computed: {
language: function() {
return this.$store.state.languages.current;
}
},
watch: {
language: function() {
this.fetch();
}
},
created: function() {
this.fetch();
},
methods: {
fetch: function() {
var t = this;
this.$api.site
.get({ view: "panel" })
.then(function(e) {
(t.site = e),
(t.tabs = e.blueprint.tabs),
(t.permissions = e.options),
(t.options = function(e) {
t.$api.site.options().then(function(t) {
e(t);
});
}),
t.$store.dispatch("breadcrumb", []),
t.$store.dispatch("title", null),
t.$store.dispatch("form/create", {
id: "site",
api: "site",
content: e.content
});
})
.catch(function(e) {
t.issue = e;
});
},
action: function(t) {
switch (t) {
case "languages":
this.$refs.languages.open();
break;
case "preview":
window.open(this.site.url);
break;
case "rename":
this.$refs.rename.open();
break;
default:
this.$store.dispatch(
"notification/error",
this.$t("notification.notImplemented")
);
break;
}
}
}
},
jh = Eh,
Th = Object(m["a"])(jh, Oh, Ch, !1, null, null, null);
Th.options.__file = "SiteView.vue";
var Ih = Th.exports,
Lh = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.issue
? n("k-error-view", [t._v("\n " + t._s(t.issue.message) + "\n")])
: n(
"k-view",
{ staticClass: "k-users-view" },
[
n(
"k-header",
[
t._v("\n " + t._s(t.$t("view.users")) + "\n "),
n(
"k-button-group",
{ attrs: { slot: "left" }, slot: "left" },
[
n(
"k-button",
{
attrs: {
disabled: !1 === t.$permissions.users.create,
icon: "add"
},
on: {
click: function(e) {
t.$refs.create.open();
}
}
},
[t._v(t._s(t.$t("user.create")))]
)
],
1
),
n(
"k-button-group",
{ attrs: { slot: "right" }, slot: "right" },
[
n(
"k-dropdown",
[
n(
"k-button",
{
attrs: { responsive: !0, icon: "funnel" },
on: {
click: function(e) {
t.$refs.roles.toggle();
}
}
},
[
t._v(
"\n " +
t._s(t.$t("role")) +
": " +
t._s(
t.role ? t.role.text : t.$t("role.all")
) +
"\n "
)
]
),
n(
"k-dropdown-content",
{ ref: "roles", attrs: { align: "right" } },
[
n(
"k-dropdown-item",
{
attrs: { icon: "bolt" },
on: {
click: function(e) {
t.filter(!1);
}
}
},
[
t._v(
"\n " +
t._s(t.$t("role.all")) +
"\n "
)
]
),
n("hr"),
t._l(t.roles, function(e) {
return n(
"k-dropdown-item",
{
key: e.value,
attrs: { icon: "bolt" },
on: {
click: function(n) {
t.filter(e);
}
}
},
[
t._v(
"\n " +
t._s(e.text) +
"\n "
)
]
);
})
],
2
)
],
1
)
],
1
)
],
1
),
t.users.length > 0
? [
n("k-collection", {
attrs: { items: t.users, pagination: t.pagination },
on: { paginate: t.paginate, action: t.action }
})
]
: 0 === t.total
? [
n("k-empty", { attrs: { icon: "users" } }, [
t._v(t._s(t.$t("role.empty")))
])
]
: t._e(),
n("k-user-create-dialog", {
ref: "create",
on: { success: t.fetch }
}),
n("k-user-email-dialog", {
ref: "email",
on: { success: t.fetch }
}),
n("k-user-language-dialog", {
ref: "language",
on: { success: t.fetch }
}),
n("k-user-password-dialog", { ref: "password" }),
n("k-user-remove-dialog", {
ref: "remove",
on: { success: t.fetch }
}),
n("k-user-rename-dialog", {
ref: "rename",
on: { success: t.fetch }
}),
n("k-user-role-dialog", {
ref: "role",
on: { success: t.fetch }
})
],
2
);
},
Ah = [],
qh = {
data: function() {
return {
page: 1,
limit: 20,
total: null,
users: [],
roles: [],
issue: null
};
},
computed: {
pagination: function() {
return { page: this.page, limit: this.limit, total: this.total };
},
role: function() {
var t = this,
e = null;
return (
this.$route.params.role &&
this.roles.forEach(function(n) {
n.value === t.$route.params.role && (e = n);
}),
e
);
}
},
watch: {
$route: function() {
this.fetch();
}
},
created: function() {
var t = this;
this.$api.roles.options().then(function(e) {
(t.roles = e), t.fetch();
});
},
methods: {
fetch: function() {
var t = this;
this.$store.dispatch("title", this.$t("view.users"));
var e = { paginate: { page: this.page, limit: this.limit } };
this.role &&
(e.filterBy = [
{ field: "role", operator: "==", value: this.role.value }
]),
this.$api.users
.list(e)
.then(function(e) {
(t.users = e.data.map(function(e) {
var n = {
id: e.id,
icon: { type: "user", back: "black" },
text: e.name || e.email,
info: e.role.title,
link: "/users/" + e.id,
options: function(n) {
t.$api.users
.options(e.id, "list")
.then(function(t) {
return n(t);
})
.catch(function(e) {
t.$store.dispatch("notification/error", e);
});
},
image: null
};
return (
e.avatar && (n.image = { url: e.avatar.url, cover: !0 }),
n
);
})),
t.role
? t.$store.dispatch("breadcrumb", [
{
link: "/users/role/" + t.role.value,
label: t.$t("role") + ": " + t.role.text
}
])
: t.$store.dispatch("breadcrumb", []),
(t.total = e.pagination.total);
})
.catch(function(e) {
t.issue = e;
});
},
paginate: function(t) {
(this.page = t.page), (this.limit = t.limit), this.fetch();
},
action: function(t, e) {
switch (e) {
case "edit":
this.$router.push("/users/" + t.id);
break;
case "email":
this.$refs.email.open(t.id);
break;
case "role":
this.$refs.role.open(t.id);
break;
case "rename":
this.$refs.rename.open(t.id);
break;
case "password":
this.$refs.password.open(t.id);
break;
case "language":
this.$refs.language.open(t.id);
break;
case "remove":
this.$refs.remove.open(t.id);
break;
}
},
filter: function(t) {
!1 === t
? this.$router.push("/users")
: this.$router.push("/users/role/" + t.value),
this.$refs.roles.close();
}
}
},
Nh = qh,
Ph = Object(m["a"])(Nh, Lh, Ah, !1, null, null, null);
Ph.options.__file = "UsersView.vue";
var Bh = Ph.exports,
Dh = function() {
var t = this,
e = t.$createElement,
n = t._self._c || e;
return t.issue
? n("k-error-view", [t._v("\n " + t._s(t.issue.message) + "\n")])
: t.ready
? n(
"div",
{ staticClass: "k-user-view" },
[
n(
"div",
{ staticClass: "k-user-profile" },
[
n(
"k-view",
[
t.avatar
? [
n(
"k-dropdown",
[
n(
"k-button",
{
staticClass: "k-user-view-image",
attrs: { tooltip: t.$t("avatar") },
on: {
click: function(e) {
t.$refs.picture.toggle();
}
}
},
[
t.avatar
? n("k-image", {
attrs: {
cover: !0,
src: t.avatar,
ratio: "1/1"
}
})
: t._e()
],
1
),
n(
"k-dropdown-content",
{ ref: "picture" },
[
n(
"k-dropdown-item",
{
attrs: { icon: "upload" },
on: {
click: function(e) {
t.$refs.upload.open();
}
}
},
[
t._v(
"\n " +
t._s(t.$t("change")) +
"\n "
)
]
),
n(
"k-dropdown-item",
{
attrs: { icon: "trash" },
on: {
click: function(e) {
t.action("picture.delete");
}
}
},
[
t._v(
"\n " +
t._s(t.$t("delete")) +
"\n "
)
]
)
],
1
)
],
1
)
]
: [
n(
"k-button",
{
staticClass: "k-user-view-image",
attrs: { tooltip: t.$t("avatar") },
on: {
click: function(e) {
t.$refs.upload.open();
}
}
},
[n("k-icon", { attrs: { type: "user" } })],
1
)
],
n(
"k-button-group",
[
n(
"k-button",
{
attrs: {
disabled: !t.permissions.changeEmail,
icon: "email"
},
on: {
click: function(e) {
t.action("email");
}
}
},
[
t._v(
t._s(t.$t("email")) +
": " +
t._s(t.user.email)
)
]
),
n(
"k-button",
{
attrs: {
disabled: !t.permissions.changeRole,
icon: "bolt"
},
on: {
click: function(e) {
t.action("role");
}
}
},
[
t._v(
t._s(t.$t("role")) +
": " +
t._s(t.user.role.title)
)
]
),
n(
"k-button",
{
attrs: {
disabled: !t.permissions.changeLanguage,
icon: "globe"
},
on: {
click: function(e) {
t.action("language");
}
}
},
[
t._v(
t._s(t.$t("language")) +
": " +
t._s(t.user.language)
)
]
)
],
1
)
],
2
)
],
1
),
n(
"k-view",
[
n(
"k-header",
{
attrs: {
editable: t.permissions.changeName,
tabs: t.tabs,
tab: t.tab
},
on: {
edit: function(e) {
t.action("rename");
}
}
},
[
t.user.name && 0 !== t.user.name.length
? [t._v(t._s(t.user.name))]
: n(
"span",
{ staticClass: "k-user-name-placeholder" },
[t._v(t._s(t.$t("name")) + " …")]
),
n(
"k-button-group",
{ attrs: { slot: "left" }, slot: "left" },
[
n(
"k-dropdown",
[
n(
"k-button",
{
attrs: { icon: "cog" },
on: {
click: function(e) {
t.$refs.settings.toggle();
}
}
},
[
t._v(
"\n " +
t._s(t.$t("settings")) +
"\n "
)
]
),
n("k-dropdown-content", {
ref: "settings",
attrs: { options: t.options },
on: { action: t.action }
})
],
1
),
n("k-languages-dropdown")
],
1
),
t.user.id && "User" === t.$route.name
? n("k-prev-next", {
attrs: {
slot: "right",
prev: t.prev,
next: t.next
},
slot: "right"
})
: t._e()
],
2
),
t.user && t.tabs.length
? n("k-tabs", {
key:
"user-" +
t.user.id +
"-tabs-" +
new Date().getTime(),
ref: "tabs",
attrs: {
parent: "users/" + t.user.id,
blueprint: t.user.blueprint.name,
tabs: t.tabs
},
on: {
tab: function(e) {
t.tab = e;
}
}
})
: t.ready
? n("k-box", {
attrs: {
text: t.$t("user.blueprint", {
role: t.user.role.name
}),
theme: "info"
}
})
: t._e(),
n("k-user-email-dialog", {
ref: "email",
on: { success: t.fetch }
}),
n("k-user-language-dialog", {
ref: "language",
on: { success: t.fetch }
}),
n("k-user-password-dialog", { ref: "password" }),
n("k-user-remove-dialog", { ref: "remove" }),
n("k-user-rename-dialog", {
ref: "rename",
on: { success: t.fetch }
}),
n("k-user-role-dialog", {
ref: "role",
on: { success: t.fetch }
}),
n("k-upload", {
ref: "upload",
attrs: {
url: t.uploadApi,
multiple: !1,
accept: "image/*"
},
on: { success: t.uploadedAvatar }
})
],
1
)
],
1
)
: t._e();
},
Fh = [],
Rh = {
mixins: [Xd],
props: { id: { type: String, required: !0 } },
data: function() {
return {
tab: null,
tabs: [],
ready: !1,
user: {
role: { name: null },
name: null,
language: null,
prev: null,
next: null
},
permissions: {
changeEmail: !0,
changeName: !0,
changeLanguage: !0,
changeRole: !0
},
issue: null,
avatar: null,
options: null
};
},
computed: {
language: function() {
return this.$store.state.languages.current;
},
next: function() {
if (this.user.next)
return {
link: this.$api.users.link(this.user.next.id),
tooltip: this.user.next.name
};
},
prev: function() {
if (this.user.prev)
return {
link: this.$api.users.link(this.user.prev.id),
tooltip: this.user.prev.name
};
},
uploadApi: function() {
return f.api + "/users/" + this.user.id + "/avatar";
}
},
watch: {
language: function() {
this.fetch();
}
},
methods: {
action: function(t) {
var e = this;
switch (t) {
case "email":
this.$refs.email.open(this.user.id);
break;
case "language":
this.$refs.language.open(this.user.id);
break;
case "password":
this.$refs.password.open(this.user.id);
break;
case "picture.delete":
this.$api.users.deleteAvatar(this.id).then(function() {
e.$store.dispatch("notification/success", ":)"),
(e.avatar = null);
});
break;
case "remove":
this.$refs.remove.open(this.user.id);
break;
case "rename":
this.$refs.rename.open(this.user.id);
break;
case "role":
this.$refs.role.open(this.user.id);
break;
default:
this.$store.dispatch(
"notification/error",
"Not yet implemented"
);
}
},
fetch: function() {
var t = this;
this.$api.users
.get(this.id, { view: "panel" })
.then(function(e) {
(t.user = e),
(t.tabs = e.blueprint.tabs),
(t.ready = !0),
(t.permissions = e.options),
(t.options = function(e) {
t.$api.users.options(t.user.id).then(function(t) {
e(t);
});
}),
e.avatar ? (t.avatar = e.avatar.url) : (t.avatar = null),
"User" === t.$route.name
? t.$store.dispatch(
"breadcrumb",
t.$api.users.breadcrumb(e)
)
: t.$store.dispatch("breadcrumb", []),
t.$store.dispatch("title", t.user.name || t.user.email),
t.$store.dispatch("form/create", {
id: "users/" + e.id,
api: t.$api.users.link(e.id),
content: e.content
});
})
.catch(function(e) {
t.issue = e;
});
},
uploadedAvatar: function() {
this.$store.dispatch("notification/success", ":)"), this.fetch();
}
}
},
Mh = Rh,
zh = (n("bd96"), Object(m["a"])(Mh, Dh, Fh, !1, null, null, null));
zh.options.__file = "UserView.vue";
var Uh = zh.exports,
Vh = [
{ path: "/", name: "Home", redirect: "/site" },
{
path: "/browser",
name: "Browser",
component: zd,
meta: { outside: !0 }
},
{ path: "/login", component: kh, meta: { outside: !0 } },
{
path: "/logout",
beforeEnter: function() {
Yh.dispatch("user/logout");
},
meta: { outside: !0 }
},
{ path: "/installation", component: rh, meta: { outside: !0 } },
{
path: "/site",
name: "Site",
meta: { view: "site" },
component: Ih,
beforeEnter: Nd
},
{
path: "/site/files/:filename",
name: "SiteFile",
meta: { view: "site" },
component: eh,
beforeEnter: Nd,
props: function(t) {
return { path: "site", filename: t.params.filename };
}
},
{
path: "/pages/:path/files/:filename",
name: "PageFile",
meta: { view: "site" },
component: eh,
beforeEnter: Nd,
props: function(t) {
return {
path: "pages/" + t.params.path,
filename: t.params.filename
};
}
},
{
path: "/users/:path/files/:filename",
name: "UserFile",
meta: { view: "users" },
component: eh,
beforeEnter: Nd,
props: function(t) {
return {
path: "users/" + t.params.path,
filename: t.params.filename
};
}
},
{
path: "/pages/:path",
name: "Page",
meta: { view: "site" },
component: Sh,
beforeEnter: Nd,
props: function(t) {
return { path: t.params.path };
}
},
{
path: "/settings",
name: "Settings",
meta: { view: "settings" },
component: dh,
beforeEnter: Nd
},
{
path: "/users/role/:role",
name: "UsersByRole",
meta: { view: "users" },
component: Bh,
beforeEnter: Nd,
props: function(t) {
return { role: t.params.role };
}
},
{
path: "/users",
name: "Users",
meta: { view: "users" },
beforeEnter: Nd,
component: Bh
},
{
path: "/users/:id",
name: "User",
meta: { view: "users" },
component: Uh,
beforeEnter: Nd,
props: function(t) {
return { id: t.params.id };
}
},
{
path: "/account",
name: "Account",
meta: { view: "account" },
component: Uh,
beforeEnter: Nd,
props: function() {
return { id: Yh.state.user.current.id };
}
},
{
path: "/plugins/:id",
name: "Plugin",
meta: { view: "plugin" },
props: function(t) {
return { plugin: t.params.id };
},
beforeEnter: Nd,
component: Yd
},
{
path: "*",
name: "NotFound",
beforeEnter: function(t, e, n) {
n("/");
}
}
];
i["a"].use(qd["a"]);
var Hh = new qd["a"]({
mode: "history",
routes: Vh,
url: "/" === f.url ? "" : f.url
});
Hh.beforeEach(function(t, e, n) {
"Browser" !== t.name && !1 === Dd.all() && n("/browser"),
Yh.dispatch("view", t.meta.view),
t.meta.outside || Yh.dispatch("user/visit", t.path),
n();
});
var Kh = Hh,
Gh = {
namespaced: !0,
state: { current: null, path: null },
mutations: {
SET_CURRENT: function(t, e) {
(t.current = e),
e && e.permissions
? ((i["a"].prototype.$user = e),
(i["a"].prototype.$permissions = e.permissions))
: ((i["a"].prototype.$user = null),
(i["a"].prototype.$permissions = null));
},
SET_PATH: function(t, e) {
t.path = e;
}
},
actions: {
current: function(t, e) {
t.commit("SET_CURRENT", e);
},
language: function(t, e) {
t.dispatch("translation/activate", e, { root: !0 }),
t.commit(
"SET_CURRENT",
Object(u["a"])({ language: e }, t.state.current)
);
},
load: function(t) {
return em.auth.user().then(function(e) {
return t.commit("SET_CURRENT", e), e;
});
},
login: function(t, e) {
return em.auth.login(e).then(function(e) {
return (
t.commit("SET_CURRENT", e),
t.dispatch("translation/activate", e.language, { root: !0 }),
Kh.push(t.state.path || "/"),
e
);
});
},
logout: function(t) {
em.auth
.logout()
.then(function() {
t.commit("SET_CURRENT", null), Kh.push("/login");
})
.catch(function() {
t.commit("SET_CURRENT", null), Kh.push("/login");
});
},
visit: function(t, e) {
t.commit("SET_PATH", e);
}
}
};
i["a"].use(Cd["a"]);
var Yh = new Cd["a"].Store({
strict: !1,
state: {
breadcrumb: [],
dialog: null,
drag: null,
isLoading: !1,
search: !1,
title: null,
view: null
},
mutations: {
SET_BREADCRUMB: function(t, e) {
t.breadcrumb = e;
},
SET_DIALOG: function(t, e) {
t.dialog = e;
},
SET_DRAG: function(t, e) {
t.drag = e;
},
SET_SEARCH: function(t, e) {
!0 === e && (e = {}), (t.search = e);
},
SET_TITLE: function(t, e) {
t.title = e;
},
SET_VIEW: function(t, e) {
t.view = e;
},
START_LOADING: function(t) {
t.isLoading = !0;
},
STOP_LOADING: function(t) {
t.isLoading = !1;
}
},
actions: {
breadcrumb: function(t, e) {
t.commit("SET_BREADCRUMB", e);
},
dialog: function(t, e) {
t.commit("SET_DIALOG", e);
},
drag: function(t, e) {
t.commit("SET_DRAG", e);
},
isLoading: function(t, e) {
t.commit(!0 === e ? "START_LOADING" : "STOP_LOADING");
},
search: function(t, e) {
t.commit("SET_SEARCH", e);
},
title: function(t, e) {
t.commit("SET_TITLE", e),
(document.title = e || ""),
t.state.system.info.title &&
(document.title +=
null !== e
? " | " + t.state.system.info.title
: t.state.system.info.title);
},
view: function(t, e) {
t.commit("SET_VIEW", e);
}
},
modules: {
form: jd,
languages: Td,
notification: Id,
system: Ld,
translation: Ad,
user: Gh
}
}),
Wh = {
running: 0,
request: function(t, e) {
var n = this;
return (
(e = Object.assign(e || {}, {
credentials: "same-origin",
headers: Object(u["a"])(
{
"x-requested-with": "xmlhttprequest",
"content-type": "application/json"
},
e.headers
)
})),
Yh.state.languages.current &&
(e.headers["x-language"] = Yh.state.languages.current.code),
(e.headers["x-csrf"] = window.panel.csrf),
em.config.onStart(),
this.running++,
fetch(em.config.endpoint + "/" + t, e)
.then(function(t) {
return t.json();
})
.then(function(t) {
if (t.status && "error" === t.status) throw t;
var e = t;
return (
t.data && t.type && "model" === t.type && (e = t.data),
n.running--,
em.config.onComplete(),
em.config.onSuccess(t),
e
);
})
.catch(function(t) {
throw (n.running--,
em.config.onComplete(),
em.config.onError(t),
t);
})
);
},
get: function(t, e, n) {
return (
e &&
(t +=
"?" +
Object.keys(e)
.map(function(t) {
return t + "=" + e[t];
})
.join("&")),
this.request(t, Object.assign(n || {}, { method: "GET" }))
);
},
post: function(t, e, n) {
var i =
arguments.length > 3 && void 0 !== arguments[3]
? arguments[3]
: "POST";
return this.request(
t,
Object.assign(n || {}, { method: i, body: JSON.stringify(e) })
);
},
patch: function(t, e, n) {
return this.post(t, e, n, "PATCH");
},
delete: function(t, e, n) {
return this.post(t, e, n, "DELETE");
}
},
Jh = {
list: function() {
return em.get("roles");
},
get: function(t) {
return em.get("roles/" + t);
},
options: function() {
return this.list().then(function(t) {
return t.data.map(function(t) {
return {
info:
t.description ||
"(".concat(
i["a"].i18n.translate("role.description.placeholder"),
")"
),
text: t.title,
value: t.name
};
});
});
}
},
Xh = {
info: function(t) {
return em.get("system", t);
},
install: function(t) {
return em.post("system/install", t).then(function(t) {
return t.user;
});
},
register: function(t) {
return em.post("system/register", t);
}
},
Qh = {
get: function(t) {
return em.get("site", t);
},
update: function(t) {
return em.post("site", t);
},
title: function(t) {
return em.patch("site/title", { title: t });
},
options: function() {
return em.get("site", { select: "options" }).then(function(t) {
var e = t.options,
n = [];
return (
n.push({
click: "rename",
icon: "title",
text: i["a"].i18n.translate("rename"),
disabled: !e.changeTitle
}),
n
);
});
},
children: function(t) {
return em.post("site/children/search", t);
},
blueprint: function() {
return em.get("site/blueprint");
},
blueprints: function() {
return em.get("site/blueprints");
}
},
Zh = {
list: function() {
return em.get("translations");
},
get: function(t) {
return em.get("translations/" + t);
},
options: function() {
var t = [];
return this.list().then(function(e) {
return (
(t = e.data.map(function(t) {
return { value: t.id, text: t.name };
})),
t
);
});
}
},
tm = {
create: function(t) {
return em.post(this.url(), t);
},
list: function(t) {
return em.post(this.url(null, "search"), t);
},
get: function(t, e) {
return em.get(this.url(t), e);
},
update: function(t, e) {
return em.patch(this.url(t), e);
},
delete: function(t) {
return em.delete(this.url(t));
},
changeEmail: function(t, e) {
return em.patch(this.url(t, "email"), { email: e });
},
changeLanguage: function(t, e) {
return em.patch(this.url(t, "language"), { language: e });
},
changeName: function(t, e) {
return em.patch(this.url(t, "name"), { name: e });
},
changePassword: function(t, e) {
return em.patch(this.url(t, "password"), { password: e });
},
changeRole: function(t, e) {
return em.patch(this.url(t, "role"), { role: e });
},
deleteAvatar: function(t) {
return em.delete(this.url(t, "avatar"));
},
blueprint: function(t) {
return em.get(this.url(t, "blueprint"));
},
breadcrumb: function(t) {
return [{ link: "/users/" + t.id, label: t.username }];
},
options: function(t) {
return em.get(this.url(t), { select: "options" }).then(function(t) {
var e = t.options,
n = [];
return (
n.push({
click: "rename",
icon: "title",
text: i["a"].i18n.translate("user.changeName"),
disabled: !e.changeName
}),
n.push({
click: "email",
icon: "email",
text: i["a"].i18n.translate("user.changeEmail"),
disabled: !e.changeEmail
}),
n.push({
click: "role",
icon: "bolt",
text: i["a"].i18n.translate("user.changeRole"),
disabled: !e.changeRole
}),
n.push({
click: "password",
icon: "key",
text: i["a"].i18n.translate("user.changePassword"),
disabled: !e.changePassword
}),
n.push({
click: "language",
icon: "globe",
text: i["a"].i18n.translate("user.changeLanguage"),
disabled: !e.changeLanguage
}),
n.push({
click: "remove",
icon: "trash",
text: i["a"].i18n.translate("user.delete"),
disabled: !e.delete
}),
n
);
});
},
url: function(t, e) {
var n = t ? "users/" + t : "users";
return e && (n += "/" + e), n;
},
link: function(t, e) {
return "/" + this.url(t, e);
}
},
em = Object(u["a"])(
{
config: {
onStart: function() {},
onComplete: function() {},
onSuccess: function() {},
onError: function(t) {
throw (window.console.log(t.message), t);
}
},
auth: wd,
files: Sd,
pages: Od,
roles: Jh,
system: Xh,
site: Qh,
translations: Zh,
users: tm
},
Wh
);
(em.config.endpoint = f.api),
(em.config.onStart = function() {
Yh.dispatch("isLoading", !0);
}),
(em.config.onComplete = function() {
Yh.dispatch("isLoading", !1);
}),
(em.config.onError = function(t) {
f.debug && window.console.error(t),
"Unauthenticated" === t.message && Yh.dispatch("user/logout");
});
var nm = setInterval(em.auth.user, 3e5);
(em.config.onSuccess = function() {
clearInterval(nm), (nm = setInterval(em.auth.user, 3e5));
}),
(i["a"].prototype.$api = em),
(i["a"].config.errorHandler = function(t) {
f.debug && window.console.error(t),
Yh.dispatch("notification/error", {
message: t.message || "An error occurred. Please reload the panel"
});
}),
(window.panel = window.panel || {}),
(window.panel.error = function(t, e) {
f.debug && window.console.error(t + ": " + e),
Yh.dispatch("error", t + ". See the console for more information.");
});
var im = n("f2f3");
i["a"].use(im["a"].plugin, Yh);
n("ffc1");
var sm = {};
for (var am in i["a"].options.components)
sm[am] = i["a"].options.components[am];
var om = function(t, e) {
e.template || e.render || e.extends
? (e.extends &&
"string" === typeof e.extends &&
((e.extends = sm[e.extends]), e.template && (e.render = null)),
e.mixins &&
(e.mixins = e.mixins.map(function(t) {
return "string" === typeof t ? sm[t] : t;
})),
sm[t] && window.console.warn('Plugin is replacing "'.concat(t, '"')),
i["a"].component(t, e))
: Yh.dispatch(
"notification/error",
'Neither template or render method provided nor extending a component when loading plugin component "'.concat(
t,
'". The component has not been registered.'
)
);
};
Object.entries(window.panel.plugins.components).forEach(function(t) {
var e = Object(Ed["a"])(t, 2),
n = e[0],
i = e[1];
om(n, i);
}),
Object.entries(window.panel.plugins.fields).forEach(function(t) {
var e = Object(Ed["a"])(t, 2),
n = e[0],
i = e[1];
om(n, i);
}),
Object.entries(window.panel.plugins.sections).forEach(function(t) {
var e = Object(Ed["a"])(t, 2),
n = e[0],
i = e[1];
om(n, Object(u["a"])({}, i, { mixins: [Wf].concat(i.mixins || []) }));
}),
Object.entries(window.panel.plugins.views).forEach(function(t) {
var e = Object(Ed["a"])(t, 2),
n = e[0],
s = e[1];
if (!s.component)
return (
Yh.dispatch(
"notification/error",
'No view component provided when loading view "'.concat(
n,
'". The view has not been registered.'
)
),
void delete window.panel.plugins.views[n]
);
(s.link = "/plugins/" + n),
void 0 === s.icon && (s.icon = "page"),
void 0 === s.menu && (s.menu = !0),
(window.panel.plugins.views[n] = {
link: s.link,
icon: s.icon,
menu: s.menu
}),
i["a"].component("k-" + n + "-plugin-view", s.component);
}),
window.panel.plugins.use.forEach(function(t) {
i["a"].use(t);
}),
(i["a"].config.productionTip = !1),
(i["a"].config.devtools = !0),
(window.panel.app = new i["a"]({
router: Kh,
store: Yh,
render: function(t) {
return t(E);
}
}).$mount("#app"));
},
5714: function(t, e, n) {},
"58e5": function(t, e, n) {},
"5c0b": function(t, e, n) {
"use strict";
var i = n("5e27"),
s = n.n(i);
s.a;
},
"5e27": function(t, e, n) {},
"5e3a": function(t, e, n) {
"use strict";
var i = n("7bb1"),
s = n.n(i);
s.a;
},
"5f4f": function(t, e, n) {},
"5f5b": function(t, e, n) {
"use strict";
var i = n("8915"),
s = n.n(i);
s.a;
},
6022: function(t, e, n) {
"use strict";
var i = n("b31f"),
s = n.n(i);
s.a;
},
"622c": function(t, e, n) {},
"64e6": function(t, e, n) {},
"68b5": function(t, e, n) {
"use strict";
var i = n("d2f5"),
s = n.n(i);
s.a;
},
6937: function(t, e, n) {},
"696b": function(t, e, n) {
"use strict";
var i = n("0cdc"),
s = n.n(i);
s.a;
},
"6a0a": function(t, e, n) {
"use strict";
var i = n("5439"),
s = n.n(i);
s.a;
},
"6ab9": function(t, e, n) {},
"6af3": function(t, e, n) {},
"6b18": function(t, e, n) {},
"6b7f": function(t, e, n) {},
"6b96": function(t, e, n) {},
"6bcd": function(t, e, n) {
"use strict";
var i = n("9e0a"),
s = n.n(i);
s.a;
},
"6d8c": function(t, e, n) {},
7027: function(t, e, n) {
"use strict";
var i = n("cd7a"),
s = n.n(i);
s.a;
},
7075: function(t, e, n) {},
7428: function(t, e, n) {},
7568: function(t, e, n) {
"use strict";
var i = n("4150"),
s = n.n(i);
s.a;
},
"75ae": function(t, e, n) {},
7737: function(t, e, n) {
"use strict";
var i = n("ca19"),
s = n.n(i);
s.a;
},
"77f7": function(t, e, n) {
"use strict";
var i = n("200b"),
s = n.n(i);
s.a;
},
"791b": function(t, e, n) {
"use strict";
var i = n("ea0f"),
s = n.n(i);
s.a;
},
"7bb1": function(t, e, n) {},
"7d5d": function(t, e, n) {
"use strict";
var i = n("6ab9"),
s = n.n(i);
s.a;
},
"813c": function(t, e, n) {
"use strict";
var i = n("c664"),
s = n.n(i);
s.a;
},
8633: function(t, e, n) {
"use strict";
var i = n("3755"),
s = n.n(i);
s.a;
},
8915: function(t, e, n) {},
"891e": function(t, e, n) {},
"8ae6": function(t, e, n) {},
"8b1d": function(t, e, n) {},
"8be2": function(t, e, n) {
"use strict";
var i = n("e0b0"),
s = n.n(i);
s.a;
},
"8e2d": function(t, e, n) {
"use strict";
var i = n("6d8c"),
s = n.n(i);
s.a;
},
"988f": function(t, e, n) {
"use strict";
var i = n("ea9f"),
s = n.n(i);
s.a;
},
"9adb": function(t, e, n) {},
"9ae6": function(t, e, n) {},
"9bd5": function(t, e, n) {
"use strict";
var i = n("64e6"),
s = n.n(i);
s.a;
},
"9df9": function(t, e, n) {},
"9e0a": function(t, e, n) {},
"9ee7": function(t, e, n) {},
a2a8: function(t, e, n) {
"use strict";
var i = n("6937"),
s = n.n(i);
s.a;
},
a319: function(t, e, n) {},
a361: function(t, e, n) {
"use strict";
var i = n("9adb"),
s = n.n(i);
s.a;
},
a89c: function(t, e, n) {
"use strict";
var i = n("acc9"),
s = n.n(i);
s.a;
},
ac27: function(t, e, n) {
"use strict";
var i = n("3c9d"),
s = n.n(i);
s.a;
},
acc9: function(t, e, n) {},
b2d3: function(t, e, n) {},
b31f: function(t, e, n) {},
b42a: function(t, e, n) {
"use strict";
var i = n("a319"),
s = n.n(i);
s.a;
},
b61e: function(t, e, n) {
"use strict";
var i = n("d268"),
s = n.n(i);
s.a;
},
b83b: function(t, e, n) {
"use strict";
var i = n("9df9"),
s = n.n(i);
s.a;
},
b8aa: function(t, e, n) {},
b8aa9: function(t, e, n) {
"use strict";
var i = n("c9df"),
s = n.n(i);
s.a;
},
bbbf: function(t, e, n) {},
bd46: function(t, e, n) {
"use strict";
var i = n("f01a"),
s = n.n(i);
s.a;
},
bd6e: function(t, e, n) {
"use strict";
var i = n("3218"),
s = n.n(i);
s.a;
},
bd96: function(t, e, n) {
"use strict";
var i = n("d6a4"),
s = n.n(i);
s.a;
},
bf53: function(t, e, n) {
"use strict";
var i = n("3c80"),
s = n.n(i);
s.a;
},
c245: function(t, e, n) {},
c664: function(t, e, n) {},
c9df: function(t, e, n) {},
ca19: function(t, e, n) {},
ca3a: function(t, e, n) {},
cd7a: function(t, e, n) {},
d11d: function(t, e, n) {
"use strict";
var i = n("0812"),
s = n.n(i);
s.a;
},
d221: function(t, e, n) {
"use strict";
var i = n("6b7f"),
s = n.n(i);
s.a;
},
d268: function(t, e, n) {},
d2f5: function(t, e, n) {},
d4da: function(t, e, n) {},
d6a4: function(t, e, n) {},
d6f2: function(t, e, n) {},
d6fc: function(t, e, n) {
"use strict";
var i = n("08ec"),
s = n.n(i);
s.a;
},
dccd: function(t, e, n) {},
dd48: function(t, e, n) {},
dea4: function(t, e, n) {
"use strict";
var i = n("dd48"),
s = n.n(i);
s.a;
},
df30: function(t, e, n) {
"use strict";
var i = n("28f4"),
s = n.n(i);
s.a;
},
e0b0: function(t, e, n) {},
e104: function(t, e, n) {
"use strict";
var i = n("6b18"),
s = n.n(i);
s.a;
},
e697: function(t, e, n) {},
ea0f: function(t, e, n) {},
ea9f: function(t, e, n) {},
eabd: function(t, e, n) {
"use strict";
var i = n("b2d3"),
s = n.n(i);
s.a;
},
ec72: function(t, e, n) {},
f01a: function(t, e, n) {},
f093: function(t, e, n) {
"use strict";
var i = n("2114"),
s = n.n(i);
s.a;
},
f09b: function(t, e, n) {},
f32d: function(t, e, n) {
"use strict";
var i = n("d4da"),
s = n.n(i);
s.a;
},
f5e3: function(t, e, n) {},
f986: function(t, e, n) {
"use strict";
var i = n("3610"),
s = n.n(i);
s.a;
},
fa25: function(t, e, n) {
"use strict";
var i = n("c245"),
s = n.n(i);
s.a;
},
fa44: function(t, e, n) {
"use strict";
var i = n("622c"),
s = n.n(i);
s.a;
},
fbb8: function(t, e, n) {
"use strict";
var i = n("f09b"),
s = n.n(i);
s.a;
},
fff9: function(t, e, n) {}
});
<file_sep><?php
namespace Kirby\Exception;
class NotFoundExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testDefaults()
{
$exception = new NotFoundException();
$this->assertEquals('error.notFound', $exception->getKey());
$this->assertEquals('Not found', $exception->getMessage());
$this->assertEquals(404, $exception->getHttpCode());
}
}
<file_sep><?php
namespace Kirby\Cms;
class TranslationsTest extends TestCase
{
public function testFactory()
{
$translations = Translations::factory([
'de' => [
'translation.name' => 'Deutsch'
],
'en' => [
'translation.name' => 'English'
]
]);
$this->assertCount(2, $translations);
$this->assertTrue($translations->has('de'));
$this->assertTrue($translations->has('en'));
}
public function testLoad()
{
$translations = Translations::load(__DIR__ . '/fixtures/translations');
$this->assertCount(2, $translations);
$this->assertTrue($translations->has('de'));
$this->assertTrue($translations->has('en'));
}
}
<file_sep><?php
namespace Kirby\Cms;
class AppRolesTest extends TestCase
{
public function testSet()
{
$app = new App([
'roles' => [
[
'name' => 'editor',
'title' => 'Editor'
]
]
]);
$this->assertCount(2, $app->roles());
$this->assertEquals('editor', $app->roles()->last()->name());
}
public function testLoad()
{
$app = new App([
'roots' => [
'site' => __DIR__ . '/fixtures'
]
]);
$this->assertCount(2, $app->roles());
$this->assertEquals('editor', $app->roles()->last()->name());
}
}
<file_sep><?php
namespace Kirby\Toolkit;
class QueryTestUser
{
public function username()
{
return 'homer';
}
public function profiles()
{
return [
'twitter' => '@homer'
];
}
public function says(...$message)
{
return implode(' ', $message);
}
public function age(int $years)
{
return $years;
}
public function isYello(bool $answer)
{
return $answer;
}
public function brainDump($dump)
{
return $dump;
}
}
<file_sep><?php
namespace Kirby\Cms;
class TranslationTest extends TestCase
{
public function testProps()
{
$translation = new Translation('de', [
'translation.author' => 'Kirby',
'translation.name' => 'English',
'translation.direction' => 'ltr',
'test' => 'Test'
]);
$this->assertEquals('Kirby', $translation->author());
$this->assertEquals('English', $translation->name());
$this->assertEquals('ltr', $translation->direction());
$this->assertEquals('Test', $translation->get('test'));
}
public function testLoad()
{
$translation = Translation::load('de', __DIR__ . '/fixtures/translations/de.json');
$this->assertEquals('de', $translation->code());
$this->assertEquals('Deutsch', $translation->name());
}
}
<file_sep><?php
namespace Kirby\Cms;
class FilenameTest extends TestCase
{
public function testAttributesToArray()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
'width' => 300,
'height' => 200,
'crop' => 'top left',
'grayscale' => true,
'blur' => 10,
'quality' => 90
]);
$expected = [
'dimensions' => '300x200',
'crop' => 'top-left',
'blur' => 10,
'bw' => true,
'q' => 90
];
$this->assertEquals($expected, $filename->attributesToArray());
}
public function attributesToStringProvider()
{
return [
[
'-300x200-crop-top-left-blur10-bw-q90',
[
'width' => 300,
'height' => 200,
'crop' => 'top left',
'grayscale' => true,
'blur' => 10,
'quality' => 90
]
],
[
'-300x200',
[
'width' => 300,
'height' => 200,
]
],
[
'-x200',
[
'height' => 200,
]
],
[
'',
[
'crop' => 'center',
]
],
];
}
/**
* @dataProvider attributesToStringProvider
*/
public function testAttributesToString($expected, $options)
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', $options);
$this->assertEquals($expected, $filename->attributesToString('-'));
}
public function blurOptionProvider()
{
return [
[false, false],
[true, 1],
[90, 90],
[90.0, 90],
['90', 90],
];
}
/**
* @dataProvider blurOptionProvider
*/
public function testBlur($value, $expected)
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
'blur' => $value
]);
$this->assertEquals($expected, $filename->blur());
}
public function cropAnchorProvider(): array
{
return [
['center', 'center'],
['top', 'top'],
['bottom', 'bottom'],
['left', 'left'],
['right', 'right'],
['top left', 'top-left'],
['top right', 'top-right'],
['bottom left', 'bottom-left'],
['bottom right', 'bottom-right'],
];
}
/**
* @dataProvider cropAnchorProvider
*/
public function testCrop($anchor, $expected)
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
'crop' => $anchor
]);
$this->assertEquals($expected, $filename->crop());
}
public function testEmptyCrop()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}');
$this->assertFalse($filename->crop());
}
public function testDisabledCrop()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
'crop' => false
]);
$this->assertFalse($filename->crop());
}
public function testCustomCrop()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
'crop' => 'something'
]);
$this->assertEquals('something', $filename->crop());
}
public function testDimensions()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', $dimensions = [
'width' => 300,
'height' => 200
]);
$this->assertEquals($dimensions, $filename->dimensions());
}
public function testEmptyDimensions()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}');
$this->assertEquals([], $filename->dimensions());
}
public function testDimensionsWithoutWidth()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
'height' => 300
]);
$this->assertEquals([
'width' => null,
'height' => 300
], $filename->dimensions());
}
public function testDimensionsWithoutHeight()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
'width' => 300
]);
$this->assertEquals([
'width' => 300,
'height' => null
], $filename->dimensions());
}
public function testExtension()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}');
$this->assertEquals('jpg', $filename->extension());
}
public function testUppercaseExtension()
{
$filename = new Filename('/test/some-file.JPG', '{{ name }}.{{ extension }}');
$this->assertEquals('jpg', $filename->extension());
}
public function testJpegExtension()
{
$filename = new Filename('/test/some-file.jpeg', '{{ name }}.{{ extension }}');
$this->assertEquals('jpg', $filename->extension());
}
public function grayscaleOptionProvider()
{
return [
['grayscale', true, true],
['grayscale', false, false],
['greyscale', true, true],
['greyscale', false, false],
['bw', true, true],
['bw', false, false],
];
}
/**
* @dataProvider grayscaleOptionProvider
*/
public function testGrayscale($prop, $value, $expected)
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}', [
$prop => $value
]);
$this->assertEquals($expected, $filename->grayscale());
}
public function testName()
{
$filename = new Filename('/var/www/some-file.jpg', '{{ name }}.{{ extension }}');
$this->assertEquals('some-file', $filename->name());
}
public function testNameSanitization()
{
$filename = new Filename('/var/www/söme file.jpg', '{{ name }}.{{ extension }}');
$this->assertEquals('some-file', $filename->name());
}
public function qualityOptionProvider()
{
return [
[false, false],
[true, false],
[90, 90],
[90.0, 90],
['90', 90],
];
}
/**
* @dataProvider qualityOptionProvider
*/
public function testQuality($value, $expected)
{
$filename = new Filename('/test/some-file.jpg', 'some-file.jpg', [
'quality' => $value
]);
$this->assertEquals($expected, $filename->quality());
}
/**
* @dataProvider attributesToStringProvider
*/
public function testToString($expected, $attributes)
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}{{ attributes }}.{{ extension }}', $attributes);
$this->assertEquals('some-file' . $expected . '.jpg', $filename->toString());
$this->assertEquals('some-file' . $expected . '.jpg', (string)$filename);
}
public function testToStringWithFalsyAttributes()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}{{ attributes }}.{{ extension }}', [
'width' => false,
'height' => false,
'crop' => false,
'blur' => false,
'grayscale' => false,
'quality' => false
]);
$this->assertEquals('some-file.jpg', $filename->toString());
$this->assertEquals('some-file.jpg', (string)$filename);
}
public function testToStringWithoutAttributes()
{
$filename = new Filename('/test/some-file.jpg', '{{ name }}.{{ extension }}');
$this->assertEquals('some-file.jpg', $filename->toString());
$this->assertEquals('some-file.jpg', (string)$filename);
}
}
<file_sep><?php
namespace Kirby\Cms;
use ReflectionClass;
class CollectionTestCase extends TestCase
{
public $collection = null;
public $collectionType = null;
public function collection($name = null)
{
return $this->kirby()->collection($name ?? $this->collection);
}
public function collectionRoot(): string
{
return $this->kirby()->root('collections') . '/' . $this->collectionName() . '.php';
}
public function collectionName(): string
{
if ($this->collection !== null) {
return $this->collection;
}
$reflect = new ReflectionClass($this);
$className = $reflect->getShortName();
return strtolower(str_replace('CollectionTest', '', $className));
}
public function collectionPagination()
{
return $this->collection()->pagination();
}
public function assertCollectionCount(int $count)
{
return $this->assertCount($count, $this->collection());
}
public function assertCollectionHasPagination()
{
return $this->assertInstanceOf(Pagination::class, $this->collectionPagination());
}
public function assertCollectionHasNoPagination()
{
return $this->assertNotInstanceOf(Pagination::class, $this->collectionPagination());
}
public function testCollectionType()
{
if ($this->collectionType === null) {
$this->markTestSkipped();
}
$this->assertInstanceOf($this->collectionType, $this->collection());
}
}
<file_sep><?php
namespace Kirby\Cms;
class PageChildrenTest extends TestCase
{
public function testDefaultChildren()
{
$page = new Page(['slug' => 'test']);
$this->assertInstanceOf(Pages::class, $page->children());
$this->assertCount(0, $page->children());
}
public function testHasChildren()
{
$page = new Page([
'slug' => 'test',
'children' => [
['slug' => 'a'],
['slug' => 'b']
]
]);
$this->assertTrue($page->hasChildren());
}
public function testHasNoChildren()
{
$page = new Page([
'slug' => 'test',
'children' => []
]);
$this->assertFalse($page->hasChildren());
}
}
<file_sep><?php
namespace Kirby\Email;
class TestCase extends \PHPUnit\Framework\TestCase
{
protected function _email($props = [], $mailer) {
return new $mailer(array_merge([
'from' => '<EMAIL>',
'to' => '<EMAIL>',
'subject' => 'Thank you for your contact request',
'body' => 'We will never reply'
], $props), true);
}
}
<file_sep><?php
namespace Kirby\Cms;
use Kirby\Http\Uri;
class PermissionsTest extends TestCase
{
public function actions()
{
return [
['files', 'changeName'],
['files', 'create'],
['files', 'delete'],
['files', 'replace'],
['files', 'update'],
['pages', 'changeSlug'],
['pages', 'changeStatus'],
['pages', 'changeTemplate'],
['pages', 'changeTitle'],
['pages', 'create'],
['pages', 'delete'],
['pages', 'sort'],
['pages', 'update'],
['site', 'changeTitle'],
['site', 'update'],
['users', 'changeEmail'],
['users', 'changeLanguage'],
['users', 'changeName'],
['users', 'changePassword'],
['users', 'changeRole'],
['users', 'create'],
['users', 'delete'],
['users', 'update'],
['user', 'changeEmail'],
['user', 'changeLanguage'],
['user', 'changeName'],
['user', 'changePassword'],
['user', 'changeRole'],
['user', 'delete'],
['user', 'update'],
];
}
/**
* @dataProvider actions
*/
public function testActions(string $category, $action)
{
// default
$p = new Permissions();
$this->assertTrue($p->for($category, $action));
// globally disabled
$p = new Permissions([$category => false]);
$this->assertFalse($p->for($category, $action));
// monster off switch
$p = new Permissions(false);
$this->assertFalse($p->for($category, $action));
// monster on switch
$p = new Permissions(true);
$this->assertTrue($p->for($category, $action));
// locally disabled
$p = new Permissions([
$category => [
$action => false
]
]);
$this->assertFalse($p->for($category, $action));
// locally enabled
$p = new Permissions([
$category => [
$action => true
]
]);
$this->assertTrue($p->for($category, $action));
}
}
<file_sep><?php
namespace Kirby\Cms;
class MyModel extends Model {
public function __construct(array $props = [])
{
$this->setProperties($props);
}
}
class ModelTest extends TestCase
{
public function testModel()
{
$model = new MyModel();
$this->assertInstanceOf(Model::class, $model);
$this->assertInstanceOf(App::class, $model->kirby());
$this->assertInstanceOf(Site::class, $model->site());
}
public function testKirby()
{
$kirby = new App();
$model = new MyModel([
'kirby' => $kirby
]);
$this->assertEquals($kirby, $model->kirby());
}
public function testSite()
{
$site = new Site();
$model = new MyModel([
'site' => $site
]);
$this->assertEquals($site, $model->site());
}
}
<file_sep><?php
namespace Kirby\Cms;
class PageContentTest extends TestCase
{
public function testDefaultContent()
{
$page = new Page(['slug' => 'test']);
$this->assertInstanceOf(Content::class, $page->content());
}
public function testContent()
{
$page = new Page([
'slug' => 'test',
'content' => $content = ['text' => 'lorem ipsum']
]);
$this->assertEquals($content, $page->content()->toArray());
$this->assertEquals('lorem ipsum', $page->text()->value());
}
/**
* @expectedException TypeError
*/
public function testInvalidContent()
{
$page = new Page([
'slug' => 'test',
'content' => 'content'
]);
}
public function testEmptyTitle()
{
$page = new Page([
'slug' => 'test',
'content' => []
]);
$this->assertEquals($page->slug(), $page->title()->value());
}
public function testTitle()
{
$page = new Page([
'slug' => 'test',
'content' => [
'title' => 'Custom Title'
]
]);
$this->assertEquals('Custom Title', $page->title()->value());
}
}
<file_sep><?php
class RegularPage extends Page {}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
class TelFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('tel');
$this->assertEquals('tel', $field->type());
$this->assertEquals('tel', $field->name());
$this->assertEquals(null, $field->value());
$this->assertEquals('phone', $field->icon());
$this->assertEquals(null, $field->placeholder());
$this->assertEquals(null, $field->counter());
$this->assertEquals('tel', $field->autocomplete());
$this->assertTrue($field->save());
}
}
<file_sep><?php
namespace Kirby\Session;
use Exception;
use Kirby\Toolkit\Str;
class InvalidSessionStore
{
}
class TestSessionStore extends SessionStore
{
public $validKey = '74686973206973207468652076616c6964206b657920696e2068657821203a29';
public $invalidKey = '616e64207965702c2074686174277320616e2065617374657220656767e280a6';
public $sessions = [];
public $hmacs = [];
public $isLocked = [];
public $collectedGarbage = false;
public function __construct()
{
$time = time();
// set test sessions
$this->sessions = [
// expired session
'1000000000.expired' => [
'startTime' => 0,
'expiryTime' => 1000000000,
'duration' => 1000000000,
'timeout' => false,
'lastActivity' => null,
'renewable' => false,
'data' => [
'id' => 'expired'
]
],
// valid session that needs to be renewed
'3000000000.renewal' => [
'startTime' => 0,
'expiryTime' => 3000000000,
'duration' => 3000000000,
'timeout' => false,
'lastActivity' => null,
'renewable' => true,
'data' => [
'id' => 'renewal'
]
],
// valid session that needs to be renewed, but can't
'3000000000.nonRenewable' => [
'startTime' => 0,
'expiryTime' => 3000000000,
'duration' => 3000000000,
'timeout' => false,
'lastActivity' => null,
'renewable' => false,
'data' => [
'id' => 'nonRenewable'
]
],
// invalid data structure
'9999999999.invalidSerialization' => 'invalid-serialization',
// invalid storage structure
'9999999999.invalidStructure' => 'invalid-structure',
// valid session that has moved
'9999999999.moved' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'newSession' => '9999999999.valid'
],
// session that has moved but is expired
'1000000000.movedExpired' => [
'startTime' => 0,
'expiryTime' => 1000000000,
'newSession' => '9999999999.valid'
],
// session that has moved and the new session doesn't exist
'9999999999.movedInvalid' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'newSession' => '9999999999.doesNotExist'
],
// valid session that has moved to a nearly expired session
'9999999999.movedRenewal' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'newSession' => '3000000000.renewal'
],
// valid session that has moved to a session that could be refreshed
'9999999999.movedTimeoutActivity' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'newSession' => '9999999999.timeoutActivity2'
],
// valid session that isn't yet started
'9999999999.notStarted' => [
'startTime' => 7777777777,
'expiryTime' => 9999999999,
'duration' => 2222222222,
'timeout' => false,
'lastActivity' => null,
'renewable' => false,
'data' => [
'id' => 'notStarted'
]
],
// session with an expired timeout
'9999999999.timeout' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'duration' => 9999999999,
'timeout' => 3600,
'lastActivity' => 1000000000,
'renewable' => false,
'data' => [
'id' => 'timeout'
]
],
// session with a timeout that doesn't need to be refreshed
'9999999999.timeoutActivity1' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'duration' => 9999999999,
'timeout' => 3600,
'lastActivity' => $time - 10,
'renewable' => false,
'data' => [
'id' => 'timeoutActivity1',
'expectedActivity' => $time - 10
]
],
// session with a timeout that could be refreshed
'9999999999.timeoutActivity2' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'duration' => 9999999999,
'timeout' => 3600,
'lastActivity' => $time - 500,
'renewable' => false,
'data' => [
'id' => 'timeoutActivity2',
'expectedActivity' => $time
]
],
// valid session without any kind of validation issues
'9999999999.valid' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'duration' => 9999999999,
'timeout' => false,
'lastActivity' => null,
'renewable' => false,
'data' => [
'id' => 'valid'
]
],
// another valid session
'9999999999.valid2' => [
'startTime' => 0,
'expiryTime' => 9999999999,
'duration' => 9999999999,
'timeout' => false,
'lastActivity' => null,
'renewable' => true,
'data' => [
'id' => 'valid2'
]
]
];
}
public function createId(int $expiryTime): string
{
do {
$id = $this->generateId();
} while ($this->exists($expiryTime, $id));
$this->sessions[$expiryTime . '.' . $id] = '';
$this->lock($expiryTime, $id);
return $id;
}
public function exists(int $expiryTime, string $id): bool
{
return isset($this->sessions[$expiryTime . '.' . $id]);
}
public function lock(int $expiryTime, string $id)
{
$this->isLocked[$expiryTime . '.' . $id] = true;
}
public function unlock(int $expiryTime, string $id)
{
unset($this->isLocked[$expiryTime . '.' . $id]);
}
public function get(int $expiryTime, string $id): string
{
$name = $expiryTime . '.' . $id;
if ($this->exists($expiryTime, $id)) {
$data = $this->sessions[$name];
// special cases
if ($data === 'invalid-serialization') {
$data = 'some gibberish';
return hash_hmac('sha256', $data, $this->validKey) . "\n" . $data;
} elseif ($data === 'invalid-structure') {
return 'some gibberish';
}
// check if this is a created or test session
if (isset($this->hmacs[$name])) {
// created session: it has its own HMAC, prepend it again
return $this->hmacs[$name] . "\n" . serialize($data);
} else {
// test session, add an HMAC based on the $validKey
$data = serialize($data);
return hash_hmac('sha256', $data, $this->validKey) . "\n" . $data;
}
} else {
throw new Exception('Session does not exist');
}
}
public function set(int $expiryTime, string $id, string $data)
{
$name = $expiryTime . '.' . $id;
if (!$this->exists($expiryTime, $id)) {
throw new Exception('Session does not exist');
}
if (!isset($this->isLocked[$name])) {
throw new Exception('Cannot write to a session that is not locked');
}
// decode the data
$hmac = Str::before($data, "\n");
$data = trim(Str::after($data, "\n"));
$data = unserialize($data);
// store the HMAC separately for the get() method above
$this->hmacs[$name] = $hmac;
$this->sessions[$name] = $data;
}
public function destroy(int $expiryTime, string $id)
{
unset($this->sessions[$expiryTime . '.' . $id]);
}
public function collectGarbage()
{
$this->collectedGarbage = true;
}
}
class MockSession extends Session {
public $ensuredToken = false;
public $preparedForWriting = false;
public function __construct()
{
// do nothing here
}
public function ensureToken()
{
$this->ensuredToken = true;
}
public function prepareForWriting()
{
$this->preparedForWriting = true;
}
}
<file_sep><?php
namespace Kirby\Email;
class PHPMailerTest extends TestCase
{
protected function _email($props = [], $mailer = PHPMailer::class) {
return parent::_email($props, $mailer);
}
public function testSend()
{
$email = $this->_email([
'to' => '<EMAIL>'
]);
$this->assertFalse($email->isSent());
$email->send(true);
$this->assertTrue($email->isSent());
}
}
<file_sep><?php
namespace Kirby\Form\Fields;
use Kirby\Form\Field;
use Kirby\Toolkit\I18n;
class ToggleFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = new Field('toggle');
$this->assertEquals('toggle', $field->type());
$this->assertEquals('toggle', $field->name());
$this->assertEquals(null, $field->value());
$this->assertTrue($field->save());
}
public function testText()
{
$field = new Field('toggle', [
'text' => 'Yay'
]);
$this->assertEquals('Yay', $field->text());
}
public function testTextWithTranslation()
{
$props = [
'text' => [
'en' => 'Yay',
'de' => 'Ja'
]
];
I18n::$locale = 'en';
$field = new Field('toggle', $props);
$this->assertEquals('Yay', $field->text());
I18n::$locale = 'de';
$field = new Field('toggle', $props);
$this->assertEquals('Ja', $field->text());
}
public function testTextToggle()
{
$field = new Field('toggle', [
'text' => [
'Yes',
'No'
]
]);
$this->assertEquals(['Yes', 'No'], $field->text());
}
public function testTextToggleWithTranslation()
{
$props = [
'text' => [
['en' => 'Yes', 'de' => 'Ja'],
['en' => 'No', 'de' => 'Nein']
]
];
I18n::$locale = 'en';
$field = new Field('toggle', $props);
$this->assertEquals(['Yes', 'No'], $field->text());
I18n::$locale = 'de';
$field = new Field('toggle', $props);
$this->assertEquals(['Ja', 'Nein'], $field->text());
}
}
<file_sep><?php
namespace Kirby\Cms;
class SiteRulesTest extends TestCase
{
public function testUpdate()
{
new App([
'users' => [
[
'email' => '<EMAIL>',
'role' => 'admin'
]
],
'user' => '<EMAIL>'
]);
$site = new Site([]);
$this->assertTrue(SiteRules::update($site, [
'copyright' => '2018'
]));
}
}
<file_sep><?php
namespace Kirby\Cms;
class CollectionsTest extends TestCase
{
public function testGet()
{
$collection = new Collection();
$collections = new Collections([
'test' => function () use ($collection) {
return $collection;
}
]);
$result = $collections->get('test');
$this->assertEquals($collection, $result);
}
public function testGetWithData()
{
$collections = new Collections([
'test' => function ($a, $b) {
return $a . $b;
}
]);
$result = $collections->get('test', [
'a' => 'a',
'b' => 'b'
]);
$this->assertEquals('ab', $result);
}
public function testGetWithRearrangedData()
{
$collections = new Collections([
'test' => function ($b, $a) {
return $a . $b;
}
]);
$result = $collections->get('test', [
'a' => 'a',
'b' => 'b'
]);
$this->assertEquals('ab', $result);
}
public function testHas()
{
$collections = new Collections([
'test' => function ($b, $a) {
return $a . $b;
}
]);
$this->assertTrue($collections->has('test'));
$this->assertFalse($collections->has('does-not-exist'));
}
public function testLoad()
{
$app = new App([
'roots' => [
'collections' => __DIR__ . '/fixtures/collections'
]
]);
$collections = Collections::load($app);
$result = $collections->get('test');
$this->assertInstanceOf(Collection::class, $result);
}
}
<file_sep><?php
namespace Kirby\Cms;
class ResponseTest extends TestCase
{
}
| 6b5b3afa79c2c4c33801233b6928e5bb533f0b3a | [
"Markdown",
"JavaScript",
"PHP"
] | 69 | PHP | tobiasfabian/kirby | d0dc99f496c39381182702999ecb610dc7311fbc | 5532c068a71aae5a85f83abe6bf807a1c238f4d4 |
refs/heads/master | <file_sep>package opgaver;
import java.io.File;
public class ReadDir {
public static void main(String[] args){
File file = null;
String[] paths;
try{
//Create new file object
file = new File(clausstaffe/);
paths.file
}catch(){
}
}
}
| 2514edcf196ebc415eb456d9093546cbc3c27fda | [
"Java"
] | 1 | Java | VidereVidereProgrammeringOpgaver/Lektion5 | eee98455d2a029742179617382ca2d0ff65d6ba0 | c9a1414bc94bf6646473a6def84473f507bb1426 |
refs/heads/master | <repo_name>1449207987/1449207987.github.ios<file_sep>/js/cdd.js
var f_right = document.getElementById('feature_right');
var r_content = f_right.children[0];
var r_nav = f_right.children[1];
var rw = r_content.children[0];
var rn = r_nav.getElementsByTagName('a');
// 获取所有的a并注册a的onmouseenter
for (var i =0; i < rn.length; i++) {
var ras = rn[i];
rn[0].style.color = 'white';
ras.index = i;
ras.onmouseenter = fn;
// ras.onmouseleave = fn1;
}
function fn() {
for (var i = 0; i < rn.length; i++) {
var ras = rn[i];
rn[i].index = i;
ras.className = '';
ras.style.color = '';
}
this.className = 'current';
this.style.color = 'white';
var aaa = this.index;
rw.style.backgroundImage = 'url(./images/zb-' + (aaa + 1) + '.jpg)';
}
<file_sep>/js/five.js
window.onload = function() {
// 5.游戏图赏部分导航栏
var cddVision = document.getElementById('cdd_vision');
var visionTop = document.getElementById('visionTop');
var ul = visionTop.children[0];
var bgBlack = visionTop.children[1];
var bgLine = visionTop.children[2];
var num = 0;
var lis=ul.children;
for (var i = 0; i < lis.length; i++) {
lis[i].index=i;
var s=0;
lis[i].onmouseenter=function(){
bgBlack.style.left=this.index*this.offsetWidth+'px';
this.children[0].style.color='#fff';
}
lis[i].onmouseleave=function(){
bgBlack.style.left=s+'px';
this.children[0].style.color='#000';
}
lis[i].onclick=function(){
s=this.index*this.offsetWidth;
}
}
// 5.4游戏图赏静态电影部分轮播图
var num1 = 0;
var timer = null;
var dyBig = document.getElementById("dyBig")
var arr1 = dyBig.children[0];
var arrLeft1 = arr1.children[0];
var arrRight1 = arr1.children[1];
// console.log(arrRight1);
var ul = dyBig.children[1];
var imgs = ul.children;
dyBig.onmouseenter = function() {
arr1.style.opacity = "1";
clearInterval(timeId);
}
dyBig.onmouseleave = function() {
arr1.style.opacity = "0";
}
var index=0;
var timeId=setInterval(play,1000)
function play(){
$(".clearfix1 li").css("opacity","0");
$(".clearfix1 li").eq(index).css("opacity","1");
index++;
if (index>=$(".clearfix1 li").length) {
index=0;
}
if (index<0) {
index=$(".clearfix1 li").length-1;
}
}
$(".arrLeft").click(function(){
index--;
play();
})
$(".arrRight").click(function(){
index++;
play();
})
}
$(function(){
//点击切换页面
$(".vision_top ul li").click(function(){
var index=$(this).index();
var divs=$(".vision_top").nextAll();
divs.css("display","none");
divs.eq(index).css("display","block");
});
var arr=[".cdd_feature",".cdd_job",".feature_right",".main",".cdd_vision"];
$(".clearfix li").click(function(){
for (var i = 0; i < arr.length; i++) {
$(arr[i]).css("display","none");
}
var index1=$(this).index()-1;
$(arr[index1]).css("display","block");
console.log(arr[index1]);
})
});
<file_sep>/js/main.js
$(function(){
$("#btn").click(function(){
$(".ad_zhuce").hide();
});
$("#lhl_tab > li").mouseenter(function(){
$(this).css("backgroundColor","#c5ac68").siblings()
.css("backgroundColor","#3b70ae");
});
$("#lhl_left").mouseenter(function(){
conslole.log("dddd");
});
});
<file_sep>/js/hq.js
$(function(){
new WOW().init();
//收起按钮
var flag=true;
$(".slide-toggle").click(function(){
if (flag) {
$(".slidebar").animate({
"right":"-153"
},function(){
$(".slide-toggle i").css({"backgroundImage":"url(./images/index_z.png)",
"backgroundPosition":"-417px -121px"
})
$(".slide-toggle span").text("展开");
})
flag=false;
}else{
$(".slidebar").animate({
"right":"0"
},function(){
$(".slide-toggle i").css({"backgroundImage":"url(./images/index_z.png)",
"backgroundPosition":"-417px -137px"
})
$(".slide-toggle span").text("收起");
})
flag=true;
}
})
//一吻定情切换
$(".b_nav a:eq(0)").css({
"backgroundPositionX":"-127px"
});
$(".b_nav a").click(function(){
var index=$(this).index();
$(this).css({
"backgroundPositionX":"-127px"
}).siblings().css("backgroundPositionX","0px");
$(".b_list").children().eq(index).css({
"opacity":"1",
"display":"block",
}).siblings().css("opacity","0").css("display","none");
$(".b_list").children().eq(index).children().css("display","block")
num=index;
})
var num=1;
var timeId=setInterval(function(){
$(".b_nav a").eq(num).click();
if (num>=$(".b_nav a").length-1) {
num=-1;
}
num++;
},3000)
$(".b_nav").mouseenter(function(){
clearInterval(timeId);
})
$(".b_nav").mouseleave(function(){
timeId=setInterval(function(){
$(".b_nav a").eq(num).click();
if (num>=$(".b_nav a").length) {
num=-1;
}
num++;
},3000)
})
//职业切换
$(".race_nav li").mouseenter(function(){
var index=$(this).index();
var Width=$(".leida").width();
var Height=$(".leida").height();
$(".race_list").children().eq(index).css({
"display":"block"
}).siblings().css({
"display":"none"
})
//姓名
$(".race_list").children().eq(index).children().eq(0).css({"backgroundImage":"url(./images/csl-name-"+(index+1)+".png)",
"transform":"translateY(0px)",
"opacity":"1"
});
// 人物
$(".race_list").children().eq(index).children().eq(5).css({"backgroundImage":"url(./images/csl-person-"+(index+1)+".png)",
"display":"block",
"transform":"translateX(0px)"
});
//属性
if (index <= 3) {
$(".race_list").children().eq(index).children().eq(3).css({"backgroundPosition":"-"+(index*Width)+"px 0px","transform":"translateY(0px)"});
}
else if (index > 3 && index <= 7) {
$(".race_list").children().eq(index).children().eq(3).css({"backgroundPosition":"-"+((index-4)*Width)+"px -"+Height+"px","transform":"translateY(0px)"});
}
else if (index > 7) {
$(".race_list").children().eq(index).children().eq(3).css({"backgroundPosition":"-"+((index-8)*Width)+"px -"+Height*2+"px","transform":"translateY(0px)"});
}
})
//返回顶部
$(".slide-top").click(function(){
// $(document).scrollTop(0);
// console.log(s);
$('html,body').animate({
scrollTop:0
},400)
})
//背景音乐播放
var play=true;
$(".player").click(function(){
if (play) {
// $(".videobox source").attr("src","");
$(".videobox audio")[0].pause();
play=false;
}else{
$(".videobox audio")[0].play();
play=true;
}
console.log(6666);
});
})
<file_sep>/js/index.js
var box1 = document.getElementById('gf_box1');
var ul = box1.children[0];
var box4 = document.getElementById('gf_box4');
// /ar link = ul.children;/
var boxCont = document.getElementById('gf_box_cont');
var flag = document.getElementById('gf_flag');
var index;
for(var i = 0; i <ul.children.length-2; i++){
var link = ul.children[i];
link.onclick = linkClick;
link.setAttribute('index',i);
}
function linkClick () {
var offsetLeft = this.offsetLeft;
animate(flag,offsetLeft,30);
for(var i = 0; i<boxCont.children.length; i++){
var div = boxCont.children[i];
if(div.className.indexOf('hide')===-1){
div.className = "onlinemes hide";
}
}
var index = parseInt(this.getAttribute('index'));
boxCont.children[index].className ='onlinemes show';
}
var timerId = null;
var box3 = document.getElementById('gf_box3');
var ul= box3.children[0];
var ol = box3.children[1];
var imageWidth =box3.offsetWidth;
var count = ul.children.length;
for(var i = 0; i < count; i++){
var li = document.createElement('li');
ol.appendChild(li);
li.innerText = i+1;
}
ol.children[0].className = 'current';
var firstLi = ul.children[0];
var cloneLi = firstLi.cloneNode(true);
ul.appendChild(cloneLi);
var olLis = ol.children;
for(var i = 0; i < olLis.length;i++){
olLis[i].index = i;
olLis[i].onclick= function(){
for(var j = 0; j< olLis.length; j++){
olLis[j].className = '';
}
olLis[this.index].className = 'current';
console.log(-this.index*imageWidth);
animate(ul,-this.index*imageWidth);
pic = this.index;
squ = this.index;
}
}
var pic = 0;
var squ = 0;
function autoPlay (){
if(pic ===olLis.length){
ul.style.left= '0px';
pic = 0;
// ol.children[1].className = '';
// ol.children[0].className = 'current';
}
//
pic++;
animate(ul,-pic*imageWidth);
}
if(squ ===olLis.length-1){
squ = -1;
}
squ++;
ol.children[squ].className = '';
ol.children[0].className = 'current';
console.log(squ);
for(var i = 0; i <olLis.length;i++){
olLis[i].className = '';
}
olLis[squ].className = 'current';
timerId = setInterval(autoPlay,3000);
box3.onmouseover = function (){
clearInterval(timerId);
}
box3.onmouseout = function(){
timerId = setInterval(autoPlay,3000);
}
// ol.children[0].className = 'current';
// var timerId = setInterval(function(){
// animate(ul,-liIndex*imageWidth);
// },2000)
// var firstLi = ul.children[0];
// var cloneLi = firstLi.cloneNode(true);
// li.appendChild(cloneLi);
var inp1= document.getElementById('inp1');
var btn = document.getElementById('btn');
var span1 = inp1.nextElementSibling;
inp1.onblur = function(){
if(this.value.trim()==''){
span1.innerText = '输入不能为空';
this.placeholder ='';
this.value ='';
}else{
span1.innerText = "";
this.value = this.value.replace(/\s/g,"");
}
}<file_sep>/js/csl_index.js
window.onload=function () {
//页面加载显示效果
new WOW().init();
//导航过度效果
var csl_nav=document.getElementById('csl_nav');
var lis=csl_nav.children[0].children;
var div=$('#csl_nav div');
var s=-681;
lis[0].style.backgroundImage='url(./images/csl_topmenu.png)';
lis[0].style.backgroundPositionX=s+'px';
lis[0].style.opacity='1';
for (var i=0;i<lis.length;i++) {
lis[i].index=i;
lis[i].onmouseenter=function () {
for(var j=0;j<lis.length;j++){
lis[j].style.backgroundImage='';
}
this.style.backgroundImage='url(./images/csl_topmenu.png)';
this.style.backgroundPositionX=this.index >=4 ? -960-this.index*140+'px' : s-this.index*140+'px';
}
}
//导航下拉
$('#csl_nav li').mouseover(function () {
$(this).children('div').stop().slideDown(300);
})
$('#csl_nav li').mouseleave(function () {
$(this).children('div').stop().slideUp(300);
})
//轮播图切换
var btn=document.querySelector('.banner-btn');
var center=document.querySelector('.center');
var banner = new FragmentBanner({
container : "#banner1",//选择容器 必选
imgs : ['images/csl_1.jpg','images/csl_2.jpg','images/csl_3.jpg','images/csl_4.jpg'],//图片集合 必选
size : {
width : 700,
height : 365
},//容器的大小 可选
//行数与列数 可选
grid : {
line : 6,
list : 5
},
index: 0,//图片集合的索引位置 可选
type : 1,//切换类型 1 , 2 可选
boxTime : 4000,//小方块来回运动的时长 可选
fnTime : 5000//banner切换的时长 可选
});
center.onmouseenter=function () {
btn.style.display='block';
}
center.onmouseleave=function () {
btn.style.display='none';
}
//角色切换
var csl_js=document.getElementById('csl_js');
var juese_left=document.querySelector('.juese_left');
var juese_right=document.querySelector('.juese_right');
var csl_li=juese_left.children[0].children;
var juese_center=document.querySelector('.juese_center');
var h3=juese_center.children[0];
for(var i=0;i<csl_li.length;i++){
csl_li[i].index=i;
juese_right.style.backgroundImage='url(./images/csl-nan-1.png)';
csl_li[i].onmouseenter=function () {
h3.style.backgroundImage='url(./images/csl_name-'+(this.index+1)+'.png)';
juese_right.style.backgroundImage='url(./images/csl-nan-'+(this.index+1)+'.png)';
new WOW().init();
$(".sex .nan").css({//滑动每个li都让按钮回到男上
"backgroundPosition":"-474px -213px"
}).siblings().css({"backgroundPosition":"-474px -259px"});
}
csl_li[i].onmouseleave=function(){
juese_right.style.transform='translateX(100px)';
}
}
//男女切换
$(".sex .nan").css({//页面加载完让男按钮选中
"backgroundPosition":"-474px -213px"
});
$(".sex span").mouseover(function(){
var str=$(h3).css('backgroundImage');
var img=str.split('-')[1];
var imgs=img.split('"')[0];
// console.log(imgs);
if ($(this).index()==0) {
$(this).css({
"backgroundPosition":"-474px -213px",
}).siblings('span').css({"backgroundPosition":"-474px -259px"});
$(juese_right).css("backgroundImage","url(images/csl-nan-"+imgs+")");
} else{
$(this).css({
"backgroundPosition":"-1164px -520px",
}).siblings('span').css({"backgroundPosition":"-696px -315px"});
$(juese_right).css("backgroundImage","url(images/csl-nv-"+imgs+")");
}
});
//公告栏滑动
var asid_caption=document.querySelector('.asid_caption');
var asid_li=asid_caption.children[0].children;
var bar=asid_caption.children[1];
var list_1=document.querySelector('.list_1');
var list_ul=list_1.children[0];
// console.log(bar.offsetLeft);
for (var i=0;i<asid_li.length;i++) {
asid_li[i].index=i;
asid_li[i].onmouseenter=function(){
bar.style.left=this.index*this.offsetWidth+7+'px';
list_1.style.left=-this.index*list_ul.offsetWidth+'px';
}
}
//花瓣飘落
$(document).snowfall('clear');
$(document).snowfall({
image: "images/huaban.png",
flakeCount:30,
minSize: 5,
maxSize: 22
});
//精彩视频开关门
$("#csl_jcsp ul li").mouseover(function(){
// $(this).children().children('span').animate({
// transform:"translateX(0px)"
// },300);
// $(this).children().children('span').css("transform","translateX(0px)");
$(this).children().children('i').css("opacity",1);
}).mouseleave(function(){
$(this).children().children('i').css("opacity",0);
});
//真人秀轮播
var zrx_mm=document.querySelector('.zrx_mm');
var ul=zrx_mm.children[0];
var mm_left=zrx_mm.children[1];
var mm_right=zrx_mm.children[2];
var zrx_li=ul.children;
var index=-1;
var count=zrx_li.length;
var timeId1=setInterval(play,2000);
function play(){
mm_right.click();
}
zrx_mm.onmouseenter=function(){
clearInterval(timeId1);
}
zrx_mm.onmouseleave=function(){
timeId1=setInterval(play,2000);
}
mm_left.onclick=function(){
if (index==0) {
ul.style.left=-count*zrx_mm.offsetWidth;
index=count;
console.log(index)
}
index--;
animate(ul,-index*zrx_mm.offsetWidth);
}
mm_right.onclick=function(){
if (index==count) {
ul.style.left='0px';
index=0;
}
index++;
if(index<zrx_li.length){
animate(ul,-index*zrx_mm.offsetWidth);
}
}
var liClone=zrx_li[0].cloneNode(true);
ul.appendChild(liClone);
function animate(element, target) {
// 通过判断,保证页面上只有一个定时器在执行动画
if (element.timerId) {
clearInterval(element.timerId);
element.timerId = null;
}
element.timerId = setInterval(function () {
// 步进 每次移动的距离
var step = 10;
// 盒子当前的位置
var current = element.offsetLeft;
// 当从400 到 800 执行动画
// 当从800 到 400 不执行动画
// 判断如果当前位置 > 目标位置 此时的step 要小于0
if (current > target) {
step = - Math.abs(step);
}
// Math.abs(current - target) <= Math.abs(step)
if (Math.abs(current - target) <= Math.abs(step)) {
// 让定时器停止
clearInterval(element.timerId);
// 让盒子到target的位置
element.style.left = target + 'px';
return;
}
// 移动盒子
current += step;
element.style.left = current + 'px';
}, 5);
}
}<file_sep>/js/yj-index.js
window.onload = function () {
//导航
//导航过度效果
var csl_nav=document.getElementById('csl_nav');
var lis=csl_nav.children[0].children;
var div=$('#csl_nav div');
var s=-681;
lis[0].style.backgroundImage='url(./images/csl_topmenu.png)';
lis[0].style.backgroundPositionX=s+'px';
lis[0].style.opacity='1';
for (var i=0;i<lis.length;i++) {
lis[i].index=i;
lis[i].onmouseenter=function () {
for(var j=0;j<lis.length;j++){
lis[j].style.backgroundImage='';
}
this.style.backgroundImage='url(./images/csl_topmenu.png)';
this.style.backgroundPositionX=this.index >=4 ? -960-this.index*140+'px' : s-this.index*140+'px';
}
}
//导航下拉
$('#csl_nav li').mouseover(function () {
$(this).children('div').stop().slideDown(300);
})
$('#csl_nav li').mouseleave(function () {
$(this).children('div').stop().slideUp(300);
})
// inner start
var txt = document.querySelector('.yj-txt');
var btn = document.querySelector('.yj-btn');
//文本框获得焦点时,文本框内容清零; 点击搜索按钮时,有网页跳出;
txt.onfocus = function() {
if (this.value === '请输入关键字') {
this.value = '';
}
}
// txt失去焦点时,文本框内容=“'请输入文本框'”
txt.onblur = function() {
if (txt.value === '') {
txt.value = '请输入关键字'
}
}
//----------------------- 注册部分--------------------------
var zslb = document.querySelector(".yj-zslb");
var zhuce = document.querySelector('.yj-zhuce');
var gb = document.querySelector('.yj-gb');
zslb.onclick = function() {
zslb.style.display = 'none';
zhuce.style.display = 'block';
}
gb.onclick = function() {
zslb.style.display = 'block';
zhuce.style.display = 'none';
}
var password = document.querySelector('.yj-password');
var gb_three = document.querySelector('.yj-gb-three');
//input账号和密码清除
var gb_two = document.querySelector('.yj-gb-two');
var email = document.querySelector('.yj-email');
email.oninput = function(){
//
if (email.value.length > 0 ) {
gb_two.style.display = 'block';
gb_two.onclick = function(){
email.value = '';
gb_two.style.display = 'none';
}
} else {
gb_two.style.display = 'none';
}
}
email.onblur = function () {
var reg = /^\w+@\w+(\.\w+)+$/;
var span = email.nextElementSibling;
if (!reg.test(this.value)) {//不匹配
span.innerText = '请输入正确的邮箱账号';
span.style.color = 'red';
gb_three.style.top = '70px';
} else { //匹配的时候
span.innerText = '';
span.style.color = '';
}
}
// addCheck(email, /^\w+@\w+(\.\w+)+$/, '请输入正确的邮箱账号' )
//函数封装 tip 提示的文本
function addCheck(element, reg, tip){
element.onblur = function() {
var span = element.nextElementSibling;
if (!reg.test(this.value)) {
span.innerText = tip;
span.style.color = 'red';
} else {
span.innerText = '';
span.style.color = '';
}
}
}
//密码 ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
password.oninput = function(){
if (password.value > 0) {
gb_three.style.display = 'block';
gb_three.onclick = function(){
password.value = '';
gb_three.style.display = 'none';
}
} else {
gb_three.style.display = 'none';
}
}
//密码验证
addCheck(password, /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,16}$/, '必须包含大小写字母和数字的组合,不能使用特殊字符,长度在6-16之间' )
// 游戏资料
var list = document.querySelectorAll('.yj-menu .wz-fen');
for(var i = 0; i < list.length; i++) {
list[i].addEventListener('mouseenter', move);
list[i].addEventListener('mouseleave', leave);
}
function move() {
this.children[1].classList.add('current');
}
function leave() {
this.children[1].classList.remove('current');
}
$(window).scroll(function () {
if($(document).scrollTop() >= 1000) {
$('.yj-sidebar').css({'position':'fixed', 'top':100,'left':179});
}else {
console.log($(document).scrollTop());
$('.yj-sidebar').css('position','absolute').css({'top':370,'left':0});
}
});
}
| 427b78a9f0c1da8a94919ab55f514d938ad6dca8 | [
"JavaScript"
] | 7 | JavaScript | 1449207987/1449207987.github.ios | 8c17ea0050cfcbadf4fb2ddbd5e14d0f4911bc79 | 7b19c431d6cd3d69e1af3d1fa6743b888087f154 |
refs/heads/master | <repo_name>yanghaipeng/YYAppCommonKit<file_sep>/Example/Podfile
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target 'YYAppCommonKit_Example', :exclusive => true do
pod "YYAppCommonKit", :path => "../"
end
target 'YYAppCommonKit_Tests', :exclusive => true do
pod "YYAppCommonKit", :path => "../"
end
| 45895b67ac3db9f0eead7bca74b9005136924a7f | [
"Ruby"
] | 1 | Ruby | yanghaipeng/YYAppCommonKit | b47592f441bd24e5d1399022eef2e6871be706f7 | 2831d5a2d2cbeae102cdf7aef211acc524fff53d |
refs/heads/master | <repo_name>Aleynikovich/DecisionMatrix<file_sep>/Program.cs
using System;
namespace DecisionMatrix
{
class Program
{
static void Main(string[] args)
{
int stratsP1, stratsP2;
Console.WriteLine("Estrategias jugador 1?");
stratsP1=Int32.Parse(Console.ReadLine());
Console.WriteLine("Estrategias jugador 2?");
stratsP2=Int32.Parse(Console.ReadLine());
StrategicDominance(stratsP1,stratsP2);
}
static void StrategicDominance(int StrategiesP1, int StrategiesP2)
{
int[,] stratMatrix = new int[100, 100];
bool correctNumber;
bool[] stratUnviable = new bool[2];
//Input data
for (int i = 0; i < StrategiesP2; i++)
{
for (int j = 0; j < StrategiesP1; j++)
{
do
{
Console.WriteLine("Input strat [{0},{1}]", i + 1, j + 1);
correctNumber = Int32.TryParse(Console.ReadLine(), out stratMatrix[i, j]);
if (!correctNumber)
{
Console.WriteLine("Numero invalido");
}
} while (!correctNumber);
}
}
Console.Clear();
//Check estrategias inviables para jugador 2
for (int i = 0; i < StrategiesP2 - 1; i++) //strat principal
{
for (int j = 1; j < StrategiesP1; j++) //strat secundaria
{
if (i < j)
{
stratUnviable[0] = false;
stratUnviable[1] = false;
//Console.WriteLine("Comparando estrategia {0} con estrategia {1}", i + 1, j + 1);
for (int k = 0; k < StrategiesP2; k++) //Filas
{
//Console.WriteLine("Comparando {0} con {1}", stratMatrix[i, k], stratMatrix[j, k]);
if (stratMatrix[i, k] > stratMatrix[j, k] && !stratUnviable[0])
{
stratUnviable[0] = true;
}
if (stratMatrix[i, k] < stratMatrix[j, k] && !stratUnviable[1])
{
stratUnviable[1] = true;
}
}
if (!stratUnviable[0])
{
Console.WriteLine("Estrategia {0} siempre es mejor que estrategia {1} para jugador 2", i + 1, j + 1);
}
if (!stratUnviable[1])
{
Console.WriteLine("Estrategia {1} siempre es mejor que estrategia {0} para jugador 2", i + 1, j + 1);
}
}
}
}
//Check estrategias inviables para jugador 1
for (int i = 0; i < StrategiesP2 - 1; i++) //strat principal
{
for (int j = 1; j < StrategiesP1; j++) //strat secundaria
{
if (i < j)
{
stratUnviable[0] = false;
stratUnviable[1] = false;
//Console.WriteLine("Comparando estrategia {0} con estrategia {1}", i + 1, j + 1);
for (int k = 0; k < StrategiesP1; k++) //Filas
{
//Console.WriteLine("Comparando {0} con {1}", stratMatrix[i, k], stratMatrix[j, k]);
if (stratMatrix[k, i] < stratMatrix[k, j] && !stratUnviable[0])
{
stratUnviable[0] = true;
}
if (stratMatrix[k, i] > stratMatrix[k, j] && !stratUnviable[1])
{
stratUnviable[1] = true;
}
}
if (!stratUnviable[0])
{
Console.WriteLine("Estrategia {0} siempre es mejor que estrategia {1} para jugador 1", i + 1, j + 1);
}
if (!stratUnviable[1])
{
Console.WriteLine("Estrategia {1} siempre es mejor que estrategia {0} para jugador 1", i + 1, j + 1);
}
}
}
}
}
}
}
| 62718b0a0dca5e04dd4056d8167860a4a6b748ec | [
"C#"
] | 1 | C# | Aleynikovich/DecisionMatrix | 51efc8f4eef39c46ccdeb25d7dcfd3a6934f0ce8 | 0664eefce55e0e56238ce1b2bae3f45ee4dbe6fb |
refs/heads/master | <repo_name>chercheur05/C-<file_sep>/扫雷.c
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 9
#define COL 9
#define MINE_COUNT 10
int safe_blank_count = 0;
int Menu() {
printf("==============\n");
printf("1.开始游戏\n0.结束游戏\n");
printf("==============\n");
printf("请输入您的选择:\n");
int choice = 0;
scanf("%d", &choice);
return choice;
}
void Init(char show_map[ROW + 2][COL + 2], char mine_map[ROW + 2][COL + 2]) {
//形参二维数组的第二个下标必须要写,并且要与实参对应
//1.把 show_map 初始化为全是‘ ’
for (int row = 0; row < ROW + 2; ++row) {
for (int col = 0; col < COL + 2; ++col) {
show_map[row][col] = ' ';
}
}
//2.把 mine_map 初始化为全是‘0’
for (int row = 0; row < ROW + 2; ++row) {
for (int col = 0; col < COL + 2; ++col) {
mine_map[row][col] = '0';
}
}
//3.把mine_map 哪些位置是地雷排布好
int mine_count = MINE_COUNT;
while (mine_count > 0) {
//尝试随机设置地雷
//[1,9]
int row = rand() % ROW + 1;
int col = rand() % COL + 1;
if (mine_map[row][col]=='1') {
//当前随机产生的坐标已经有地雷了
continue;
}
mine_map[row][col] = '1';
--mine_count;
}
}
void DisplayMap(char map[ROW + 2][COL + 2]) {
//打印地图
//不光要打印出地图的详细内容,顺便打印出坐标
//先打印出左上角的空格
printf(" ");
//打印列的坐标
for (int i = 1; i <= ROW; ++i) {
printf(" %d", i);
}
printf("\n");
//打印上边框
for (int i = 1; i <= ROW; ++i) {
printf("---");
}
printf("\n");
//按行打印地图内容
for (int row = 1; row <= ROW; ++row) {
//先打印行号
printf(" %d|", row);
//打印该行的每一列
for (int col = 1; col <= COL; ++col) {
printf(" %c", map[row][col]);
}
printf("\n");
}
}
void UpdataShowMap(char show_map[ROW + 2][COL + 2], char mine_map[ROW + 2][COL + 2], int row, int col) {
//统计当前位置周围8个格子有几个地雷,把数字更新到格子上
//row的范围[1,9]
int count = 0;
//如果不加边框,必须保证每个坐标访问的时候都不能越界
//代码就要多加许多的 if 判定
count = (mine_map[row - 1][col - 1] - '0') + (mine_map[row - 1][col] - '0')
+ (mine_map[row - 1][col + 1] - '0') + (mine_map[row][col - 1] - '0')
+ (mine_map[row][col + 1] - '0') + (mine_map[row + 1][col - 1] - '0')
+ (mine_map[row + 1][col] - '0') + (mine_map[row + 1][col + 1] - '0');
//必须是个位数,否则无法转换为字符格式
show_map[row][col] = '0' + count;
}
void Updata(char show_map[ROW+2][COL+2], char mine_map[ROW + 2][COL + 2],int row,int col) {
if (row >= 1 && row <= ROW && col >= 1 && col <= COL&& show_map[row][col] == ' ') {
//行数在[1,9]的区间内,且未赋过值,才可进行递归
UpdataShowMap(show_map, mine_map, row, col);
++safe_blank_count;
if (show_map[row][col] == '0') {
//算该格子周围的八个格子,一直到数字不为0
Updata(show_map, mine_map, row - 1, col - 1);
Updata(show_map, mine_map, row - 1, col);
Updata(show_map, mine_map, row - 1, col + 1);
Updata(show_map, mine_map, row, col - 1);
Updata(show_map, mine_map, row, col + 1);
Updata(show_map, mine_map, row + 1, col - 1);
Updata(show_map, mine_map, row + 1, col);
Updata(show_map, mine_map, row + 1, col + 1);
}
else {
return;
}
}
}
//1.使用二维数组表示地图
// a)地雷布局地图(char类型的二维数组,用'0'表示不是地雷,'1'表示是地雷)
// b)玩家看到的地图(哪些位置未翻开,哪些位置已翻开),
// (char类型的二维数组表示,如果是' ',表示未翻开,
// 数字表示已翻开,并且当前位置周围8个格子有几个雷)
//2.初始化
// a)地雷的布局地图,先把这个二维数组全都初始化成‘0’,再随机的设定若干位置为地雷
// b)玩家看到的地图,全部初始化成‘ ’表示未翻开
//3.先打印地图(玩家看的地图),提示玩家输入坐标,校验玩家输入数据是否合法
//4.如果玩家翻开的格子是地雷,游戏结束(提示扫雷失败)
//5.如果玩家翻开的格子不是地雷,并且这个格子是地图上非地雷的最后一个位置,扫雷成功
//6.如果玩家翻开的不是地雷,并且这个格子不是地图上最后一个非地雷的格子,
// 就把地图上的位置设为展开状态,并且更新该位置附近的8个格子的地雷数目
void Game() {
//在地图外加上一圈边框
char show_map[ROW+2][COL+2];
char mine_map[ROW+2][COL+2];
//由于数组作为参数会隐式转换为指针,拿着数组名传到函数里面就已经成为指针了,
//在函数内部对参数进行修改是会影响到外部的数组的
Init(show_map,mine_map);
while (1) {
DisplayMap(show_map);
int row = 0;
int col = 0;
printf("请输入坐标:");
scanf("%d %d", &row, &col);
if (row<1 || row>ROW || col<1 || col>col) {
//坐标输入非法.需要注意!地图是带边框的,所以判定规则要小心对待
printf("您输入的坐标不合法,请重新输入!\n");
continue;
}
//验证是否踩到地雷
if (mine_map[row][col] == '1') {
printf("游戏结束!扫雷失败\n");
break;
}
//验证是否扫雷成功
if (safe_blank_count+1 == ROW * COL - MINE_COUNT) {
printf("游戏结束!扫雷成功!\n");
break;
}
//更新地图的状态
Updata(show_map, mine_map,row, col);
system("cls");
}
DisplayMap(mine_map);
}
int main() {
srand((unsigned int)time(0));
while (1) {
int choice = Menu();
if (choice == 0) {
printf("Goodbye!\n");
break;
}
if (choice == 1) {
Game();
}
}
system("pause");
return 0;
}<file_sep>/三子棋.c
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//1.使用字符类型二维数组来表示棋盘(3*3)
// 使用‘x'表示玩家的子,‘o’表示电脑的子
//2.玩家落子,给玩家一个提示,提示让玩家落子,输入一个坐标(row,col)
//3.判定游戏结束
// a)玩家获胜
// b)电脑获胜
// c)和棋
// d)游戏没结束
//4.电脑落子,电脑随便下(随机数的方式)
//5.判定游戏结束
// a)玩家获胜
// b)电脑获胜
// c)和棋
// d)游戏没结束
#define ROW 3
#define COL 3
//g_ 前缀表示全局变量
char g_broad[ROW][COL];
void Init() {
//把数组中的每个元素都初始化成‘ ’空格
for (int row = 0; row < ROW; ++row) {
for (int col = 0; col < COL; ++col) {
g_broad[row][col] = ' ';
}
}
}
void Print() {
for (int row=0; row < ROW; ++row) {
printf("| %c | %c | %c |\n", g_broad[row][0],
g_broad[row][1], g_broad[row][2]);
if (row != ROW - 1) {
printf("|---|---|---|\n");
}
}
}
void PlayerMove() {
printf("玩家落子!\n");
while (1) {
printf("请输入一组坐标(row col):");
int row = 0;
int col = 0;
scanf("%d %d", &row, &col);
if (row < 0 || row >= ROW || col < 0 || col >= COL) {
//用户输入坐标非法
printf("坐标输入非法!请重新输入!\n");
continue;
}
if (g_broad[row][col] != ' ') {
printf("当前位置已经有子了,请重新输入!\n");
continue;
}
g_broad[row][col] = 'x';
break;
}
}
void ComputerMove() {
//随便下 电脑产生两个随机数
printf("电脑落子!\n");
while (1) {
int row = rand() % ROW;
int col = rand() % COL;
if (g_broad[row][col] != ' ') {
//当前的位置已经被占用了!
continue;
}
g_broad[row][col] = 'o';
break;
}
}
//如果满了,返回1,如果没满,返回0
int IsFull() {
for (int row = 0; row < ROW; ++row) {
for (int col = 0; col < COL; ++col) {
if (g_broad[row][col]==' ') {
return 0;
}
}
}
//如果遍历结束也没有找到空格,说明棋盘满了!和棋
return 1;
}
//这个函数返回了当前游戏胜负情况
//返回了‘x',表示玩家获胜
//返回了‘o',表示电脑获胜
//返回了‘q’,表示和棋
//返回了‘ ’,表示游戏还没有结束
char CheckWinner(){
//先检查所有的行
for (int row = 0; row < ROW; ++row) {
if (g_broad[row][0] == g_broad[row][1]
&& g_broad[row][0] == g_broad[row][2]
&& g_broad[row][0] != ' ') {
return g_broad[row][0];
}
}
//再检查所有的列
for (int col = 0; col < COL; ++col) {
if (g_broad[0][col] == g_broad[1][col]
&& g_broad[0][col] == g_broad[2][col]
&& g_broad[0][col] != ' ') {
return g_broad[0][col];
}
}
//在检查所有的对角线
if (g_broad[0][0] == g_broad[1][1]
&& g_broad[0][0] == g_broad[2][2]
&& g_broad[0][0] != ' ') {
return g_broad[0][0];
}
if (g_broad[2][0] == g_broad[1][1]
&& g_broad[2][0] == g_broad[0][2]
&& g_broad[2][0] != ' ') {
return g_broad[2][0];
}
if (IsFull()) {
return 'q';
}
return ' ';
}
int main() {
srand((unsigned int)time(0));//强制类型转换,防止有警告
Init();//初始化函数,因为字符数组是全局变量,所以不需要传参
char winner = '\0';
while (1)
{
system("cls");//清理棋盘
Print();//打印棋盘
PlayerMove();
winner = CheckWinner();
if(winner != ' '){
Print();
printf("游戏结束,赢家是 %c\n",winner);
return 0;
}
ComputerMove();
winner = CheckWinner();
if(winner != ' '){
Print();
printf("游戏结束,赢家是 %c\n",winner);
return 0;
}
}
system("pause");
return 0;
} | a51166ff8f24c08da7a275e3dd786a73db832ccc | [
"C"
] | 2 | C | chercheur05/C- | 4f7a19a107dc630f5804551e7736cde794a6f794 | cb2115cf73da8df186efb7ed4a157ad691c18fbf |
refs/heads/master | <repo_name>matijabk4/TrackDataServer<file_sep>/src/rs/ac/bg/fon/ps/repository/db/impl/RepositoryDBUser.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.repository.db.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import rs.ac.bg.fon.ps.domain.RaceItem;
import rs.ac.bg.fon.ps.domain.User;
import rs.ac.bg.fon.ps.repository.db.DBConnectionFactory;
import rs.ac.bg.fon.ps.repository.db.DBRepository;
/**
*
* @author Matija
*/
public class RepositoryDBUser implements DBRepository<User> {
@Override
public List<User> getAll() throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
List<User> users = new ArrayList<>();
String sql = "SELECT * FROM user";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
User user = new User();
user.setId(rs.getLong("id"));
user.setFirstname(rs.getString("firstname"));
user.setLastname(rs.getString("lastname"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("<PASSWORD>"));
users.add(user);
}
return users;
} catch (SQLException ex) {
Logger.getLogger(RepositoryDBUser.class.getName()).log(Level.SEVERE, null, ex);
throw new Exception("Error establishing connection!");
}
}
@Override
public void add(User obj) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void edit(User param) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(User param) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<User> getByCriteria(Object criteria) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void update(Object r) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<User> getAll(User param) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>/src/rs/ac/bg/fon/ps/repository/db/impl/RepositoryDBRace.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.repository.db.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import rs.ac.bg.fon.ps.domain.MotorcycleMake;
import rs.ac.bg.fon.ps.domain.Race;
import rs.ac.bg.fon.ps.domain.RaceItem;
import rs.ac.bg.fon.ps.repository.db.DBConnectionFactory;
import rs.ac.bg.fon.ps.repository.db.DBRepository;
/**
*
* @author Matija
*/
public class RepositoryDBRace implements DBRepository<Race> {
@Override
public List<Race> getAll() throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
List<Race> races = new ArrayList<>();
String sql = "SELECT * FROM race";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yyyy.");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd.MM.yyyy.");
while (rs.next()) {
Race race = new Race();
race.setId(rs.getInt("id"));
race.setTrack(rs.getString("track"));
race.setDate(rs.getDate("date"));
race.setName(rs.getString("name"));
race.setTotalLaps(rs.getInt("totallaps"));
races.add(race);
}
rs.close();
statement.close();
return races;
} catch (SQLException ex) {
Logger.getLogger(RepositoryDBRider.class.getName()).log(Level.SEVERE, null, ex);
throw new Exception();
}
}
@Override
public void add(Race race) throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
String sql = "insert into race (track,date,name,totallaps,created_on) values (?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, race.getTrack());
ps.setDate(2, new java.sql.Date(race.getDate().getTime()));
ps.setString(3, race.getName());
ps.setInt(4, race.getTotalLaps());
ps.setTimestamp(5, race.getCreatedOn());
ps.executeUpdate();
ResultSet rsKey = ps.getGeneratedKeys();
if (rsKey.next()) {
int id = rsKey.getInt(1);
race.setId(id);
sql = "insert into race_item(id,racenumber,riderid,startposition,teamid) values (?,?,?,?,?) ";
ps = conn.prepareStatement(sql);
for (RaceItem item : race.getItems()) {
ps.setInt(1, race.getId());
ps.setInt(2, item.getRaceNumber());
ps.setLong(3, item.getRider().getID());
ps.setInt(4, item.getStartPosition());
ps.setInt(5, item.getTeam().getId());
ps.executeUpdate();
}
} else {
throw new Exception("Race id is not generated!");
}
ps.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
throw new Exception("Race could not be created!");
}
}
@Override
public void edit(Race r) throws Exception {
try {
String sql = "UPDATE race SET "
+ "track='" + r.getTrack()+ "', "
+ "date='" +new java.sql.Date(r.getDate().getTime())+ "', "
+ "name='" + r.getName()+ "',"
+ "totallaps='" + r.getTotalLaps()+ "',"
+ "updated_on='" + r.getUpdatedOn() + "' "
+ "WHERE id=" + r.getId();
System.out.println(sql);
Connection connection = DBConnectionFactory.getInstance().getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("Update race DB error: \n" + ex.getMessage());
}
}
@Override
public void delete(Race r) throws Exception {
try {
Connection connection = DBConnectionFactory.getInstance().getConnection();
String sql = "DELETE FROM race_item where id = "+r.getId();
System.out.println(sql);
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
sql = "DELETE FROM race WHERE id=" + r.getId();
System.out.println(sql);
statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("Delete race DB error: \n" + ex.getMessage());
}
}
@Override
public List<Race> getByCriteria(Object criteria) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void update(Object rr) throws Exception {
try {
int raceId = (int) rr;
Connection conn = DBConnectionFactory.getInstance().getConnection();
String sql = "update race set updated_on=? where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
ps.setInt(2, raceId);
int rows = ps.executeUpdate();
System.out.println(rows);
ps.close();
} catch (SQLException ex) {
Logger.getLogger(RepositoryDBRider.class.getName()).log(Level.SEVERE, null, ex);
throw new Exception();
}
}
@Override
public List<Race> getAll(Race param) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>/src/rs/ac/bg/fon/ps/repository/db/impl/RepositoryDBRider.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.repository.db.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import rs.ac.bg.fon.ps.domain.MotorcycleMake;
import rs.ac.bg.fon.ps.domain.Rider;
import rs.ac.bg.fon.ps.repository.db.DBConnectionFactory;
import rs.ac.bg.fon.ps.repository.db.DBRepository;
/**
*
* @author Matija
*/
public class RepositoryDBRider implements DBRepository<Rider> {
@Override
public List<Rider> getAll() throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
List<Rider> riders = new ArrayList<>();
String sql = "SELECT * FROM rider";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
Rider rider = new Rider();
rider.setID(rs.getLong("id"));
rider.setFirstname(rs.getString("firstname"));
rider.setSurname(rs.getString("surname"));
rider.setNationality(rs.getString("nationality"));
rider.setMotorcycle(MotorcycleMake.valueOf(rs.getString("motorcyclemake")));
rider.setRacingNum(rs.getInt("racingnumber"));
riders.add(rider);
}
rs.close();
statement.close();
return riders;
} catch (SQLException ex) {
Logger.getLogger(RepositoryDBRider.class.getName()).log(Level.SEVERE, null, ex);
throw new Exception();
}
}
@Override
public void add(Rider rider) throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
int max = 0;
String msg="";
String sql = "select max(id) as maximum from rider";
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(sql);
if (rs.next()) {
max = rs.getInt("maximum");
}
int id = ++max;
rider.setID(Long.parseLong(String.valueOf(id)));
sql = "insert into rider (id, firstname, surname, nationality, motorcyclemake, racingnumber, created_on) values (?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setLong(1, id);
ps.setString(2, rider.getFirstname());
ps.setString(3, rider.getSurname());
ps.setString(4, rider.getNationality());
ps.setString(5, rider.getMotorcycle().toString());
ps.setInt(6, rider.getRacingNum());
ps.setDate(7, new java.sql.Date(new Date().getTime()));
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
throw new Exception("Rider could not be created!");
}
}
@Override
public void edit(Rider r) throws Exception {
try {
String sql = "UPDATE Rider SET "
+ "firstname='" + r.getFirstname() + "', "
+ "surname='" + r.getSurname() + "', "
+ "nationality='" + r.getNationality() + "',"
+ "motorcyclemake='" + r.getMotorcycle() + "',"
+ "racingnumber=" + r.getRacingNum() + ", "
+"updated_on='"+new java.sql.Timestamp(new java.util.Date().getTime())+"' "
+ "WHERE id=" + r.getID();
System.out.println(sql);
Connection connection = DBConnectionFactory.getInstance().getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("Update rider DB error: \n" + ex.getMessage());
}
}
@Override
public void delete(Rider r) throws Exception {
try {
Connection connection = DBConnectionFactory.getInstance().getConnection();
String sql = "DELETE FROM race_item where riderid = "+r.getID();
System.out.println(sql);
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
sql = "DELETE FROM rider WHERE id=" + r.getID();
System.out.println(sql);
statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("Delete rider DB error: \n" + ex.getMessage());
}
}
@Override
public List<Rider> getByCriteria(Object criteria) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void update(Object r) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Rider> getAll(Rider param) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>/src/rs/ac/bg/fon/ps/operation/rider/ShowAllRiders.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.operation.rider;
import java.util.List;
import rs.ac.bg.fon.ps.domain.Rider;
import rs.ac.bg.fon.ps.operation.AbstractGenericOperation;
/**
*
* @author Matija
*/
public class ShowAllRiders extends AbstractGenericOperation {
private List<Rider> riders;
@Override
protected void preconditions(Object param) throws Exception {
}
@Override
protected void executeOperation(Object param) throws Exception {
riders = repository.getAll((Rider) param);
}
public List<Rider> getRiders() {
return riders;
}
}
<file_sep>/src/rs/ac/bg/fon/ps/repository/db/impl/RepositoryDBGeneric.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.repository.db.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import rs.ac.bg.fon.ps.domain.GenericEntity;
import rs.ac.bg.fon.ps.domain.MotorcycleMake;
import rs.ac.bg.fon.ps.domain.Rider;
import rs.ac.bg.fon.ps.repository.db.DBConnectionFactory;
import rs.ac.bg.fon.ps.repository.db.DBRepository;
/**
*
* @author Matija
*/
public class RepositoryDBGeneric implements DBRepository<GenericEntity> {
@Override
public void add(GenericEntity entity) throws Exception {
try {
Connection connection = DBConnectionFactory.getInstance().getConnection();
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ")
.append(entity.getTableName())
.append(" (").append(entity.getColumnNamesForInsert()).append(")")
.append(" VALUES (")
.append(entity.getInsertValues())
.append(")");
String query = sb.toString();
System.out.println(query);
Statement statement = connection.createStatement();
statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
ResultSet rsKey = statement.getGeneratedKeys();
if (rsKey.next()) {
Long id = rsKey.getLong(1);
entity.setId(id);
}
System.out.println(query);
statement.close();
rsKey.close();
} catch (SQLException ex) {
throw ex;
}
}
@Override
public List<GenericEntity> getAll() throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<GenericEntity> getByCriteria(Object criteria) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void edit(GenericEntity entity) throws Exception {
try {
Connection connection = DBConnectionFactory.getInstance().getConnection();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ")
.append(entity.getTableName())
.append(" SET ").append(entity.getColumnNamesForInsert())
.append(" WHERE ").append(entity.getColumnNameForDelete())
.append(" = ").append(entity.getIDForEdit());
String query = sb.toString();
Statement statement = connection.createStatement();
statement.executeUpdate(query);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception(ex.getMessage());
}
}
@Override
public void delete(GenericEntity entity) throws Exception {
try {
Connection connection = DBConnectionFactory.getInstance().getConnection();
StringBuilder sb = new StringBuilder();
sb.append("DELETE FROM ")
.append(entity.getTableName())
.append(" WHERE ").append(entity.getColumnNameForDelete())
.append(" = ")
.append(entity.getIDForDelete());
String query = sb.toString();
System.out.println(query);
Statement statement = connection.createStatement();
statement.executeUpdate(query);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception(ex.getMessage());
}
}
@Override
public void update(Object r) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<GenericEntity> getAll(GenericEntity entity) throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
List<GenericEntity> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ")
.append(entity.getTableName());
String query = sb.toString();
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
entity.setValues(rs);
list.add(entity);
System.out.println(entity.toString());
}
rs.close();
statement.close();
return list;
} catch (SQLException ex) {
Logger.getLogger(RepositoryDBRider.class.getName()).log(Level.SEVERE, null, ex);
throw new Exception();
}
}
}
<file_sep>/src/rs/ac/bg/fon/ps/operation/team/DeleteTeam.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.operation.team;
import rs.ac.bg.fon.ps.operation.rider.*;
import rs.ac.bg.fon.ps.domain.RacingTeam;
import rs.ac.bg.fon.ps.operation.AbstractGenericOperation;
/**
*
* @author Matija
*/
public class DeleteTeam extends AbstractGenericOperation{
@Override
protected void preconditions(Object param) throws Exception {
}
@Override
protected void executeOperation(Object param) throws Exception {
repository.delete((RacingTeam) param);
}
}
<file_sep>/src/rs/ac/bg/fon/ps/repository/db/impl/RepositoryDBTeam.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.repository.db.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import rs.ac.bg.fon.ps.domain.MotorcycleMake;
import rs.ac.bg.fon.ps.domain.RaceItem;
import rs.ac.bg.fon.ps.domain.RacingTeam;
import rs.ac.bg.fon.ps.domain.Rider;
import rs.ac.bg.fon.ps.repository.db.DBConnectionFactory;
import rs.ac.bg.fon.ps.repository.db.DBRepository;
/**
*
* @author Matija
*/
public class RepositoryDBTeam implements DBRepository<RacingTeam> {
@Override
public List<RacingTeam> getAll() throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
List<RacingTeam> teams = new ArrayList<>();
String sql = "SELECT * FROM team";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
RacingTeam team = new RacingTeam();
team.setId(rs.getInt("id"));
team.setBudget(rs.getDouble("budget"));
team.setGeneralManager(rs.getString("generalmanager"));
team.setHeadquarters(rs.getString("headquarters"));
team.setName(rs.getString("name"));
team.setSponsor(rs.getString("sponsor"));
teams.add(team);
}
rs.close();
statement.close();
return teams;
} catch (SQLException ex) {
Logger.getLogger(RepositoryDBRider.class.getName()).log(Level.SEVERE, null, ex);
throw new Exception();
}
}
@Override
public void add(RacingTeam team) throws Exception {
try {
Connection conn = DBConnectionFactory.getInstance().getConnection();
String sql = "insert into team values (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, team.getId());
ps.setString(2, team.getSponsor());
ps.setDouble(3, team.getBudget());
ps.setString(4, team.getName());
ps.setString(5, team.getGeneralManager());
ps.setString(6, team.getHeadquarters());
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
throw new Exception("Team could not be created!");
}
}
@Override
public void edit(RacingTeam r) throws Exception {
try {
String sql = "UPDATE team SET "
+ "sponsor='" + r.getSponsor() + "', "
+ "budget='" + r.getBudget() + "', "
+ "name='" + r.getName() + "',"
+ "generalmanager='" + r.getGeneralManager() + "',"
+ "headquarters='" + r.getHeadquarters() + "', "
+"updated_on='"+new java.sql.Timestamp(new java.util.Date().getTime())+"' "
+ "WHERE id=" + r.getId();
System.out.println(sql);
Connection connection = DBConnectionFactory.getInstance().getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("Update team DB error: \n" + ex.getMessage());
}
}
@Override
public void delete(RacingTeam r) throws Exception {
try {
Connection connection = DBConnectionFactory.getInstance().getConnection();
String sql = "DELETE FROM race_item where teamid = "+r.getId();
System.out.println(sql);
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
sql = "DELETE FROM team WHERE id=" + r.getId();
System.out.println(sql);
statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("Delete team DB error: \n" + ex.getMessage());
}
}
@Override
public List<RacingTeam> getByCriteria(Object criteria) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void update(Object r) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<RacingTeam> getAll(RacingTeam param) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 2e138e7d39dd8a26685666f9ed564bd60ad656fb | [
"Java"
] | 7 | Java | matijabk4/TrackDataServer | 3b73625e0f25aff83644eeda0582ced606059f02 | c65ddcdc0ebd85c064019c3c5b2fcd6afb1ccd20 |
refs/heads/master | <file_sep># VTOP-Web-Scraping
The project aims at developing an automated software system that can extract various information from VIT's student/faculty portal using Python 3.
<file_sep>import os, datetime, re, exam_schedule, platform, shutil, time, logging
#set up log configuration to log download records
logging.basicConfig(filename = 'log/downloadlog.txt', level = logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s')
def find_dir_name():
date_re_str = r'(\d{2})-([A-Za-z]{3})-(\d{4})'
date_re = re.compile(date_re_str)
mo = date_re.search(lecture_date)
lecture_date = datetime.datetime(int(mo.group(3)),int(exam_schedule.monthname_monthnum[mo.group(2)]),int(mo.group(1)))
if exam_schedule.exam_schedule['CAT-1_end'] >= lecture_date:
return 'CAT-1'
elif exam_schedule.exam_schedule['CAT-1_end'] < lecture_date and exam_schedule.exam_schedule['CAT-2_end'] >= lecture_date:
return 'CAT-2'
else:
return 'FAT'
def find_download_dir():
if platform.system() == 'Windows':
download_dir = 'C:\\VTOP_Course_Materials'
elif platform.system() == 'Linux':
download_dir = os.environ['HOME'] + '/VTOP_Course_Materials'
return download_dir
def download_files(browser, dir_name, download_links):
root_dir_name = browser.find_element_by_css_selector('#CoursePageLectureDetail > div > div.panel-body > div:nth-child(1) > div > table > tbody > tr:nth-child(2) > td:nth-child(2)').text
logging.debug('Course name: ' + root_dir_name)
download_dir = find_download_dir()
print('Download directory: ' + download_dir)
if not os.path.isdir(download_dir):
os.mkdir(download_dir)
os.chdir(download_dir)
if not os.path.isdir(root_dir_name):
os.mkdir(root_dir_name)
if not os.path.isdir('temp'):
os.mkdir('temp')
os.chdir(root_dir_name)
faculty_name = browser.find_element_by_css_selector('#CoursePageLectureDetail > div > div.panel-body > div:nth-child(1) > div > table > tbody > tr:nth-child(2) > td:nth-child(6)').text
faculty_name = (faculty_name.split(' - '))[1]
logging.debug('Faculty name: ' + faculty_name)
if not os.path.isdir(faculty_name):
os.mkdir(faculty_name)
os.chdir(faculty_name)
if not os.path.isdir(dir_name):
os.mkdir(dir_name)
else:
print('Files already downloaded.')
logging.debug('Files were already downloaded')
return
os.chdir(os.path.join(download_dir, 'temp'))
#Download and save and rename the file in temp directory synchronously, ie, wait for one file to complete download before starting the next
for k, v in download_links.items(): # v is a list
counter_append = 0
if len(v) > 1:
logging.debug(k + ': ' + str(len(v)) + ' files')
for link in v:
counter_append += 1
intuitive_file_name = k + '_' + str(counter_append)
browser.get(link)
time.sleep(2)
while True:
download_file_name = (os.listdir())[0]
filename, extension = os.path.splitext(download_file_name) # if download is done before this line is executed, then extension will be ppt or pdf, else it will be crdownload
# if download was done, download_ext will be empty str, else it will be pdf or ppt
if extension != '.crdownload': # and not download_ext: # download is complete
shutil.move(filename+extension, intuitive_file_name)
shutil.move(intuitive_file_name, os.path.join(download_dir, root_dir_name, faculty_name, dir_name))
logging.debug('File ' + str(counter_append) + ' downloaded.')
break
else:
continue
else:
counter = 1
for link in v:
intuitive_file_name = k
# if intuitive_file_name == '':
# intuitive_file_name = 'file' + str(counter)
# counter += 1
# browser.switch_to_window(browser.window_handles[0])
logging.debug(intuitive_file_name + ': 1 file')
browser.get(link)
time.sleep(2)
# browser.switch_to_window(browser.window_handles[1])
while True:
download_file_name = (os.listdir())[0]
filename, extension = os.path.splitext(download_file_name) # if download is done before this line is executed, then extension will be ppt or pdf, else it will be crdownload
# if download was done, download_ext will be empty str, else it will be pdf or ppt
if extension != '.crdownload':# and (download_ext == 'pdf' or 'ppt' in download_ext or 'doc' in download_ext): # download is complete
shutil.move(filename+extension, intuitive_file_name)
shutil.move(intuitive_file_name, os.path.join(download_dir, root_dir_name, faculty_name, dir_name))
logging.debug('1 file downloaded.')
break
else:
continue
def download_course_materials(browser):
print('Hold your seat, your files are downloading...')
rows_in_ref_material_table = browser.find_elements_by_css_selector('#CoursePageLectureDetail > div > div.panel-body > div:nth-child(3) > div:nth-child(2) > div > table > tbody > tr')
logging.debug('Number of rows in the course table originally: ' + str(len(rows_in_ref_material_table)))
now = datetime.datetime.now()
today_date = datetime.datetime(now.year, now.month, now.day)
date_re_str = r'(\d{2})-([A-Za-z]{3})-(\d{4})'
date_re = re.compile(date_re_str)
#Finding the most recent exam that got finished
any_exam_done = False
today_date = datetime.datetime(2018,1,29)
if exam_schedule.exam_schedule['CAT-1_end'] < today_date:
exam_done = 'CAT-1' # ie, download after lecture dates that fall in CAT-1 period, or do not download CAT-1 files
exam_done_end_date = exam_schedule.exam_schedule[exam_done +'_end']
# print(exam_done_end_date)
any_exam_done = True
if exam_schedule.exam_schedule['CAT-2_end'] < today_date:
exam_done = 'CAT-2' # downlaod after lecture dates that fall in CAT-1 and CAT-2 period
exam_done_end_date = exam_schedule.exam_schedule[exam_done +'_end']
# print(exam_done_end_date)
any_exam_done = True
if any_exam_done == False:
exam_done = 'none'
exam_done_end_date = datetime.datetime(1,1,1) # smaller than any other date in the recent
# Remove those rows whose lecture_date < end date of exam that has alrady been conducted
initial_row_num = len(rows_in_ref_material_table)
updated_row_num = initial_row_num
#NOTE: while it may appear that using two nested loop (while-for) is not required for removing elements from the
#NOTE contd..: list rows_in_ref_material_table and that it can be done with the single for loop similar to the inner for loop, it cannot be actually. Because
#NOTE contd..: for remove method removes item and then does a left shift as well, so for eg, l = [1,2,3,4,5] for i in l: l.remove(i) will actually remove the objects
#NOTE contd..: 1,3,5 not all the objects of the list. Same happens in the indexed loop used in association with range function.
not_done = True
while not_done:
for i in range(1, initial_row_num):
if i >= updated_row_num:
not_done = False
break
cells = rows_in_ref_material_table[i].find_elements_by_css_selector('td')
lecture_date = cells[1].text
# print(lecture_date)
mo = date_re.search(lecture_date)
lecture_date = datetime.datetime(int(mo.group(3)),int(exam_schedule.monthname_monthnum[mo.group(2)]),int(mo.group(1)))
# print(lecture_date)
if exam_done_end_date > lecture_date:
logging.debug('Row topic to be deleted: ' + cells[3].text + ' | ' + 'Row lecture date to be deleted: ' + cells[1].text)
rows_in_ref_material_table.remove(rows_in_ref_material_table[i])
updated_row_num -= 1
break
logging.debug('Number of rows after removing irrelevant rows: ' + str(len(rows_in_ref_material_table)))
# Accumulate the download links for the reference materials
download_links = {}
removed_dates = []
for i in range(1, len(rows_in_ref_material_table)):
cells = rows_in_ref_material_table[i].find_elements_by_css_selector('td')
anchor_tags = cells[len(cells)-1].find_elements_by_css_selector('p a')
if len(anchor_tags) == 0:
removed_dates.append(cells[1].text)
continue
else:
logging.debug('Files uploaded on ' + cells[1].text + ' ' + str(anchor_tags))
key = cells[3].text
if key == '':
key = cells[1].text
download_links[key] = []
for anchor_tag in anchor_tags:
href = anchor_tag.get_attribute('href')
download_link = href
download_links[key].append(download_link)
if exam_done == 'CAT-1':
dir_name = 'CAT-2'
elif exam_done == 'CAT-2':
dir_name = 'FAT'
else:
dir_name = 'CAT-1'
logging.debug('Dates which had no reference materials uploaded against them and got removed: ' + str(removed_dates))
logging.debug('Filtered download links dictionary: ' + str(download_links))
download_files(browser, dir_name, download_links)
print('Download finished!')
<file_sep># Make the imports
import requests, sys, pytesseract, base64, getpass, datetime, time, threading, platform, os, argparse, shelve, logging
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchWindowException
from selenium.webdriver.support.ui import Select
from PIL import Image
from parser import CaptchaParse
from source_of_functions import *
print(
'''
How to execute:
new user login--- 1. if user doesn't want his username/password to be saved python automate_vtop.py -n
2. 1. if user wants his username/password to be saved python automate_vtop.py -n -s
login with saved credentials: python automate_vtop.py
Make sure you used the appropriate way to execute the script, if not, press "CTRL+C" now to exit and retry running the program.
'''
)
#Set up log settings
logging.basicConfig(filename = 'log/downloadlog.txt', level = logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s')
log_file = open('log/downloadlog.txt','w')
log_file.close()
#1. Parse the arguments
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--newuser', help= 'Give this option if you are logging in for the first time or \
you want to login into a new account.', action = 'store_true')
parser.add_argument('-s', '--savecredentials', help = 'Give this option to save the username and password you entered.', action = 'store_true')
args = parser.parse_args()
#2. Read registration number, password and semester from user-inputs if this is first time login or new login
# and also shelve the credentials
if args.newuser and args.savecredentials:
registration_num = input('Enter registration number: ')
password = <PASSWORD>('Enter password: ')
if registration_num == '' or password == '':
print('None of registration number, password can be left empty.')
logging.debug('Registration number/password not entered correctly. Attempted with -ns options')
sys.exit()
shelf_file = shelve.open('./shelf/shelf_file')
shelf_file['registration_num'] = registration_num
shelf_file['password'] = <PASSWORD>
shelf_file.close()
print('** make sure you enter correct registration number and password **')
if args.newuser and not args.savecredentials:
registration_num = input('Enter registration number: ')
password = <PASSWORD>('Enter password: ')
if registration_num == '' or password == '':
print('None of registration number, password, semester fields can be left empty.')
logging.debug('None of registration number, password can be left empty. Attempted with -n option')
sys.exit()
#it is a plausible case that a user will choose to save credentials but is not using new credentials becase the plan is to ask
# the user for new credentials only, ie, args.savecredentials and not args.newuser is being dropped to code for
if not args.newuser and not args.savecredentials:
if not os.path.isfile('./shelf/shelf_file.dat'):
print('No saved credentials. Try again with -n option to login as a new user. You can use -s option with -n to save the credentials entered.')
logging.debug('Did not run the script either with -n or -s options and no credentials have been saved before')
sys.exit()
try:
shelf_file = shelve.open('./shelf/shelf_file')
registration_num = shelf_file['registration_num']
password = shelf_file['password']
shelf_file.close()
except:
pass
today = datetime.datetime.now()
print('Attempting to log you in...')
#3. Open a controllable browser using Selenium webdriver module with a custom download directory
chrome_options = webdriver.ChromeOptions()
download_dir = find_download_dir()
prefs = {'download.default_directory': download_dir + '/temp'}
chrome_options.add_experimental_option('prefs', prefs)
chromedriver = './chromedriver'
browser = webdriver.Chrome(executable_path=chromedriver, chrome_options = chrome_options)
browser.maximize_window()
#4. Create wait object
waiting = WebDriverWait(browser,300)
#5. Open vtop home page
try:
try:
browser.get('http://vtop.vit.ac.in')
except:
print('Check your internet connection!')
sys.exit()
#6. Find the link to the vtopbeta page
try:
vtopbeta_elem = browser.find_element_by_css_selector('a[href = "https://vtopbeta.vit.ac.in/vtop"] font b')
# print('Found element that href\'s to vtopbeta')
except:
print('Unexpected error: failed to load the page. Please retry')
logging.debug('No element with attribute value a[href="https://vtopbeta.vit.ac.in/vtop"] was found')
sys.exit()
#7. Open vtopbeta
browser.get(vtopbeta_elem.text)
#8. Find the link to login page on vtopbeta captcha_img_elem and click on the elem to open the next page, ie, the login page
try:
login_page_link_elem = browser.find_element_by_css_selector('.btn.btn-primary.pull-right')
# print('Found element that href\'s to the login page')
except NoSuchElementException:
print('Unexpected error: Unable to open vtopbeta page properly. Please retry')
logging.debug('Check the css selector for the button leading to the login page: ' + str(err))
sys.exit()
login_page_link_elem.click()
waiting.until(lambda browser: len(browser.window_handles) == 2)
browser.switch_to_window(browser.window_handles[1])
#9. From the login page, find the input elements (uname and pwd boxes and captcha box)
try:
waiting.until(EC.presence_of_element_located((By.ID, 'captchaCheck')))
username_elem = browser.find_element_by_css_selector('#uname')
password_elem = browser.find_element_by_css_selector('#passwd')
captcha_elem = browser.find_element_by_css_selector('#captchaCheck')
captcha_img_elem = browser.find_element_by_css_selector('img[alt = "vtopCaptcha"]')
except NoSuchElementException as err:
print('Unexpected error: Failed to load the login page properly. Please retry')
logging.debug('Input elements with the given css selectors were not found: ' + err)
sys.exit()
#10. Find the image source of the captcha image
captcha_img_src = captcha_img_elem.get_attribute('src')
#11. Extract the base64 stribg of the captcha image from the captcha_img_src
base64_img = captcha_img_src[22:]
#12. Save the captcha image
captcha_img = open('./captcha_save/captcha.png','wb')
captcha_img.write(base64.b64decode(base64_img))
captcha_img.close()
#13. Convert the image into string
img = Image.open('./captcha_save/captcha.png')
captcha_str = CaptchaParse(img)
#14. Fill in login details
username_elem.send_keys(registration_num)
password_elem.send_keys(<PASSWORD>)
captcha_elem.send_keys(captcha_str)
#15. Sign in
# note: the form doesn't have a submit button, the sign in button is not the submit button
# so maybe that is why using submit method on form elements leads to a page that doesn't exist
signin_button = browser.find_element_by_css_selector('.btn.btn-primary.pull-right')
signin_button.click()
#16. Handle wrong reg/pwd inputs
try:
WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.user-image')))
except:
print('Wrong registration number/password')
logging.debug('Wrong user credentials')
sys.exit()
#TODO: scrapped the profile to obtain different informations- time table of currrent day, for eg
#17. Open the menu on the left using the toggle hamburger button- first find the button and then click
try:
waiting.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a[role = "button"]')))
except:
print('VTOP taking too long to respond!')
logging.debug('VTOP server taking too long to respond')
sys.exit()
hamburger_elem = browser.find_element_by_css_selector('a[role = "button"]')
hamburger_elem.click()
#18. Find the Academics option in the left menu and lick on it
academics_elem = browser.find_element_by_css_selector('#dbMenu ul.sidebar-menu.tree>li:nth-child(2)')
academics_elem.click()
#19. Get the time table element and click on it
waiting.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#dbMenu ul.sidebar-menu.tree>li:nth-child(2) li:nth-child(2)>a span')))
coursepage_elem = browser.find_element_by_css_selector('#dbMenu ul.sidebar-menu.tree>li:nth-child(2) li:nth-child(5)>a span')
coursepage_elem.click()
hamburger_elem.click()
#20. Let the user select semester name and course from the page manually
print('Choose Semester Name and Course from the dropdown on the page.')
waiting.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.table')))
js = '''
window.filterTable = function() {
var faculty_name = document.getElementById('faculty').value
console.log("hahaha");
var all_rows = Array.prototype.slice.call(document.querySelectorAll('tbody tr'));
all_rows = all_rows.slice(1,);
console.log('hahahah2');
for(var i = 0; i < all_rows.length; i++) {
var all_tds = Array.prototype.slice.call(all_rows[i].querySelectorAll("td"));
var td_faculty_name = (all_tds[6].textContent.split(' - '))[1];
if(td_faculty_name.includes(faculty_name.toUpperCase())) {
console.log('hahahah3');
all_rows[i].style.display = "";
continue;
}
else {
console.log('hahaha4');
all_rows[i].style.display = "none";
}
};
document.body.setAttribute("faculty_name", faculty_name);
}
document.getElementById('getSlotIdForCoursePage').style.display = 'none';
document.querySelector('#getFacultyForCoursePage label').outerHTML = '<font color= "red">' + document.querySelector('#getFacultyForCoursePage label').outerHTML + '</font>'
var faculty_selector_parent = document.getElementById('faculty').parentNode
faculty_selector_parent.innerHTML = "<input placeholder = 'Enter name of the faculty' onkeyup = 'filterTable()' class = 'form-control' id = 'faculty'>";
'''
browser.execute_script(js)
js = '''
window.filterTable = function() {
var faculty_name = document.getElementById('faculty').value;
console.log("hahaha");
var all_rows = Array.prototype.slice.call(document.querySelectorAll('tbody tr'));
all_rows = all_rows.slice(1,);
console.log('hahahah2');
for(var i = 0; i < all_rows.length; i++) {
var all_tds = Array.prototype.slice.call(all_rows[i].querySelectorAll("td"));
var td_faculty_name = (all_tds[6].textContent.split(' - '))[1];
if(td_faculty_name.includes(faculty_name.toUpperCase())) {
console.log('hahahah3');
all_rows[i].style.display = "";
continue;
}
else {
console.log('hahaha4');
all_rows[i].style.display = "none";
}
}
document.body.setAttribute("faculty_name", faculty_name);
};
document.getElementById('courseCode').onchange = function() {
getSlotIdForCoursePage('courseCode','getSlotIdForCoursePage','source');
setTimeout(function() {
document.getElementById('getSlotIdForCoursePage').style.display = 'none';
document.querySelector('#getFacultyForCoursePage label').outerHTML = '<font color= "red">' + document.querySelector('#getFacultyForCoursePage label').outerHTML + '</font>';
var faculty_selector_parent = document.getElementById('faculty').parentNode;
faculty_selector_parent.innerHTML = "<input placeholder = 'Enter name of the faculty' onkeyup = 'filterTable()' class = 'form-control' id = 'faculty'>";
}, 3500);
};
'''
js2 = '''
alert('Download for the exam to follow completed, PRESS OK and go to the command prompt/terminal to continue/quit. ');
'''
def find_download_element():
try:
time.sleep(1) # sleep so that the course material gets loaded by then if the button to view the page is clicked
course_plan_download_elem = browser.find_element_by_css_selector('a[href="/vtop/academics/common/coursePlanReport/"]')
# print('False')
return False
except NoSuchElementException:
# print('True')
return True
#21. Create download thread, complete a download and then take user response whether or not the user wants to download more files
while True:
while find_download_element():
browser.execute_script(js)
downloader_thread = threading.Thread(target = download_course_materials, args = [browser])
downloader_thread.start()
downloader_thread.join()
browser.execute_script(js2)
resp = input('Do you want to download for other courses?(y or n) ')
resp = resp.lower()
if resp == 'y' or resp == 'yes':
back_btn = browser.find_element_by_css_selector('#back')
back_btn.click()
waiting.until(EC.presence_of_element_located((By.ID, 'semesterSubId')))
print('Choose Semester Name and Course from the dropdown on the page.')
continue
else:
browser.quit()
except NoSuchWindowException:
print('Either the browser is closed or the Authorization failed! Do comeback!')
logging.debug('Browser closed/Authorization failed')
<file_sep>import datetime
exam_schedule = {
'CAT-1_end': datetime.datetime(2018,1,28),
'CAT-2_end': datetime.datetime(2018,3,11),
#dates after CAT-2_end will be considered for FAT
}
monthname_monthnum = {
'Jan': '01',
'Feb': '02',
'Mar': '03',
'Apr': '04',
'May': '05',
'Jul': '07',
'Aug': '08',
'Sep': '09',
'Oct': '10',
'Nov': '11',
'Dec': '12',
}
<file_sep># VtopBeta Auto Login
Parses the captcha in <vtopbeta.vit.ac.in>
Following is how you can run the scraping script:
python scrap_vtop.py `<registration number>` `<password>`
| 2f3b656d9a45bb38dd418a0631bb9d39e2fc7873 | [
"Markdown",
"Python"
] | 5 | Markdown | krishnakrmahto/VTOP-Web-Scraping-completed | 7fb3aadd98d7fab2b9839454cabb6bcf4c00b8da | 5b94f4c5cc35b25d838f684468b6d6418e93a047 |
refs/heads/main | <repo_name>kevinesg/neural-network-from-scratch<file_sep>/predict_MNIST.py
from nn import NeuralNetwork
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
data_df = pd.read_csv('train.csv')
data = np.array(data_df)
y = data[:, 0]
y = y.reshape(y.shape[0], 1)
X = data[:, 1:] / 255
y = LabelBinarizer().fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2
)
print('[INFO] training network...')
nn = NeuralNetwork([X_train.shape[1], 512, 100, 10])
print(f'[INFO] {nn}')
nn.fit(X_train, y_train, batch_size=32, epochs=100, verbose=1)
print('[INFO] evaluating network...')
preds = nn.predict(X_test)
preds = preds.argmax(axis=1)
print(classification_report(y_test.argmax(axis=1), preds))<file_sep>/predict_mini_MNIST.py
from nn import NeuralNetwork
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn import datasets
print('[INFO] loading MNIST (sample) dataset...')
# 8x8 pixels MNIST dataset images
digits = datasets.load_digits()
data = digits.data.astype('float')
data = (data - data.min()) / (data.max() - data.min())
labels = LabelBinarizer().fit_transform(digits.target)
X_train, X_test, y_train, y_test = train_test_split(
data, labels, test_size=0.25
)
print('[INFO] training network...')
nn = NeuralNetwork([X_train.shape[1], 64, 32, 10])
print(f'[INFO] {nn}')
nn.fit(X_train, y_train, batch_size=8, epochs=1000)
print('[INFO] evaluating network...')
preds = nn.predict(X_test)
preds = preds.argmax(axis=1)
print(classification_report(y_test.argmax(axis=1), preds))<file_sep>/README.md
# Neural Network from scratch
The neural network can be found at `nn.py`. The tunable hyperparameters are number of layers, number of nodes of each layer, learning rate, batch size, and choice between `mean squared error` and `binary crossentropy` as the loss function. The activation function of all layers is sigmoid. I plan on adding more loss functions and activation functions as well.
The neural network can be used to train and predict XOR values. `predict_xor.py` can be used to check this. `predict_mini_MNIST.py` trains a "mini" version of the MNIST dataset (8x8 pixels and less sample size). `predict_MNIST.py` on the other hand uses the whole training set from Kaggle. Both datasets can achieve 99% validation set accuracy in less than 100 epochs.
The neural network architecture is heavily inspired by the book `Deep Learning for Computer Vision` by <NAME>. In fact, majority of the code came from there but I changed some lines and added batch training and categorical crossentropy loss, as compared to the original architecture which trains the dataset one sample at a time and the only loss function is sum of squared error.
#
If you have any questions or suggestions, feel free to contact me here. Thanks for reading!
<file_sep>/nn.py
import numpy as np
class NeuralNetwork:
# Initialize weight matrix, layers dimensions, and learning rate
def __init__(self, layers, lr=0.1):
self.W = []
self.layers = layers # List of number of nodes per layer
self.lr = lr
for i in range(0, len(layers) - 2):
w = np.random.randn(layers[i] + 1, layers[i + 1] + 1)
# Normalize the weights depending on the number of nodes per layer
self.W.append(w / np.sqrt(layers[i]))
# Last layer (no need to add bias)
w = np.random.randn(layers[-2] + 1, layers[-1])
# Normalize
self.W.append(w / np.sqrt(layers[-1]))
def __repr__(self):
return f'NeuralNetwork: {"-".join(str(l) for l in self.layers)}'
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
# Input x should be the output of the sigmoid function
def sigmoid_deriv(self, x):
return x * (1 - x)
def fit(self, X, y, batch_size=1, epochs=1000, verbose=100):
# Add bias
X = np.hstack([X, np.ones((X.shape[0], 1))])
# Generate and randomize indexes for batch training
indexes = np.arange(X.shape[0])
for epoch in range(0, epochs):
np.random.shuffle(indexes)
for i in range(0, X.shape[0], batch_size):
batch_indexes = indexes[i:i + batch_size]
X_batch = X[batch_indexes]
y_batch = y[batch_indexes]
self.fit_partial(X_batch, y_batch)
# Print updates about loss and accuracy
if epoch == 0 or (epoch + 1) % verbose == 0:
loss = self.calculate_loss(X, y, loss='binary_crossentropy')
acc = self.calculate_accuracy(X, y)
print(f'[INFO] epoch={epoch + 1}, loss={loss:.7f}, acc={acc:.4f}')
def fit_partial(self, x, y):
A = [np.atleast_2d(x)]
# Feedforward
for layer in range(0, len(self.W)):
raw = A[layer].dot(self.W[layer])
activated = self.sigmoid(raw)
A.append(activated)
# Compute gradients
error = y - A[-1]
D = [error * self.sigmoid_deriv(A[-1])]
for layer in range(len(A) - 2, 0, -1):
delta = D[-1].dot(self.W[layer].T)
delta = delta * self.sigmoid_deriv(A[layer])
D.append(delta)
# Reverse the gradients list since we constructed it backwards
D = D[::-1]
# Adjust weights
for layer in range(0, len(self.W)):
self.W[layer] += self.lr * A[layer].T.dot(D[layer])
def predict(self, X, bias=True):
p = np.atleast_2d(X)
if bias == True:
p = np.hstack([p, np.ones((p.shape[0], 1))])
# Feedforward
for layer in range(0, len(self.W)):
p = self.sigmoid(p.dot(self.W[layer]))
return p
def calculate_loss(self, X, y, loss):
y = np.atleast_2d(y)
preds = self.predict(X, bias=False)
if loss == 'mse':
loss = ((preds - y) ** 2) / X.shape[0]
elif loss == 'binary_crossentropy':
loss = -1 / X.shape[0] * np.sum(y * np.log(preds) + (1 - y) * np.log(1 - preds))
return loss
def calculate_accuracy(self, X, y):
y = np.atleast_2d(y)
preds = self.predict(X, bias=False)
preds = np.argmax(preds, axis=1)
y = np.argmax(y, axis=1)
acc = (preds == y).mean()
return acc<file_sep>/predict_xor.py
from nn import NeuralNetwork
import numpy as np
X = np.array([
[0, 0],
[0, 1],
[1, 0],
[1, 1]
])
y = np.array([
[0],
[1],
[1],
[0]
])
nn = NeuralNetwork([2, 2, 1], lr=0.5)
nn.fit(X, y, batch_size=2, epochs=20000)
for (x, label) in zip(X, y):
pred = nn.predict(x)[0][0]
step = 1 if pred > 0.5 else 0
print(f'[INFO] data={x}, ground truth={label[0]}, pred={pred:.4f}, step={step}') | f8056a7a9e75df55cbfc677634572f3708e9f69b | [
"Markdown",
"Python"
] | 5 | Python | kevinesg/neural-network-from-scratch | 270e87f327b22154c3d0bbd2dd1727537c9d8947 | b279aa9c6968b47bf5175a9698349147c7a943d9 |
refs/heads/master | <file_sep>package dao;
import model.Student;
import java.util.List;
public interface StudentMapper {
Student getStudentById(long id) ;
void addStudent(Student student);
void updateStudent(Student student);
void delete(Student student);
List<Student> listAll();
}
<file_sep>package dao;
import model.Student;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
public interface StudentDao {
//添加方法
public void insert(Student stu)throws SQLException;
//更新方法
public void update(Student stu)throws SQLException;
//删除方法
public void delete(long id)throws SQLException;
//查找方法
public Student FindById(long id)throws SQLException;
//查找所有
public List<Student> FindAll()throws SQLException;
}
<file_sep>jdbc.url=jdbc:mysql://localhost:3306/studnet?useSSL=false&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=
jdbc.driver=com.mysql.jdbc.Driver<file_sep>jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost/studnet?characterEncoding=utf-8&autoReconnect=true
jdbc.username = root
jdbc.password =<file_sep>package model;
public class Student {
private long id ;
private String name;
private String major;
private String school_id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getSchool_id() {
return school_id;
}
public void setSchool_id(String school_id) {
this.school_id = school_id;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", major='" + major + '\'' +
", school_id='" + school_id + '\'' +
'}';
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<name>mysql</name>
<groupId>com.jnshu</groupId>
<artifactId>mysql</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.10.v20160621</version>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
<dependencies>
<!-- 依赖包集合 -->
<!--junit3.0使用编程方式运行,junit4.0使用注解方式运行 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!--使用范围 -->
<scope>test</scope>
</dependency>
<!--<!– pageHelper分页依赖包 –>-->
<!--<dependency>-->
<!--<groupId>com.github.pagehelper</groupId>-->
<!--<artifactId>pagehelper</artifactId>-->
<!--<version>4.0.1</version>-->
<!--</dependency>-->
<!--<!–json依赖包 –>-->
<!--<dependency>-->
<!--<groupId>net.sf.json-lib</groupId>-->
<!--<artifactId>json-lib-ext-spring</artifactId>-->
<!--<version>1.0.2</version>-->
<!--</dependency>-->
<!--1.志相关依赖 -->
<!--slf4j规范接口 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta1</version>
</dependency>
<!--logback日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--实现slf4j接口并整合-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.6</version>
</dependency>
<!--2. 数据库相关依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
<scope>runtime</scope>
</dependency>
<!-- 阿里druid数据源,优化数据库操作 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<!--3. DAO框架:Mybatis依赖-->
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--spring只针对ibatis做了依赖,所以mybatis自身实现的spring整合依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--Servlet web相关依赖-->
<!--jsp相关依赖 -->
<!--<dependency>-->
<!--<groupId>taglibs</groupId>-->
<!--<artifactId>standard</artifactId>-->
<!--<version>1.1.2</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>jstl</groupId>-->
<!--<artifactId>jstl</artifactId>-->
<!--<version>1.2</version>-->
<!--</dependency>-->
<!--<!–jackson相关依赖 –>-->
<!--<dependency>-->
<!--<groupId>com.fasterxml.jackson.core</groupId>-->
<!--<artifactId>jackson-databind</artifactId>-->
<!--<version>2.5.4</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>javax.servlet-api</artifactId>-->
<!--<version>3.1.0</version>-->
<!--</dependency>-->
<!--4. spring依赖-->
<!--1)spring核心依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<!--spring ioc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<!--spring 扩展依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<!--2)spring dao层依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<!--3)spring web相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<!--4) spring test相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-beta1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.5.6</version>
</dependency><dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.6</version>
</dependency>
</dependencies>
</project>
<file_sep>package Impl;
import dao.StudentDao;
import model.Student;
import org.junit.Test;
import java.sql.SQLException;
import java.util.List;
import static org.junit.Assert.*;
public class StudentImplTest {
@Test
public void insert() throws SQLException {
StudentDao dao = new StudentImpl();
dao.insert(new Student("赵伟鹏", "JAVA", "JAVA-5551"));
}
@Test
public void update() throws SQLException {
StudentDao dao = new StudentImpl();
dao.update(new Student("田媛", "WEB", "WEB-5421", 2));
}
@Test
public void delete() throws SQLException {
StudentDao dao = new StudentImpl();
dao.delete(1);
}
@Test
public void FindById() throws SQLException {
StudentDao dao = new StudentImpl();
Student stu = dao.FindById(3);
System.out.println(stu);
}
@Test
public void FindAll() throws SQLException {
StudentDao dao = new StudentImpl();
List<Student> students = dao.FindAll();
System.out.println(students);
}
}<file_sep>package service;
import dao.StudentsDao;
import model.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class StudentServiceTest {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src\\main\\java\\app.xml");
StudentService studentService = (StudentService) applicationContext.getBean("StudentService");
@org.junit.Test
public void insert() {
Student student = new Student();
student.setName("赵伟鹏");
student.setMajor("JAVA");
student.setSchool_id("JAVA1234");
studentService.insert(student);
}
@org.junit.Test
public void update() {
Student student = new Student();
student.setName("田媛");
student.setId(11);
studentService.update(student);
}
@org.junit.Test
public void delete() {
Student student = new Student();
student.setId(14);
studentService.delete(student);
}
@org.junit.Test
public void findAll() {
List<Student> students = studentService.findAll();
System.out.println(students);
}
}<file_sep>package mapper;
//import model.Student;
import model.Teacher;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface TeacherMapper {
@Select(" select * from teacher ")
@Results({
@Result(property="student",column="id",one=@One(select="mapper.StudentMapper.get"))
})
public List<Teacher> list();
@Insert(" insert into teacher ( name ) values (#{name}) ")
public long add(Teacher teacher);
@Delete(" delete from teacher where id= #{id} ")
public void delete(long id);
@Select("select * from teacher where id= #{id} ")
public Teacher get(long id);
@Update("update teacher set name=#{name} where id=#{id} ")
public int update(Teacher teacher);
}
<file_sep>package dao;
import model.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class StudentsDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void insert(Student student) {
String sql = "insert into students (name, major,school_id,create_time,update_time) values (?,?,?,now(),sysdate())";
jdbcTemplate.update(sql, student.getName(), student.getMajor(),student.getSchool_id());
}
public void update(Student student) {
String sql = "update students set name = ? where id =?";
jdbcTemplate.update(sql, student.getName(), student.getId());
}
public void delete(Student student) {
String sql = "delete from students where id =?";
jdbcTemplate.update(sql,student.getId());
}
public List<Student> findAll(){
String sql = "SELECT * FROM students";
List<Student> students = getJdbcTemplate().query(sql, new BeanPropertyRowMapper(Student.class));
return students;
}
// public List<Student> findById(){
// Student a = new Student();
// String sql = "SELECT * FROM students where id =?";
//
// List<Student> students = getJdbcTemplate().query(sql, new BeanPropertyRowMapper(Student.class),a.getId());
//
// return students;
// }
}<file_sep>package model;
import org.springframework.beans.factory.annotation.Autowired;
public class Tercher {
private long id;
private String name;
private int age;
@Autowired
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
<file_sep>user=root
password=
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/studnet?useSSL=false&characterEncoding=UTF-8
initPoolSize = 5
maxPoolSize = 10 | 7404c0ddafd64daae74b7589eb8973654c8be58b | [
"Java",
"Maven POM",
"INI"
] | 12 | Java | ptteng/ZWPtest1 | ef5d1f7d88fa1d262926b5cddf674f0421eabaab | ee36d2c715401249023225e6aeb8b01c183bcc05 |
refs/heads/master | <file_sep>angular.module('sfi-app.services', [])
.factory('Clips', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var clips = [
{
id: 'one',
title: 'Rain',
artist: 'Drake',
url: 'http://www.schillmania.com/projects/soundmanager2/demo/_mp3/rain.mp3'
},
{
id: 'two',
title: 'Walking',
artist: '<NAME>',
url: 'http://www.schillmania.com/projects/soundmanager2/demo/_mp3/walking.mp3'
},
{
id: 'three',
title: 'Barrlping with Carl (featureblend.com)',
artist: 'Akon',
url: 'http://www.freshly-ground.com/misc/music/carl-3-barlp.mp3'
},
{
id: 'four',
title: 'Angry cow sound?',
artist: 'A Cow',
url: 'http://www.freshly-ground.com/data/audio/binaural/Mak.mp3'
},
{
id: 'five',
title: 'Things that open, close and roll',
artist: 'Someone',
url: 'http://www.freshly-ground.com/data/audio/binaural/Things%20that%20open,%20close%20and%20roll.mp3'
}
];
return {
all: function() {
return clips;
},
remove: function(clip) {
clips.splice(clips.indexOf(clip), 1);
},
get: function(clipId) {
for (var i = 0; i < clips.length; i++) {
if (clips[i]._id === parseInt(clipId)) {
return clips[i];
}
}
return null;
}
};
});
<file_sep>angular
.module('sfi-app')
.controller('ClipsCtrl', ['$scope', 'Clips',
function($scope, Clips) {
$scope.clips = Clips.all();
$scope.remove = remove;
////////////
function remove (clip) {
Clips.remove(clip);
}
}]);
<file_sep>angular.module('sfi-app', [
'ionic',
'sfi-app.services',
'angularSoundManager'
]);
<file_sep>angular
.module('sfi-app')
.config(config);
function config ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.sounds', {
url: '/sounds',
views: {
'menuContent': {
templateUrl: 'templates/sounds.html'
}
}
})
.state('app.clips', {
url: '/clips',
views: {
'menuContent': {
templateUrl: 'templates/clips.html',
controller: 'ClipsCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/clips');
};
| 41ea7612874b5d8d2b42d2a8a050863ec99032e2 | [
"JavaScript"
] | 4 | JavaScript | strangemodern/sfi-app | 8e94d08113d9b3214e52e0b4541c19e867b370ea | 57cca69a1fce2da69a75fe420d1059de6423ac84 |
refs/heads/master | <repo_name>webavant/dotfiles<file_sep>/bin/makepatch.sh
#! /bin/sh
pkgver=;pkgname=;eval `cat ../PKGBUILD | sed -e "s/\(pkgver=\S*\)/\1/p" -e "s/\(pkgname=\S*\)/\1/p" -n`
pkg="${pkgname%%-*}-$pkgver"; cd $pkg; echo "building patches for $pkg"; echo
echo "changing directory" `pwd`; echo
declare -a add
declare -a mod
mod=() add=()
for new in `find * -type f`; do
orig="$pkg.orig/$new"
eval diff -rq ../$orig $new >& /dev/null; ret=$?
case "$ret" in
0) ;;
1) mod+=("$new") ;;
2) add+=("$new") ;;
*) echo Unhandled case for $new. Add a case to handle this problem. ;;
esac
done
cd ..
echo "New Files:"; printf '%s\n' ${add[@]}; echo
echo "Modified Files:"; printf '%s\n' ${mod[@]}; echo
echo "changing directory" `pwd`; echo
for (( i=0; $i<${#add[@]}; i+=1 )); do
echo diff -ruN $pkg.orig/${add[$i]} $pkg/${add[$i]} >> patch.txt
diff -ruN $pkg.orig/${add[$i]} $pkg/${add[$i]} >> patch.txt
done
for (( i=0; $i<${#mod[@]}; i+=1 )); do
echo diff -ruN $pkg.orig/${mod[$i]} $pkg/${mod[$i]} >> patch.txt
diff -ruN $pkg.orig/${mod[$i]} $pkg/${mod[$i]} >> patch.txt
done
<file_sep>/README.md
# dotfiles
Nothing much here, for now. Safekeeping, mostly.
| bccaae13297d8c508df19096b2ea437d52ac3b6f | [
"Markdown",
"Shell"
] | 2 | Shell | webavant/dotfiles | 233aebbaa4c3ad64436b1b9fe7a2e3c96fdffb1f | 11e1469e291f34eab35a756171d41548e8cfcbb5 |
refs/heads/main | <repo_name>Siumauricio/Vinculation-Proyect<file_sep>/Frontend.DPI/Frontend/src/app/police-record/police-record.module.ts
import { PoliceRecordDeleteComponent } from './police-record-delete/police-record-delete.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgxPaginationModule } from 'ngx-pagination';
import { ModalModule } from 'ngx-bootstrap/modal';
import { PoliceRecordListComponent } from './police-record-list/police-record-list.component';
import { PoliceRecordCreateComponent } from './police-record-create/police-record-create.component';
import { PoliceRecordRoutingModule } from './police-record-routing.module';
import { PoliceRecordFilterPipe } from './pipes/PoliceRecord-filter.pipe';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { PoliceRecordUpdateComponent } from './police-record-update/police-record-update.component';
@NgModule({
declarations: [
PoliceRecordListComponent,
PoliceRecordCreateComponent,
PoliceRecordDeleteComponent,
PoliceRecordFilterPipe,
PoliceRecordUpdateComponent,
],
imports: [
CommonModule,
PoliceRecordRoutingModule,
FormsModule,
ReactiveFormsModule,
NgxPaginationModule,
ModalModule.forRoot(),
]
})
export class PoliceRecordModule { }
<file_sep>/Frontend.DPI/Frontend/src/app/police-record/police-record-delete/police-record-delete.component.ts
import { PoliceRecordService } from './../police.record.service';
import { PoliceRecord } from './../../criminals/Interfaces/criminal-interface';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { CriminalGroup } from '../../criminals/Interfaces/criminal-interface';
import Swal from 'sweetalert2';
@Component({
selector: 'app-police-record-delete',
templateUrl: './police-record-delete.component.html',
styleUrls: ['./police-record-delete.component.css']
})
export class PoliceRecordDeleteComponent {
policeRecord: PoliceRecord[];
dniCriminal: string;
rolTemporal
userFilterSelected
totalRecords :number;
page:number =1;
constructor(
private criminalService:PoliceRecordService
) { }
async getPoliceRecords(dni: string) {
this.dniCriminal = dni;
console.log(this.policeRecord)
console.log(this.dniCriminal)
await this.criminalService.getPoliceRecordByDNI(dni.trim()).then((resp) => {
this.policeRecord = resp;
console.log(resp)
});
}
//050118090223305
async DeletePoliceRecord(id) {
Swal.fire({
title: '¿Seguro que desea eliminar el usuario?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.criminalService.deletePoliceRecord(id).then(async (resp) => {
if (resp == true) {
this.policeRecord = null;
await this.getPoliceRecords( this.dniCriminal);
}else{
}
});
}
});
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/^[a-zA-Z0-9_ ]*$/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Models/CriminalGroup.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class CriminalGroup
{
public CriminalGroup()
{
CriminalHistories = new HashSet<CriminalHistory>();
}
public int IdCg { get; set; }
public string NombreGrupoCriminal { get; set; }
public virtual ICollection<CriminalHistory> CriminalHistories { get; set; }
}
}
<file_sep>/Backend.DPI/Backend.DPI/Models/Privilege.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class Privilege
{
public Privilege()
{
RolPrivileges = new HashSet<RolPrivilege>();
}
public int IdPrivilege { get; set; }
public string Name { get; set; }
public string TipoPrivilegio { get; set; }
public virtual ICollection<RolPrivilege> RolPrivileges { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/users-routing.module.ts
import { RolDeleteComponent } from './../Roles/rol-delete/rol-delete.component';
import { RolListComponent } from './../Roles/rol-list/rol-list.component';
import { UserDeleteComponent } from './users-crud/user-delete/user-delete.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UpdateUserComponent } from './users-crud/user-update/user-update.component';
import { UserListComponent } from './users-crud/user-list/user-list.component';
import { UserCreateComponent } from './users-crud/user-create/user-create.component';
import { UserAuthenticationGuard } from '../user-authentication.guard';
const routes: Routes = [
{
path: 'Modificar Usuario',
component: UpdateUserComponent,
data: { title: 'update' },
},
{
path: 'Listar Usuario',
component: UserListComponent,
data: { title: 'List' },
},
{
path: 'Agregar Usuario',
component: UserCreateComponent,
data: { title: 'List' },
},
{
path: 'Eliminar Usuario',
component: UserDeleteComponent,
data: { title: 'List' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class UsersRoutingModule {}
<file_sep>/Frontend.DPI/Frontend/src/app/app.component.ts
import { Component, HostListener } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { AuthenticationService } from './authentication.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Frontend';
userActivity;
userInactive: Subject<any> = new Subject();
constructor(private auth:AuthenticationService,
private router: Router) {
this.setTimeout();
this.userInactive.subscribe(() => {
this.auth.logout();
this.router.navigate(["login"]);
});
}
setTimeout() {
this.userActivity = setTimeout(() => this.userInactive.next(undefined), 3600000);
}
@HostListener('window:keydown')
@HostListener('window:mousemove') refreshUserState() {
clearTimeout(this.userActivity);
this.setTimeout();
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Roles/roles.service.ts
import { User, Rol } from './../users/interfaces/user';
import { Injectable } from '@angular/core';
import { WEB_SERVICE } from '../configurations/config';
import { HttpClient } from '@angular/common/http';
import Swal from 'sweetalert2';
@Injectable({
providedIn: 'root',
})
export class RolesService {
constructor(private http: HttpClient) {}
async createRol(Rolname:string){
const url = `${WEB_SERVICE}Roles/CreateRol?rolName=${Rolname}`;
let answer: any = {};
await this.http
.post(url, Rolname)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se ha creado el Rol con exito!');
})
.catch(async (error) => {
this.errorMessage('Error creando un nuevo Rol');
console.log(error);
});
return answer;
}
async getRolByName(Rolname:string){
const url = `${WEB_SERVICE}Roles/GetRolByName?rolName=${Rolname}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Rol Obtenido Con Exito!');
})
.catch(async (error) => {
this.errorMessage('Este Rol No Existe');
console.log(error);
});
return answer;
}
async DeleteRol(Rolname:string){
const url = `${WEB_SERVICE}Roles/DeleteRol?nameRol=${Rolname}`;
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Rol Eliminado Con Exito!');
})
.catch(async (error) => {
this.errorMessage('Fallo Al Eliminar Este Rol');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Backend.DPI/Backend.DPI/Models/UserRolPrivilege.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class UserRolPrivilege
{
public int IdUserRolPrivilege { get; set; }
public int SpecialPrivilege { get; set; }
public string UserUsername { get; set; }
public int? IdRolPrivilege { get; set; }
public virtual User UserUsernameNavigation { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/users.service.ts
import { Injectable } from '@angular/core';
import { WEB_SERVICE } from '../configurations/config';
import { AuthenticationService } from '../authentication.service';
import { HttpClient } from '@angular/common/http';
import Swal from 'sweetalert2';
import { User } from './interfaces/user';
@Injectable({
providedIn: 'root',
})
export class UsersService {
privilegeType:any[]
constructor(private http: HttpClient,private auth:AuthenticationService) {}
async getUsuers() {
Swal.fire({
title: 'Espere un momento',
html: 'Cargando usuarios',
didOpen: () => {
Swal.showLoading();
},
});
const url = `${WEB_SERVICE}User/getUsers`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos de usuarios');
});
return answer;
}
async getRols() {
const url = `${WEB_SERVICE}Roles/GetRols`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
this.errorMessage('Error extrayendo roles');
});
return answer;
}
async getDepartments() {
const url = `${WEB_SERVICE}Department/GetDepartments`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
this.errorMessage('Error extrayendo departamentos 1');
});
return answer;
}
async createUser(user: User) {
let body = {
username: user.username,
password: <PASSWORD>,
departmentIdDepartment: Number(user.departmentIdDepartment),
rolIdRol: Number(user.rolIdRol),
};
const url = `${WEB_SERVICE}User/AddUser`;
let answer: any = {};
await this.http
.post(url, body)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se ha creado el usuario con exito!');
})
.catch(async (error) => {
this.errorMessage('Error creando un nuevo usuario');
});
return answer;
}
async getUserByUsername(username: string) {
const url = `${WEB_SERVICE}User/UserById?username=${username}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
this.succesMessage('Usuario encontrado satisfactoriamente');
})
.catch(async (error) => {
this.errorMessage('Error estrayendo datos del usuarios');
});
return answer;
}
async updtUser(user: User) {
let body = {
username: user.username,
password: <PASSWORD>,
departmentIdDepartment: Number(user.departmentIdDepartment),
rolIdRol: Number(user.rolIdRol),
};
const url = `${WEB_SERVICE}User/UpdateUser`;
let answer: any = {};
await this.http
.post(url, body)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se ha modificado el usuario con exito!');
})
.catch(async (error) => {
this.errorMessage('Error al modificar datos de usuario');
});
return answer;
}
async getRolPriviliges() {
const url = `${WEB_SERVICE}Privilege/GetRolPrivilege`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (respuestaApi) => {
this.errorMessage('Error extrayendo departamentos 2');
});
return answer;
}
async GetPrivilegesByUser(username) {
const url = `${WEB_SERVICE}Privilege/GetUserRolPrivilegesByUser?username=${username}`;
let answer: any;
await this.http.post(url,username).toPromise().then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (respuestaApi) => {
});
return answer;
}
async loadPrivilegesUser(){
if (this.auth.isLoggedIn) {
await this.GetPrivilegesByUser(this.auth.currentUser.username).then((resp)=>{
this.auth.privileges=resp;
});
if( this.auth.privileges!=null){
localStorage.setItem("Privileges",JSON.stringify(this.auth.privileges));
localStorage.setItem("SizePrivileges",this.auth.privileges.length.toString());
this.privilegeType = this.getUniqueValuesFromPrivilegeType();
return this.privilegeType;
}else{
this.privilegeType = null;
}
}
return null;
}
getUniqueValuesFromPrivilegeType(){
const unique = [...new Set(this.auth.privileges.map(item => item.tipo_privilegio))];
let privileges = [];
for (let i = 0; i < unique.length; i++) {
let namePrivileges = [];
for (let j = 0; j < this.auth.privileges.length; j++) {
if (this.auth.privileges[j].tipo_privilegio == unique[i]) {
namePrivileges.push(this.auth.privileges[j].name_Privilege);
}
}
const object = {
privilegeType : unique[i],
privilege : namePrivileges,
icon : Icons[unique[i]]
}
privileges.push(object);
}
return privileges;
}
async updtUserPrivilege(
idRolPrivilege: number,
username: string,
specialPrivilege: number
) {
let body = {
userUsername: username,
idRolPrivilege: idRolPrivilege,
specialPrivilege: specialPrivilege,
};
const url = `${WEB_SERVICE}Privilege/AddUserRolPrivilege`;
let answer: any = {};
await this.http
.post(url, body)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han asignado los privilegios con exito!');
})
.catch(async (error) => {
this.errorMessage('Error al asignar privilegios de usuario');
});
return answer;
}
async DeleteUser(username: string) {
const url = `${WEB_SERVICE}User/DeleteUser?username=${username}`;
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han eliminado el usuario con exito!');
})
.catch(async (error) => {
this.errorMessage('Error al eliminar el usuario');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
const Icons = {
'Departamentos' : 'fa fa-building',
"Privilegios" : 'fa fa-key',
'Privilegios de Usuarios' : 'fa fa-id-badge',
'Privilegios a Roles' : 'fa fa-cogs',
'Sospechosos' : 'fa fa-user-secret',
'Usuarios' : 'fa fa-user',
'Roles' : 'fa fa-sitemap',
'Grupos Criminales' : 'fa fa-users',
'Historial Delictivo': 'fa fa-address-book',
'Historial Criminal': 'fa fa-book',
'Historial Policial': 'fa fa-clipboard',
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/DepartmentRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Backend.DPI.Repository
{
public class DepartmentRepository : IDepartmentRepository
{
private readonly DPIContext dpiContext;
public DepartmentRepository(DPIContext _dpiContext)
{
this.dpiContext = _dpiContext;
}
public async Task<Department> CreateDepartmentAsync(string name)
{
var result = await dpiContext.AddAsync(new Department
{
Name = name
});
await dpiContext.SaveChangesAsync();
return new Department {
Name = name
};
}
public async Task<bool> DeleteDepartmentAsync(string departmentName)
{
var result = await dpiContext.Departments.FirstOrDefaultAsync(u => u.Name.ToLower() == departmentName.ToLower());
if (result == null)
{
return false;
}
dpiContext.Departments.Remove(result);
await dpiContext.SaveChangesAsync();
return true;
}
public async Task<IReadOnlyList<Department>> GetDepartmentsAsync()
{
return await dpiContext.Departments.OrderBy(departments=>departments.Name).ToListAsync();
}
public async Task<Department> GetDepartmentsByNameAsync(string departmentName)
{
var result = await dpiContext.Departments.FirstOrDefaultAsync(u => u.Name.ToLower() == departmentName.ToLower());
if (result == null)
{
return null;
}
return result;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Departamentos/departamento-delete/departamento-delete.component.ts
import { DepartmentService } from './../deparment.service';
import { Department } from './../../users/interfaces/user';
import { Component, OnInit } from '@angular/core';
import Swal from 'sweetalert2';
@Component({
selector: 'app-departamento-delete',
templateUrl: './departamento-delete.component.html',
styleUrls: ['./departamento-delete.component.css']
})
export class DepartamentoDeleteComponent {
userFilterSelected: string = '';
DepartmentData: Department[] ;
constructor(private departmentService: DepartmentService) {}
async getRolbyName(rolName: string) {
await this.departmentService.getDepartmentByName(rolName.trim()).then((resp) => {
this.DepartmentData = resp;
});
}
async DeleteRol(username: string) {
Swal.fire({
title: '¿Seguro que desea eliminar el usuario?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.departmentService.DeleteDepartment(username).then((resp) => {
if (resp == true) {
this.DepartmentData = null;
this.userFilterSelected ='';
}else{
}
});
}
});
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/^[a-zA-Z0-9_ ]*$/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminal-record/criminals.record.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import Swal from 'sweetalert2';
import { WEB_SERVICE } from '../configurations/config';
import { CriminalRecord } from '../criminals/Interfaces/criminal-interface';
@Injectable({
providedIn: 'root'
})
export class CriminalRecordService {
constructor(private http: HttpClient) { }
async createRecordCriminal(criminal:CriminalRecord ) {
const url = `${WEB_SERVICE}CriminalRecord/AddCriminalRecord`;
let answer: any = {};
await this.http
.post(url, criminal)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se han ingresado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('DNI de sospechoso aun no existe');
});
return answer;
}
async getCriminalRecords(){
Swal.fire({
title: 'Espere un momento',
html: 'Cargando usuarios',
didOpen: () => {
Swal.showLoading();
},
});
const url = `${WEB_SERVICE}CriminalRecord/GetCriminalRecords`;
let answer: any;
await this.http.get(url).toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async getCriminalByDNI(dni: string) {
const url = `${WEB_SERVICE}CriminalRecord/GetCriminalRecordByDNI?DNI=${dni}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Error estrayendo datos');
});
return answer;
}
async updtCriminalRecord(criminal:CriminalRecord) {
const url = `${WEB_SERVICE}CriminalRecord/UpdateCriminalRecordByDni`;
let answer: any = {};
await this.http
.put(url, criminal)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han modificado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('Erro al modificar los datos');
});
return answer;
}
async deleteCriminalRecord(criminalRecord) {
const url = `${WEB_SERVICE}CriminalRecord/DeleteCriminalRecord?IdCriminalRecord=${criminalRecord}`;
console.log(url)
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han Eliminado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('Error al Eliminar los datos');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminal-record/criminal-record-list/criminal-record-list.component.ts
import { Component, OnInit } from '@angular/core';
import { CriminalRecord } from '../../criminals/Interfaces/criminal-interface';
import { Department } from '../../users/interfaces/user';
import { UsersService } from '../../users/users.service';
import { CriminalRecordService } from '../criminals.record.service';
@Component({
selector: 'app-criminal-record-list',
templateUrl: './criminal-record-list.component.html',
styleUrls: ['./criminal-record-list.component.css']
})
export class CriminalRecordListComponent implements OnInit {
totalRecords :number;
page:number =1;
userFilterSelected: string = '';
criminalRecords: CriminalRecord[];
constructor(private criminalRecord: CriminalRecordService) {}
async ngOnInit() {
await this.getDepartments();
}
async getDepartments() {
await this.criminalRecord.getCriminalRecords().then((resp) => {
this.criminalRecords = resp;
console.log(this.criminalRecords)
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/create-user-modal/create-user-modal.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
@Component({
selector: 'app-create-user-modal',
templateUrl: './create-user-modal.component.html',
styleUrls: ['./create-user-modal.component.css']
})
export class CreateUserModalComponent implements OnInit {
@ViewChild('createUserModal', { static: true }) createUserModal: ModalDirective;
constructor() { }
ngOnInit(): void {
}
buildModal(){
this.createUserModal.show();
}
closeModal(){
this.createUserModal.hide();
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/rol_privileges/interfaces/rol-privilege.ts
export interface RolPrivilege{
idRolPrivilege: number,
name_Rol: string,
name_Privilege: string
};
export interface CreateRolPrivilege{
privilegeIdPrivilege: number,
rolIdRol: number
}
export interface Privilege{
idPrivilege: number,
name: string
}
export interface Rol{
idRol: number,
name: string
}<file_sep>/Backend.DPI/Backend.DPI/Repository/IPoliceRecordRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface IPoliceRecordRepository
{
Task<bool> CreatePoliceRecord(PoliceRecord policeRecord);
Task<IReadOnlyList<PoliceRecord>> GetPoliceRecord();
Task<IReadOnlyList<PoliceRecord>> GetPoliceRecordByDNISuspect(string dniSuspect);
Task<bool> DeletePoliceRecord(int idPoliceRecord);
Task<bool> ModifyPoliceRecord(PoliceRecord police);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/suspect-routing.module.ts
import { SospechosoDeleteComponent } from './sospechoso-delete/sospechoso-delete.component';
import { SospechosoUpdateComponent } from './sospechoso-update/sospechoso-update.component';
import { SospechosoListPerDayComponent } from './sospechoso-list-per-day/sospechoso-list-per-day.component';
import { SospechosoCreateComponent } from './sospechoso-create/sospechoso-create.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SuspectListComponent } from './sospechoso-list/suspect-list.component';
import { DatePipe } from '@angular/common';
import { SospechosoListPerDayChiefComponent } from './sospechoso-list-per-day-chief/sospechoso-list-per-day-chief.component';
const routes: Routes = [
{
path: 'Listar Sospechosos',
component: SuspectListComponent,
data: { title: 'List' },
},
{
path: 'Agregar Sospechosos',
component: SospechosoCreateComponent,
data: { title: 'List' },
},
{
path: 'Listar Sospechosos Ingresados Hoy',
component: SospechosoListPerDayComponent,
data: { title: 'List' },
},
{
path: 'Sospechosos Ingresados Hoy Nacional',
component: SospechosoListPerDayChiefComponent,
data: { title: 'List' },
},
{
path: 'Modificar Sospechosos',
component: SospechosoUpdateComponent,
data: { title: 'List' },
},
{
path: 'Eliminar Sospechosos',
component: SospechosoDeleteComponent,
data: { title: 'List' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
providers: [DatePipe]
})
export class SuspectRoutingModule {}<file_sep>/Frontend.DPI/Frontend/src/app/police-record/police-record-list/police-record-list.component.ts
import { PoliceRecord } from './../../criminals/Interfaces/criminal-interface';
import { Component, OnInit } from '@angular/core';
import { PoliceRecordService } from '../police.record.service';
@Component({
selector: 'app-police-record-list',
templateUrl: './police-record-list.component.html',
styleUrls: ['./police-record-list.component.css']
})
export class PoliceRecordListComponent implements OnInit {
totalRecords :number;
page:number =1;
userFilterSelected: string = '';
policeRecord: PoliceRecord[];
constructor(private criminalRecord: PoliceRecordService) {}
async ngOnInit() {
await this.getPoliceRecord();
}
async getPoliceRecord() {
await this.criminalRecord.getPoliceRecords().then((resp) => {
this.policeRecord = resp;
console.log(this.policeRecord)
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/user-rol-privilege/user-rol-privilege-crud/user-rol-privilege-delete/user-rol-privilege-delete.component.ts
import { RolPrivilege } from './../../../users/interfaces/user';
import { Component, OnInit } from '@angular/core';
import { FormBuilder} from '@angular/forms';
import Swal from 'sweetalert2';
import { UserRolPrivilegesService } from '../../user-rol-privileges.service';
import { UserRolPrivilge } from '../../interfaces/user-rol-privilege';
import { UsersService } from '../../../users/users.service';
import { AuthenticationService } from '../../../authentication.service';
@Component({
selector: 'app-user-rol-privilege-delete',
templateUrl: './user-rol-privilege-delete.component.html',
styleUrls: ['./user-rol-privilege-delete.component.css']
})
export class UserRolPrivilegeDeleteComponent implements OnInit {
userRolPrivilegeSingle: UserRolPrivilge [];
userRolPrivilegeFilterSelected: string = '';
userRolPrivilegeData: UserRolPrivilge[];
buttonDisabled: boolean;
privileges:RolPrivilege;
constructor(private userRolPrivilegeService: UserRolPrivilegesService,
private formBuilder:FormBuilder,
private auth: AuthenticationService,
private userService:UsersService) {
}
async ngOnInit() {
this.buttonDisabled=false;
}
async getUserRolPrivilegeByUsername(username: string) {
await this.userRolPrivilegeService.getUserRolPrivilegeByUsername(username).then((resp) => {
this.userRolPrivilegeData = resp;
this.userRolPrivilegeSingle = resp;
});
}
async deleteUserRolPrivilege(idUserRolPrivilege: number, index: number) {
Swal.fire({
title: '¿Seguro que desea eliminar el usuario?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.userRolPrivilegeService.DeleteUserRolPrivilege(idUserRolPrivilege).then(async (resp) => {
if (resp == true) {
await this.userService.loadPrivilegesUser();
this.userRolPrivilegeSingle[index] = null;
this.userRolPrivilegeSingle.splice(
this.userRolPrivilegeSingle.findIndex((userRolPrivilege) => userRolPrivilege.idUserRolPrivilege ==idUserRolPrivilege ), 1);
}
});
}
});
}
}
<file_sep>/Backend.DPI/Backend.DPI/Models/User.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class User
{
public User()
{
UserRolPrivileges = new HashSet<UserRolPrivilege>();
}
public string Username { get; set; }
public string Password { get; set; }
public DateTime CreationDatetime { get; set; }
public int DepartmentIdDepartment { get; set; }
public int RolIdRol { get; set; }
public virtual Department DepartmentIdDepartmentNavigation { get; set; }
public virtual Rol RolIdRolNavigation { get; set; }
public virtual ICollection<UserRolPrivilege> UserRolPrivileges { get; set; }
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/IPrivilegeRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface IPrivilegeRepository
{
Task<RolPrivilege> CreateRolPrivilegeAsync(RolPrivilege RolPrivilege);
Task<Privilege> CreatePrivilegeAsync(Privilege Privilege);
Task<IReadOnlyList<Privilege>> GetPrivilegesAsync();
Task<IReadOnlyList<object>> GetRolPrivilegesAsync();
Task<UserRolPrivilege> AddUserRolPrivilegeAsync(UserRolPrivilege UserRolPrivilege);
Task<IReadOnlyList<object>> GetUserRolPrivilegesByUserAsync(string Username);
Task<object> GetRolPrivilegeByNameAsync(string NameRolPrivilege);
Task<bool> DeleteRolPrivilegeByIdAsync(int IdRolPrivilege);
Task<IReadOnlyList<object>> GetUserRolPrivilegesAsync();
Task<IReadOnlyList<Privilege>> GetPrivilegesByUserAsync(string username);
Task<bool> DeleteUserRolPrivilegeByIdAsync(int IdUserRolPrivilege);
Task<bool> DeleteUserRolPrivilegeByUserAsync(string Username);
}
}
<file_sep>/Backend.DPI/Backend.DPI/ModelDto/RolPrivilegeDto.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.ModelDto
{
public class RolPrivilegeDto
{
public int IdRolPrivilege { get; set; }
public int PrivilegeIdPrivilege { get; set; }
public int RolIdRol { get; set; }
public virtual PrivilegeDto PrivilegeIdPrivilegeNavigation { get; set; }
public virtual RolDto RolIdRolNavigation { get; set; }
}
}
<file_sep>/Backend.DPI/Backend.DPI/Controllers/UserController.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using Backend.DPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class UserController : Controller
{
private readonly UserRepository _userRepository = new UserRepository();
[Authorize]
[HttpGet("GetUsers")]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
var Users = await _userRepository.GetUsersAsync();
if (Users == null)
{
return NotFound();
}
return Ok(Users);
}
[Authorize]
[HttpGet("UserById")]
public async Task<ActionResult<IEnumerable<User>>> GetUsersById(string username)
{
var User = await _userRepository.GetUserByUsernameAsync(username);
return Ok(User);
}
[Authorize]
[HttpPost("AddUser")]
public async Task<ActionResult<IEnumerable<User>>> AddUser(UserDto user)
{
var User = await _userRepository.CreateUserAsync(user);
return Ok(User);
}
[Authorize]
[HttpPost("UpdatePassword")]
public async Task<ActionResult<IEnumerable<User>>> UpdatePassword(string username,string password)
{
var User = await _userRepository.UpdatePasswordUserAsync(username, password);
return Ok(User);
}
[Authorize]
[HttpPost("UpdateRol")]
public async Task<ActionResult<IEnumerable<User>>> UpdateRol(string username, int rol)
{
var User = await _userRepository.UpdateRolUserAsync(username, rol);
return Ok(User);
}
[Authorize]
[HttpPost("UpdateDepartment")]
public async Task<ActionResult<IEnumerable<User>>> UpdateDepartment(string username, int department)
{
var User = await _userRepository.UpdateDepartmentUserAsync(username, department);
return Ok(User);
}
[Authorize]
[HttpPost("UpdateUser")]
public async Task<ActionResult<IEnumerable<User>>> UpdateUser(UserDto user)
{
var User = await _userRepository.UpdateUser(user);
return Ok(User);
}
[Authorize]
[HttpDelete("DeleteUser")]
public async Task<ActionResult<IEnumerable<User>>> DeleteUser(string username)
{
var User = await _userRepository.DeleteUserAsync(username);
return Ok(User);
}
[HttpPost("Login")]
public async Task<ActionResult<object>> Login(UserDto user) {
var result = await _userRepository.LoginAsync(user.Username, user.Password);
if (result == null) return NotFound();
return Ok(result);
}
[Authorize]
[HttpGet("UpdateToken")]
public async Task<ActionResult<object>> UpdateToken(string Token) {
var result = await _userRepository.UpdateTokenAsync(Token);
if (result == null) return NotFound();
return Ok(result);
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/users.module.ts
import { UpdateUserComponent } from './users-crud/user-update/user-update.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UsersRoutingModule } from './users-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ModalModule } from 'ngx-bootstrap/modal';
import { UserFilterPipe } from './pipes/user-filter.pipe';
import { UserListComponent } from './users-crud/user-list/user-list.component';
import { UserCreateComponent } from './users-crud/user-create/user-create.component';
import { UserDeleteComponent } from './users-crud/user-delete/user-delete.component';
import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
declarations: [
UserFilterPipe,
UserListComponent,
UpdateUserComponent,
UserCreateComponent,
UserDeleteComponent,
],
imports: [
CommonModule,
UsersRoutingModule,
FormsModule,
ModalModule.forRoot(),
ReactiveFormsModule,
NgxPaginationModule
],
})
export class UsersModule {}
<file_sep>/Backend.DPI/Backend.DPI/Models/DPIContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable disable
namespace Backend.DPI.Models
{
public partial class DPIContext : DbContext
{
public DPIContext()
{
}
public DPIContext(DbContextOptions<DPIContext> options)
: base(options)
{
}
public virtual DbSet<CriminalGroup> CriminalGroups { get; set; }
public virtual DbSet<CriminalHistory> CriminalHistories { get; set; }
public virtual DbSet<CriminalRecord> CriminalRecords { get; set; }
public virtual DbSet<Department> Departments { get; set; }
public virtual DbSet<PoliceRecord> PoliceRecords { get; set; }
public virtual DbSet<Privilege> Privileges { get; set; }
public virtual DbSet<Rol> Rols { get; set; }
public virtual DbSet<RolPrivilege> RolPrivileges { get; set; }
public virtual DbSet<Suspect> Suspects { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<UserRolPrivilege> UserRolPrivileges { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseSqlServer("Server=dpi.database.windows.net;Database=DPI;User=admindpi;Password=<PASSWORD>$;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
modelBuilder.Entity<CriminalGroup>(entity =>
{
entity.HasKey(e => e.IdCg)
.HasName("criminal_group_pk");
entity.ToTable("criminal_group");
entity.Property(e => e.IdCg).HasColumnName("id_cg");
entity.Property(e => e.NombreGrupoCriminal)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("nombre_grupo_criminal");
});
modelBuilder.Entity<CriminalHistory>(entity =>
{
entity.HasKey(e => e.IdCriminalHistory)
.HasName("criminal_history_pk");
entity.ToTable("criminal_history");
entity.Property(e => e.IdCriminalHistory).HasColumnName("id_criminal_history");
entity.Property(e => e.CriminalGroupIdCg).HasColumnName("criminal_group_id_cg");
entity.Property(e => e.HierarchyCriminalGroup)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("hierarchy_criminal_group");
entity.Property(e => e.IncidenceType)
.HasMaxLength(9)
.IsUnicode(false)
.HasColumnName("incidence_type");
entity.Property(e => e.IncidenceZone)
.HasMaxLength(16)
.IsUnicode(false)
.HasColumnName("incidence_zone");
entity.Property(e => e.OperationPlace)
.IsRequired()
.HasMaxLength(60)
.IsUnicode(false)
.HasColumnName("operation_place");
entity.Property(e => e.PeriodBelong)
.IsRequired()
.HasMaxLength(25)
.IsUnicode(false)
.HasColumnName("period_belong");
entity.Property(e => e.SuspectDni)
.IsRequired()
.HasMaxLength(16)
.IsUnicode(false)
.HasColumnName("suspect_dni");
entity.Property(e => e.TatooType)
.HasMaxLength(11)
.IsUnicode(false)
.HasColumnName("tatoo_type");
entity.HasOne(d => d.CriminalGroupIdCgNavigation)
.WithMany(p => p.CriminalHistories)
.HasForeignKey(d => d.CriminalGroupIdCg)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("criminal_history_cg_fk");
entity.HasOne(d => d.SuspectDniNavigation)
.WithMany(p => p.CriminalHistories)
.HasForeignKey(d => d.SuspectDni)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("criminal_history_suspect_fk");
});
modelBuilder.Entity<CriminalRecord>(entity =>
{
entity.HasKey(e => e.IdCriminalRecord)
.HasName("criminal_record_pk");
entity.ToTable("criminal_record");
entity.Property(e => e.IdCriminalRecord).HasColumnName("id_criminal_record");
entity.Property(e => e.Crime)
.HasMaxLength(65)
.IsUnicode(false)
.HasColumnName("crime");
entity.Property(e => e.ModuleCellPrison)
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnName("module_cell_prison");
entity.Property(e => e.PenitentiaryCenter)
.HasMaxLength(35)
.IsUnicode(false)
.HasColumnName("penitentiary_center");
entity.Property(e => e.SentenceFinalDate)
.HasColumnType("date")
.HasColumnName("sentence_final_date");
entity.Property(e => e.SentenceStartDate)
.HasColumnType("date")
.HasColumnName("sentence_start_date");
entity.Property(e => e.SuspectDni)
.IsRequired()
.HasMaxLength(16)
.IsUnicode(false)
.HasColumnName("suspect_dni");
entity.HasOne(d => d.SuspectDniNavigation)
.WithMany(p => p.CriminalRecords)
.HasForeignKey(d => d.SuspectDni)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("criminal_record_suspect_fk");
});
modelBuilder.Entity<Department>(entity =>
{
entity.HasKey(e => e.IdDepartment)
.HasName("department_pk");
entity.ToTable("department");
entity.Property(e => e.IdDepartment).HasColumnName("id_department");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(60)
.IsUnicode(false)
.HasColumnName("name");
});
modelBuilder.Entity<PoliceRecord>(entity =>
{
entity.HasKey(e => e.IdPoliceRecord)
.HasName("police_record_pk");
entity.ToTable("police_record");
entity.Property(e => e.IdPoliceRecord).HasColumnName("id_police_record");
entity.Property(e => e.CapturedByOrganization)
.IsRequired()
.HasMaxLength(6)
.IsUnicode(false)
.HasColumnName("captured_by_organization");
entity.Property(e => e.Caserio)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("caserio");
entity.Property(e => e.Colonia)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("colonia");
entity.Property(e => e.ConfiscationDescription)
.HasMaxLength(65)
.IsUnicode(false)
.HasColumnName("confiscation_description");
entity.Property(e => e.ConfiscationQuantity)
.HasMaxLength(65)
.IsUnicode(false)
.HasColumnName("confiscation_quantity");
entity.Property(e => e.ConfiscationType)
.HasMaxLength(40)
.IsUnicode(false)
.HasColumnName("confiscation_type");
entity.Property(e => e.DetentionDate)
.HasColumnType("date")
.HasColumnName("detention_date");
entity.Property(e => e.DetentionDepartment)
.IsRequired()
.HasMaxLength(17)
.IsUnicode(false)
.HasColumnName("detention_department");
entity.Property(e => e.DetentionMunicipio)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("detention_municipio");
entity.Property(e => e.ReasonDetention)
.IsRequired()
.HasMaxLength(65)
.IsUnicode(false)
.HasColumnName("reason_detention");
entity.Property(e => e.SuspectDni)
.IsRequired()
.HasMaxLength(16)
.IsUnicode(false)
.HasColumnName("suspect_dni");
entity.Property(e => e.Village)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("village");
entity.HasOne(d => d.SuspectDniNavigation)
.WithMany(p => p.PoliceRecords)
.HasForeignKey(d => d.SuspectDni)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("police_record_suspect_fk");
});
modelBuilder.Entity<Privilege>(entity =>
{
entity.HasKey(e => e.IdPrivilege)
.HasName("access_pk");
entity.ToTable("privilege");
entity.Property(e => e.IdPrivilege).HasColumnName("id_privilege");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(40)
.IsUnicode(false)
.HasColumnName("name");
entity.Property(e => e.TipoPrivilegio)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("tipo_privilegio");
});
modelBuilder.Entity<Rol>(entity =>
{
entity.HasKey(e => e.IdRol)
.HasName("rol_pk");
entity.ToTable("rol");
entity.Property(e => e.IdRol).HasColumnName("id_rol");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(40)
.IsUnicode(false)
.HasColumnName("name");
});
modelBuilder.Entity<RolPrivilege>(entity =>
{
entity.HasKey(e => e.IdRolPrivilege);
entity.ToTable("rol_privilege");
entity.Property(e => e.IdRolPrivilege).HasColumnName("id_rol_privilege");
entity.Property(e => e.PrivilegeIdPrivilege).HasColumnName("privilege_id_privilege");
entity.Property(e => e.RolIdRol).HasColumnName("rol_id_rol");
entity.HasOne(d => d.PrivilegeIdPrivilegeNavigation)
.WithMany(p => p.RolPrivileges)
.HasForeignKey(d => d.PrivilegeIdPrivilege)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("rol_privilege_privilege_fk");
entity.HasOne(d => d.RolIdRolNavigation)
.WithMany(p => p.RolPrivileges)
.HasForeignKey(d => d.RolIdRol)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("rol_privilege_rol_fk");
});
modelBuilder.Entity<Suspect>(entity =>
{
entity.HasKey(e => e.DniSuspect)
.HasName("suspect_pk");
entity.ToTable("suspect");
entity.Property(e => e.DniSuspect)
.HasMaxLength(16)
.IsUnicode(false)
.HasColumnName("dni_suspect");
entity.Property(e => e.Age).HasColumnName("age");
entity.Property(e => e.Alias)
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnName("alias");
entity.Property(e => e.Avenue)
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnName("avenue");
entity.Property(e => e.Build)
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnName("build");
entity.Property(e => e.Caserio)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("caserio");
entity.Property(e => e.CivilStatus)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("civil_status");
entity.Property(e => e.Colonia)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("colonia");
entity.Property(e => e.CreationDate)
.HasColumnType("date")
.HasColumnName("creation_date")
.HasDefaultValueSql("('2021-09-02')");
entity.Property(e => e.DateOfBirth)
.HasColumnType("date")
.HasColumnName("date_of_birth");
entity.Property(e => e.Deleted).HasColumnName("deleted");
entity.Property(e => e.Department)
.IsRequired()
.HasMaxLength(17)
.IsUnicode(false)
.HasColumnName("department");
entity.Property(e => e.DepartmentIdDepartment).HasColumnName("department_id_department");
entity.Property(e => e.EyesColor)
.IsRequired()
.HasMaxLength(15)
.IsUnicode(false)
.HasColumnName("eyes_color");
entity.Property(e => e.FirstName)
.IsRequired()
.HasMaxLength(15)
.IsUnicode(false)
.HasColumnName("first_name");
entity.Property(e => e.Height).HasColumnName("height");
entity.Property(e => e.HouseNumber).HasColumnName("house_number");
entity.Property(e => e.LastModificationUser)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("last_modification_user");
entity.Property(e => e.LastName)
.HasMaxLength(15)
.IsUnicode(false)
.HasColumnName("last_name");
entity.Property(e => e.MiddleName)
.HasMaxLength(15)
.IsUnicode(false)
.HasColumnName("middle_name");
entity.Property(e => e.Municipio)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("municipio");
entity.Property(e => e.Nationaliy)
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnName("nationaliy");
entity.Property(e => e.Ocupattion)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("ocupattion");
entity.Property(e => e.OperationPlace)
.IsRequired()
.HasMaxLength(60)
.IsUnicode(false)
.HasColumnName("operation_place");
entity.Property(e => e.ParticularSign)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("particular_sign");
entity.Property(e => e.Pasaje)
.HasMaxLength(25)
.IsUnicode(false)
.HasColumnName("pasaje");
entity.Property(e => e.PassportNumber)
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnName("passport_number");
entity.Property(e => e.PersonFrom)
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnName("person_from");
entity.Property(e => e.ReferenceAddress)
.HasMaxLength(40)
.IsUnicode(false)
.HasColumnName("reference_address");
entity.Property(e => e.Sex)
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnName("sex");
entity.Property(e => e.Street)
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnName("street");
entity.Property(e => e.Tattoo)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("tattoo");
entity.Property(e => e.ThirdName)
.IsRequired()
.HasMaxLength(15)
.IsUnicode(false)
.HasColumnName("third_name");
entity.Property(e => e.UsernameRegistryData)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("username_registry_data");
entity.Property(e => e.Village)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("village");
entity.Property(e => e.Weight).HasColumnName("weight");
entity.HasOne(d => d.DepartmentIdDepartmentNavigation)
.WithMany(p => p.Suspects)
.HasForeignKey(d => d.DepartmentIdDepartment)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("suspect_department_fk");
});
modelBuilder.Entity<User>(entity =>
{
entity.HasKey(e => e.Username)
.HasName("user_pk");
entity.ToTable("User");
entity.Property(e => e.Username)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("username");
entity.Property(e => e.CreationDatetime)
.HasColumnType("date")
.HasColumnName("creation_datetime");
entity.Property(e => e.DepartmentIdDepartment).HasColumnName("department_id_department");
entity.Property(e => e.Password)
.IsRequired()
.HasMaxLength(65)
.IsUnicode(false)
.HasColumnName("password");
entity.Property(e => e.RolIdRol).HasColumnName("rol_id_rol");
entity.HasOne(d => d.DepartmentIdDepartmentNavigation)
.WithMany(p => p.Users)
.HasForeignKey(d => d.DepartmentIdDepartment)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("user_department_fk");
entity.HasOne(d => d.RolIdRolNavigation)
.WithMany(p => p.Users)
.HasForeignKey(d => d.RolIdRol)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("user_rol_fk");
});
modelBuilder.Entity<UserRolPrivilege>(entity =>
{
entity.HasKey(e => e.IdUserRolPrivilege)
.HasName("user_rol_privilege_pk");
entity.ToTable("user_rol_privilege");
entity.Property(e => e.IdUserRolPrivilege).HasColumnName("id_user_rol_privilege");
entity.Property(e => e.IdRolPrivilege).HasColumnName("id_rol_privilege");
entity.Property(e => e.SpecialPrivilege).HasColumnName("special_privilege");
entity.Property(e => e.UserUsername)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("user_username");
entity.HasOne(d => d.UserUsernameNavigation)
.WithMany(p => p.UserRolPrivileges)
.HasForeignKey(d => d.UserUsername)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("user_rol_privilege_user_fk");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/police-record/police.record.service.ts
import { PoliceRecord } from './../criminals/Interfaces/criminal-interface';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import Swal from 'sweetalert2';
import { WEB_SERVICE } from '../configurations/config';
@Injectable({
providedIn: 'root'
})
export class PoliceRecordService {
constructor(private http: HttpClient) { }
async createPoliceRecord(criminal:PoliceRecord ) {
const url = `${WEB_SERVICE}PoliceRecord/CreatePoliceRecord`;
let answer: any = {};
await this.http
.post(url, criminal)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se han ingresado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('DNI de sospechoso aun no existe');
});
return answer;
}
async getPoliceRecords(){
Swal.fire({
title: 'Espere un momento',
html: 'Cargando usuarios',
didOpen: () => {
Swal.showLoading();
},
});
const url = `${WEB_SERVICE}PoliceRecord/GetPoliceRecords`;
let answer: any;
await this.http.get(url).toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async getPoliceRecordByDNI(dni: string) {
const url = `${WEB_SERVICE}PoliceRecord/GetPoliceRecordsByDNI?dniSuspect=${dni}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Error estrayendo datos');
});
return answer;
}
async getCriminalGroups(){
const url = `${WEB_SERVICE}CriminalGroup/GetCriminalGroups`;
let answer: any;
await this.http.get(url).toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async updatePoliceRecord(policeRecord:PoliceRecord) {
const url = `${WEB_SERVICE}PoliceRecord/ModifyPoliceRecord`;
let answer: any = {};
await this.http
.post(url, policeRecord)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han modificado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('Erro al modificar los datos');
});
return answer;
}
async deletePoliceRecord(policeRecordid) {
const url = `${WEB_SERVICE}PoliceRecord/DeletePoliceRecord?idPoliceRecord=${policeRecordid}`;
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han modificado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('Erro al modificar los datos');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/configurations/config.ts
export const WEB_SERVICE ="https://backenddpi.azurewebsites.net/"
<file_sep>/Backend.DPI/Backend.DPI/Models/CriminalHistory.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class CriminalHistory
{
public int IdCriminalHistory { get; set; }
public string IncidenceType { get; set; }
public string IncidenceZone { get; set; }
public string HierarchyCriminalGroup { get; set; }
public string PeriodBelong { get; set; }
public string OperationPlace { get; set; }
public string TatooType { get; set; }
public string SuspectDni { get; set; }
public int CriminalGroupIdCg { get; set; }
public virtual CriminalGroup CriminalGroupIdCgNavigation { get; set; }
public virtual Suspect SuspectDniNavigation { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/users-crud/user-delete/user-delete.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Department, Rol, User } from '../../interfaces/user';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { UsersService } from '../../users.service';
import Swal from 'sweetalert2';
@Component({
selector: 'app-user-delete',
templateUrl: './user-delete.component.html',
styleUrls: ['./user-delete.component.css']
})
export class UserDeleteComponent implements OnInit {
newUser: User = {} as User;
userFilterSelected: string = '';
userData: User[];
buttonDisabled: boolean;
constructor(private userService: UsersService) {
}
async ngOnInit() {
this.buttonDisabled=false;
}
async getUserByUsername(username: string) {
await this.userService.getUserByUsername(username).then((resp) => {
this.userData = resp;
this.newUser = resp;
});
}
async deleteUser(username: string) {
Swal.fire({
title: '¿Seguro que desea eliminar el usuario?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.userService.DeleteUser(username).then((resp) => {
if (resp == true) {
this.userFilterSelected='';
this.userData = null;
this.userData.splice(
this.userData.findIndex((user) => user.username == username),
1
);
}
});
}
});
}
}
<file_sep>/Backend.DPI/Backend.DPI/ModelDto/UserRolPrivilegeDto.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.ModelDto
{
public partial class UserRolPrivilegeDto
{
public int IdUserRolPrivilege { get; set; }
public int SpecialPrivilege { get; set; }
public string UserUsername { get; set; }
public int? IdRolPrivilege { get; set; }
public virtual UserDto UserUsernameNavigation { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { HomeComponent } from './home/home.component';
import { SweetAlert2Module } from '@sweetalert2/ngx-sweetalert2';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';
import { LoginComponent } from './login/login.component';
import { UserAuthenticationGuard } from './user-authentication.guard';
import { AuthenticationService } from './authentication.service';
import { JwtModule } from '@auth0/angular-jwt';
import { TokenInterceptorProviders } from './TokenInterceptor.service';
export function tokenGetter(){
return localStorage.getItem("Token");
}
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
HomeComponent,
PagenotfoundComponent,
LoginComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
SweetAlert2Module.forRoot(),
HttpClientModule,
FormsModule,
ReactiveFormsModule,
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ["http://localhost:4200"],
disallowedRoutes: [],
}
})
],
providers: [UserAuthenticationGuard,AuthenticationService,TokenInterceptorProviders],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/Backend.DPI/Backend.DPI/Models/PoliceRecord.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class PoliceRecord
{
public int IdPoliceRecord { get; set; }
public string ReasonDetention { get; set; }
public DateTime DetentionDate { get; set; }
public string DetentionDepartment { get; set; }
public string CapturedByOrganization { get; set; }
public string ConfiscationType { get; set; }
public string ConfiscationQuantity { get; set; }
public string ConfiscationDescription { get; set; }
public string DetentionMunicipio { get; set; }
public string Colonia { get; set; }
public string Caserio { get; set; }
public string Village { get; set; }
public string SuspectDni { get; set; }
public virtual Suspect SuspectDniNavigation { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/criminals.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CriminalsRoutingModule } from './criminals-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgxPaginationModule } from 'ngx-pagination';
import { CriminalFilterPipe } from './pipes/user-filter.pipe';
import { ModalModule } from 'ngx-bootstrap/modal';
import { HistorialCriminalCreateComponent } from './criminal-create/criminal-create.component';
import { HistorialCriminalUpdateComponent } from './criminal-update/criminal-update.component';
import { HistorialCriminalListComponent } from './criminal-list/criminal-list.component';
import { HistorialCriminalDeleteComponent } from './criminal-delete/criminal-delete.component';
@NgModule({
declarations: [
HistorialCriminalCreateComponent,
HistorialCriminalUpdateComponent,
HistorialCriminalListComponent,
CriminalFilterPipe,
HistorialCriminalDeleteComponent
],
imports: [
CommonModule,
CriminalsRoutingModule,
ReactiveFormsModule,
FormsModule,
NgxPaginationModule,
ModalModule.forRoot(),
]
})
export class CriminalsModule { }
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/sospechoso-list-per-day-chief/sospechoso-list-per-day-chief.component.ts
import { AuthenticationService } from '../../authentication.service';
import { SuspectService } from '../suspect.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { Suspects } from '../interfaces/suspects';
@Component({
selector: 'app-sospechoso-list-per-day-chief',
templateUrl: './sospechoso-list-per-day-chief.component.html',
styleUrls: ['./sospechoso-list-per-day-chief.component.css']
})
export class SospechosoListPerDayChiefComponent implements OnInit {
@ViewChild('viewSuspectChiefInfoModal', { static: true }) viewSuspectChiefInfoModal: ModalDirective;
userFilterSelected: string = '';
totalRecords :number;
page:number =1;
Suspects: Suspects[];
currentSuspect: Suspects;
modalOpen :boolean=false;
constructor(private suspectService:SuspectService,private authService:AuthenticationService) { }
async ngOnInit() {
await this.getRegistersPerDay();
}
async getRegistersPerDay(){
await this.suspectService.getSuspectsInsertedToday().then((resp)=>{
this.Suspects = resp;
this.totalRecords = this.Suspects.length;
})
}
ShowModal(suspect:Suspects){
this.currentSuspect = suspect;
this.modalOpen=true;
this.viewSuspectChiefInfoModal.show();
}
closeModal() {
this.viewSuspectChiefInfoModal.hide();
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/sospechoso-list/suspect-list.component.ts
import { FormGroup } from '@angular/forms';
import { SuspectService } from './../suspect.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Suspects } from '../interfaces/suspects';
import { ModalDirective } from 'ngx-bootstrap/modal';
@Component({
selector: 'app-suspect-list',
templateUrl: './suspect-list.component.html',
styleUrls: ['./suspect-list.component.css']
})
export class SuspectListComponent implements OnInit {
@ViewChild('viewSuspectInfoModal', { static: true }) viewSuspectInfoModal: ModalDirective;
userFilterSelected: string = '';
totalRecords :number;
page:number =1;
Suspects: Suspects[];
currentSuspect: Suspects;
modalOpen :boolean=false;
constructor(private SuspectService: SuspectService) {}
async ngOnInit() {
await this.getSuspects();
}
async getSuspects() {
await this.SuspectService.getSuspects().then((resp) => {
this.Suspects = resp;
this.totalRecords = this.Suspects.length;
});
}
ShowModal(suspect:Suspects){
this.currentSuspect = suspect;
this.modalOpen=true;
this.viewSuspectInfoModal.show();
}
closeModal() {
this.viewSuspectInfoModal.hide();
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Departamentos/departamento-create/departamento-create.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DepartmentService } from '../deparment.service';
@Component({
selector: 'app-departamento-create',
templateUrl: './departamento-create.component.html',
styleUrls: ['./departamento-create.component.css']
})
export class DepartamentoCreateComponent implements OnInit {
DepartmentForm : FormGroup;
constructor(private DepartmentService: DepartmentService,private formBuilder:FormBuilder) {
this.DepartmentForm = this.formBuilder.group({
departmentName: ['',Validators.required],
})
}
ngOnInit(): void {
}
async onSubmit(){
await this.DepartmentService.createDepartment(this.DepartmentForm.controls['departmentName'].value.trim()).then((resp)=>{
if (resp) {
this.DepartmentForm.setValue({
departmentName:''
})
}
});
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/^[a-zA-Z0-9_ ]*$/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/UserRepository.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using Backend.DPI.TokenUser;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public class UserRepository : IUserRepository
{
private readonly DPIContext dbContext = new DPIContext();
private readonly TokenUserService tokenUserService=new TokenUserService();
public async Task<bool> CreateUserAsync(UserDto user)
{
var result = await dbContext.Users.FirstOrDefaultAsync(u => u.Username.ToLower() == user.Username.ToLower());
if (result!=null)
{
return false;
}
var encryptedPassword = await GetSHA256(user.Password);
User uf = new User { Username = user.Username.ToLower(), Password = <PASSWORD>, RolIdRol = user.RolIdRol, DepartmentIdDepartment = user.DepartmentIdDepartment, CreationDatetime = DateTime.Now };
await dbContext.Users.AddAsync(uf);
await dbContext.SaveChangesAsync();
return true;
}
private async Task<string> GetSHA256(string str)
{
await Task.Delay(100);
SHA256 sha256 = SHA256Managed.Create();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] stream = null;
StringBuilder sb = new StringBuilder();
stream = sha256.ComputeHash(encoding.GetBytes(str));
for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
return sb.ToString();
}
public async Task<bool> DeleteUserAsync(string user)
{
var deletePrivileges = new PrivilegeRepository(dbContext);
var result = await dbContext.Users.FirstOrDefaultAsync(u => u.Username.ToLower() == user.ToLower());
if (result == null)
{
return false;
}
var resultDeletePrivilege = await deletePrivileges.DeleteUserRolPrivilegeByUserAsync(user);
dbContext.Users.Remove(result);
await dbContext.SaveChangesAsync();
return true;
}
//User Data, privilegios
public async Task<object> GetUserByUsernameAsync(string username)
{
var result = await (from a in dbContext.Users
join b in dbContext.Rols on a.RolIdRol equals b.IdRol
join c in dbContext.Departments on a.DepartmentIdDepartment equals c.IdDepartment
where a.Username == username
select new { Username = a.Username, FechaCreacion = a.CreationDatetime, NombreRol = b.Name, NombreDepartamento = c.Name,a.RolIdRol,a.DepartmentIdDepartment }).FirstOrDefaultAsync();
if (result == null)
{
return null;
}
return result;
}
public async Task<IReadOnlyList<object>> GetUsersAsync()
{
var result = await (from a in dbContext.Users
join b in dbContext.Rols on a.RolIdRol equals b.IdRol
join c in dbContext.Departments on a.DepartmentIdDepartment equals c.IdDepartment
select new { Username = a.Username, FechaCreacion = a.CreationDatetime, NombreRol = b.Name,NombreDepartamento = c.Name }).OrderBy(users => users.Username).ToListAsync();
if (result == null)
{
return null;
}
return result;
}
public async Task<bool> UpdatePasswordUserAsync(string username, string password)
{
User result = await dbContext.Users.FirstOrDefaultAsync(u => u.Username.ToLower() == username.ToLower());
if (result == null)
{
return false;
}
result.Password = <PASSWORD>;
await dbContext.SaveChangesAsync();
return true;
}
public async Task<bool> UpdateRolUserAsync(string username, int rol)
{
User result = await dbContext.Users.FirstOrDefaultAsync(u => u.Username.ToLower() == username.ToLower());
Rol dp = await dbContext.Rols.FirstOrDefaultAsync(r => r.IdRol == rol);
if (result == null || dp == null)
{
return false;
}
result.RolIdRol = rol;
await dbContext.SaveChangesAsync();
return true;
}
public async Task<bool> UpdateDepartmentUserAsync(string username, int department)
{
User result = await dbContext.Users.FirstOrDefaultAsync(u => u.Username.ToLower() == username.ToLower());
Department dp = dbContext.Departments.FirstOrDefault(d => d.IdDepartment == department);
if (result == null || dp == null)
{
return false;
}
result.DepartmentIdDepartment = department;
await dbContext.SaveChangesAsync();
return true;
}
public async Task<bool> UpdateUser(UserDto user)
{
User result = await dbContext.Users.FirstOrDefaultAsync(u => u.Username.ToLower() == user.Username.ToLower());
if (result == null)
{
return false;
}
if (user.Password != null)
{
var encryptedPassword = await GetSHA256(user.Password);
result.Password = <PASSWORD>;
}
result.RolIdRol = user.RolIdRol;
result.DepartmentIdDepartment = user.DepartmentIdDepartment;
await dbContext.SaveChangesAsync();
return true;
}
public async Task<object> LoginAsync(string Username,string Password)
{
var encryptedPassword = await GetSHA256(Password);
var data = await (from user in dbContext.Users
join department in dbContext.Departments on user.DepartmentIdDepartment equals department.IdDepartment
join rol in dbContext.Rols on user.RolIdRol equals rol.IdRol
where user.Username == Username && user.Password== encrypted<PASSWORD>
select new
{
Username = user.Username,
Rol = rol.Name,
Department= department.Name,
idDepartment = department.IdDepartment
}).FirstOrDefaultAsync();
if (data == null) return null;
return new {
Username = data.Username,
Rol = data.Rol,
Department = data.Department,
idDepartment = data.idDepartment,
TokenString = await tokenUserService.GetTokenAsync()
};
}
public async Task<object> UpdateTokenAsync(string Token) {
var validateToken = await tokenUserService.TokenValidationUserAsync(Token);
if (!validateToken) {
return null;
}
var result = await tokenUserService.GetTokenAsync();
if (result == null) return null;
return new {Token = result } ;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/RolesRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using Backend.DPI.Repository;
using Microsoft.EntityFrameworkCore;
namespace Backend.DPI.Services
{
public class RolesRepository :IRolesRepository
{
private DPIContext dbContext = new DPIContext();
public async Task<bool> CreateRolAsync(string rolName)
{
Rol rl = new Rol {Name= rolName };
await dbContext.Rols.AddAsync(rl);
await dbContext.SaveChangesAsync();
return true;
}
public async Task<bool> DeleteRolAsync(string rol)
{
var result = await dbContext.Rols.FirstOrDefaultAsync(u => u.Name.ToLower() == rol.ToLower());
if (result == null)
{
return false;
}
dbContext.Rols.Remove(result);
await dbContext.SaveChangesAsync();
return true;
}
public async Task<IReadOnlyList<Rol>> GetRoles()
{
return await dbContext.Rols.OrderBy(rols=>rols.Name).ToListAsync();
}
public async Task<Rol> getRolbyName(string rolName)
{
var result = await dbContext.Rols.FirstOrDefaultAsync(u => u.Name.ToLower() == rolName.ToLower());
if (result == null)
{
return null;
}
return result;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/rol_privileges/rol_privilege.service.ts
import { Injectable } from '@angular/core';
import { WEB_SERVICE } from '../configurations/config';
import { HttpClient } from '@angular/common/http';
import Swal from 'sweetalert2';
import { CreateRolPrivilege } from './interfaces/rol-privilege';
@Injectable({
providedIn: 'root',
})
export class RolPrivilegeService {
constructor(private http: HttpClient) {}
async getRolPrivileges() {
Swal.fire({
title: 'Espere un momento',
html: 'Cargando Roles por privilegios',
didOpen: () => {
Swal.showLoading();
},
});
const url = `${WEB_SERVICE}Privilege/GetRolPrivileges`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async getRols() {
const url = `${WEB_SERVICE}Roles/GetRols`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
this.errorMessage('Error extrayendo roles');
});
return answer;
}
async getPrivileges() {
const url = `${WEB_SERVICE}Privilege/GetPrivileges`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
this.errorMessage('Error extrayendo privilegios');
});
return answer;
}
async createRolPrivilege(createRolPrivilege: CreateRolPrivilege) {
let body = {
rolIdRol: createRolPrivilege.rolIdRol,
privilegeIdPrivilege: createRolPrivilege.privilegeIdPrivilege
};
const url = `${WEB_SERVICE}Privilege/CreateRolPrivilege`;
let answer: any = {};
await this.http
.post(url, body)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se ha creado el rol por privilegio!');
})
.catch(async (error) => {
this.errorMessage('Error creando rol por privilegio');
});
return answer;
}
async getRolPrivilegeByName(nameRolPrivilege: string) {
const url = `${WEB_SERVICE}Privilege/GetRolPrivilegeByName?NameRolPrivilege=${nameRolPrivilege}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
this.succesMessage('Rol por privilegio encontrado satisfactoriamente');
})
.catch(async (error) => {
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async deleteRolPrivilege(idRolPrivilege: number) {
const url = `${WEB_SERVICE}Privilege/DeleteRolPrivilegeById?idRolPrivilege=${idRolPrivilege}`;
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han eliminado el dato con exito!');
})
.catch(async (error) => {
this.errorMessage('Error al eliminar el rol por privilegio');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/suspect.module.ts
import { SuspectFilterPipe } from './pipes/suspect-filter.pipe';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ModalModule } from 'ngx-bootstrap/modal';
import { SuspectListComponent } from './sospechoso-list/suspect-list.component';
import { SuspectRoutingModule } from './suspect-routing.module';
import { SospechosoCreateComponent } from './sospechoso-create/sospechoso-create.component';
import { NgxPaginationModule } from 'ngx-pagination';
import { SospechosoListPerDayComponent } from './sospechoso-list-per-day/sospechoso-list-per-day.component';
import { SospechosoUpdateComponent } from './sospechoso-update/sospechoso-update.component';
import { SospechosoDeleteComponent } from './sospechoso-delete/sospechoso-delete.component';
import { SospechosoListPerDayChiefComponent } from './sospechoso-list-per-day-chief/sospechoso-list-per-day-chief.component';
@NgModule({
declarations: [
SuspectFilterPipe,
SuspectListComponent,
SospechosoCreateComponent,
SospechosoListPerDayComponent,
SospechosoUpdateComponent,
SospechosoDeleteComponent,
SospechosoListPerDayChiefComponent
],
imports: [
CommonModule,
SuspectRoutingModule,
FormsModule,
ModalModule.forRoot(),
ReactiveFormsModule,
NgxPaginationModule,
],
})
export class SuspectModule {}
<file_sep>/Backend.DPI/Backend.DPI/Controllers/CriminalRecordController.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using Backend.DPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize]
public class CriminalRecordController : Controller
{
private readonly ICriminalRecordRepository criminalRecord;
public CriminalRecordController(ICriminalRecordRepository criminalRecord)
{
this.criminalRecord = criminalRecord;
}
[HttpGet("GetCriminalRecords")]
public async Task<ActionResult<IEnumerable<CriminalRecordDto>>> GetCriminalRecords() {
var result = await criminalRecord.GetCriminalRecordsAsync();
if (result == null) return Ok(null);
return Ok(result.Select(x => new CriminalRecordDto
{
Crime=x.Crime,
IdCriminalRecord=x.IdCriminalRecord,
ModuleCellPrison=x.ModuleCellPrison,
PenitentiaryCenter=x.PenitentiaryCenter,
SentenceFinalDate=x.SentenceFinalDate,
SentenceStartDate=x.SentenceStartDate,
SuspectDni=x.SuspectDni,
}));
}
[HttpPost("AddCriminalRecord")]
public async Task<ActionResult<bool>> AddCriminalRecord([FromBody] CriminalRecord CriminalRecord) {
var result = await criminalRecord.AddCriminalRecordAsync(CriminalRecord);
return Ok(result);
}
[HttpDelete("DeleteCriminalRecord")]
public async Task<ActionResult<bool>> DeleteCriminalRecord(int IdCriminalRecord) {
var result = await criminalRecord.DeleteCriminaRecordAsync(IdCriminalRecord);
return Ok(result);
}
[HttpGet("GetCriminalRecordByDNI")]
public async Task<IReadOnlyList<CriminalRecord>> GetCriminalRecordByDNI(string DNI) {
var result = await criminalRecord.GetCriminalRecordByDNIAsync(DNI);
return result;
}
[HttpPut("UpdateCriminalRecordByDni")]
public async Task<ActionResult<bool>> UpdateCriminalRecordByDni([FromBody] CriminalRecord CriminalRecord) {
var result = await criminalRecord.UpdateCriminalRecordAsync(CriminalRecord);
return Ok(result);
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/CriminalGroupRepository.cs
using Backend.DPI.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public class CriminalGroupRepository : ICriminalGroupRepository
{
private readonly DPIContext _dpiContext;
public CriminalGroupRepository(DPIContext dpiContext)
{
this._dpiContext = dpiContext;
}
public async Task<IReadOnlyList<CriminalGroup>> GetCriminalGroupsAsync()
{
return await this._dpiContext.CriminalGroups.OrderBy(criminalGroup=>criminalGroup.NombreGrupoCriminal).ToListAsync();
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Roles/roles-routing.module.ts
import { RolCreateComponent } from './rol-create/rol-create.component';
import { RolDeleteComponent } from './rol-delete/rol-delete.component';
import { RolListComponent } from './rol-list/rol-list.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'Listar Rol',
component: RolListComponent,
data: { title: 'List' },
},
{
path: 'Eliminar Rol',
component: RolDeleteComponent,
data: { title: 'List' },
},
{
path: 'Crear Rol',
component: RolCreateComponent,
data: { title: 'List' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class RolesRoutingModule {}<file_sep>/Backend.DPI/Backend.DPI/ModelDto/CriminalHistoryDto.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.ModelDto
{
public partial class CriminalHistoryDto
{
public int IdCriminalData { get; set; }
public string IncidenceType { get; set; }
public string IncidenceZone { get; set; }
public string HierarchyCriminalGroup { get; set; }
public string PeriodBelong { get; set; }
public string OperationPlace { get; set; }
public string TatooType { get; set; }
public string SuspectDni { get; set; }
public int CriminalGroupIdCg { get; set; }
public virtual CriminalGroupDto CriminalGroupDto { get; set; }
public virtual SuspectDto SuspectDniNavigation { get; set; }
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/IDepartmentRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface IDepartmentRepository
{
Task<Department> CreateDepartmentAsync(string name);
Task<IReadOnlyList<Department>> GetDepartmentsAsync();
Task<Department> GetDepartmentsByNameAsync(string departmentName);
Task<bool> DeleteDepartmentAsync(string departmentName);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/user-rol-privilege/user-rol-privileges-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserAuthenticationGuard } from '../user-authentication.guard';
import { UserAddRolPrivilegeComponent } from './user-rol-privilege-crud/user-rol-privilege-create/user-rol-privilege-create.component';
import { UserRolPrivilegeDeleteComponent } from './user-rol-privilege-crud/user-rol-privilege-delete/user-rol-privilege-delete.component';
import { UserRolPrivilegeListComponent } from './user-rol-privilege-crud/user-rol-privilege-list/user-rol-privileges-list.component';
const routes: Routes = [
{
path: 'Listar Privilegios Usuarios',
component: UserRolPrivilegeListComponent,
data: { title: 'List' },
},
{
path: 'Agregar Privilegios Usuarios',
component: UserAddRolPrivilegeComponent,
data: { title: 'Add' },
},
{
path: 'Eliminar Privilegios Usuarios',
component: UserRolPrivilegeDeleteComponent,
data: { title: 'List' },
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class UserRolPrivilegesRoutingModule {}
<file_sep>/Frontend.DPI/Frontend/src/app/Departamentos/deparment.service.ts
import { User, Rol } from '../users/interfaces/user';
import { Injectable } from '@angular/core';
import { WEB_SERVICE } from '../configurations/config';
import { HttpClient } from '@angular/common/http';
import Swal from 'sweetalert2';
@Injectable({
providedIn: 'root',
})
export class DepartmentService {
constructor(private http: HttpClient) {}
async createDepartment(Departmentname:string){
const url = `${WEB_SERVICE}Department/AddDepartment?name=${Departmentname}`;
let answer: any = {};
await this.http
.post(url, Departmentname)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se ha creado el Departamento con exito!');
})
.catch(async (error) => {
this.errorMessage('Error creando un nuevo Departamento');
});
return answer;
}
async getDepartmentByName(Departmentname:string){
const url = `${WEB_SERVICE}Department/GetDepartmentByName?departmentName=${Departmentname}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('Departamento Obtenido Con Exito!');
})
.catch(async (error) => {
this.errorMessage('Este Departamento No Existe');
});
return answer;
}
async DeleteDepartment(Departmentname:string){
const url = `${WEB_SERVICE}Department/DeleteDepartment?departmentName=${Departmentname}`;
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('Departamento Eliminado Con Exito!');
})
.catch(async (error) => {
this.errorMessage('Fallo Al Eliminar Este Departamento');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/user-rol-privilege/user-rol-privilege-crud/user-rol-privilege-create/user-rol-privilege-create.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import Swal from 'sweetalert2';
import { UserRolPrivilegesService } from '../../user-rol-privileges.service';
import { RolPrivilege, User } from '../../interfaces/user-rol-privilege';
import { ValueConverter } from '@angular/compiler/src/render3/view/template';
import { UsersService } from '../../../users/users.service';
import { AuthenticationService } from '../../../authentication.service';
@Component({
selector: 'app-user-rol-privilege-create',
templateUrl: './user-rol-privilege-create.component.html',
styleUrls: ['./user-rol-privilege-create.component.css']
})
export class UserAddRolPrivilegeComponent implements OnInit {
usersData: User[];
rolPrivilegesData: RolPrivilege[];
profileForm : FormGroup;
buttonDisabled:boolean =false;
constructor(private userRolPrivilegeService: UserRolPrivilegesService,
private formBuilder:FormBuilder,
private userService: UsersService,
private auth: AuthenticationService) {
this.profileForm = this.formBuilder.group({
username: ['',Validators.required],
idRolPrivileges: ['',Validators.required],
specialPrivilege: []
})
}
async ngOnInit() {
await this.getUsers();
await this.getRolPrivileges();
}
async getUsers() {
await this.userRolPrivilegeService.getUsers().then((resp) => {
this.usersData = resp;
});
}
async getRolPrivileges() {
await this.userRolPrivilegeService.getRolPrivileges().then((resp) => {
this.rolPrivilegesData = resp;
});
}
async onSubmit(){
await this.userRolPrivilegeService.createUserRolPrivilege(this.profileForm.getRawValue()).then(async (resp) => {
if (resp) {
await this.userService.loadPrivilegesUser();
} else {
Swal.fire(
'Error',
'Error privilegio ya existe',
'error'
);
}
});
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminal-record/criminals-record-routing.module.ts
import { CriminalRecordCreateComponent } from './criminal-record-create/criminal-record-create.component';
import { CriminalRecordUpdateComponent } from './criminal-record-update/criminal-record-update.component';
import { CriminalRecordDeleteComponent } from './criminal-record-delete/criminal-record-delete.component';
import { CriminalRecordListComponent } from './criminal-record-list/criminal-record-list.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'Listar Historial Criminal',
component: CriminalRecordListComponent,
data: { title: 'update' },
},
{
path: 'Eliminar Historial Criminal',
component: CriminalRecordDeleteComponent,
data: { title: 'update' },
},
{
path: 'Modificar Historial Criminal',
component: CriminalRecordUpdateComponent,
data: { title: 'update' },
},
{
path: 'Agregar Historial Criminal',
component: CriminalRecordCreateComponent,
data: { title: 'update' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class CriminalsRecordRoutingModule { }<file_sep>/Backend.DPI/Backend.DPI/Controllers/CriminalGroupController.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize]
public class CriminalGroupController : Controller
{
private readonly ICriminalGroupRepository _criminalGroupRepository;
public CriminalGroupController(ICriminalGroupRepository criminalGroupRepository)
{
this._criminalGroupRepository = criminalGroupRepository;
}
[HttpGet("GetCriminalGroups")]
public async Task<ActionResult<CriminalGroupDto>> GetCriminalGroups() {
var result = await this._criminalGroupRepository.GetCriminalGroupsAsync();
return (result!=null)?
Ok(result.Select(x => new CriminalGroupDto
{
IdCg = x.IdCg,
NombreGrupoCriminal = x.NombreGrupoCriminal
}))
:Ok(null);
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Roles/roles.module.ts
import { RolCreateComponent } from './rol-create/rol-create.component';
import { RolDeleteComponent } from './rol-delete/rol-delete.component';
import { RolListComponent } from './rol-list/rol-list.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ModalModule } from 'ngx-bootstrap/modal';
import { RolesRoutingModule } from './roles-routing.module';
import { RolesFilterPipe } from './pipes/roles-filter.pipe';
import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
declarations: [
RolesFilterPipe,
RolListComponent,
RolDeleteComponent,
RolCreateComponent,
],
imports: [
CommonModule,
RolesRoutingModule,
FormsModule,
ModalModule.forRoot(),
ReactiveFormsModule,
NgxPaginationModule
],
})
export class RolesModule {}
<file_sep>/Frontend.DPI/Frontend/src/app/user-rol-privilege/user-rol-privilege-crud/user-rol-privilege-list/user-rol-privileges-list.component.ts
import { Component, OnInit } from '@angular/core';
import { UserRolPrivilege } from '../../../users/interfaces/user';
import { UserRolPrivilegesService } from '../../user-rol-privileges.service';
@Component({
selector: 'app-user-rol-privileges-list',
templateUrl: './user-rol-privileges-list.component.html',
styleUrls: ['./user-rol-privileges-list.component.css'],
})
export class UserRolPrivilegeListComponent implements OnInit {
userRolPriviligeFilterSelected: string = '';
userRolPrivilegesData: UserRolPrivilege[];
totalRecords :number;
page:number =1;
constructor(private userRolPrivilegesService: UserRolPrivilegesService) {}
async ngOnInit() {
await this.getDataUserRolPrivileges();
}
async getDataUserRolPrivileges() {
await this.userRolPrivilegesService.getUserRolPrivileges().then((resp) => {
this.userRolPrivilegesData = resp;
});
}
}
<file_sep>/Backend.DPI/Backend.DPI/ModelDto/CriminalRecordDto.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.ModelDto
{
public partial class CriminalRecordDto
{
public int IdCriminalRecord { get; set; }
public string Crime { get; set; }
public DateTime? SentenceStartDate { get; set; }
public DateTime? SentenceFinalDate { get; set; }
public string PenitentiaryCenter { get; set; }
public string ModuleCellPrison { get; set; }
public string SuspectDni { get; set; }
public virtual SuspectDto SuspectDniNavigation { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/criminal-delete/criminal-delete.component.ts
import { Component, OnInit } from '@angular/core';
import { CriminalsService } from '../criminals.service';
import { Criminal } from '../Interfaces/criminal-interface';
@Component({
selector: 'app-criminal-delete',
templateUrl: './criminal-delete.component.html',
styleUrls: ['./criminal-delete.component.css']
})
export class HistorialCriminalDeleteComponent implements OnInit {
criminalData: Criminal[];
dniCriminal: string;
constructor(
private criminalService:CriminalsService
) { }
ngOnInit(): void {
}
async getCriminalDataByDNI(dni:string){
await this.criminalService.getCriminalByDNI(dni).then(resp=>{
this.criminalData = resp;
console.log(this.criminalData);
})
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/PrivilegeRepository.cs
using Backend.DPI.Models;
using Backend.DPI.ModelDto;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Backend.DPI.Repository
{
public class PrivilegeRepository : IPrivilegeRepository
{
private readonly DPIContext dpiContext;
public PrivilegeRepository(DPIContext _dpiContext)
{
this.dpiContext = _dpiContext;
}
public async Task<UserRolPrivilege> AddUserRolPrivilegeAsync(UserRolPrivilege UserRolPrivilege)
{
var result = await dpiContext.UserRolPrivileges.AddAsync(new UserRolPrivilege
{
UserUsername = UserRolPrivilege.UserUsername,
SpecialPrivilege=UserRolPrivilege.SpecialPrivilege,
IdRolPrivilege=UserRolPrivilege.IdRolPrivilege
}) ;
await dpiContext.SaveChangesAsync();
return new UserRolPrivilege{
UserUsername=UserRolPrivilege.UserUsername,
IdRolPrivilege=UserRolPrivilege.IdRolPrivilege
};
}
public async Task<Privilege> CreatePrivilegeAsync(Privilege Privilege)
{
var result = await dpiContext.Privileges.AddAsync(new Privilege
{
Name=Privilege.Name,
});
await dpiContext.SaveChangesAsync();
return new Privilege
{
Name = Privilege.Name
};
}
public async Task<RolPrivilege> CreateRolPrivilegeAsync(RolPrivilege RolPrivilege)
{
var result = await dpiContext.RolPrivileges.AddAsync(new RolPrivilege
{
PrivilegeIdPrivilege = RolPrivilege.PrivilegeIdPrivilege,
RolIdRol = RolPrivilege.RolIdRol
});
await dpiContext.SaveChangesAsync();
return new RolPrivilege
{
PrivilegeIdPrivilege = RolPrivilege.PrivilegeIdPrivilege,
IdRolPrivilege = RolPrivilege.IdRolPrivilege
};
}
public async Task<bool> DeleteRolPrivilegeByIdAsync(int IdRolPrivilege)
{
var result = await dpiContext.RolPrivileges.FirstOrDefaultAsync(x => x.IdRolPrivilege == IdRolPrivilege);
if (result == null) return false;
dpiContext.RolPrivileges.Remove(result);
await dpiContext.SaveChangesAsync();
return true;
}
public async Task<bool> DeleteUserRolPrivilegeByIdAsync(int IdUserRolPrivilege)
{
var result = await dpiContext.UserRolPrivileges.FirstOrDefaultAsync(x => x.IdUserRolPrivilege == IdUserRolPrivilege);
if (result == null) return false;
dpiContext.UserRolPrivileges.Remove(result);
await dpiContext.SaveChangesAsync();
return true;
}
public async Task<IReadOnlyList<Privilege>> GetPrivilegesAsync()
{
return await dpiContext.Privileges.OrderBy(privileges => privileges.TipoPrivilegio).ToListAsync();
}
public async Task<object> GetRolPrivilegeByNameAsync(string NameRolPrivilege)
{
var result = await (from rol_Privileges in dpiContext.RolPrivileges
join rols in dpiContext.Rols on rol_Privileges.RolIdRol equals rols.IdRol
join privileges in dpiContext.Privileges on rol_Privileges.PrivilegeIdPrivilege equals privileges.IdPrivilege
where privileges.Name.ToLower()== NameRolPrivilege.ToLower()
select new
{
IdRolPrivilege = rol_Privileges.IdRolPrivilege,
Name_Rol = rols.Name,
Name_Privilege = privileges.Name
}).FirstOrDefaultAsync();
if (result == null) return null;
return result;
}
public async Task<IReadOnlyList<object>> GetUserRolPrivilegesByUserAsync(string Username)
{
var result = await (from username in dpiContext.Users
join user_rol_privilege in dpiContext.UserRolPrivileges on username.Username equals user_rol_privilege.UserUsername
join rol_privilege in dpiContext.RolPrivileges on user_rol_privilege.IdRolPrivilege equals rol_privilege.IdRolPrivilege
join rol in dpiContext.Rols on rol_privilege.RolIdRol equals rol.IdRol
join privilege in dpiContext.Privileges on rol_privilege.PrivilegeIdPrivilege equals privilege.IdPrivilege
where username.Username==Username
select new
{
IdUserRolPrivilege = user_rol_privilege.IdUserRolPrivilege,
Username=username.Username,
Name_Rol = rol.Name,
Name_Privilege = privilege.Name,
Special_Privilege = user_rol_privilege.SpecialPrivilege,
tipo_privilegio = privilege.TipoPrivilegio
}).OrderBy(q => q.tipo_privilegio).ToListAsync();
if (result.Count == 0) return null;
return result;
}
public async Task<IReadOnlyList<object>> GetRolPrivilegesAsync()
{
var result= await (from rol_Privileges in dpiContext.RolPrivileges
join rols in dpiContext.Rols on rol_Privileges.RolIdRol equals rols.IdRol
join privileges in dpiContext.Privileges on rol_Privileges.PrivilegeIdPrivilege equals privileges.IdPrivilege
select new {
IdRolPrivilege= rol_Privileges.IdRolPrivilege,
Name_Rol= rols.Name,
Name_Privilege=privileges.Name
} ).OrderBy(rol_privileges=>rol_privileges.Name_Rol).ToListAsync();
return result;
}
public async Task<IReadOnlyList<object>> GetUserRolPrivilegesAsync()
{
var result = await (from users in dpiContext.Users
join user_rol_privilege in dpiContext.UserRolPrivileges on users.Username equals user_rol_privilege.UserUsername
join rol_privilege in dpiContext.RolPrivileges on user_rol_privilege.IdRolPrivilege equals rol_privilege.IdRolPrivilege
join rol in dpiContext.Rols on rol_privilege.RolIdRol equals rol.IdRol
join privilege in dpiContext.Privileges on rol_privilege.PrivilegeIdPrivilege equals privilege.IdPrivilege
select new
{
IdUserRolPrivilege = user_rol_privilege.IdUserRolPrivilege,
Username= user_rol_privilege.UserUsername,
Special_Privilege = user_rol_privilege.SpecialPrivilege,
Name_Rol = rol.Name,
Name_Privilege = privilege.Name,
Type_Privilege=privilege.TipoPrivilegio
}).OrderBy(users_rol_privileges=>users_rol_privileges.Username).OrderBy(users_rol_privileges=>users_rol_privileges.Type_Privilege).ToListAsync();
return result;
}
public Task<IReadOnlyList<Privilege>> GetPrivilegesByUserAsync(string username)
{
//var result = await(from a in dpiContext.prvi
// join b in dpiContext.Rols on a.RolIdRol equals b.IdRol
// where a.Username == username
// select new { Username = a.Username, FechaCreacion = a.CreationDatetime, NombreRol = b.Name, NombreDepartamento = c.Name, a.RolIdRol, a.DepartmentIdDepartment, a.Password }).FirstOrDefaultAsync();
return null;
}
public async Task<bool> DeleteUserRolPrivilegeByUserAsync(string Username)
{
var result = await (from username in dpiContext.Users
join user_rol_privilege in dpiContext.UserRolPrivileges on username.Username equals user_rol_privilege.UserUsername
join rol_privilege in dpiContext.RolPrivileges on user_rol_privilege.IdRolPrivilege equals rol_privilege.IdRolPrivilege
join rol in dpiContext.Rols on rol_privilege.RolIdRol equals rol.IdRol
join privilege in dpiContext.Privileges on rol_privilege.PrivilegeIdPrivilege equals privilege.IdPrivilege
where username.Username == Username
select new UserRolPrivilege
{
IdUserRolPrivilege = user_rol_privilege.IdUserRolPrivilege,
}).ToListAsync();
if (result == null) return false;
dpiContext.UserRolPrivileges.RemoveRange(result);
await dpiContext.SaveChangesAsync();
return true;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/IUserRepository.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface IUserRepository
{
Task<bool> CreateUserAsync(UserDto user);
Task<bool> DeleteUserAsync(string user);
Task<bool> UpdatePasswordUserAsync(string username,string newUser);
Task<bool> UpdateUser(UserDto user);
Task<bool> UpdateRolUserAsync(string username, int rol);
Task<bool> UpdateDepartmentUserAsync(string username, int department);
Task<object> GetUserByUsernameAsync(string username);
Task<object> LoginAsync(string Username, string Password);
Task<IReadOnlyList<object>> GetUsersAsync();
Task<object> UpdateTokenAsync(string Token);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/user-rol-privilege/user-rol-privileges.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import Swal from 'sweetalert2';
import { WEB_SERVICE } from 'src/app/configurations/config';
import { newUserRolPrivilege } from './interfaces/user-rol-privilege';
@Injectable({
providedIn: 'root',
})
export class UserRolPrivilegesService {
constructor(private http: HttpClient) {}
token:any;
async getUserRolPrivileges() {
Swal.fire({
title: 'Espere un momento',
html: 'Cargando listado de privilegios por usuario',
didOpen: () => {
Swal.showLoading();
},
});
const url = `${WEB_SERVICE}Privilege/GetUserRolPrivileges`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async getUsers() {
const url = `${WEB_SERVICE}User/GetUsers`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
this.errorMessage('Error extrayendo usuarios');
});
return answer;
}
async getRolPrivileges() {
const url = `${WEB_SERVICE}Privilege/GetRolPrivileges`;
let answer: any;
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
this.errorMessage('Error extrayendo Privilegios');
});
return answer;
}
async createUserRolPrivilege(userRolPrivilege ) {
let body = <newUserRolPrivilege>{
userUsername: userRolPrivilege.username,
specialPrivilege: +userRolPrivilege.specialPrivilege,
idRolPrivilege: userRolPrivilege.idRolPrivileges
};
const url = `${WEB_SERVICE}Privilege/AddUserRolPrivilege`;
let answer: any = {};
await this.http
.post(url, body)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage(`¡Se ha agregado el privilegio al usuario ${body.userUsername} con exito!`);
//es aqui
})
.catch(async (error) => {
this.errorMessage(`Error agregando el privilegio al usuario ${body.userUsername}`);
});
return answer;
}
async getUserRolPrivilegeByUsername(username: string) {
Swal.fire({
title: 'Espere un momento',
html: 'Cargando privilegios del usuario',
didOpen: () => {
Swal.showLoading();
},
});
let header = new Headers();
const url = `${WEB_SERVICE}Privilege/GetUserRolPrivilegesByUser?username=${username}`;
let answer: any = {};
await this.http
.post(url,username)
.toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
this.succesMessage('Usuario encontrado satisfactoriamente');
})
.catch(async (error) => {
Swal.close();
this.errorMessage('Error extrayendo datos del usuario');
});
return answer;
}
async DeleteUserRolPrivilege(IdUserRolPrivilege: number) {
const url = `${WEB_SERVICE}Privilege/DeleteUserRolPrivilegeById?IdUserRolPrivilege=${IdUserRolPrivilege}`;
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se ha eliminado el privilegio con exito!');
})
.catch(async (error) => {
this.errorMessage('Error al eliminar el privilegio');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/privilegios/privileges.service.ts
import { User, Rol } from '../users/interfaces/user';
import { Injectable } from '@angular/core';
import { WEB_SERVICE } from '../configurations/config';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import Swal from 'sweetalert2';
@Injectable({
providedIn: 'root',
})
export class PrivilegesService {
constructor(private http: HttpClient) {}
async getPrivileges(){
const url = `${WEB_SERVICE}Privilege/GetPrivileges` ;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Fallo al Obtener Privilegios');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Departamentos/department-routing.module.ts
import {DepartamentoCreateComponent } from './departamento-create/departamento-create.component';
import { DepartamentoDeleteComponent } from './departamento-delete/departamento-delete.component';
import { DepartamentoListComponent } from './departamento-list/departamento-list.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'Listar Departamentos',
component: DepartamentoListComponent,
data: { title: 'List' },
},
{
path: 'Eliminar Departamentos',
component: DepartamentoDeleteComponent,
data: { title: 'List' },
},
{
path: 'Crear Departamentos',
component: DepartamentoCreateComponent,
data: { title: 'List' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class DepartamentRoutingModule {}<file_sep>/Frontend.DPI/Frontend/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import Swal from 'sweetalert2';
import { AuthenticationService } from '../authentication.service';
import { User } from '../users/interfaces/user';
import { UsersService } from '../users/users.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
submitted = false;
returnUrl: string;
newUser: User = {} as User;
constructor(private formBuilder: FormBuilder, private route: ActivatedRoute,private router: Router,private auth: AuthenticationService,private userService :UsersService ) {
if (this.auth.isLoggedIn) {
this.router.navigate(['/']);
}
}
ngOnInit(): void {
this.loginForm = this.formBuilder.group({
user: ['', Validators.required],
password: ['', Validators.required],
});
}
get f() {
return this.loginForm.controls;
}
async onSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
await this.auth.login(this.f.user.value, this.f.password.value).then(async (resp)=>{
if (resp) {
await this.userService.loadPrivilegesUser();
this.router.navigate(['home']);
} else {
Swal.fire(
'Error',
'La credenciales no concuerdan con los registros existentes'
);
}
});
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/privilegios/pipes/privileges-filter.pipe.ts
import { User } from '../../users/interfaces/user';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'privilegeFilter'
})
export class PrivilegesFilterPipe implements PipeTransform {
transform(array: any[], query: string): any {
try {
if (!array[0]){
return;
}
if (query) {
var data: any[] = [];
var elemnts= [] = query.split(' ');
var concatenar:any = "";
array.forEach(i => {
let valida:any = [];
Object.keys(i).forEach(async function(k, v) {
concatenar += String(i[k]) + ' ';
});
elemnts.forEach(element => {
if(concatenar.toUpperCase().indexOf(element.toUpperCase()) > -1){
valida.push(true);
}
});
if(elemnts.length == valida.length){
data.push(i);
}
concatenar = "";
});
return data;
}
} catch (error) {
}
return array;
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/sospechoso-delete/sospechoso-delete.component.ts
import { SuspectService } from './../suspect.service';
import { Component, OnInit } from '@angular/core';
import Swal from 'sweetalert2';
import { Suspects } from '../interfaces/suspects';
@Component({
selector: 'app-sospechoso-delete',
templateUrl: './sospechoso-delete.component.html',
styleUrls: ['./sospechoso-delete.component.css']
})
export class SospechosoDeleteComponent {
userFilterSelected: string = '';
suspectData: Suspects ;
constructor(private suspectService: SuspectService) {}
async getSuspectByDni(dniSuspect: string) {
await this.suspectService.getSuspectByDNI(dniSuspect.trim()).then((resp) => {
if (resp) {
this.suspectData = resp;
}
});
}
async DeleteSuspect(dni: string) {
Swal.fire({
title: '¿Seguro que desea eliminar el usuario?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.suspectService.deleteSuspect(dni.trim()).then((resp) => {
if (resp == true) {
this.suspectData = null;
this.userFilterSelected ='';
}else{
}
});
}
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/criminal-create/criminal-create.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, PatternValidator, Validators } from '@angular/forms';
import { CriminalsService } from '../criminals.service';
import { CriminalGroup } from '../Interfaces/criminal-interface';
@Component({
selector: 'app-criminal-create',
templateUrl: './criminal-create.component.html',
styleUrls: ['./criminal-create.component.css']
})
export class HistorialCriminalCreateComponent implements OnInit {
validForm:boolean =true;
criminalForm : FormGroup;
criminalGroups : CriminalGroup[];
constructor(
private formBuilder:FormBuilder,
private criminalService:CriminalsService) {
this.criminalForm = this.formBuilder.group({
incidenceType: [''],
incidenceZone: [''],
hierarchyCriminalGroup: ['',Validators.required],
periodBelong: ['',Validators.required],
operationPlace: ['',Validators.required],
tatooType: [''],
suspectDni: ['',[Validators.required,Validators.pattern('[0-9]+')]],
criminalGroupIdCg: ['',Validators.required],
})
}
async ngOnInit(){
await this.getCriminalGroups();
}
get suspectDni() {
return this.criminalForm.get('suspectDni');
}
async getCriminalGroups(){
await this.criminalService.getCriminalGroups().then(resp=>{
if(resp){
this.criminalGroups = resp;
}
})
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
onSubmit(){
if(this.criminalForm.valid){
this.validForm = true;
this.criminalService.createCriminal(this.criminalForm.getRawValue()).then(resp=>{
console.log(resp);
})
}else{
this.validForm = false;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Departamentos/departamento-list/departamento-list.component.ts
import { Department } from './../../users/interfaces/user';
import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../users/users.service';
@Component({
selector: 'app-departamento-list',
templateUrl: './departamento-list.component.html',
styleUrls: ['./departamento-list.component.css']
})
export class DepartamentoListComponent implements OnInit {
totalRecords :number;
page:number =1;
userFilterSelected: string = '';
Departments: Department[];
constructor(private userService: UsersService) {}
async ngOnInit() {
await this.getDepartments();
}
async getDepartments() {
await this.userService.getDepartments().then((resp) => {
this.Departments = resp;
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/criminals-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HistorialCriminalCreateComponent } from './criminal-create/criminal-create.component';
import { HistorialCriminalDeleteComponent } from './criminal-delete/criminal-delete.component';
import { HistorialCriminalListComponent } from './criminal-list/criminal-list.component';
import { HistorialCriminalUpdateComponent } from './criminal-update/criminal-update.component';
const routes: Routes = [
{
path: 'Agregar Historial Delictivo',
component: HistorialCriminalCreateComponent,
data: { title: 'update' },
},
{
path: 'Listar Historial Delictivo',
component: HistorialCriminalListComponent,
data: { title: 'update' },
},
{
path: 'Modificar Historial Delictivo',
component: HistorialCriminalUpdateComponent,
data: { title: 'update' },
},
{
path: 'Eliminar Historial Delictivo',
component: HistorialCriminalDeleteComponent,
data: { title: 'update' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class CriminalsRoutingModule { }<file_sep>/Frontend.DPI/Frontend/src/app/user-rol-privilege/interfaces/user-rol-privilege.ts
export interface UserRolPrivilge{
idUserRolPrivilege: number,
username: string,
special_Privilege: number,
name_Rol: string,
name_Privilege: string
}
export interface User{
username: string,
nombreDepartamento: string
}
export interface RolPrivilege{
idRolPrivilege: number,
name_Rol: string,
name_Privilege: string
}
export interface newUserRolPrivilege{
userUsername:string,
specialPrivilege: number
idRolPrivilege:number
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/criminal-update/criminal-update.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { CriminalsService } from '../criminals.service';
import { Criminal, CriminalGroup } from '../Interfaces/criminal-interface';
@Component({
selector: 'app-criminal-update',
templateUrl: './criminal-update.component.html',
styleUrls: ['./criminal-update.component.css']
})
export class HistorialCriminalUpdateComponent implements OnInit {
@ViewChild('updateCriminalModal', { static: true }) updateCriminalModal: ModalDirective;
criminalData: Criminal[];
dniCriminal: string;
criminalForm : FormGroup;
criminalGroups : CriminalGroup[];
validForm:boolean=true;
constructor(
private criminalService:CriminalsService,
private formBuilder:FormBuilder
) {
this.criminalForm = this.formBuilder.group({
idCriminalData: [''],
incidenceType: [''],
incidenceZone: [''],
hierarchyCriminalGroup: [''],
periodBelong: ['',Validators.required],
operationPlace: ['',Validators.required],
tatooType: [''],
suspectDni: ['',[Validators.required,Validators.pattern('[0-9]+')]],
criminalGroupIdCg: ['',Validators.required],
})
}
async ngOnInit() {
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
async getCriminalDataByDNI(dni:string){
await this.criminalService.getCriminalByDNI(dni).then(resp=>{
this.criminalData = resp;
})
}
async ShowModal(criminal:Criminal){
await this.getCriminalGroups();
this.criminalForm = this.formBuilder.group({
idCriminalData: [criminal.idCriminalData],
incidenceType: [criminal.incidenceType],
incidenceZone: [criminal.incidenceZone],
hierarchyCriminalGroup: [criminal.hierarchyCriminalGroup],
periodBelong: [Number(criminal.periodBelong.split(' ')[0]),Validators.required],
operationPlace: [criminal.operationPlace,Validators.required],
tatooType: [criminal.tatooType],
suspectDni: [criminal.suspectDni,[Validators.required,Validators.pattern('[0-9]+')]],
criminalGroupIdCg: [criminal.criminalGroupIdCg,Validators.required],
})
this.updateCriminalModal.show();
}
async getCriminalGroups(){
await this.criminalService.getCriminalGroups().then(resp=>{
if(resp){
this.criminalGroups = resp;
}
})
}
async onSubmit(){
if(this.criminalForm.valid){
this.validForm = true;
await this.criminalService.updtCriminalData(this.criminalForm.getRawValue()).then(async resp=>{
if(resp){
this.updateCriminalModal.hide();
await this.getCriminalDataByDNI(this.dniCriminal);
}
})
}else{
this.validForm = false;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/Interfaces/criminal-interface.ts
import { User } from "src/app/users/interfaces/user";
export interface CriminalGroupIdCgNavigation {
idCg: number;
nombreGrupoCriminal: string;
criminalData: any[];
}
export interface PrivilegeIdPrivilegeNavigation {
idPrivilege: number;
name: string;
tipoPrivilegio: string;
rolPrivileges: any[];
}
export interface RolPrivilege {
idRolPrivilege: number;
privilegeIdPrivilege: number;
rolIdRol: number;
privilegeIdPrivilegeNavigation: PrivilegeIdPrivilegeNavigation;
}
export interface RolIdRolNavigation {
idRol: number;
name: string;
rolPrivileges: RolPrivilege[];
users: any[];
}
export interface UserRolPrivilege {
idUserRolPrivilege: number;
specialPrivilege: number;
userUsername: string;
idRolPrivilege: number;
}
export interface DepartmentIdDepartmentNavigation {
idDepartment: number;
name: string;
suspects: any[];
users: User[];
}
export interface CriminalRecord {
idCriminalRecord: number;
crime: string;
sentenceStartDate?: Date;
sentenceFinalDate?: Date;
penitentiaryCenter: string;
moduleCellPrison: string;
suspectDni: string;
}
export interface PoliceRecord {
idPoliceRecord: number;
reasonDetention: string;
detentionDate: Date;
detentionDepartment: string;
capturedByOrganization: string;
confiscationType: string;
confiscationQuantity: string;
confiscationDescription: string;
detentionMunicipio: string;
colonia: string;
caserio: string;
village: string;
suspectDni: string;
}
export interface SuspectDniNavigation {
dniSuspect: string;
firstName: string;
middleName: string;
thirdName: string;
lastName: string;
alias: string;
sex: string;
height: number;
weight: number;
eyesColor: string;
build: string;
personFrom: string;
ocupattion: string;
passportNumber: string;
particularSign: string;
tattoo: string;
operationPlace: string;
dateOfBirth: Date;
nationaliy: string;
age: number;
civilStatus: string;
colonia: string;
street: string;
avenue: string;
village: string;
caserio: string;
houseNumber: number;
pasaje: string;
referenceAddress: string;
department: string;
municipio: string;
recordStatus: string;
usernameRegistryData: string;
departmentIdDepartment: number;
creationDate: Date;
lastModificationUser: string;
departmentIdDepartmentNavigation: DepartmentIdDepartmentNavigation;
criminalData: any[];
criminalRecords: CriminalRecord[];
policeRecords: PoliceRecord[];
}
export interface Criminal {
idCriminalData: number;
incidenceType: string;
incidenceZone: string;
hierarchyCriminalGroup: string;
periodBelong: string;
operationPlace: string;
tatooType: string;
suspectDni: string;
criminalGroupName:string;
criminalGroupIdCg: number;
criminalGroupIdCgNavigation: CriminalGroupIdCgNavigation;
suspectDniNavigation: SuspectDniNavigation;
}
export interface CriminalGroup {
idCg:number;
nombreGrupoCriminal:string;
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/interfaces/user.ts
export interface Department {
idDepartment: number;
name: string;
users: any[];
}
export interface Privileges {
idPrivilege: number;
name: string;
rolPrivileges: any[];
}
export interface RolPrivilege {
idRolPrivilege: number;
name_Privilege: string;
name_Rol: string;
tipo_privilegio:string;
}
export interface Rol {
idRol: number;
name: string;
rolPrivileges: RolPrivilege[];
users: any[];
}
export interface UserRolPrivilege {
idUserRolPrivilege: number;
specialPrivilege: number;
userUsername: string;
idRolPrivilege: number;
}
export interface User {
username: string;
password: string;
creationDatetime: string;
fechaCreacion: string
nombreDepartamento: string;
nombreRol: string;
departmentIdDepartment: number;
rolIdRol: number;
departmentIdDepartmentNavigation: Department;
rolIdRolNavigation: Rol;
userRolPrivileges: UserRolPrivilege[];
}
export interface UserLogin{
username:string,
password:string
}<file_sep>/Frontend.DPI/Frontend/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NavbarComponent } from './navbar/navbar.component';
import { HomeComponent } from './home/home.component';
import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';
import { UserAuthenticationGuard } from './user-authentication.guard';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
{
path: '',
children: [
{
path: '',
component: HomeComponent,
canActivate: [UserAuthenticationGuard],
},
{
path: 'home',
component: HomeComponent,
canActivate: [UserAuthenticationGuard]
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./users/users.module').then((m) => m.UsersModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./rol_privileges/rol_privilege.module').then((m) => m.RolPrivilegesModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./user-rol-privilege/user-rol-privileges.module').then((m) => m.UserRolPrivilegesModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./Roles/roles.module').then((m) => m.RolesModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./Departamentos/department.module').then((m) => m.DepartmentModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./privilegios/privileges.module').then((m) => m.PrivilegesModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./sospechosos/suspect.module').then((m) => m.SuspectModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./criminals/criminals.module').then((m)=> m.CriminalsModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./criminal-record/criminals-record.module').then((m)=> m.CriminalRecordModule),
},
{
path: 'privileges',
canActivate: [UserAuthenticationGuard],
canActivateChild:[UserAuthenticationGuard],
loadChildren: () =>
import('./police-record/police-record.module').then((m)=> m.PoliceRecordModule),
},
],
},
{ path: 'login', component: LoginComponent },
{ path: '**', component: PagenotfoundComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
<file_sep>/Backend.DPI/Backend.DPI/Repository/IRolesRepository.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface IRolesRepository
{
Task<IReadOnlyList<Rol>> GetRoles();
Task<bool> CreateRolAsync(string rolName);
Task<bool> DeleteRolAsync(string user);
Task<Rol> getRolbyName(string rolName);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/criminals.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import Swal from 'sweetalert2';
import { WEB_SERVICE } from '../configurations/config';
import { Criminal } from './Interfaces/criminal-interface';
@Injectable({
providedIn: 'root'
})
export class CriminalsService {
constructor(private http: HttpClient) { }
async createCriminal(criminal:Criminal ) {
let body = {
incidenceType: criminal.incidenceType,
incidenceZone: criminal.incidenceZone,
hierarchyCriminalGroup: criminal.hierarchyCriminalGroup,
periodBelong: String(criminal.periodBelong) + ' MESES',
operationPlace: criminal.operationPlace.toUpperCase(),
tatooType: criminal.tatooType,
suspectDni: criminal.suspectDni,
criminalGroupIdCg: Number(criminal.criminalGroupIdCg),
};
const url = `${WEB_SERVICE}CriminalDatum/AddCriminalData`;
let answer: any = {};
await this.http
.post(url, body)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se han ingresado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('DNI de sospechoso aun no existe');
});
return answer;
}
async getCriminals(){
Swal.fire({
title: 'Espere un momento',
html: 'Cargando usuarios',
didOpen: () => {
Swal.showLoading();
},
});
const url = `${WEB_SERVICE}CriminalDatum/GetCriminalData`;
let answer: any;
await this.http.get(url).toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async getCriminalByDNI(dni: string) {
const url = `${WEB_SERVICE}CriminalDatum/GetCriminalDAtaByDni?DNI=${dni}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Error estrayendo datos');
});
return answer;
}
async getCriminalGroups(){
const url = `${WEB_SERVICE}CriminalGroup/GetCriminalGroups`;
let answer: any;
await this.http.get(url).toPromise()
.then(async (ApiAnswer: any) => {
Swal.close();
answer = ApiAnswer;
})
.catch(async (ApiAnswer) => {
Swal.close();
this.errorMessage('Error extrayendo datos');
});
return answer;
}
async updtCriminalData(criminal:Criminal) {
let body = {
idCriminalData: criminal.idCriminalData,
incidenceType: criminal.incidenceType,
incidenceZone: criminal.incidenceZone,
hierarchyCriminalGroup: criminal.hierarchyCriminalGroup,
periodBelong: String(criminal.periodBelong) + ' MESES',
operationPlace: criminal.operationPlace.toUpperCase(),
tatooType: criminal.tatooType,
suspectDni: criminal.suspectDni,
criminalGroupIdCg: Number(criminal.criminalGroupIdCg),
};
console.log(JSON.stringify(body));
const url = `${WEB_SERVICE}CriminalDatum/UpdateCriminalDataById`;
let answer: any = {};
await this.http
.put(url, body)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (answer)
this.succesMessage('¡Se han modificado los datos con exito!');
})
.catch(async (error) => {
this.errorMessage('Erro al modificar los datos');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/police-record/police-record-update/police-record-update.component.ts
import { PoliceRecord } from './../../criminals/Interfaces/criminal-interface';
import { PoliceRecordService } from './../police.record.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { CriminalRecordService } from '../../criminal-record/criminals.record.service';
import { CriminalRecord } from '../../criminals/Interfaces/criminal-interface';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-police-record-update',
templateUrl: './police-record-update.component.html',
styleUrls: ['./police-record-update.component.css']
})
export class PoliceRecordUpdateComponent {
@ViewChild('updateCriminalModal', { static: true }) updateCriminalModal: ModalDirective;
policeRecordData: CriminalRecord[];
dniCriminal: string ='';
criminalForm : FormGroup;
newSuspect: PoliceRecord = {} as PoliceRecord;
newCriminal :PoliceRecord;
saveDNI :string;
testCriminal:PoliceRecord
validForm:boolean=true;
constructor(
private policeService:PoliceRecordService,
private formBuilder:FormBuilder
) {
this.criminalForm = this.formBuilder.group({
colonia: [''],
confiscationDescription: [''],
confiscationQuantity: [''],
confiscationType: [''],
detentionDepartment: ['',[Validators.required]],
detentionMunicipio: ['',[Validators.required]],
reasonDetention: ['',[Validators.required]],
capturedByOrganization: ['',[Validators.required]],
caserio: [''],
village: [''],
suspectDni: ['',[Validators.required,Validators.pattern('[0-9]+')]],
})
}
onChange(newValue) {
this.newSuspect.detentionDate=newValue;
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
async getPoliceRecordByDNI(dni:string){
this.saveDNI = dni;
await this.policeService.getPoliceRecordByDNI(dni).then(resp=>{
this.policeRecordData = resp;
})
}
async ShowModal(police:PoliceRecord){
this.newSuspect = police;
this.testCriminal = police
this.criminalForm = this.formBuilder.group({
colonia: [police.colonia],
confiscationDescription: [police.confiscationDescription],
confiscationQuantity: [police.confiscationQuantity],
confiscationType: [police.confiscationType],
detentionDepartment: [police.detentionDepartment,[Validators.required]],
detentionMunicipio: [police.detentionMunicipio,[Validators.required]],
reasonDetention: [police.reasonDetention,[Validators.required]],
capturedByOrganization: [police.capturedByOrganization,[Validators.required]],
caserio: [police.caserio],
village: [police.village],
suspectDni: [police.suspectDni,[Validators.required,Validators.pattern('[0-9]+')]],
})
this.updateCriminalModal.show();
await this.getPoliceRecordByDNI(this.saveDNI);
}
async onSubmit(){
if(this.criminalForm.valid && this.newSuspect.detentionDate?.toString() != ""){
this.validForm = true;
let result:PoliceRecord = this.criminalForm.getRawValue();
result.idPoliceRecord = this.newSuspect.idPoliceRecord;
result.detentionDate = this.newSuspect.detentionDate;
this.validForm = true;
await this.policeService.updatePoliceRecord(result).then(async resp=>{
if(resp){
this.updateCriminalModal.hide();
this.newSuspect = result;
await this.getPoliceRecordByDNI(this.saveDNI);
}
})
}else{
this.newSuspect = this.testCriminal;
this.validForm = false;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/rol_privileges/rol_privilege-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RolPrivilegeDeleteComponent } from './rol_privileges_crud/rol-privilege-delete/rol-privilege-delete.component';
import { RolPrivilegeCreateComponent } from './rol_privileges_crud/rol_privilege-create/rol-privilege-create.component';
import { RolPrivilegeListComponent } from './rol_privileges_crud/rol_privilege-list/rol-privilege-list.component';
const routes: Routes = [
{
path: 'Listar Roles Privilegios',
component: RolPrivilegeListComponent,
data: { title: 'List' },
},
{
path: 'Crear Roles Privilegios',
component: RolPrivilegeCreateComponent,
data: { title: 'Create' },
},
{
path: 'Eliminar Roles Privilegios',
component: RolPrivilegeDeleteComponent,
data: { title: 'List' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class RolPrivilegeRoutingModule {}
<file_sep>/Frontend.DPI/Frontend/src/app/rol_privileges/rol_privileges_crud/rol_privilege-create/rol-privilege-create.component.ts
import { Component, OnInit } from '@angular/core';
import { Privilege,Rol } from '../../interfaces/rol-privilege';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import Swal from 'sweetalert2';
import { RolPrivilegeService } from '../../rol_privilege.service';
import { UsersService } from 'src/app/users/users.service';
@Component({
selector: 'app-rol-privilege-create',
templateUrl: './rol-privilege-create.component.html',
styleUrls: ['./rol-privilege-create.component.css']
})
export class RolPrivilegeCreateComponent implements OnInit {
rolsData: Rol[];
privilegesData: Privilege[];
profileForm : FormGroup;
buttonDisabled:boolean =false;
constructor(private userService: UsersService,
private rolPrivilegeService: RolPrivilegeService,
private formBuilder:FormBuilder) {
this.profileForm = this.formBuilder.group({
rolIdRol: ['',Validators.required],
privilegeIdPrivilege: ['',Validators.required],
})
}
async ngOnInit() {
await this.getDataRols();
await this.getDataPrivileges();
}
async getDataRols() {
await this.userService.getRols().then((resp) => {
this.rolsData = resp;
});
}
async getDataPrivileges() {
await this.rolPrivilegeService.getPrivileges().then((resp) => {
this.privilegesData = resp;
});
}
onSubmit(){
this.rolPrivilegeService.createRolPrivilege(this.profileForm.getRawValue()).then((resp) => {
if (resp) {
} else {
Swal.fire(
'Error',
'Datos ya existen',
'error'
);
}
});
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/ICriminalGroupRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface ICriminalGroupRepository
{
Task<IReadOnlyList<CriminalGroup>> GetCriminalGroupsAsync();
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/users-crud/user-list/user-list.component.ts
import { Component, OnInit } from '@angular/core';
import { User } from '../../interfaces/user';
import { UsersService } from '../../users.service';
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
styleUrls: ['./user-list.component.css'],
})
export class UserListComponent implements OnInit {
userFilterSelected: string = '';
userData: User[];
totalRecords :number;
page:number =1;
constructor(private userService: UsersService) {}
async ngOnInit() {
await this.getDataUsers();
}
async getDataUsers() {
await this.userService.getUsuers().then((resp) => {
this.userData = resp;
});
}
}
<file_sep>/Backend.DPI/Backend.DPI/ModelDto/CriminalGroupDto.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.ModelDto
{
public partial class CriminalGroupDto
{
public CriminalGroupDto()
{
CriminalData = new HashSet<CriminalHistoryDto>();
}
public int IdCg { get; set; }
public string NombreGrupoCriminal { get; set; }
public virtual ICollection<CriminalHistoryDto> CriminalData { get; set; }
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/CriminalRecordRepository.cs
using Backend.DPI.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public class CriminalRecordRepository :ICriminalRecordRepository
{
private readonly DPIContext _dpiContext;
public CriminalRecordRepository(DPIContext dpiContext)
{
this._dpiContext = dpiContext;
}
public async Task<bool> AddCriminalRecordAsync(CriminalRecord CriminalRecord)
{
await _dpiContext.CriminalRecords.AddAsync(CriminalRecord);
if(await _dpiContext.SaveChangesAsync()>0) return true;
return false;
}
public async Task<bool> DeleteCriminaRecordAsync(int IdCriminalRecord)
{
var result = await _dpiContext.CriminalRecords.FirstOrDefaultAsync(x => x.IdCriminalRecord == IdCriminalRecord);
if (result == null) return false;
_dpiContext.Remove(result);
await _dpiContext.SaveChangesAsync();
return true;
}
public async Task<IReadOnlyList<CriminalRecord>> GetCriminalRecordByDNIAsync(string DNI)
{
var result = await _dpiContext.CriminalRecords.Where(x=>x.SuspectDni==DNI).ToListAsync();
if (result == null) return null;
return result;
}
public async Task<IReadOnlyList<CriminalRecord>> GetCriminalRecordsAsync()
{
var result = await _dpiContext.CriminalRecords.ToListAsync();
if (result == null) return null;
return result;
}
public async Task<bool> UpdateCriminalRecordAsync(CriminalRecord criminalRecord)
{
var result = await _dpiContext.CriminalRecords.FirstOrDefaultAsync(x => x.IdCriminalRecord == criminalRecord.IdCriminalRecord);
if (result == null)
return false;
result.ModuleCellPrison = criminalRecord.ModuleCellPrison;
result.PenitentiaryCenter = criminalRecord.PenitentiaryCenter;
result.SentenceFinalDate = criminalRecord.SentenceFinalDate;
result.SentenceStartDate = criminalRecord.SentenceStartDate;
result.SuspectDni = criminalRecord.SuspectDni;
result.Crime = criminalRecord.Crime;
await _dpiContext.SaveChangesAsync();
return true;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Controllers/CriminalDataController.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using Backend.DPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize]
public class CriminalDatumController : Controller
{
private readonly ICriminalHistoryRepository _criminalDataRepository;
public CriminalDatumController(ICriminalHistoryRepository criminalDataRepository)
{
this._criminalDataRepository = criminalDataRepository;
}
[HttpGet("GetCriminalDataByDNI")]
public async Task<ActionResult<IEnumerable<object>>> GetCriminalDataByDNI(string DNI)
{
var result = await _criminalDataRepository.GetCriminalHistoryByDNIAsync(DNI);
if (result == null) return NotFound();
return Ok(result);
}
[HttpPost("AddCriminalData")]
public async Task<ActionResult<bool>> AddCriminalData([FromBody] CriminalHistory CriminalHistory)
{
var result = await _criminalDataRepository.AddCriminalHistoryAsync(CriminalHistory);
return Ok(result);
}
[HttpDelete("DeleteCriminalDataById")]
public async Task<ActionResult<bool>> DeleteCriminalDataById(int Id)
{
var result = await _criminalDataRepository.DeleteCriminalHistoryByIdAsync(Id);
return Ok(result);
}
[HttpGet("GetCriminalData")]
public async Task<ActionResult<IEnumerable<object>>> GetCriminalData()
{
var result = await _criminalDataRepository.GetCriminalHistoryAsync();
if (result == null) return NotFound();
return Ok(result);
}
[HttpPut("UpdateCriminalDataById")]
public async Task<ActionResult<bool>> UpdateCriminalDataById([FromBody] CriminalHistory CriminalDatum)
{
var result = await _criminalDataRepository.UpdateCriminalHistoryByIdAsync(CriminalDatum);
return Ok(result);
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/suspect.service.ts
import { Suspects } from './interfaces/suspects';
import { Injectable } from '@angular/core';
import { WEB_SERVICE } from '../configurations/config';
import { HttpClient } from '@angular/common/http';
import Swal from 'sweetalert2';
@Injectable({
providedIn: 'root',
})
export class SuspectService {
constructor(private http: HttpClient) {}
async addSuspect(suspect){
const url = `${WEB_SERVICE}Suspect/AddSuspect`;
let answer: any = {};
console.log(suspect);
await this.http
.post(url, suspect)
.toPromise()
.then((ApiAnswer: any) => {
answer = ApiAnswer;
if (answer) this.succesMessage('¡Se ha agregado el sospechos con exito!');
})
.catch((error) => {
console.log(url)
this.errorMessage('Error asegurese que este sospechoso no existe');
});
return answer;
}
async getSuspects(){
const url = `${WEB_SERVICE}Suspect/GetSuspects`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Error Al Obtener Sospechosos');
});
return answer;
}
async getSuspectsInsertedTodayByUser(username:string){
const url = `${WEB_SERVICE}Suspect/GetRegisterPerDayPerUser?username=${username}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Error Al Obtener Sospechosos');
});
return answer;
}
async getSuspectsInsertedToday(){
const url = `${WEB_SERVICE}Suspect/GetRegisterPerDay`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Error Al Obtener Sospechosos');
});
return answer;
}
async getSuspectByDNI(dni:string){
const url = `${WEB_SERVICE}Suspect/GetSuspectByDNI?dni=${dni}`;
let answer: any = {};
await this.http
.get(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
})
.catch(async (error) => {
this.errorMessage('Error Al Obtener Sospechosos');
});
return answer;
}
async deleteSuspect(dni:string){
const url = `${WEB_SERVICE}Suspect/DeleteSuspect?DNI=${dni}`;
let answer: any = {};
await this.http
.delete(url)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (ApiAnswer) {
this.succesMessage('Sospechoso Eliminado Correctamente!');
}
})
.catch(async (error) => {
this.errorMessage('Error Al Eliminar Sospechoso');
});
return answer;
}
async updateSuspect(dniLast,suspect){
const url = `${WEB_SERVICE}Suspect/UpdateSuspect?lastDNI=${dniLast}`;
let answer: any = {};
await this.http
.post(url,suspect)
.toPromise()
.then(async (ApiAnswer: any) => {
answer = ApiAnswer;
if (ApiAnswer) {
this.succesMessage('Sospechoso Modificado Correctamente!');
}
})
.catch(async (error) => {
this.errorMessage('Error Al Modificar Sospechoso');
});
return answer;
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/authentication.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import Swal from 'sweetalert2';
import { WEB_SERVICE } from './configurations/config';
import { RolPrivilege, User, UserLogin } from './users/interfaces/user';
import { JwtHelperService } from "@auth0/angular-jwt";
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser:User;
public actualUser:any;
openSidebar:boolean=false;
public isLoggedIn:boolean;
public privileges:RolPrivilege[];
constructor(private http: HttpClient,
private jwtHelper: JwtHelperService) {
this.isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
async login(user, password) {
let body=<UserLogin>{
username:user,
password:<PASSWORD>
}
let response:any;
await this.http.post(`${WEB_SERVICE}User/Login`,body)
.toPromise()
.then( res => {
if (res) this.succesMessage('Bienvenido');
response = res;
})
.catch( (err) => {
this.errorMessage('La credenciales no concuerdan con los registros existentes');
});
if (response) {
let userLog={
username:response.username,
rol:response.rol,
department: response.department,
departmentIdDepartment : response.idDepartment
}
this.isLoggedIn = true;
localStorage.setItem('currentUser', JSON.stringify(userLog));
localStorage.setItem('Token',response.tokenString)
this.currentUserSubject.next(response);
localStorage.setItem("isLoggedIn", "true");
this.currentUser = response;
this.actualUser = response;
return this.isLoggedIn
}
return false;
}
logout(){
this.openSidebar=false;
this.isLoggedIn = false;
localStorage.removeItem('currentUser');
localStorage.removeItem('Token');
localStorage.removeItem('Privileges');
localStorage.removeItem('SizePrivileges');
localStorage.setItem("isLoggedIn", "false");
}
async updateToken(token:string){
let response:any;
await this.http.get(`${WEB_SERVICE}User/UpdateToken?Token=${token}`)
.toPromise()
.then(async (res) => {
response=res;
})
.catch(async (err) => {
console.log('No se pudo validar el inicio de sesion');
// this.errorMessage('No se pudo validar el inicio de sesion');
});
if (response) {
localStorage.setItem('Token',response.token);
return true;
}
return false;
}
getToken(){
return localStorage.getItem("Token");
}
succesMessage(message) {
Swal.fire({
position: 'center',
icon: 'success',
title: message,
showConfirmButton: false,
timer: 1500,
});
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/sospechoso-create/sospechoso-create.component.ts
import { Departamentos, Nacionalidades, Suspects, EstadoCivil, Municipios } from './../interfaces/suspects';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import Swal from 'sweetalert2';
import { Department, Rol } from '../../users/interfaces/user';
import { UsersService } from '../../users/users.service';
import { AuthenticationService } from '../../authentication.service';
import { SuspectService } from '../suspect.service';
@Component({
selector: 'app-sospechoso-create',
templateUrl: './sospechoso-create.component.html',
styleUrls: ['./sospechoso-create.component.css']
})
export class SospechosoCreateComponent {
suspectForm : FormGroup;
buttonDisabled:boolean =false;
suspect:Suspects;
Nacionalidades = Nacionalidades;
Departamentos = Departamentos;
EstadoCivil = EstadoCivil;
Municipios = Municipios;
MunicipiosLst:any;
constructor(private auth: AuthenticationService,private suspectService:SuspectService,private formBuilder:FormBuilder) {
this.suspectForm = this.formBuilder.group({
dniSuspect: ['',Validators.required],
firstName: ['',Validators.required],
middleName:[''],
thirdName: ['',Validators.required],
lastName: [''],
alias: [''],
sex: ['',Validators.required],
height: [''],
weight: [''],
eyesColor: ['',Validators.required],
build: ['',Validators.required],
personFrom: ['',Validators.required],
ocupattion: ['',Validators.required],
passportNumber: [''],
particularSign: ['',Validators.required],
tattoo: [''],
operationPlace: ['',Validators.required],
dateOfBirth: [''],
nationaliy: ['',Validators.required],
age: ['',Validators.required],
civilStatus: ['',Validators.required],
colonia: [''],
street: [''],
avenue: [''],
village:[''],
caserio: [''],
houseNumber: [''],
pasaje: [''],
referenceAddress: [''],
department: ['',Validators.required],
municipio: ['',Validators.required],
usernameRegistryData: [''],
departmentIdDepartment: [''],
})
// console.log(Municipios.length);
}
onSubmit(){
this.suspect = this.suspectForm.getRawValue();
this.suspect.deleted = 0;
if (this.suspect.dateOfBirth.toString() == "") {
delete this.suspect.dateOfBirth;
}
if (this.suspect.weight.toString() == "") {
delete this.suspect.weight;
}
if (this.suspect.houseNumber.toString() == "") {
delete this.suspect.houseNumber;
}
if (this.suspect.height.toString() == "") {
delete this.suspect.height;
}
this.suspect.usernameRegistryData = this.auth.currentUser.username;
this.suspect.departmentIdDepartment = this.auth.currentUser.departmentIdDepartment;
console.log(this.suspectForm.getRawValue())
this.suspectService.addSuspect(this.suspect).then((resp) => {
if (resp == true) {
this.suspectForm.reset();
} else {
Swal.fire(
'Error',
'Error al ingresar sospechoso',
'error'
);
}
});
}
getDepartment(){
this.MunicipiosLst=Municipios[this.suspectForm.controls.department.value];
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/PoliceRecordRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Backend.DPI.Repository
{
public class PoliceRecordRepository : IPoliceRecordRepository
{
private readonly DPIContext dpiContext = new DPIContext();
public async Task<bool> CreatePoliceRecord(PoliceRecord policeRecord)
{
var result = await dpiContext.Suspects.FirstOrDefaultAsync(x => x.DniSuspect == policeRecord.SuspectDni);
if (result == null) {
return false;
}
await dpiContext.PoliceRecords.AddAsync(policeRecord);
await dpiContext.SaveChangesAsync();
return true;
}
public async Task<bool> DeletePoliceRecord(int idPoliceRecord)
{
var result = await this.dpiContext.PoliceRecords.FirstOrDefaultAsync(x => x.IdPoliceRecord == idPoliceRecord);
if (result == null)
{
return false;
}
this.dpiContext.PoliceRecords.Remove(result);
await dpiContext.SaveChangesAsync();
return true;
}
public async Task<IReadOnlyList<PoliceRecord>> GetPoliceRecord()
{
return await this.dpiContext.PoliceRecords.ToListAsync();
}
public async Task<IReadOnlyList<PoliceRecord>> GetPoliceRecordByDNISuspect(string dniSuspect)
{
var result = await this.dpiContext.PoliceRecords.Where(x => x.SuspectDni == dniSuspect).ToListAsync();
if (result == null)
{
return null;
}
return result;
}
public async Task<bool> ModifyPoliceRecord(PoliceRecord police)
{
var result = await this.dpiContext.PoliceRecords.FirstOrDefaultAsync(x => x.IdPoliceRecord == police.IdPoliceRecord);
if (result == null)
{
return false;
}
result.DetentionDate = police.DetentionDate;
result.ConfiscationType = police.ConfiscationType;
result.ConfiscationQuantity = police.ConfiscationQuantity;
result.ConfiscationDescription = police.ConfiscationDescription;
result.DetentionDepartment = police.DetentionDepartment;
result.DetentionMunicipio = police.DetentionMunicipio;
result.ReasonDetention = police.ReasonDetention;
result.SuspectDni = police.SuspectDni;
result.Village = police.Village;
result.Colonia = police.Colonia;
result.Caserio = police.Caserio;
result.CapturedByOrganization = police.CapturedByOrganization;
await this.dpiContext.SaveChangesAsync();
return true;
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminal-record/criminals-record.module.ts
import { CriminalRecordListComponent } from './criminal-record-list/criminal-record-list.component';
import { CriminalRecordUpdateComponent } from './criminal-record-update/criminal-record-update.component';
import { CriminalRecordDeleteComponent } from './criminal-record-delete/criminal-record-delete.component';
import { CriminalRecordCreateComponent } from './criminal-record-create/criminal-record-create.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgxPaginationModule } from 'ngx-pagination';
import { CriminalRecordFilterPipe } from './pipes/CriminalRecord-filter.pipe';
import { ModalModule } from 'ngx-bootstrap/modal';
import { CriminalsRecordRoutingModule } from './criminals-record-routing.module';
@NgModule({
declarations: [
CriminalRecordCreateComponent,
CriminalRecordDeleteComponent,
CriminalRecordUpdateComponent,
CriminalRecordFilterPipe,
CriminalRecordListComponent,
],
imports: [
CommonModule,
CriminalsRecordRoutingModule,
ReactiveFormsModule,
FormsModule,
NgxPaginationModule,
ModalModule.forRoot(),
]
})
export class CriminalRecordModule { }
<file_sep>/Backend.DPI/Backend.DPI/Models/Rol.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class Rol
{
public Rol()
{
RolPrivileges = new HashSet<RolPrivilege>();
Users = new HashSet<User>();
}
public int IdRol { get; set; }
public string Name { get; set; }
public virtual ICollection<RolPrivilege> RolPrivileges { get; set; }
public virtual ICollection<User> Users { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/privilegios/privileges-list/privileges-list.component.ts
import { PrivilegesService } from './../privileges.service';
import { Component, OnInit } from '@angular/core';
import { Privileges } from '../../users/interfaces/user';
@Component({
selector: 'app-privileges-list',
templateUrl: './privileges-list.component.html',
styleUrls: ['./privileges-list.component.css']
})
export class PrivilegesListComponent implements OnInit {
totalRecords :number;
page:number =1;
privilegeFilterSelected: string = '';
privileges: Privileges[];
constructor(private privilegesService: PrivilegesService) {}
async ngOnInit() {
await this.getPrivileges();
}
async getPrivileges() {
await this.privilegesService.getPrivileges().then((resp) => {
this.privileges = resp;
});
}
}
<file_sep>/Backend.DPI/Backend.DPI/ModelDto/DepartmentDto.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.ModelDto
{
public partial class DepartmentDto
{
public DepartmentDto()
{
Users = new HashSet<UserDto>();
}
public int IdDepartment { get; set; }
public string Name { get; set; }
public virtual ICollection<UserDto> Users { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/police-record/police-record-create/police-record-create.component.ts
import { PoliceRecordService } from './../police.record.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PoliceRecord } from '../../criminals/Interfaces/criminal-interface';
import Swal from 'sweetalert2';
@Component({
selector: 'app-police-record-create',
templateUrl: './police-record-create.component.html',
styleUrls: ['./police-record-create.component.css']
})
export class PoliceRecordCreateComponent implements OnInit {
validForm:boolean =true;
criminalForm : FormGroup;
criminalGroups : PoliceRecord[];
constructor(
private formBuilder:FormBuilder,
private police:PoliceRecordService) {
this.criminalForm = this.formBuilder.group({
colonia: [''],
confiscationDescription: [''],
confiscationQuantity: [''],
confiscationType: [''],
detentionDate: ['',[Validators.required]],
detentionDepartment: ['',[Validators.required]],
detentionMunicipio: ['',[Validators.required]],
reasonDetention: ['',[Validators.required]],
capturedByOrganization: ['',[Validators.required]],
caserio: [''],
village: [''],
suspectDni: ['',[Validators.required,Validators.pattern('[0-9]+')]],
})
}
async ngOnInit(){
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
onSubmit(){
if(this.criminalForm.valid){
let result = this.criminalForm.getRawValue();
this.validForm = true;
if (result.detentionDate== "") {
delete result.detentionDate;
}
this.police.createPoliceRecord(result).then(resp=>{
if (resp == true) {
this.criminalForm.reset();
}else{
this.errorMessage('No existe el DNI');
}
})
}else{
this.validForm = false;
}
}
errorMessage(message) {
Swal.fire({
title: 'Error',
text: message,
icon: 'error',
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/users/users-crud/user-update/user-update.component.ts
import { Department, Rol, User } from '../../interfaces/user';
import { Component, OnInit, ViewChild } from '@angular/core';
import { UsersService } from '../../users.service';
import { stringify } from 'querystring';
import { InvokeFunctionExpr } from '@angular/compiler';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { FormControl, FormGroup, Validators, FormBuilder, AbstractControl, ValidatorFn, ValidationErrors } from '@angular/forms';
@Component({
selector: 'app-user-update',
templateUrl: './user-update.component.html',
styleUrls: ['./user-update.component.css'],
})
export class UpdateUserComponent implements OnInit {
@ViewChild('updateUserModal', { static: true }) updateUserModal: ModalDirective;
newUser: User = {} as User;
userFilterSelected: string = '';
userData: User[];
rolsData: Rol[];
departmentsData: Department[];
profileForm : FormGroup;
buttonDisabled: boolean;
constructor(private userService: UsersService,private formBuilder:FormBuilder) {
this.profileForm = this.formBuilder.group({
username: new FormControl({value:'',disabled:true}),
password: new FormControl(''),
confirmPassword: new FormControl(''),
rolIdRol: new FormControl(''),
departmentIdDepartment: new FormControl(''),
})
}
async ngOnInit() {
this.buttonDisabled=false;
await this.getDataRols();
await this.getDataDepartments();
}
async getUserByUsername(username: string) {
await this.userService.getUserByUsername(username).then((resp) => {
this.userData = resp;
this.newUser = resp;
console.log(this.newUser.password);
this.profileForm.setValue({
username: this.newUser.username,
password: '',
confirmPassword: '',
rolIdRol: this.newUser.rolIdRol,
departmentIdDepartment: this.newUser.departmentIdDepartment,
});
});
}
checkPasswords() {
if (!this.profileForm.controls.password.dirty) {
return;
}
if (this.profileForm.get('password').value == '' && this.profileForm.get('confirmPassword').value =='') {
this.profileForm.setErrors(null);
return ''
}
if (this.profileForm.get('password').value != this.profileForm.get('confirmPassword').value || this.profileForm.get('password').value == '' ) {
this.buttonDisabled=false;
this.profileForm.setErrors({required:true})
return 'is-invalid'
}
else
this.buttonDisabled=true; true
}
ShowModal() {
this.updateUserModal.show();
}
closeModal() {
this.updateUserModal.hide();
}
async getDataRols() {
await this.userService.getRols().then((resp) => {
this.rolsData = resp;
});
}
async getDataDepartments() {
await this.userService.getDepartments().then((resp) => {
this.departmentsData = resp;
});
}
async onSubmit() {
//console.warn(this.profileForm.getRawValue());
await this.updateUser(this.profileForm.getRawValue())
}
async updateUser(newUser) {
if (newUser.password == null || newUser.password == '') {
console.log('no hay')
delete newUser.password;
delete newUser.confirmPassword;
}
await this.userService.updtUser(newUser).then((resp) => {
/* this.profileForm.setValue({
username: this.newUser.username,
password: '',
confirmPassword: '',
rolIdRol: this.newUser.rolIdRol,
departmentIdDepartment: this.newUser.departmentIdDepartment,
});*/
// this.userData[0]=newUser;
this.closeModal();
});
}
isValid(){
return !this.profileForm.dirty || this.profileForm.invalid ;
}
cleanUser(user: User) {
if (user.username != null)
user.username = user.username.replace(/[^0-9A-Za-z-._]/g, '');
if (user.password != null)
user.password = user.password.replace(/[^0-9A-Za-z-._]/g, '');
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Controllers/PrivilegeController.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using Backend.DPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize]
public class PrivilegeController : Controller
{
private readonly IPrivilegeRepository privilegeRepository;
public PrivilegeController(IPrivilegeRepository _privilegeRepository)
{
this.privilegeRepository = _privilegeRepository;
}
[HttpPost("CreatePrivilege")]
public async Task<ActionResult<PrivilegeDto>> CreatePrivilege([FromBody] Privilege Privilege)
{
var result = await privilegeRepository.CreatePrivilegeAsync(Privilege);
return Ok(new PrivilegeDto
{
Name = Privilege.Name
}); ;
}
[HttpPost("CreateRolPrivilege")]
public async Task<ActionResult<RolPrivilegeDto>> CreateRolPrivilege([FromBody] RolPrivilege RolPrivilege)
{
var result = await privilegeRepository.CreateRolPrivilegeAsync(RolPrivilege);
return Ok(new RolPrivilegeDto
{
PrivilegeIdPrivilege = RolPrivilege.PrivilegeIdPrivilege,
RolIdRol = RolPrivilege.RolIdRol
});
}
[HttpGet("GetPrivileges")]
public async Task<ActionResult<IEnumerable<PrivilegeDto>>> GetPrivileges()
{
var result = await privilegeRepository.GetPrivilegesAsync();
return Ok(result.Select(x => new PrivilegeDto
{
IdPrivilege = x.IdPrivilege,
Name = x.Name
}));
}
[HttpGet("GetRolPrivileges")]
public async Task<ActionResult<IEnumerable<RolPrivilegeDto>>> GetRolPrivileges()
{
var result = await privilegeRepository.GetRolPrivilegesAsync();
return Ok(result);
}
[HttpPost("AddUserRolPrivilege")]
public async Task<ActionResult<UserRolPrivilegeDto>> AddUserRolPrivilege(UserRolPrivilege UserRolPrivilege)
{
var result = await privilegeRepository.AddUserRolPrivilegeAsync(UserRolPrivilege);
return Ok(result = new UserRolPrivilege
{
UserUsername = UserRolPrivilege.UserUsername,
IdRolPrivilege = UserRolPrivilege.IdRolPrivilege,
SpecialPrivilege = UserRolPrivilege.SpecialPrivilege
});
}
[HttpGet("GetUserRolPrivileges")]
public async Task<ActionResult<IEnumerable<UserRolPrivilegeDto>>> GetUserRolPrivileges()
{
var result = await privilegeRepository.GetUserRolPrivilegesAsync();
return Ok(result);
}
[HttpGet("GetRolPrivilegeByName")]
public async Task<ActionResult<RolPrivilegeDto>> GetRolPrivilegeByName(string NameRolPrivilege)
{
var result = await privilegeRepository.GetRolPrivilegeByNameAsync(NameRolPrivilege);
if (result == null) return NotFound();
return Ok(result);
}
[HttpPost("GetUserRolPrivilegesByUser")]
public async Task<ActionResult<IEnumerable<RolPrivilegeDto>>> GetUserRolPrivilegesByUser(string username)
{
var result = await privilegeRepository.GetUserRolPrivilegesByUserAsync(username);
return Ok(result);
}
[HttpDelete("DeleteRolPrivilegeById")]
public async Task<ActionResult<bool>> DeleteRolPrivilegeById(int IdRolPrivilege)
{
var result = await privilegeRepository.DeleteRolPrivilegeByIdAsync(IdRolPrivilege);
return Ok(result);
}
[HttpDelete("DeleteUserRolPrivilegeById")]
public async Task<ActionResult<bool>> DeleteUserRolPrivilegeById(int IdUserRolPrivilege)
{
var result = await privilegeRepository.DeleteUserRolPrivilegeByIdAsync(IdUserRolPrivilege);
return Ok(result);
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/ICriminalHistoryRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface ICriminalHistoryRepository
{
Task<bool> AddCriminalHistoryAsync(CriminalHistory CriminalData);
Task<IReadOnlyList<object>> GetCriminalHistoryAsync();
Task<IReadOnlyList<object>> GetCriminalHistoryByDNIAsync(string DNI);
Task<bool> UpdateCriminalHistoryByIdAsync(CriminalHistory CriminalData);
Task<bool> DeleteCriminalHistoryByIdAsync(int IdCriminalData);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminal-record/criminal-record-update/criminal-record-update.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { CriminalsService } from '../../criminals/criminals.service';
import { Criminal, CriminalGroup, CriminalRecord } from '../../criminals/Interfaces/criminal-interface';
import { CriminalRecordService } from '../criminals.record.service';
@Component({
selector: 'app-criminal-record-update',
templateUrl: './criminal-record-update.component.html',
styleUrls: ['./criminal-record-update.component.css']
})
export class CriminalRecordUpdateComponent implements OnInit {
@ViewChild('updateCriminalModal', { static: true }) updateCriminalModal: ModalDirective;
criminalData: CriminalRecord[];
dniCriminal: string;
criminalForm : FormGroup;
newSuspect: CriminalRecord = {} as CriminalRecord;
newCriminal :CriminalRecord;
saveDNI :string;
testCriminal:CriminalRecord
validForm:boolean=true;
constructor(
private criminalService:CriminalRecordService,
private formBuilder:FormBuilder
) {
this.criminalForm = this.formBuilder.group({
idCriminalRecord:[''],
crime: [''],
sentenceStartDate: [''],
sentenceFinalDate: [''],
penitentiaryCenter: [''],
moduleCellPrison: [''],
suspectDni: ['',[Validators.required,Validators.pattern('[0-9]+')]],
})
}
async ngOnInit() {
}
onChange(newValue) {
this.newSuspect.sentenceStartDate=newValue;
}
onChange2(newValue) {
this.newSuspect.sentenceFinalDate=newValue;
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
async getCriminalRecordByDNI(dni:string){
this.saveDNI = dni;
await this.criminalService.getCriminalByDNI(dni).then(resp=>{
this.criminalData = resp;
})
}
async ShowModal(criminal:CriminalRecord){
this.newSuspect = criminal;
this.testCriminal = criminal
this.criminalForm = this.formBuilder.group({
idCriminalRecord:[criminal.idCriminalRecord],
crime: [criminal.crime],
sentenceStartDate: [criminal.sentenceStartDate],
sentenceFinalDate: [criminal.sentenceFinalDate],
penitentiaryCenter: [criminal.penitentiaryCenter],
moduleCellPrison: [criminal.moduleCellPrison],
suspectDni: [criminal.suspectDni,[Validators.required,Validators.pattern('[0-9]+')]],
})
this.updateCriminalModal.show();
await this.getCriminalRecordByDNI(this.saveDNI);
}
async onSubmit(){
if(this.criminalForm.valid){
this.validForm = true;
let result:CriminalRecord = this.criminalForm.getRawValue();
result.sentenceFinalDate = this.newSuspect.sentenceFinalDate;
result.sentenceStartDate = this.newSuspect.sentenceStartDate;
this.validForm = true;
if (result.sentenceFinalDate?.toString()== "") {
delete result.sentenceFinalDate;
}
if (result.sentenceStartDate?.toString() == "") {
delete result.sentenceStartDate;
}
await this.criminalService.updtCriminalRecord(result).then(async resp=>{
if(resp){
this.updateCriminalModal.hide();
this.newSuspect = result;
await this.getCriminalRecordByDNI(this.saveDNI);
}
})
}else{
this.newSuspect = this.testCriminal;
this.validForm = false;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/CriminalHistoryRepository.cs
using Backend.DPI.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public class CriminalHistoryRepository : ICriminalHistoryRepository
{
private readonly DPIContext _dpiContext;
public CriminalHistoryRepository(DPIContext dpiContext)
{
this._dpiContext = dpiContext;
}
public async Task<bool> AddCriminalHistoryAsync(CriminalHistory CriminalData)
{
await _dpiContext.CriminalHistories.AddAsync(CriminalData);
if (await _dpiContext.SaveChangesAsync()>0) return true;
return false;
}
public async Task<bool> DeleteCriminalHistoryByIdAsync(int IdCriminalData)
{
var result = await _dpiContext.CriminalHistories.FirstOrDefaultAsync(x => x.IdCriminalHistory == IdCriminalData);
if (result == null) return false;
_dpiContext.Remove(result);
await _dpiContext.SaveChangesAsync();
return true;
}
public async Task<IReadOnlyList<object>> GetCriminalHistoryAsync()
{
var result = await (from criminal_data in _dpiContext.CriminalHistories
join criminal_group in _dpiContext.CriminalGroups on criminal_data.CriminalGroupIdCg equals criminal_group.IdCg
select new
{
IdCriminalData = criminal_data.IdCriminalHistory,
IncidenceType = criminal_data.IncidenceType,
IncidenceZone = criminal_data.IncidenceZone,
OperationPlace = criminal_data.OperationPlace,
PeriodBelong = criminal_data.PeriodBelong,
TatooType = criminal_data.TatooType,
SuspectDni = criminal_data.SuspectDni,
HierarchyCriminalGroup = criminal_data.HierarchyCriminalGroup,
CriminalGroupName = criminal_group.NombreGrupoCriminal
}).ToListAsync();
if (result == null) return null;
return result;
}
public async Task<IReadOnlyList<object>> GetCriminalHistoryByDNIAsync(string DNI)
{
var result = await (from criminal_data in _dpiContext.CriminalHistories
join criminal_group in _dpiContext.CriminalGroups on criminal_data.CriminalGroupIdCg equals criminal_group.IdCg
where criminal_data.SuspectDni.Contains(DNI)
select new
{
IdCriminalData = criminal_data.IdCriminalHistory,
IncidenceType = criminal_data.IncidenceType,
IncidenceZone = criminal_data.IncidenceZone,
OperationPlace = criminal_data.OperationPlace,
PeriodBelong = criminal_data.PeriodBelong,
TatooType = criminal_data.TatooType,
SuspectDni = criminal_data.SuspectDni,
HierarchyCriminalGroup = criminal_data.HierarchyCriminalGroup,
CriminalGroupName = criminal_group.NombreGrupoCriminal,
CriminalGroupIdCg = criminal_data.CriminalGroupIdCg
}).ToListAsync();
if (result == null) return null;
return result;
}
public async Task<bool> UpdateCriminalHistoryByIdAsync(CriminalHistory CriminalData)
{
var result = await _dpiContext.CriminalHistories.FirstOrDefaultAsync(x => x.IdCriminalHistory == CriminalData.IdCriminalHistory);
if (result == null)
return false;
result.SuspectDni = CriminalData.SuspectDni;
result.CriminalGroupIdCg = CriminalData.CriminalGroupIdCg;
result.PeriodBelong = CriminalData.PeriodBelong;
result.TatooType = CriminalData.TatooType;
result.OperationPlace = CriminalData.OperationPlace;
result.IncidenceType = CriminalData.IncidenceType;
result.HierarchyCriminalGroup = CriminalData.HierarchyCriminalGroup;
result.IncidenceZone = CriminalData.IncidenceZone;
await _dpiContext.SaveChangesAsync();
return true;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Models/Suspect.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class Suspect
{
public Suspect()
{
CriminalHistories = new HashSet<CriminalHistory>();
CriminalRecords = new HashSet<CriminalRecord>();
PoliceRecords = new HashSet<PoliceRecord>();
}
public string DniSuspect { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string ThirdName { get; set; }
public string LastName { get; set; }
public string Alias { get; set; }
public string Sex { get; set; }
public float? Height { get; set; }
public float? Weight { get; set; }
public string EyesColor { get; set; }
public string Build { get; set; }
public string PersonFrom { get; set; }
public string Ocupattion { get; set; }
public string PassportNumber { get; set; }
public string ParticularSign { get; set; }
public string Tattoo { get; set; }
public string OperationPlace { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Nationaliy { get; set; }
public int Age { get; set; }
public string CivilStatus { get; set; }
public string Colonia { get; set; }
public string Street { get; set; }
public string Avenue { get; set; }
public string Village { get; set; }
public string Caserio { get; set; }
public int? HouseNumber { get; set; }
public string Pasaje { get; set; }
public string ReferenceAddress { get; set; }
public string Department { get; set; }
public string Municipio { get; set; }
public int? Deleted { get; set; }
public string UsernameRegistryData { get; set; }
public int DepartmentIdDepartment { get; set; }
public DateTime CreationDate { get; set; }
public string LastModificationUser { get; set; }
public virtual Department DepartmentIdDepartmentNavigation { get; set; }
public virtual ICollection<CriminalHistory> CriminalHistories { get; set; }
public virtual ICollection<CriminalRecord> CriminalRecords { get; set; }
public virtual ICollection<PoliceRecord> PoliceRecords { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/privilegios/privileges.module.ts
import { PrivilegesListComponent } from './privileges-list/privileges-list.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ModalModule } from 'ngx-bootstrap/modal';
import { PrivilegesRoutingModule } from './privileges-routing.module';
import { PrivilegesFilterPipe } from './pipes/privileges-filter.pipe';
import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
declarations: [
PrivilegesFilterPipe,
PrivilegesListComponent,
],
imports: [
CommonModule,
PrivilegesRoutingModule,
FormsModule,
ModalModule.forRoot(),
ReactiveFormsModule,
NgxPaginationModule
],
})
export class PrivilegesModule {}
<file_sep>/Frontend.DPI/Frontend/src/app/user-rol-privilege/user-rol-privileges.module.ts
import { NgxPaginationModule } from 'ngx-pagination';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ModalModule } from 'ngx-bootstrap/modal';
import { UserRolPrivilegesRoutingModule } from './user-rol-privileges-routing.module';
import { UserRolPrivilegeFilterPipe } from './pipes/user-rol-privilege-filter.pipe';
import { UserRolPrivilegeListComponent } from './user-rol-privilege-crud/user-rol-privilege-list/user-rol-privileges-list.component';
import { UserAddRolPrivilegeComponent } from './user-rol-privilege-crud/user-rol-privilege-create/user-rol-privilege-create.component';
import { UserRolPrivilegeDeleteComponent } from './user-rol-privilege-crud/user-rol-privilege-delete/user-rol-privilege-delete.component';
@NgModule({
declarations: [
UserRolPrivilegeFilterPipe,
UserRolPrivilegeListComponent,
UserAddRolPrivilegeComponent,
UserRolPrivilegeDeleteComponent
],
imports: [
CommonModule,
UserRolPrivilegesRoutingModule,
FormsModule,
ModalModule.forRoot(),
ReactiveFormsModule,
NgxPaginationModule
],
})
export class UserRolPrivilegesModule {}
<file_sep>/Backend.DPI/Backend.DPI/TokenUser/TokenUserService.cs
using Backend.DPI.TokenUser;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Backend.DPI.TokenUser
{
public class TokenUserService
{
private readonly string ServerFrontEnd = "https://dpihn.azurewebsites.net";
public async Task<bool> TokenValidationUserAsync(string Token) {
await Task.Delay(100);
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("<KEY>"));
var myIssuer = ServerFrontEnd;
var myAudience = ServerFrontEnd;
var tokenHandler = new JwtSecurityTokenHandler();
try
{
tokenHandler.ValidateToken(Token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = myIssuer,
ValidAudience = myAudience,
IssuerSigningKey = secretKey
}, out SecurityToken validatedToken);
}
catch
{
return false;
}
return true;
}
public async Task<string> GetTokenAsync()
{
await Task.Delay(100);
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("<KEY>"));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokeOptions = new JwtSecurityToken(
issuer: ServerFrontEnd,
audience: ServerFrontEnd,
claims: new List<Claim>(),
expires: DateTime.Now.AddMinutes(60),
signingCredentials: signinCredentials
);
return new JwtSecurityTokenHandler().WriteToken(tokeOptions);
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/sospechosos/sospechoso-update/sospechoso-update.component.ts
import { SuspectService } from './../suspect.service';
import { UsersService } from './../../users/users.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { stringify } from 'querystring';
import { InvokeFunctionExpr } from '@angular/compiler';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { FormControl, FormGroup, Validators, FormBuilder, AbstractControl } from '@angular/forms';
import { Department, Rol, User } from '../../users/interfaces/user';
import { Departamentos, EstadoCivil, Municipios, Nacionalidades, Suspects } from '../interfaces/suspects';
import { AuthenticationService } from '../../authentication.service';
import { DatePipe, formatDate } from '@angular/common';
@Component({
selector: 'app-sospechoso-update',
templateUrl: './sospechoso-update.component.html',
styleUrls: ['./sospechoso-update.component.css']
})
export class SospechosoUpdateComponent implements OnInit {
@ViewChild('updateUserModal', { static: true }) updateUserModal: ModalDirective;
newSuspect: Suspects = {} as Suspects;
userFilterSelected: string = '';
suspectForm : FormGroup;
buttonDisabled: boolean;
suspectData: Suspects ;
isDirty:boolean=false;
data:any;
MunicipiosLst:any;
Nacionalidades = Nacionalidades;
Departamentos = Departamentos;
EstadoCivil = EstadoCivil;
Municipios = Municipios;
constructor(private suspectService: SuspectService,private formBuilder:FormBuilder,private auth: AuthenticationService,public datepipe: DatePipe) {
this.suspectForm = this.formBuilder.group({
dniSuspect: ['',Validators.required],
firstName: ['',Validators.required],
middleName:'',
thirdName: ['',Validators.required],
lastName: [''],
alias: [''],
sex: ['',Validators.required],
height: [''],
weight: [''],
eyesColor: ['',Validators.required],
build: ['',Validators.required],
personFrom: ['',Validators.required],
ocupattion: ['',Validators.required],
passportNumber: [''],
particularSign: ['',Validators.required],
tattoo: [''],
operationPlace: ['',Validators.required],
dateOfBirth: [''],
nationaliy: ['',Validators.required],
age: ['',Validators.required],
civilStatus: ['',Validators.required],
colonia: [''],
street: [''],
avenue: [''],
village:[''],
caserio: [''],
houseNumber: ['0'],
pasaje: [''],
referenceAddress: [''],
department: ['',Validators.required],
municipio: ['',Validators.required],
usernameRegistryData: [''],
departmentIdDepartment: [''],
})
}
async ngOnInit() {
this.buttonDisabled=false;
}
onChange(newValue) {
this.suspectForm.controls.dateOfBirth.setValue(newValue);
this.suspectForm.controls['dateOfBirth'].markAsDirty();
}
async getSuspectByDni(dniSuspect: string) {
await this.suspectService.getSuspectByDNI(dniSuspect.trim()).then((resp) => {
if (resp) {
this.suspectData = resp;
this.newSuspect = resp;
}
});
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9_\u00F1A ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
isValid(){
return !this.suspectForm.dirty || this.suspectForm.invalid ;
}
ShowModal() {
this.suspectForm.setValue({
dniSuspect: this.newSuspect.dniSuspect,
firstName: this.newSuspect.firstName,
middleName: this.newSuspect.middleName,
thirdName: this.newSuspect.thirdName,
lastName: this.newSuspect.lastName,
alias : this.newSuspect.alias,
sex: this.newSuspect.sex,
height: this.newSuspect.height,
weight: this.newSuspect.weight,
eyesColor: this.newSuspect.eyesColor,
build: this.newSuspect.build,
personFrom: this.newSuspect.personFrom,
ocupattion: this.newSuspect.ocupattion,
passportNumber: this.newSuspect.passportNumber,
particularSign: this.newSuspect.particularSign,
tattoo: this.newSuspect.tattoo,
operationPlace: this.newSuspect.operationPlace,
dateOfBirth: this.newSuspect.dateOfBirth,
nationaliy:this.newSuspect.nationaliy,
age: this.newSuspect.age,
civilStatus: this.newSuspect.civilStatus,
colonia: this.newSuspect.colonia,
street: this.newSuspect.street,
avenue: this.newSuspect.avenue,
village:this.newSuspect.village,
caserio: this.newSuspect.caserio,
houseNumber: this.newSuspect.houseNumber,
pasaje: this.newSuspect.pasaje,
referenceAddress: this.newSuspect.referenceAddress,
department: this.newSuspect.department,
municipio: this.newSuspect.municipio,
usernameRegistryData: this.newSuspect.usernameRegistryData,
departmentIdDepartment: this.newSuspect.departmentIdDepartment,
});
this.updateUserModal.show();
this.getDepartment();
}
closeModal() {
this.updateUserModal.hide();
}
async onSubmit() {
let Suspect :Suspects = this.suspectForm.getRawValue();
if (Suspect.dateOfBirth?.toString() == "") {
delete Suspect.dateOfBirth;
}
if (Suspect.houseNumber.toString() == "") {
delete Suspect.houseNumber;
}
if (Suspect.weight.toString() == "") {
delete Suspect.weight;
}
if (Suspect.height.toString() == "") {
delete Suspect.height;
}
console.log( this.suspectForm.getRawValue())
Suspect.lastModificationUser = this.auth.currentUser.username;
await this.updateSuspect(this.suspectData.dniSuspect,Suspect);
}
async updateSuspect(dni,Suspect) {
console.log(Suspect)
await this.suspectService.updateSuspect(dni,Suspect).then((resp) => {
if (resp) {
this.newSuspect = Suspect;
this.suspectData =Suspect;
this.suspectForm.reset();
}
});
setTimeout(()=>{
this.closeModal();
},1200);
}
getDepartment(){
this.MunicipiosLst=Municipios[this.suspectForm.controls.department.value];
}
cleanUser(user: User) {
if (user.username != null)
user.username = user.username.replace(/[^0-9A-Za-z-._]/g, '');
if (user.password != null)
user.password = <PASSWORD>.password.replace(/[^0-9A-Za-z-._]/g, '');
}
}
<file_sep>/Backend.DPI/Backend.DPI/Controllers/DepartmentController.cs
using Backend.DPI.ModelDto;
using Backend.DPI.Models;
using Backend.DPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize]
public class DepartmentController : Controller
{
private readonly IDepartmentRepository departmentRepository;
public DepartmentController(IDepartmentRepository _departmentRepository)
{
this.departmentRepository = _departmentRepository;
}
[HttpPost("AddDepartment")]
public async Task<ActionResult<DepartmentDto>> AddDepartment(string name) {
var result = await this.departmentRepository.CreateDepartmentAsync(name);
return Ok(new DepartmentDto
{
Name = name
});
}
[HttpGet("GetDepartments")]
public async Task<ActionResult<IEnumerable<DepartmentDto>>> GetDepartment() {
var result = await this.departmentRepository.GetDepartmentsAsync();
return Ok(result.Select(x => new DepartmentDto
{
IdDepartment=x.IdDepartment,
Name=x.Name
}));
}
[HttpGet("GetDepartmentByName")]
public async Task<ActionResult<IEnumerable<Department>>> GetDepartmentByName(string departmentName)
{
var result = await this.departmentRepository.GetDepartmentsByNameAsync(departmentName);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
[HttpDelete("DeleteDepartment")]
public async Task<ActionResult<IEnumerable<User>>> DeleteDepartment(string departmentName)
{
var result = await departmentRepository.DeleteDepartmentAsync(departmentName);
return Ok(result);
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/ModelDto/PrivilegeDto.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.ModelDto
{
public partial class PrivilegeDto
{
public PrivilegeDto()
{
RolPrivileges = new HashSet<RolPrivilegeDto>();
}
public int IdPrivilege { get; set; }
public string Name { get; set; }
public virtual ICollection<RolPrivilegeDto> RolPrivileges { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/user-authentication.guard.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Observable } from 'rxjs';
import { AuthenticationService } from './authentication.service';
import { RolPrivilege } from './users/interfaces/user';
@Injectable({
providedIn: 'root'
})
export class UserAuthenticationGuard implements CanActivate, CanActivateChild {
constructor(private router: Router,
private jwtHelper: JwtHelperService,
private auth: AuthenticationService){}
privileges:Array<RolPrivilege>;
privilegesSize:number;
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const token=localStorage.getItem('Token');
const isAuthenticated = localStorage.getItem('isLoggedIn');
if (isAuthenticated=='true' && token && !this.jwtHelper.isTokenExpired(token)) {
return true;
}
if (isAuthenticated=='true' && token && this.jwtHelper.isTokenExpired(token)) {
return this.ValidateToken(token);
}
return this.FailedAccess();
}
async ValidateToken(token:string){
let response:any;
await this.auth.updateToken(token).then(async (resp)=>{
response=resp;
});
if(response){
return true;
}
return this.FailedAccess();
}
FailedAccess(){
this.auth.logout();
this.router.navigate(['/login']);
return false;
}
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return (this.checkAccessToPrivilege(decodeURI(route?.url.toString())))? true: this.router.navigate["/home"];
}
checkAccessToPrivilege(incomingUrl){
this.privileges=JSON.parse(localStorage.getItem("Privileges"));
this.privilegesSize=+localStorage.getItem("SizePrivileges");
if(this.privilegesSize==null) return false;
for(let i=0; i<this.privilegesSize; i++){
if(this.privileges[i].name_Privilege==incomingUrl){
return true;
}
}
return false;
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/rol_privileges/rol_privileges_crud/rol-privilege-delete/rol-privilege-delete.component.ts
import { Component, OnInit } from '@angular/core';
import Swal from 'sweetalert2';
import { RolPrivilege } from '../../interfaces/rol-privilege';
import { RolPrivilegeService } from '../../rol_privilege.service';
@Component({
selector: 'app-rol-privilege-delete',
templateUrl: './rol-privilege-delete.component.html',
styleUrls: ['./rol-privilege-delete.component.css']
})
export class RolPrivilegeDeleteComponent implements OnInit {
rolPrivilegeFilterSelected: string = '';
rolPrivilegeData: RolPrivilege[];
buttonDisabled: boolean;
constructor(private rolPrivilegeService: RolPrivilegeService) {
}
async ngOnInit() {
this.buttonDisabled=false;
}
async getRolPrivilegeByName(nameRolPrivilege: string) {
await this.rolPrivilegeService.getRolPrivilegeByName(nameRolPrivilege).then((resp) => {
this.rolPrivilegeData = resp;
});
}
async deleteRolPrivilege(idRolPrivilege: number) {
Swal.fire({
title: '¿Seguro que desea eliminar el dato?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.rolPrivilegeService.deleteRolPrivilege(idRolPrivilege).then((resp) => {
if (resp == true) {
this.rolPrivilegeData = null;
this.rolPrivilegeData.splice(
this.rolPrivilegeData.findIndex((rolPrivilege) => rolPrivilege.idRolPrivilege == idRolPrivilege),
1
);
}
});
}
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminals/criminal-list/criminal-list.component.ts
import { Component, OnInit } from '@angular/core';
import { CriminalsService } from '../criminals.service';
import { Criminal } from '../Interfaces/criminal-interface';
@Component({
selector: 'app-criminal-list',
templateUrl: './criminal-list.component.html',
styleUrls: ['./criminal-list.component.css']
})
export class HistorialCriminalListComponent implements OnInit {
totalRecords :number;
page:number =1;
criminalsFilter:string;
criminals: Criminal[];
constructor(
private criminalService:CriminalsService
) { }
async ngOnInit() {
await this.getCriminalsData();
}
async getCriminalsData(){
await this.criminalService.getCriminals().then(resp=>{
if(resp !=null){
this.criminals = resp;
this.totalRecords = this.criminals.length;
console.log(this.criminals);
}
})
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/SuspectRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Backend.DPI.ModelDto;
namespace Backend.DPI.Repository
{
public class SuspectRepository : ISuspectRepository
{
private readonly DPIContext dpiContext = new DPIContext();
public async Task<bool> AddSuspectAsync(Suspect suspect)
{
var result = await dpiContext.Suspects.FirstOrDefaultAsync(s => s.DniSuspect == suspect.DniSuspect.Trim());
if (result !=null)
{
return false;
}
suspect.CreationDate = DateTime.Now;
await dpiContext.Suspects.AddAsync(suspect);
await dpiContext.SaveChangesAsync();
return true;
}
public async Task<IReadOnlyList<object>> GetSuspectsAsync()
{
var result = await (from a in dpiContext.Suspects
join b in dpiContext.Departments on a.DepartmentIdDepartment equals b.IdDepartment
select new { a.Age, a.Alias, a.Avenue, a.CreationDate, a.LastModificationUser, a.UsernameRegistryData, a.DepartmentIdDepartment, a.Department, a.Build, a.Caserio, a.CivilStatus, a.Colonia, a.DateOfBirth, a.DniSuspect, a.EyesColor, a.FirstName, a.Height, a.HouseNumber, a.LastName, a.MiddleName, a.Municipio, a.Nationaliy, a.Ocupattion, a.OperationPlace, a.ParticularSign, a.Pasaje, a.PassportNumber, a.PersonFrom, a.ReferenceAddress, a.Sex, a.Street, a.Tattoo, a.ThirdName, a.Village, a.Weight, b.Name }).ToListAsync();
return result;
}
public async Task<IReadOnlyList<object>> GetSuspectsInsertedByDateByUserAsync(string username)
{
var s3 = dpiContext.Suspects.ToList();
int day = DateTime.Now.Day;
int mont = DateTime.Now.Month;
int year = DateTime.Now.Year;
var result = await (from a in dpiContext.Suspects
join b in dpiContext.Departments on a.DepartmentIdDepartment equals b.IdDepartment
where a.UsernameRegistryData == username && day == a.CreationDate.Day && a.CreationDate.Year == year && a.CreationDate.Month == mont
select new { a.Age, a.Alias, a.Avenue, a.LastModificationUser,a.UsernameRegistryData,a.CreationDate ,a.DepartmentIdDepartment, a.Department, a.Build, a.Caserio, a.CivilStatus, a.Colonia, a.DateOfBirth, a.DniSuspect, a.EyesColor, a.FirstName, a.Height, a.HouseNumber, a.LastName, a.MiddleName, a.Municipio, a.Nationaliy, a.Ocupattion, a.OperationPlace, a.ParticularSign, a.Pasaje, a.PassportNumber, a.PersonFrom,a.ReferenceAddress, a.Sex, a.Street, a.Tattoo, a.ThirdName, a.Village, a.Weight, b.Name }).ToListAsync();
if (result ==null)
{
return null;
}
return result;
}
public async Task<IReadOnlyList<object>> GetSuspectsInsertedByDateAsync()
{
var s3 = dpiContext.Suspects.ToList();
int day = DateTime.Now.Day;
int mont = DateTime.Now.Month;
int year = DateTime.Now.Year;
var result = await (from a in dpiContext.Suspects
join b in dpiContext.Departments on a.DepartmentIdDepartment equals b.IdDepartment
where day == a.CreationDate.Day && a.CreationDate.Year == year && a.CreationDate.Month == mont
select new { a.Age, a.Alias, a.Avenue, a.LastModificationUser, a.UsernameRegistryData, a.CreationDate, a.DepartmentIdDepartment, a.Department, a.Build, a.Caserio, a.CivilStatus, a.Colonia, a.DateOfBirth, a.DniSuspect, a.EyesColor, a.FirstName, a.Height, a.HouseNumber, a.LastName, a.MiddleName, a.Municipio, a.Nationaliy, a.Ocupattion, a.OperationPlace, a.ParticularSign, a.Pasaje, a.PassportNumber, a.PersonFrom, a.ReferenceAddress, a.Sex, a.Street, a.Tattoo, a.ThirdName, a.Village, a.Weight, b.Name }).ToListAsync();
if (result == null)
{
return null;
}
return result;
}
public async Task<bool> DeleteSuspect(string DNI)
{
var result = await dpiContext.Suspects.FirstOrDefaultAsync(x => x.DniSuspect == DNI.ToLower());
if (result == null)
{
return false;
}
dpiContext.Suspects.Remove(result);
await dpiContext.SaveChangesAsync();
return true;
}
public async Task<Suspect> GetSuspectByDni(string DNI)
{
var result = await dpiContext.Suspects.FirstOrDefaultAsync(x => x.DniSuspect == DNI);
if (result == null)
{
return null;
}
return result;
}
public async Task<bool> ModifySuspect(string lastDni, Suspect suspectModified)
{
var result =await dpiContext.Suspects.FirstOrDefaultAsync(s => s.DniSuspect == lastDni);
if (result == null)
{
return false;
}
suspectModified.CreationDate = result.CreationDate;
dpiContext.Suspects.Remove(result);
dpiContext.Suspects.Add(suspectModified);
await dpiContext.SaveChangesAsync();
return true;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Controllers/SuspectController.cs
using Backend.DPI.Models;
using Backend.DPI.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
// [Authorize]
public class SuspectController : Controller
{
private readonly SuspectRepository _suspectRepository = new SuspectRepository();
[HttpGet("GetSuspects")]
public async Task<ActionResult<IEnumerable<Suspect>>> GetSuspects()
{
var suspects = await _suspectRepository.GetSuspectsAsync();
if (suspects == null)
{
return NotFound();
}
return Ok(suspects);
}
[HttpPost("AddSuspect")]
public async Task<ActionResult<bool>> AddSuspect(Suspect suspect)
{
var suspects = await _suspectRepository.AddSuspectAsync(suspect);
return suspects;
}
[HttpGet("GetRegisterPerDayPerUser")]
public async Task<ActionResult<IEnumerable<Suspect>>> GetRegisterPerDayPerUser(string username)
{
var suspects = await _suspectRepository.GetSuspectsInsertedByDateByUserAsync(username);
if (suspects == null)
{
return NotFound();
}
return Ok(suspects);
}
[HttpGet("GetRegisterPerDay")]
public async Task<ActionResult<IEnumerable<Suspect>>> GetRegisterPerDay()
{
var suspects = await _suspectRepository.GetSuspectsInsertedByDateAsync();
if (suspects == null)
{
return NotFound();
}
return Ok(suspects);
}
[HttpGet("GetSuspectByDNI")]
public async Task<ActionResult<IEnumerable<Suspect>>> GetSuspectByDNI(string dni)
{
var suspects = await _suspectRepository.GetSuspectByDni(dni);
if (suspects == null)
{
return NotFound();
}
return Ok(suspects);
}
[HttpDelete("DeleteSuspect")]
public async Task<ActionResult<IEnumerable<bool>>> DeleteSuspect(string DNI)
{
var suspects = await _suspectRepository.DeleteSuspect(DNI);
return Ok(suspects);
}
[HttpPost("UpdateSuspect")]
public async Task<ActionResult<IEnumerable<bool>>> UpdateSuspect(string lastDNI, Suspect suspectModified)
{
var suspects = await _suspectRepository.ModifySuspect(lastDNI,suspectModified);
if (suspects == false)
{
return NotFound();
}
return Ok(suspects);
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Models/RolPrivilege.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Backend.DPI.Models
{
public partial class RolPrivilege
{
public int IdRolPrivilege { get; set; }
public int PrivilegeIdPrivilege { get; set; }
public int RolIdRol { get; set; }
public virtual Privilege PrivilegeIdPrivilegeNavigation { get; set; }
public virtual Rol RolIdRolNavigation { get; set; }
}
}
<file_sep>/Backend.DPI/Backend.DPI/Controllers/RolesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Backend.DPI.Models;
using Backend.DPI.Services;
using Backend.DPI.ModelDto;
using Microsoft.AspNetCore.Authorization;
namespace Backend.DPI.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize]
public class RolesController : ControllerBase
{
private readonly RolesRepository _rolesRepository = new RolesRepository();
[HttpGet("GetRols")]
public async Task<ActionResult<IEnumerable<Rol>>> Get()
{
var Roles = await _rolesRepository.GetRoles();
if (Roles==null)
{
return NotFound();
}
return Ok(Roles);
}
[HttpGet("GetRolByName")]
public async Task<ActionResult<IEnumerable<Rol>>> GetRolByName(string rolName)
{
var Roles = await _rolesRepository.getRolbyName(rolName);
if (Roles == null)
{
return NotFound();
}
return Ok(Roles);
}
[HttpPost("CreateRol")]
public async Task<ActionResult<IEnumerable<Rol>>> CreateRol(string rolName)
{
var Roles = await _rolesRepository.CreateRolAsync(rolName);
return Ok(Roles);
}
[HttpDelete("DeleteRol")]
public async Task<ActionResult<IEnumerable<Rol>>> DeleteRol(string nameRol)
{
var Roles = await _rolesRepository.DeleteRolAsync(nameRol);
return Ok(Roles);
}
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Roles/rol-list/rol-list.component.ts
import { Rol } from './../../users/interfaces/user';
import { Component, OnInit } from '@angular/core';
import { User } from '../../users/interfaces/user';
import { UsersService } from '../../users/users.service';
@Component({
selector: 'app-rol-list',
templateUrl: './rol-list.component.html',
styleUrls: ['./rol-list.component.css']
})
export class RolListComponent implements OnInit {
totalRecords :number;
page:number =1;
userFilterSelected: string = '';
Roles: Rol[];
constructor(private userService: UsersService) {}
async ngOnInit() {
await this.getRoles();
}
async getRoles() {
await this.userService.getRols().then((resp) => {
this.Roles = resp;
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Roles/rol-delete/rol-delete.component.ts
import { RolesService } from './../roles.service';
import { Rol } from './../../users/interfaces/user';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import Swal from 'sweetalert2';
@Component({
selector: 'app-rol-delete',
templateUrl: './rol-delete.component.html',
styleUrls: ['./rol-delete.component.css']
})
export class RolDeleteComponent {
userFilterSelected: string = '';
rolsData: Rol[] ;
constructor(private rolesService: RolesService) {}
async getRolbyName(rolName: string) {
await this.rolesService.getRolByName(rolName.trim()).then((resp) => {
this.rolsData = resp;
});
}
async DeleteRol(username: string) {
Swal.fire({
title: '¿Seguro que desea eliminar el usuario?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.rolesService.DeleteRol(username).then((resp) => {
if (resp == true) {
this.rolsData = null;
this.userFilterSelected ='';
}else{
}
});
}
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/rol_privileges/rol_privileges_crud/rol_privilege-list/rol-privilege-list.component.ts
import { Component, OnInit } from '@angular/core';
import {RolPrivilege } from '../../interfaces/rol-privilege';
import { RolPrivilegeService } from '../../rol_privilege.service';
@Component({
selector: 'app-rol-privilege-list',
templateUrl: './rol-privilege-list.component.html',
styleUrls: ['./rol-privilege-list.component.css'],
})
export class RolPrivilegeListComponent implements OnInit {
rolPrivilegeFilterSelected: string = '';
rolPrivilegeData: RolPrivilege[];
totalRecords :number;
page:number =1;
constructor(private rolPrivilegeService: RolPrivilegeService) {}
async ngOnInit() {
await this.getDataRolPrivilege();
}
async getDataRolPrivilege() {
await this.rolPrivilegeService.getRolPrivileges().then((resp) => {
this.rolPrivilegeData = resp;
});
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminal-record/criminal-record-delete/criminal-record-delete.component.ts
import { CriminalsService } from './../../criminals/criminals.service';
import { Criminal, CriminalRecord } from './../../criminals/Interfaces/criminal-interface';
import { Component, OnInit } from '@angular/core';
import Swal from 'sweetalert2';
import { CriminalRecordService } from '../criminals.record.service';
@Component({
selector: 'app-criminal-record-delete',
templateUrl: './criminal-record-delete.component.html',
styleUrls: ['./criminal-record-delete.component.css']
})
export class CriminalRecordDeleteComponent {
criminalRecords: CriminalRecord[];
dniCriminal: string;
rolTemporal
userFilterSelected
totalRecords :number;
page:number =1;
constructor(
private criminalService:CriminalRecordService
) { }
async getCriminalRecordByDNI(dni: string) {
this.dniCriminal = dni;
console.log(this.criminalRecords)
console.log(this.dniCriminal)
await this.criminalService.getCriminalByDNI(dni.trim()).then((resp) => {
this.criminalRecords = resp;
console.log(resp)
});
}
//050118090223305
async DeleteCriminalRecord(id) {
Swal.fire({
title: '¿Seguro que desea eliminar el usuario?',
text: 'No podras revertir el cambio',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar',
}).then(async (result) => {
if (result.isConfirmed) {
await this.criminalService.deleteCriminalRecord(id).then(async (resp) => {
if (resp == true) {
this.criminalRecords = null;
await this.getCriminalRecordByDNI( this.dniCriminal);
}else{
}
});
}
});
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/^[a-zA-Z0-9_ ]*$/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
}
<file_sep>/Backend.DPI/Backend.DPI/Repository/ISuspectRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface ISuspectRepository
{
Task<IReadOnlyList<object>> GetSuspectsAsync();
Task<bool> AddSuspectAsync(Suspect s);
Task<bool> DeleteSuspect(string DNI);
Task<Suspect> GetSuspectByDni(string DNI);
Task<bool> ModifySuspect(string lastDni, Suspect suspectModified);
Task<IReadOnlyList<object>> GetSuspectsInsertedByDateAsync();
Task<IReadOnlyList<object>> GetSuspectsInsertedByDateByUserAsync(string username);
//Task<bool> DeleteDepartmentAsync(string departmentName);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/Departamentos/department.module.ts
import {DepartamentoCreateComponent } from './departamento-create/departamento-create.component';
import { DepartamentoDeleteComponent } from './departamento-delete/departamento-delete.component';
import { DepartamentoListComponent } from './departamento-list/departamento-list.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ModalModule } from 'ngx-bootstrap/modal';
import { DepartamentRoutingModule } from './department-routing.module';
import { DepartmentFilterPipe } from './pipes/department-filter.pipe';
import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
declarations: [
DepartmentFilterPipe,
DepartamentoListComponent,
DepartamentoDeleteComponent,
DepartamentoCreateComponent,
],
imports: [
CommonModule,
DepartamentRoutingModule,
FormsModule,
ModalModule.forRoot(),
ReactiveFormsModule,
NgxPaginationModule
],
})
export class DepartmentModule {}
<file_sep>/Backend.DPI/Backend.DPI/Repository/ICriminalRecordRepository.cs
using Backend.DPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.Repository
{
public interface ICriminalRecordRepository
{
Task<IReadOnlyList<CriminalRecord>> GetCriminalRecordsAsync();
Task<IReadOnlyList<CriminalRecord>> GetCriminalRecordByDNIAsync(string DNI);
Task<bool> AddCriminalRecordAsync(CriminalRecord CriminalRecord);
Task<bool> UpdateCriminalRecordAsync(CriminalRecord criminalRecord);
Task<bool> DeleteCriminaRecordAsync(int IdCriminalRecord);
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/police-record/police-record-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PoliceRecordCreateComponent } from './police-record-create/police-record-create.component';
import { PoliceRecordDeleteComponent } from './police-record-delete/police-record-delete.component';
import { PoliceRecordListComponent } from './police-record-list/police-record-list.component';
import { PoliceRecordUpdateComponent } from './police-record-update/police-record-update.component';
const routes: Routes = [
{
path: 'Listar Historial Policial',
component: PoliceRecordListComponent,
data: { title: 'update' },
},
{
path: 'Crear Historial Policial',
component: PoliceRecordCreateComponent,
data: { title: 'update' },
},
{
path: 'Eliminar Historial Policial',
component: PoliceRecordDeleteComponent,
data: { title: 'update' },
},
{
path: 'Modificar Historial Policial',
component: PoliceRecordUpdateComponent,
data: { title: 'update' },
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PoliceRecordRoutingModule { }<file_sep>/Backend.DPI/Backend.DPI/ModelDto/SuspectDto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Backend.DPI.ModelDto
{
public class SuspectDto
{
public string DniSuspect { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string ThirdName { get; set; }
public string LastName { get; set; }
public string Alias { get; set; }
public string Sex { get; set; }
public float Height { get; set; }
public float Weight { get; set; }
public string EyesColor { get; set; }
public string Build { get; set; }
public string PersonFrom { get; set; }
public string Ocupattion { get; set; }
public string PassportNumber { get; set; }
public string ParticularSign { get; set; }
public string Tattoo { get; set; }
public string OperationPlace { get; set; }
public DateTime DateOfBirth { get; set; }
public string Nationaliy { get; set; }
public int Age { get; set; }
public string CivilStatus { get; set; }
public string Colonia { get; set; }
public string Street { get; set; }
public string Avenue { get; set; }
public string Village { get; set; }
public string Caserio { get; set; }
public int? HouseNumber { get; set; }
public string Pasaje { get; set; }
public string ReferenceAddress { get; set; }
public string Department { get; set; }
public string Municipio { get; set; }
public string RecordStatus { get; set; }
public string UsernameRegistryData { get; set; }
public int DepartmentIdDepartment { get; set; }
public DateTime CreationDate { get; set; }
public string LastModificationUser { get; set; }
}
}
<file_sep>/Frontend.DPI/Frontend/src/app/criminal-record/criminal-record-create/criminal-record-create.component.ts
import { PoliceRecordService } from './../../police-record/police.record.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CriminalGroup } from '../../criminals/Interfaces/criminal-interface';
import { CriminalRecordService } from '../criminals.record.service';
@Component({
selector: 'app-criminal-record-create',
templateUrl: './criminal-record-create.component.html',
styleUrls: ['./criminal-record-create.component.css']
})
export class CriminalRecordCreateComponent implements OnInit {
validForm:boolean =true;
criminalForm : FormGroup;
criminalGroups : CriminalGroup[];
constructor(
private formBuilder:FormBuilder,
private criminalService:CriminalRecordService) {
this.criminalForm = this.formBuilder.group({
crime: [''],
sentenceStartDate: [''],
sentenceFinalDate: [''],
penitentiaryCenter: [''],
moduleCellPrison: [''],
suspectDni: ['',[Validators.required,Validators.pattern('[0-9]+')]],
})
}
// idCriminalRecord: number;
// crime: string;
// sentenceStartDate: Date;
// sentenceFinalDate: Date;
// penitentiaryCenter: string;
// moduleCellPrison: string;
// suspectDni: string;
async ngOnInit(){
}
keyPressAlphanumeric(event) {
var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9\u00F1A_ ]/.test(inp)) {
return true;
} else {
event.preventDefault();
return false;
}
}
onSubmit(){
if(this.criminalForm.valid){
let result = this.criminalForm.getRawValue();
this.validForm = true;
if (result.sentenceFinalDate== "") {
delete result.sentenceFinalDate;
}
if (result.sentenceStartDate == "") {
delete result.sentenceStartDate;
}
this.criminalService.createRecordCriminal(result).then(resp=>{
if (resp==true) {
console.log(resp)
this.criminalForm.reset();
}
})
}else{
this.validForm = false;
}
}
}
| 282c6a8398ede964c238976229f640b0bcd2f251 | [
"C#",
"TypeScript"
] | 118 | TypeScript | Siumauricio/Vinculation-Proyect | 84f88045793cc932c014d1098953908ec735a437 | b7f9e563f10d4f3448bcc8feb4cb8491fa6482ef |
refs/heads/master | <file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/10 15:12:45 by bsouchet #+# #+# */
/* Updated: 2016/10/06 15:56:01 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
void start_screen(t_var *v)
{
if (v->start == 0 && v->loop++ <= 150)
;
if (v->loop == 150 && (v->loop = 0) == 0)
v->start++;
}
static int ft_sizeline(char *str, int pos)
{
int counter;
counter = 0;
while (str[pos] != 0 && str[pos] != '\n')
{
pos++;
counter++;
}
return (counter);
}
static int find_player(t_var *v, char c, int x, int y)
{
int i;
int counter;
i = -1;
counter = 0;
while (v->buf[++i] != 0)
{
if (v->buf[i] == 10 && ++y != 0)
x = 0;
else if (v->buf[i] == c && ++counter != 0)
{
v->p_x = ((double)x - 0.5);
v->p_y = ((double)y + 0.5);
v->p_r = 0.;
}
x++;
}
return (counter);
}
int check(t_var *v)
{
int pos;
v->i = -1;
v->y = 0;
if (ft_checkstr(v->buf, "01X\n") == 1 || find_player(v, 'X', 0, 0) != 1)
return (error(v, 5, 2));
v->wth = ft_sizeline(v->buf, 0);
while (++v->i > -1 && v->y < v->lns && (pos = 0) == 0)
{
if (v->y != 0 && ft_sizeline(v->buf, v->i) != v->wth)
return (error(v, 5, 2));
while (v->buf[v->i] != 0 && v->buf[v->i] != '\n')
{
if (((v->y == 0 || v->y == (v->lns - 1)) && v->buf[v->i] != '1') ||
((pos == 0 || pos == (v->wth - 1)) && v->buf[v->i] != '1'))
return (error(v, 5, 2));
pos++;
v->i++;
}
v->y++;
}
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mlx_int.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/02 17:26:10 by bsouchet #+# #+# */
/* Updated: 2016/09/22 18:07:25 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MLX_INT_H
# define MLX_INT_H
# define BG_CLR 0x735432
#define MAX_EVENT 32
#define MAX_PIXEL_NB 200000
#define UNIQ_BPP 4
#define FONT_WIDTH 10
#define FONT_HEIGHT 20
typedef int (*func_t)();
typedef struct glsl_info_s
{
GLuint pixel_vshader;
GLuint pixel_fshader;
GLuint pixel_program;
GLint loc_pixel_position;
GLint loc_pixel_texture;
GLint loc_pixel_winhalfsize;
GLuint image_vshader;
GLuint image_fshader;
GLuint image_program;
GLint loc_image_position;
GLint loc_image_winhalfsize;
GLint loc_image_texture;
GLint loc_image_pos;
GLint loc_image_size;
GLuint font_vshader;
GLuint font_fshader;
GLuint font_program;
GLint loc_font_position;
GLint loc_font_winhalfsize;
GLint loc_font_texture;
GLint loc_font_color;
GLint loc_font_posinwin;
GLint loc_font_posinatlas;
GLint loc_font_atlassize;
} glsl_info_t;
typedef struct mlx_img_list_s
{
int width;
int height;
char *buffer;
GLfloat vertexes[8];
struct mlx_img_list_s *next;
} mlx_img_list_t;
typedef struct mlx_img_ctx_s
{
GLuint texture;
GLuint vbuffer;
mlx_img_list_t *img;
struct mlx_img_ctx_s *next;
} mlx_img_ctx_t;
typedef struct mlx_win_list_s
{
void *winid;
mlx_img_ctx_t *img_list;
int nb_flush;
int pixmgt;
struct mlx_win_list_s *next;
} mlx_win_list_t;
typedef struct mlx_ptr_s
{
void *appid;
mlx_win_list_t *win_list;
mlx_img_list_t *img_list;
void (*loop_hook)(void *);
void *loop_hook_data;
void *loop_timer;
mlx_img_list_t *font;
int main_loop_active;
} mlx_ptr_t;
typedef struct s_xpm_col
{
int name;
int col;
} t_xpm_col;
struct s_col_name
{
char *name;
int color;
};
int mlx_shaders(glsl_info_t *glsl);
char **mlx_int_str_to_wordtab(char *str);
int mlx_int_str_str(char *str, char *find, int len);
int mlx_int_str_str_cote(char *str, char *find, int len);
int mlx_destroy_img(mlx_ptr_t *mlx_ptr,
mlx_img_list_t *img_ptr);
void *mlx_new_img();
void *mlx_xpm_to_image(mlx_ptr_t *xvar, char **xpm_data,
int *width,int *height);
int mlx_do_sync(mlx_ptr_t *mlx_ptr);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* textures.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/24 14:59:01 by bsouchet #+# #+# */
/* Updated: 2016/10/24 17:01:08 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
void import_textures(t_var *v)
{
v->ui = mlx_xpm_to_img(v->mlx, "./assets/images/ui/normal.xpm");
v->ui_t = mlx_xpm_to_img(v->mlx, "./assets/images/ui/normal_t.xpm");
v->ps = mlx_xpm_to_img(v->mlx, "./assets/images/start/prods.xpm");
v->ss = mlx_xpm_to_img(v->mlx, "./assets/images/start/start.xpm");
v->wt = mlx_xpm_to_img(v->mlx, "./assets/images/textures/wall.xpm");
v->fl = mlx_xpm_to_img(v->mlx, "./assets/images/textures/stone.xpm");
v->cl = mlx_xpm_to_img(v->mlx, "./assets/images/textures/ceilling.xpm");
v->hr = mlx_xpm_to_img(v->mlx, "./assets/images/ui/hardcore.xpm");
v->hr_t = mlx_xpm_to_img(v->mlx, "./assets/images/ui/hardcore_t.xpm");
}
static void draw_textured_floor_ceilling(t_var *v, double tx, double ty, int y)
{
int clr;
int t_x;
int t_y;
double dist;
while (y < WIN_H)
{
v->val = (y < 466) ? .02 :
((1.22 / (((y - 466.) / 100.) + .56)) - 0.18) / 100.;
tx += cos(((v->p_r + v->ray) + 90.) * (PI / 180.)) * v->val;
ty += sin(((v->p_r + v->ray) + 90.) * (PI / 180.)) * v->val;
t_x = 511. * FT(tx - (int)tx);
t_y = 511. * FT(ty - (int)ty);
dist = (sqrt(pow((tx - v->posx), 2.) + pow((ty - v->posy), 2.))) *
cos(v->ray * (PI / 180.));
clr = mlx_get_pixel_clr(v->fl, t_x, t_y);
clr = (v->easy != 1) ? ft_gt_colors(clr, AO,
((dist - 0.4) / ((4. - (2. * FT(v->h))) - 0.4))) : clr;
y = ((WIN_H / 2) + round(((v->s_dist - 200.) / dist) / 2.));
mlx_put_pixel(v->img, v->x, y, clr);
clr = mlx_get_pixel_clr(v->cl, t_x, t_y);
clr = (v->easy != 1) ? ft_gt_colors(clr, AO,
((dist - 0.4) / ((4. - (2. * FT(v->h))) - 0.4))) : clr;
mlx_put_pixel(v->img, v->x, (WIN_H - y), clr);
}
}
void draw_textured_wall(t_var *v, double tx, double ty, int y)
{
int t_x;
int t_y;
int clr;
t_x = (v->p_clr == WALL_W || v->p_clr == WALL_E) ?
511. * FT(ty - (int)ty) : 511. * FT(tx - (int)tx);
while (++y < WIN_H && y <= v->max)
{
t_y = 511. * FT(y - v->min) / FT(v->max - v->min);
clr = mlx_get_pixel_clr(v->wt, t_x, t_y);
clr = (v->easy != 1) ? ft_gt_colors(clr, AO,
((v->dist - 0.4) / ((4. - (2. * FT(v->h))) - 0.4))) : clr;
mlx_put_pixel(v->img, v->x, y,
ft_add_ao(clr, ((y - v->min) * 100. / (v->max - v->min))));
}
draw_textured_floor_ceilling(v, tx, ty, 0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* misc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/06/22 11:33:00 by bsouchet #+# #+# */
/* Updated: 2016/10/19 15:42:06 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
void reset_values(t_var *v)
{
v->h = 0;
v->t = 0;
v->m = 0;
v->sp = 1.;
v->p_r = 0.;
v->easy = 0;
v->posx = v->p_x;
v->posy = v->p_y;
}
int close_prog(t_var *v)
{
mlx_destroy_img(v->mlx, v->ui);
mlx_destroy_img(v->mlx, v->ps);
mlx_destroy_img(v->mlx, v->ss);
mlx_destroy_img(v->mlx, v->hr);
mlx_destroy_img(v->mlx, v->wt);
mlx_destroy_img(v->mlx, v->fl);
mlx_destroy_img(v->mlx, v->cl);
mlx_destroy_img(v->mlx, v->ui_t);
mlx_destroy_img(v->mlx, v->hr_t);
mlx_destroy_img(v->mlx, v->img);
mlx_destroy_win(v->mlx, v->win);
if (v->mu > 0)
system("killall afplay 2&>/dev/null >/dev/null");
free(v->name);
free(v->map);
free(v);
exit(0);
return (0);
}
int free_stuff(t_var *v, int type)
{
if (type == 0)
return (1);
else if (type == 1)
;
else if (type == 2)
free(v->buf);
else if (type == 3)
free(v->map);
else if (type == 4)
{
free(v->buf);
free(v->map);
}
free(v);
return (1);
}
int error(t_var *v, int t1, int t2)
{
char *s;
if (t1 == 0)
write(2, MSG0, ft_strlen(MSG0));
else if (t1 == 1)
write(2, MSG1, ft_strlen(MSG1));
else if (t1 == 2)
write(2, MSG2, ft_strlen(MSG2));
else if (t1 == 3)
write(2, MSG3, ft_strlen(MSG3));
else if (t1 == 4 || t1 == 6)
{
s = ft_strjoin(ft_strjoin("error : ", strerror(errno), 'N'), ".", 'L');
write(2, s, ft_strlen(s));
free(s);
}
else if (t1 == 5)
write(2, MSG5, ft_strlen(MSG5));
write(2, "\n", 1);
return (free_stuff(v, t2));
}
void change_song(t_var *v, int song_num)
{
if (v->mu > 0)
system("killall afplay 2&>/dev/null >/dev/null");
if (song_num == 1)
system("afplay ./assets/songs/song1.mp3&");
else if (song_num == 2)
system("afplay ./assets/songs/song2.mp3&");
else if (song_num == 3)
system("afplay ./assets/songs/song3.mp3&");
else if (song_num == 4)
system("afplay ./assets/songs/song4.mp3&");
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/02 17:30:09 by bsouchet #+# #+# */
/* Updated: 2016/10/24 15:19:10 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
static int convert(t_var *v)
{
v->i = -1;
v->y = -1;
v->pts = (int **)malloc(sizeof(int *) * 4);
while (++v->i < 4)
v->pts[v->i] = (int *)malloc(sizeof(int) * 2);
v->i = 0;
if (!(v->map = (int ***)malloc(sizeof(int **) * v->lns)))
return (error(v, 0, 2));
while (++v->y < v->lns && (v->x = 0) == 0)
{
if (!(v->map[v->y] = (int **)malloc(sizeof(int *) * v->wth)))
return (error(v, 0, 4));
while (v->x < v->wth)
{
v->map[v->y][v->x] = (int *)malloc(sizeof(int) * 3);
v->map[v->y][v->x][0] = (106 - ((int)v->p_y * S_L)) + (S_L * v->y);
v->map[v->y][v->x][1] = (106 - ((int)v->p_x * S_L)) + (S_L * v->x);
v->map[v->y][v->x++][2] = v->buf[v->i++];
}
v->i++;
}
free(v->buf);
return (0);
}
static void init_values(t_var *v)
{
v->h = 0;
v->t = 0;
v->m = 0;
v->mu = 1;
v->sp = 1.;
v->add = 0;
v->loop = 0;
v->easy = 0;
v->start = 0;
v->h_frame = 0;
v->h_repeat = 0;
v->posx = v->p_x;
v->posy = v->p_y;
v->p_clr = WALL_W;
import_textures(v);
v->name = ft_strjoin("Map : ", ft_del_dir_name(v->file), 'R');
v->len = ((WIN_W - 50) - (ft_strlen(v->name) * 10)) + 11;
v->mid = (WIN_W / 2) - ((ft_strlen(START) * 10) / 2);
v->s_dist = round(((WIN_W - 214) / 2) / tan((FOV / 2.) * (PI / 180.)));
}
static void init_win(t_var *v)
{
v->mlx = mlx_init();
init_values(v);
v->img = mlx_new_img(v->mlx, WIN_W, WIN_H, AO);
v->win = mlx_new_win(v->mlx, -1, -1, WIN_W, WIN_H, WIN_TITLE);
system("afplay ./assets/songs/start_screen.mp3&");
mlx_hook(v->win, 2, (1L << 0), key_press_hook, v);
mlx_hook(v->win, 3, (1L << 1), key_release_hook, v);
mlx_hook(v->win, 6, (1L << 6), motion_hook, v);
mlx_hook(v->win, 17, (1L << 17), close_prog, v);
mlx_mouse_hook(v->win, mouse_hook, v);
mlx_loop_hook(v->mlx, expose_hook, v);
mlx_loop(v->mlx);
exit(0);
}
static int execute(t_var *v, int fd)
{
v->lns = 0;
if (!(v->buf = (char *)malloc(sizeof(char))))
return (error(v, 0, 1));
v->buf[0] = 0;
if (ft_strchr_at_end(v->file, ".w3d") == -1)
return (error(v, 3, 2));
if ((fd = open(v->file, O_RDONLY)) == -1)
return (error(v, 4, 2));
while (get_next_line(fd, &v->line) > 0 && ++v->lns > 0)
v->buf = ft_strjoin(v->buf, ft_strjoin(v->line, "\n", 'L'), 'B');
if (v->lns < 3)
return (error(v, 5, 2));
if (check(v) != 0 || convert(v) != 0)
return (-1);
if (close(fd) == -1)
return (error(v, 6, 3));
init_win(v);
return (0);
}
int main(int ac, char **av)
{
t_var *v;
if (!(v = (t_var *)malloc(sizeof(t_var))))
return (error(v, 0, 0));
if (ac != 2)
return (error(v, 1, 1));
if (WIN_W < 1024 || WIN_H < 576)
return (error(v, 2, 1));
v->file = av[1];
return (execute(v, 0));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* keys.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/22 15:36:51 by bsouchet #+# #+# */
/* Updated: 2016/10/24 19:32:16 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
void player_transform(t_var *v)
{
int tmp;
tmp = ((WIN_W - 214) / 2);
if (v->mx >= 214 && v->mx < WIN_W && v->my >= 0 && v->my < WIN_H)
{
if (v->mx >= 214 && v->mx <= 284)
v->add -= 3;
if (v->mx >= (WIN_W - 70) && v->mx < WIN_W)
v->add += 3;
v->p_r = (((v->mx - (tmp + 213)) * 55) / tmp) + v->add;
}
}
static void key_detect_walls(t_var *v)
{
if (v->map[I(v->posy)][I(v->posx) - 1][2] == '1')
v->posx = (v->posx < I(v->posx) + .15) ? I(v->posx) + .15 : v->posx;
if (v->map[I(v->posy)][I(v->posx) + 1][2] == '1')
v->posx = (v->posx > I(v->posx) + .85) ? I(v->posx) + .85 : v->posx;
if (v->map[I(v->posy) - 1][I(v->posx)][2] == '1')
v->posy = (v->posy < I(v->posy) + .15) ? I(v->posy) + .15 : v->posy;
if (v->map[I(v->posy) + 1][I(v->posx)][2] == '1')
v->posy = (v->posy > I(v->posy) + .85) ? I(v->posy) + .85 : v->posy;
}
void key_operations(t_var *v)
{
if (v->h != 1 && v->t != 1)
v->sp = (v->k[257] != 0 || v->k[258] != 0) ? 1.455 : 1.;
else if (v->t != 1)
v->sp = (v->k[257] != 0 || v->k[258] != 0) ? .565 : .4;
else if (v->h != 1)
v->sp = (v->k[257] != 0 || v->k[258] != 0) ? 1.755 : 1.55;
else
v->sp = (v->k[257] != 0 || v->k[258] != 0) ? 1.250 : 1.245;
if (v->k[12] != 0 || v->k[123] != 0)
v->p_r -= (v->t != 1 && v->h != 0) ? 2. : 3.5;
if (v->k[14] != 0 || v->k[124] != 0)
v->p_r += (v->t != 1 && v->h != 0) ? 2. : 3.5;
}
void key_transform(t_var *v, double px, double py)
{
if (v->k[0] != 0)
v->posy -= cos((v->p_r - 90.) * (PI / 180.)) * (STEP_L * v->sp);
if (v->k[0] != 0)
v->posx += sin((v->p_r - 90.) * (PI / 180.)) * (STEP_L * v->sp);
if (v->k[2] != 0)
v->posy += cos((v->p_r - 90.) * (PI / 180.)) * (STEP_L * v->sp);
if (v->k[2] != 0)
v->posx -= sin((v->p_r - 90.) * (PI / 180.)) * (STEP_L * v->sp);
px = v->posx;
py = v->posy;
if (v->k[1] != 0 || v->k[125] != 0)
py += cos(v->p_r * (PI / 180.)) * (STEP_L * v->sp);
v->posy = (v->map[(int)py][(int)v->posx][2] != '1') ? py : v->posy;
if (v->k[1] != 0 || v->k[125] != 0)
px -= sin(v->p_r * (PI / 180.)) * (STEP_L * v->sp);
v->posx = (v->map[(int)v->posy][(int)px][2] != '1') ? px : v->posx;
if (v->k[13] != 0 || v->k[126] != 0)
py -= cos(v->p_r * (PI / 180.)) * (STEP_L * v->sp);
v->posy = (v->map[(int)py][(int)v->posx][2] != '1') ? py : v->posy;
if (v->k[13] != 0 || v->k[126] != 0)
px += sin(v->p_r * (PI / 180.)) * (STEP_L * v->sp);
v->posx = (v->map[(int)v->posy][(int)px][2] != '1') ? px : v->posx;
key_detect_walls(v);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* raycasting.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/06 15:33:54 by bsouchet #+# #+# */
/* Updated: 2016/10/24 20:03:09 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
static void draw_wall(t_var *v, int y, int clr)
{
clr = (v->easy != 1) ? ft_gt_colors(v->p_clr, AO,
((v->dist - 0.4) / ((4. - (2. * FT(v->h))) - 0.4))) : v->p_clr;
while (++y < WIN_H && y <= v->max)
mlx_put_pixel(v->img, v->x, y,
ft_add_ao(clr, ((y - v->min) * 100. / (v->max - v->min))));
}
static void wall_color_detection(t_var *v, double tx, double ty)
{
if (ty == I(ty) && tx == I(tx))
v->p_clr = v->p_clr;
else if (ty == I(ty) && v->posy > ty)
v->p_clr = WALL_N;
else if (ty == I(ty) && v->posy <= ty)
v->p_clr = WALL_S;
else if (tx == I(tx) && v->posx <= tx)
v->p_clr = WALL_E;
else if (tx == I(tx) && v->posx > tx)
v->p_clr = WALL_W;
}
static void execute_raycasting(t_var *v, int x, double tx, double ty)
{
int y;
int height;
v->ray = (FOV * atan(((x - 214.) - ((WIN_W - 215.) / 2.)) / v->s_dist));
while (v->map[I(ty)][I(tx)][2] != '1')
{
tx += cos(((v->p_r + v->ray) - 90.) * (PI / 180.)) * 0.003;
ty += sin(((v->p_r + v->ray) - 90.) * (PI / 180.)) * 0.003;
}
tx = (!(tx >= (I(tx) + 0.0030) && tx <= (I(tx) + 0.9970))) ? round(tx) : tx;
ty = (!(ty >= (I(ty) + 0.0030) && ty <= (I(ty) + 0.9970))) ? round(ty) : ty;
v->dist = (sqrt(pow((tx - v->posx), 2.) + pow((ty - v->posy), 2.)) *
cos(v->ray * (PI / 180.)));
height = round(((v->s_dist - 200.) / v->dist) / 2.);
v->tmp = ((height > (WIN_H / 2)) == 1) ? WIN_H / 2 : height;
if (x == v->x && x != 214 && v->tmp >= (v->p_height + 20))
execute_raycasting(v, (x + 15), v->posx, v->posy);
else
wall_color_detection(v, tx, ty);
v->min = ((WIN_H / 2) - height);
v->max = ((WIN_H / 2) + height);
y = (v->min < -1) ? -1 : v->min;
if (x == v->x && (v->p_height = v->tmp) != 0)
(v->t != 1) ? draw_wall(v, y, 0) : draw_textured_wall(v, tx, ty, y);
}
static void draw_background(t_var *v, double val, int clr)
{
v->y = -1;
while (++v->y < WIN_H && (v->x = 213) != 0)
{
if (v->easy != 0)
val = 0.;
else if (v->h != 1)
val = (v->y < 370) ?
(-(0.75 / ((FT(v->y + 20) / 100.) - 3.78)) - 0.1) :
((0.75 / (((FT(v->y) - 430) / 100.) + 0.68)) - 0.1);
else
val = (v->y < 370) ?
(-(1.55 / ((FT(v->y + 20) / 100.) - 3.69)) - 0.2) :
((1.55 / (((FT(v->y) - 500) / 100.) + 1.29)) - 0.2);
clr = ft_gt_colors(((v->y < 370) ? WALL_T : WALL_B), AO, val);
while (++v->x < WIN_W)
mlx_put_pixel(v->img, v->x, v->y, clr);
}
}
void raycasting(t_var *v)
{
if (v->t != 1)
draw_background(v, 0., 0);
v->x = 213;
while (++v->x < WIN_W)
execute_raycasting(v, v->x, v->posx, v->posy);
v->x = v->len - 14;
v->y = (WIN_H - 65);
draw_rectangle(v, (WIN_W - 25), (WIN_H - 25), ((v->t != 1) ? UI_B : UI_F));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/02/02 13:30:40 by bsouchet #+# #+# */
/* Updated: 2016/10/19 18:56:20 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBFT_H
# define LIBFT_H
# include <string.h>
# include <unistd.h>
# include <stdlib.h>
# include <errno.h>
# include <math.h>
# define BUFF_SIZE 1
# define D (double)
# define AO 0x000000
char *ft_del_dir_name(char *file);
char *ft_itoa(int n);
int ft_checkstr(char *s1, char *s2);
void *ft_memcpy(void *dst, void *src, size_t len);
void *ft_memmove(void *dst, void *src, size_t len);
char *ft_strchr(char *str, int c);
int ft_strlen(char *str);
int ft_strlen_wspace(char *str);
char *ft_strjoin(char *s1, char *s2, char type);
char *ft_strdup(char *str);
int ft_strchr_at_end(char *str, char *find);
int get_next_line(int fd, char **line);
int ft_shade_color(int clr, double val);
int ft_gt_colors(int clr1, int clr2, double val);
int ft_add_ao(int clr, double percent);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* hook.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/02 18:35:58 by bsouchet #+# #+# */
/* Updated: 2016/10/24 17:00:13 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
int expose_hook(t_var *v)
{
if (v->start == 2 && v->mu == 1 && ++v->start == 3)
system("killall afplay 2&>/dev/null >/dev/null\n \
afplay /System/Library/Sounds/Hero.aiff&\n \
afplay ./assets/songs/song1.mp3&");
if (v->start > 2)
mlx_clear_img(v->img, AO);
mlx_clear_win(v->mlx, v->win);
(v->start < 2) ? start_screen(v) : draw_ui(v, 0, -1);
if (v->start > 2)
raycasting(v);
if (v->start == 0)
mlx_put_img_to_win(v->mlx, v->win, v->ps, 0, 0);
else if (v->start == 1)
mlx_put_img_to_win(v->mlx, v->win, v->ss, 0, 0);
else
mlx_put_img_to_win(v->mlx, v->win, v->img, 0, 0);
(v->start < 2) ? draw_start_texts(v) : draw_ui_texts(v);
return (0);
}
int key_press_hook(int key, t_var *v)
{
++v->start;
if (key == 53)
return (close_prog(v));
v->k[key] = 1;
return (0);
}
int key_release_hook(int key, t_var *v)
{
if (key == 4 && (v->easy = 0) != 1)
v->h = (v->h != 1) ? 1 : 0;
if (key == 6 && (v->h = 0) != 1)
v->easy = (v->easy != 1) ? 1 : 0;
if (key == 17)
v->t = (v->t != 1) ? 1 : 0;
if (key == 46)
v->m = (v->m != 1) ? 1 : 0;
if (v->start > 3 && key == 35 && v->mu == 1 && (v->mu = 2) == 2)
system("killall -SIGSTOP afplay 2&>/dev/null >/dev/null");
else if (v->start > 3 && key == 35 && v->mu == 2 && (v->mu = 1) == 1)
system("killall -SIGCONT afplay 2&>/dev/null >/dev/null");
if (v->start > 3 && key >= 18 && key <= 21)
change_song(v, key - 17);
if (v->start > 3 && key >= 83 && key <= 86)
change_song(v, key - 82);
if (key == 71)
reset_values(v);
v->k[key] = 0;
return (0);
}
int motion_hook(int x, int y, t_var *v)
{
v->mx = x;
v->my = y;
return (0);
}
int mouse_hook(int button, int x, int y, t_var *v)
{
(void)x;
(void)y;
(void)button;
++v->start;
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/06/18 16:55:00 by bsouchet #+# #+# */
/* Updated: 2016/09/10 15:48:38 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int resultat(char **line, char *buf_save)
{
char *eol;
eol = ft_strchr(buf_save, '\n');
if (NULL != eol)
{
*eol = '\0';
*line = ft_strdup(buf_save);
ft_memmove(buf_save, &eol[1], ft_strlen(&eol[1]) + 1);
return (1);
}
if (0 < ft_strlen(buf_save))
{
*line = ft_strdup(buf_save);
*buf_save = '\0';
return (1);
}
return (0);
}
int get_next_line(int const fd, char **line)
{
static char *buf_save = NULL;
char buffer[BUFF_SIZE + 1];
char *line_tmp;
int ret;
if (NULL == line || fd < 0 || BUFF_SIZE <= 0)
return (-1);
if (NULL == buf_save)
buf_save = (char *)malloc(sizeof(char));
while (!ft_strchr(buf_save, '\n'))
{
ret = read(fd, buffer, BUFF_SIZE);
if (ret == -1)
return (-1);
if (0 == ret)
break ;
buffer[ret] = '\0';
line_tmp = ft_strjoin(buf_save, buffer, 'L');
buf_save = line_tmp;
}
return (resultat(line, buf_save));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* minimap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/10 14:45:30 by bsouchet #+# #+# */
/* Updated: 2016/10/06 15:57:07 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
static int check_mm_point(t_var *v, int y, int x)
{
int i;
int j;
int c;
c = 0;
i = 0;
j = (4 - 1);
while (i < 4)
{
if (((v->pts[i][0] >= y) != (v->pts[j][0] >= y)) &
(x <= (v->pts[j][1] - v->pts[i][1]) * (double)(y - v->pts[i][0]) /
(double)(v->pts[j][0] - v->pts[i][0]) + v->pts[i][1]))
c = !c;
j = i++;
}
return (c);
}
static void rotate_mm_square(t_var *v, int i)
{
int x;
x =
(FT(int)(cos(FT(-(v->p_r)) * (PI / 180.)) * 10000000) / 10000000) *
FT(FT(v->pts[i][1]) - MID_MM_W) -
(FT(int)(sin(FT(-(v->p_r)) * (PI / 180.)) * 10000000) / 10000000) *
FT(FT(v->pts[i][0]) - MID_MM_H) + MID_MM_W;
v->pts[i][0] =
(FT(int)(sin(FT(-(v->p_r)) * (PI / 180.)) * 10000000) / 10000000) *
FT(FT(v->pts[i][1]) - MID_MM_W) +
(FT(int)(cos(FT(-(v->p_r)) * (PI / 180.)) * 10000000) / 10000000) *
FT(FT(v->pts[i][0]) - MID_MM_H) + MID_MM_H;
v->pts[i][1] = x;
}
static void draw_mm_square(t_var *v, int y, int x, int i)
{
int clr;
clr = (v->t != 1) ? MM_CLR : TX_CLR;
v->pts[0][0] = (v->map[y][x][0] - S_M) - ((v->posy - v->p_y) * S_L);
v->pts[0][1] = (v->map[y][x][1] - S_M) - ((v->posx - v->p_x) * S_L);
v->pts[1][0] = (v->map[y][x][0] - S_M) - ((v->posy - v->p_y) * S_L);
v->pts[1][1] = (v->map[y][x][1] + S_M) - ((v->posx - v->p_x) * S_L);
v->pts[2][0] = (v->map[y][x][0] + S_M) - ((v->posy - v->p_y) * S_L);
v->pts[2][1] = (v->map[y][x][1] + S_M) - ((v->posx - v->p_x) * S_L);
v->pts[3][0] = (v->map[y][x][0] + S_M) - ((v->posy - v->p_y) * S_L);
v->pts[3][1] = (v->map[y][x][1] - S_M) - ((v->posx - v->p_x) * S_L);
while (++i < 4)
rotate_mm_square(v, i);
y = 25;
while (++y <= 187 && (x = 25) == 25)
while (++x <= 187)
if (check_mm_point(v, y, x) == 1)
mlx_put_pixel(v->img, x, y, clr);
}
void draw_mm_hardcore(t_var *v, int x, int y, int clr)
{
char *str;
void *img;
v->h_frame = (v->h_frame == 12) ? 0 : v->h_frame;
str = ft_strjoin(ft_strjoin("./assets/images/noise/", ft_itoa(v->h_frame),
'R'), ".xpm", 'L');
img = mlx_xpm_to_img(v->mlx, str);
while (++y < 162 && (x = -1) != 0)
while (++x < 162 && (clr = mlx_get_pixel_clr(img, x, y)) != 0)
mlx_put_pixel(v->img, (x + 26), (y + 26), clr);
mlx_destroy_img(v->mlx, img);
v->h_frame += (v->h_repeat == 3) ? 1 : 0;
v->h_repeat = (v->h_repeat == 3) ? 0 : ++v->h_repeat;
free(str);
}
void draw_mm(t_var *v, int x, int y, int m)
{
int clr;
int end_x;
int end_y;
m = (I(v->posx) - 5 >= 0) ? I(v->posx) - 5 : 0;
end_x = (I(v->posx) + 5 >= v->wth) ? v->wth : I(v->posx) + 5;
y = (I(v->posy) - 5 >= 0) ? I(v->posy) - 5 : 0;
end_y = (I(v->posy) + 5 >= v->lns) ? v->lns : I(v->posy) + 5;
while (++y < end_y && (x = m) == m)
while (++x < end_x)
if (v->map[y][x][2] != '1')
draw_mm_square(v, y, x, -1);
clr = (v->t != 1) ? UI_B : UI_T;
draw_player_triangle(v, 106, 109, clr);
}
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: bsouchet <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2016/02/04 18:49:05 by bsouchet #+# #+# #
# Updated: 2016/10/25 15:43:23 by bsouchet ### ########.fr #
# #
# **************************************************************************** #
C = clang
NAME = wolf3d
FLAGS = -Wall -Wextra -Werror -O2
LIBFT = libft
DIR_S = sources
DIR_O = temporary
DIR_MLX = libmlx
HEADER = include
SOURCES = main.c \
hook.c \
keys.c \
draw.c \
check.c \
minimap.c \
textures.c \
raycasting.c \
misc.c
SRCS = $(addprefix $(DIR_S)/,$(SOURCES))
OBJS = $(addprefix $(DIR_O)/,$(SOURCES:.c=.o))
opti:
@$(MAKE) all -j
all: temporary $(NAME)
$(NAME): $(OBJS)
@make -C $(LIBFT)
@make -C $(DIR_MLX)
@$(CC) $(FLAGS) -L $(LIBFT) -lft -o $@ $^ -framework OpenGL -framework AppKit -L $(DIR_MLX) -lmlx
temporary:
@mkdir -p temporary
$(DIR_O)/%.o: $(DIR_S)/%.c $(HEADER)/$(NAME).h
@$(CC) $(FLAGS) -I $(HEADER) -c -o $@ $<
norme:
@make norme -C $(LIBFT)
@echo
norminette ./$(HEADER)
@echo
norminette ./$(DIR_S)
clean:
@rm -f $(OBJS)
@make clean -C $(LIBFT)
@make clean -C $(DIR_MLX)
@rm -rf $(DIR_O)
fclean: clean
@rm -f $(NAME)
@make fclean -C $(LIBFT)
@make fclean -C $(DIR_MLX)
re: fclean
@$(MAKE) all -j
.PHONY: temporary, norme, clean
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_color.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/28 19:06:33 by bsouchet #+# #+# */
/* Updated: 2016/10/19 18:56:29 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_gt_colors(int clr1, int clr2, double val)
{
int r;
int g;
int b;
if (val > 1.0)
val = 1.0;
else if (val < 0.0)
val = 0.0;
r = floor(D((clr1 >> 16) & 0xFF) -
((D((clr1 >> 16) & 0xFF) - D((clr2 >> 16) & 0xFF)) * val));
g = floor(D((clr1 >> 8) & 0xFF) -
((D((clr1 >> 8) & 0xFF) - D((clr2 >> 8) & 0xFF)) * val));
b = floor(D((clr1) & 0xFF) - ((D((clr1) & 0xFF) - D((clr2) & 0xFF)) * val));
return (((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff));
}
int ft_shade_color(int clr, double val)
{
int r;
int g;
int b;
if (val > 1.0)
val = 1.0;
else if (val < 0.0)
val = 0.0;
r = floor(D((clr >> 16) & 0xFF) + D((0.0 - D((clr >> 16) & 0xFF)) * val));
g = floor(D((clr >> 8) & 0xFF) + D((0.0 - D((clr >> 8) & 0xFF)) * val));
b = floor(D((clr) & 0xFF) + D((0.0 - D((clr) & 0xFF)) * val));
return (((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff));
}
int ft_add_ao(int clr, double percent)
{
double intensity;
if (percent >= 0. && percent <= 10.)
{
intensity = ((1.4 / (((percent * 25.) / 100.) + 1.)) - 0.4);
intensity /= 5.;
clr = ft_shade_color(clr, intensity);
}
else if (percent >= 90. && percent <= 100. && (percent -= 90.) != -1)
{
intensity = ((1.4 / (-((percent * 25.) / 100.) + 3.5)) - 0.4);
intensity /= 5.;
clr = ft_shade_color(clr, intensity);
}
return (clr);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mlx.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/25 11:16:33 by bsouchet #+# #+# */
/* Updated: 2016/09/22 19:30:18 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MLX_H
# define MLX_H
void *mlx_init();
void *mlx_new_win(void *mlx_ptr, int pos_x, int pos_y,
int size_x, int size_y, char *title);
int mlx_width_screen(void);
int mlx_clear_img(void *img, int clr);
int mlx_clear_win(void *mlx_ptr, void *win_ptr);
int mlx_put_pixel(void *img, int x, int y, int clr);
void *mlx_new_img(void *mlx_ptr,int width,int height, int clr);
char *mlx_get_data_addr(void *img_ptr, int *bits_per_pixel,
int *size_line, int *endian);
int mlx_put_img_to_win(void *mlx_ptr, void *win_ptr,
void *img_ptr, int x, int y);
unsigned mlx_get_color_value(void *mlx_ptr, int color);
int mlx_get_pixel_clr(void *img, int x, int y);
int mlx_mouse_hook(void *win_ptr, int (*funct_ptr)(), void *param);
int mlx_key_hook(void *win_ptr, int (*funct_ptr)(), void *param);
int mlx_expose_hook(void *win_ptr, int (*funct_ptr)(), void *param);
int mlx_loop_hook(void *mlx_ptr, int (*funct_ptr)(), void *param);
int mlx_loop(void *mlx_ptr);
int mlx_put_str(void *mlx, void *win, int x, int y, int clr,
char *str);
void *mlx_xpm_to_image(void *mlx_ptr, char **xpm_data,
int *width, int *height);
void *mlx_xpm_to_img(void *mlx_ptr, char *filename);
int mlx_destroy_win(void *mlx_ptr, void *win_ptr);
int mlx_destroy_img(void *mlx_ptr, void *img_ptr);
int mlx_hook(void *win_ptr, int x_event, int x_mask,
int (*funct)(), void *param);
int mlx_do_key_autorepeatoff(void *mlx_ptr);
int mlx_do_key_autorepeaton(void *mlx_ptr);
int mlx_do_sync(void *mlx_ptr);
#endif
<file_sep># Wolf3D
Wolf3D is a program developed for my learning course at 42 school.<br/><br/>
The objective of this project is to recreate the principle of ray casting of the famous game Wolfenstein.<br/>
For this we have to realize in C all necessary functions without using graphic libraries (except the Libmlx library required to create a window on MacOS provided by the 42 school).<br/><br/>
PS : This game has not a real goal, you can simply explore the mazes.<br/><br/>
<img align="center" src="http://i.imgur.com/IhvdtKf.jpg" width="100%" />
Several options are available (see [Keyboard shortcuts](https://github.com/BenjaminSouchet/Wolf3D#keyboard-shortcuts) or/and [Mouse controls](https://github.com/BenjaminSouchet/Wolf3D#mouse-controls) sections for more infos) :
* Move in any directions (sideways movements included)
* Rotation with keys (or mouse position)
* Textured Mode (with floor and ceil casting)
* Walls collision (with an slight realistic offset)
* Minimap with rotation according to the player rotation
* Fire Torch Lighting simulation (in Normal & Hardcore Mode only)
* Several songs (with Selection of track / Play / Pause and Stop options)
* Hardcore Mode & Easy Mode
* Ambient occlusion
## Install & launch
```bash
git clone https://github.com/BenjaminSouchet/Wolf3D ~/Wolf3D
cd ~/Wolf3D && ./wolf3d maps/good/Maze_Medium.w3d
```
You have to launch the program with a parameter. This is the name of the map you would like open at the execution of the program. This parameter as to be the name of a valid map, below the list of available maps :<br />
*maps/good/Basic_00.w3d*<br />
*maps/good/Basic_01.w3d*<br />
*maps/good/Maze_Small.w3d*<br />
*maps/good/Maze_Medium.w3d*<br />
*maps/good/Maze_Large.w3d*<br />
Example :
Open one maze map ⇣
```bash
./wolf3d maps/good/Maze_Large.w3d
```
## Keyboard shortcuts
<table width="100%">
<thead>
<tr>
<td width="65%" height="60px" align="center" cellpadding="0">
<strong>Description</strong>
</td>
<td width="10%" align="center" cellpadding="0">
<span style="width:70px"> </span><strong>Key(s)</strong><span style="width:50px"> </span>
</td>
</tr>
</thead>
<tbody>
<tr>
<td valign="top" height="30px">Close the program (aka quit/exit)</td>
<td valign="top" align="center"><kbd> esc </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Reset all the changes made</td>
<td valign="top" align="center"><kbd> clear </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Hold to run faster</td>
<td valign="top" align="center"><kbd> shift </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Enable or disable the mouse controls</td>
<td valign="top" align="center"><kbd> M </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Make a step forward</td>
<td valign="top" align="center"><kbd> ▲ </kbd> or <kbd> W </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Make a step backward</td>
<td valign="top" align="center"><kbd> ▼ </kbd> or <kbd> S </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Make a step to the left</td>
<td valign="top" align="center"><kbd> A </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Make a step to the left</td>
<td valign="top" align="center"><kbd> D </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Rotate to the left</td>
<td valign="top" align="center"><kbd> ◄ </kbd> or <kbd> Q </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Rotate to the right</td>
<td valign="top" align="center"><kbd> ► </kbd> or <kbd> E </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Hardcore Mode Switcher</td>
<td valign="top" align="center"><kbd> H </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Easy Mode Switcher</td>
<td valign="top" align="center"><kbd> Z </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Play / Pause the current song</td>
<td valign="top" align="center"><kbd> P </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Switch to the first song</td>
<td valign="top" align="center"><kbd> 1 </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Switch to the second song</td>
<td valign="top" align="center"><kbd> 2 </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Switch to the third song</td>
<td valign="top" align="center"><kbd> 3 </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Switch to the fourth song</td>
<td valign="top" align="center"><kbd> 4 </kbd></td>
</tr>
</tbody>
</table>
## Mouse controls
<table width="100%">
<thead>
<tr>
<td width="60%" height="60px" align="center" cellpadding="0">
<strong>Description</strong>
</td>
<td width="10%" align="center" cellpadding="0">
<span style="width:70px"> </span><strong>Action</strong><span style="width:50px"> </span>
</td>
</tr>
</thead>
<tbody>
<tr>
<td valign="top" height="30px">Change the view according to the mouse position in the window</td>
<td valign="top" align="center"><kbd> Move the cusor in the window </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Rotate to the left</td>
<td valign="top" align="center"><kbd> Stay the cursor in left side of the window </kbd></td>
</tr>
<tr>
<td valign="top" height="30px">Rotate to the right</td>
<td valign="top" align="center"><kbd> Stay the cursor in right side of the window </kbd></td>
</tr>
</tbody>
</table>
## Contact & contribute
If you want to contact me, or fix / improve this project, just send me a mail at **<EMAIL>**
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* wolf3d.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/02 17:26:10 by bsouchet #+# #+# */
/* Updated: 2016/10/24 19:48:17 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef WOLF3D_H
# define WOLF3D_H
# include <math.h>
# include <fcntl.h>
# include <errno.h>
# include "../libft/include/libft.h"
# include "../libmlx/includes/mlx.h"
# define WIN_TITLE "Wolf3D - bsouchet"
# define UI_B 0x2686D9
# define UI_T 0xAB7C49
# define UI_F 0xB58752
# define BG_CLR 0x353535
# define BG_MAP 0x2F2F2F
# define TX_CLR 0x453A2E
# define MM_CLR 0x3d3d3d
# define WALL_T 0x0D3558
# define WALL_B 0x0B2D4B
# define WALL_N 0x174F80
# define WALL_E 0x1B5C96
# define WALL_S 0x14446e
# define WALL_W 0x804d17
# define FOV 70.
# define WIN_W 1280
# define WIN_H 720
# define MID_W 640
# define MID_H 360
# define MID_VIEW_W 746
# define MID_VIEW_H 360
# define MID_MM_W 106.
# define MID_MM_H 106.
# define S_L 26
# define S_M 13
# define STEP_L 0.068
# define START "PRESS ANY BUTTON TO START"
# define MSG0 "error: Dynamic memory allocation failed."
# define MSG1 "usage: ./wolf3d input_file.w3d"
# define MSG2 "error: The window size must be greater than 1024 x 576."
# define MSG3 "error: The input file haven't the right extension (.w3d)."
# define MSG5 "error: The input file isn't a valid wolf3d map."
# define PI 3.14159265359
# define I (int)
# define FT (float)
typedef struct s_var
{
int i;
int m;
int x;
int y;
int h;
int t;
int mu;
int mx;
int my;
int add;
int lns;
int len;
int mid;
int loop;
int easy;
int start;
int p_clr;
double s_dist;
char *file;
char *name;
double sp;
char *buf;
char *line;
int **pts;
int ***map;
int h_frame;
int h_repeat;
int wth;
double p_x;
double p_y;
double p_r;
double ray;
double val;
double dist;
double posx;
double posy;
char k[280];
void *img;
void *mlx;
void *win;
void *ps;
void *ss;
void *ui;
void *hr;
void *ui_t;
void *hr_t;
void *wt;
void *fl;
void *cl;
int min;
int max;
int p_height;
int tmp;
} t_var;
int check(t_var *v);
int error(t_var *v, int t1, int t2);
int free_stuff(t_var *v, int type);
int close_prog(t_var *v);
int expose_hook(t_var *v);
int key_press_hook(int key, t_var *v);
int key_release_hook(int key, t_var *v);
void key_operations(t_var *v);
void key_transform(t_var *v, double px, double py);
int mouse_hook(int button, int x, int y, t_var *v);
int motion_hook(int x, int y, t_var *v);
void player_transform(t_var *v);
void start_screen(t_var *v);
void import_textures(t_var *v);
void draw_textured_wall(t_var *v, double tx, double ty, int y);
void draw_mm(t_var *v, int x, int y, int m);
void draw_mm_hardcore(t_var *v, int x, int y, int clr);
void draw_player_triangle(t_var *v, int center, int height, int clr);
void draw_rectangle(t_var *v, int x, int y, int clr);
void draw_start_texts(t_var *v);
void draw_ui(t_var *v, int x, int y);
void draw_ui_texts(t_var *v);
void raycasting(t_var *v);
void change_song(t_var *v, int song_num);
void reset_values(t_var *v);
#endif
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: bsouchet <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2016/02/02 15:48:09 by bsouchet #+# #+# #
# Updated: 2016/09/28 19:07:51 by bsouchet ### ########.fr #
# #
# **************************************************************************** #
C = clang
NAME = libft.a
FLAGS = -Wall -Wextra -Werror -O3
DIR_S = sources
DIR_O = temporary
HEADER = include
SOURCES = ft_itoa.c \
ft_checkstr.c \
ft_del_dir_name.c \
ft_memcpy.c \
ft_memmove.c \
ft_strchr.c \
ft_strchr_at_end.c \
ft_strdup.c \
ft_strjoin.c \
ft_strlen.c \
ft_color.c \
get_next_line.c
SRCS = $(addprefix $(DIR_S)/,$(SOURCES))
OBJS = $(addprefix $(DIR_O)/,$(SOURCES:.c=.o))
all: temporary $(NAME)
$(NAME): $(OBJS)
@ar rc $(NAME) $(OBJS)
@ranlib $(NAME)
temporary:
@mkdir -p temporary
$(DIR_O)/%.o: $(DIR_S)/%.c
@$(CC) $(FLAGS) -I $(HEADER) -o $@ -c $<
norme:
norminette ../libft/$(HEADER)
@echo
norminette ../libft/$(DIR_S)
clean:
@rm -f $(OBJS)
@rm -rf $(DIR_O)
fclean: clean
@rm -f $(NAME)
re: fclean all
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* draw.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsouchet <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/02 18:39:52 by bsouchet #+# #+# */
/* Updated: 2016/10/21 16:39:28 by bsouchet ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
void draw_player_triangle(t_var *v, int center, int height, int clr)
{
int start;
int end;
start = center;
end = center;
v->y = center - 2;
while (++v->y < height && (v->x = start--) > 0 && ++end > 0)
while (v->x <= end)
if (v->x++ > 0 && mlx_get_pixel_clr(v->img, v->x, v->y) != BG_MAP)
mlx_put_pixel(v->img, v->x, v->y, clr);
}
void draw_rectangle(t_var *v, int x, int y, int clr)
{
int p_x;
int p_y;
p_x = v->x;
p_y = v->y;
while (v->x < x && mlx_put_pixel(v->img, v->x, v->y, clr) == 0)
v->x++;
while (v->y < y && mlx_put_pixel(v->img, v->x, v->y, clr) == 0)
v->y++;
while (v->x > p_x && mlx_put_pixel(v->img, v->x, v->y, clr) == 0)
v->x--;
while (v->y > p_y && mlx_put_pixel(v->img, v->x, v->y, clr) == 0)
v->y--;
}
void draw_start_texts(t_var *v)
{
if (v->start != 1)
return ;
v->loop = (v->loop >= 60) ? 0 : v->loop + 1;
if (v->loop < 40)
mlx_put_str(v->mlx, v->win, v->mid, (WIN_H - 115), UI_B, START);
}
void draw_ui(t_var *v, int x, int y)
{
int clr;
void *img;
if (v->t == 0)
img = (v->h != 1) ? v->ui : v->hr;
else
img = (v->h == 0) ? v->ui_t : v->hr_t;
while (++y < WIN_H && (x = -1) != 0)
while (++x < 214 && (clr = mlx_get_pixel_clr(img, x, y)) != 0)
mlx_put_pixel(v->img, x, y, clr);
if (v->m != 0)
player_transform(v);
key_operations(v);
key_transform(v, 0., 0.);
(v->h == 1) ? draw_mm_hardcore(v, -1, -1, 0) : draw_mm(v, 0, 0, 0);
}
void draw_ui_texts(t_var *v)
{
if (v->t != 1)
mlx_put_str(v->mlx, v->win, v->len, (WIN_H - 55), UI_B, v->name);
else
mlx_put_str(v->mlx, v->win, v->len, (WIN_H - 55), UI_F, v->name);
if (v->h == 1 && v->t == 0)
mlx_put_str(v->mlx, v->win, 66, 95, UI_B, "DISABLED");
else if (v->h == 1)
mlx_put_str(v->mlx, v->win, 66, 95, UI_T, "DISABLED");
}
| ce20efbd0d2390396159edea346480300b8f57cc | [
"Markdown",
"C",
"Makefile"
] | 18 | C | BenjaminSouchet/Wolf3D | 37a1a4fbd9d3e911c18ed28a8a80995c22fa9443 | e7f683e4d959e834f59ef1a988b2cfbc6cbd6119 |
refs/heads/master | <file_sep>//
// ViewController.swift
// Catch the Kenny
//
// Created by <NAME> on 6/10/18.
// Copyright © 2018 NabeelNaveed. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var kenny1: UIImageView!
@IBOutlet weak var kenny2: UIImageView!
@IBOutlet weak var kenny3: UIImageView!
@IBOutlet weak var kenny4: UIImageView!
@IBOutlet weak var kenny5: UIImageView!
@IBOutlet weak var kenny6: UIImageView!
@IBOutlet weak var kenny7: UIImageView!
@IBOutlet weak var kenny8: UIImageView!
@IBOutlet weak var kenny9: UIImageView!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var heighScoreLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
var score = 0
var counter = 0
var timer = Timer()
var hideTimer = Timer()
var kennyArray = [UIImageView]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//check high score
let highScore = UserDefaults.standard.object(forKey: "highscore")
if highScore == nil{
heighScoreLabel.text = "0"
}
if let newScore = highScore as? Int {
heighScoreLabel.text = String(newScore)
}
scoreLabel.text = "Score: \(score)"
let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture3 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture4 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture5 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture6 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture7 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture8 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
let gesture9 = UITapGestureRecognizer(target: self, action: #selector(ViewController.increaseScore))
kenny1.addGestureRecognizer(gesture1)
kenny2.addGestureRecognizer(gesture2)
kenny3.addGestureRecognizer(gesture3)
kenny4.addGestureRecognizer(gesture4)
kenny5.addGestureRecognizer(gesture5)
kenny6.addGestureRecognizer(gesture6)
kenny7.addGestureRecognizer(gesture7)
kenny8.addGestureRecognizer(gesture8)
kenny9.addGestureRecognizer(gesture9)
kenny1.isUserInteractionEnabled = true
kenny2.isUserInteractionEnabled = true
kenny3.isUserInteractionEnabled = true
kenny4.isUserInteractionEnabled = true
kenny5.isUserInteractionEnabled = true
kenny6.isUserInteractionEnabled = true
kenny7.isUserInteractionEnabled = true
kenny8.isUserInteractionEnabled = true
kenny9.isUserInteractionEnabled = true
// set timers
counter = 30
timeLabel.text = "\(counter)"
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.countDown), userInfo: nil, repeats: true)
hideTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.hidekenny), userInfo: nil, repeats: true)
//creating array
kennyArray.append(kenny1)
kennyArray.append(kenny2)
kennyArray.append(kenny3)
kennyArray.append(kenny4)
kennyArray.append(kenny5)
kennyArray.append(kenny6)
kennyArray.append(kenny7)
kennyArray.append(kenny8)
kennyArray.append(kenny9)
hidekenny()
}
@objc func increaseScore(){
//this is what is happen when the gester is called
score += 1
scoreLabel.text = "Score: \(score)"
}
@objc func countDown(){
counter = counter - 1
timeLabel.text = "\(counter)"
if counter == 0 {
timer.invalidate()
hideTimer.invalidate()
//score higher
if self.score > Int(heighScoreLabel.text!)!
{
UserDefaults.standard.set(self.score, forKey: "highscore")
heighScoreLabel.text = String(self.score)
}
//alert creation
let alert = UIAlertController(title: "Time!", message: "Your Time is Yup!", preferredStyle: UIAlertControllerStyle.alert)
let extbtn = UIAlertAction(title: "Exit", style: UIAlertActionStyle.destructive, handler: {(UIAlertAction) in
exit(0);
})
alert.addAction(extbtn)
/*let resetApp = UIAlertAction(title: "Close Now", style: .destructive) {
(alert) -> Void in
// home button pressed programmatically - to thorw app to background
UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
// terminaing app in background
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
exit(EXIT_SUCCESS)
})
}
alert.addAction(resetApp)*/
let replay = UIAlertAction(title: "Replay!", style: UIAlertActionStyle.default, handler: {(UIAlertAction) in
self.score = 0
self.scoreLabel.text = "Score: \(self.score)"
self.counter = 30
self.timeLabel.text = "\(self.counter)"
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.countDown), userInfo: nil, repeats: true)
self.hideTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(ViewController.hidekenny), userInfo: nil, repeats: true)
})
alert.addAction(replay)
self.present(alert, animated: true, completion: nil)
}
}
@objc func hidekenny(){
for kenny in kennyArray{
kenny.isHidden = true
}
let randomNumbers = Int(arc4random_uniform(UInt32(kennyArray.count-1)))
kennyArray[randomNumbers].isHidden = false
}
}
| 8db6db313e12a736eb8b5782faf84537cdd5eea2 | [
"Swift"
] | 1 | Swift | nabeelnaveed/iOS-Practice-Project---Catch-the-Kenny | bbb94dd1c0144bb3ab2e680fc148a5a2284c3b38 | 328fe87c2723a5d5b98c6bc558f982f005d34863 |
refs/heads/master | <file_sep>package ua.semeniuk.artem.statistic;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by semen_000 on 9/3/2016.
*/
public class StatisticService extends IntentService {
private static final String TAG_NAME = "StatisticService";
private static final int POLL_INTERVAL = 1000*60;
private static final int POLL_INTERVAL_HALF_HOUR = 1000*60*30;
private final int COUNT = 3;
private UsageStatsManager mUsageStatsManager;
private static final String BROADCAST_ACTION = "ua.semeniuk.artem.statistic.action";
public StatisticService() {
super(TAG_NAME);
}
@Override
protected void onHandleIntent(Intent intent) {
mUsageStatsManager = (UsageStatsManager) getSystemService("usagestats");
ArrayList<UsageStats> usageStatsList = getUsageStatistics(UsageStatsManager.INTERVAL_DAILY);
if (usageStatsList != null){
Intent i = new Intent(BROADCAST_ACTION);
i.putExtra("group_title", System.currentTimeMillis());
i.putExtra("usage_stats",usageStatsList);
sendBroadcast(i);
}
}
public ArrayList<UsageStats> getUsageStatistics(int intervalType) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
List<UsageStats> queryUsageStats = mUsageStatsManager
.queryUsageStats(intervalType, cal.getTimeInMillis(),
System.currentTimeMillis());
ArrayList<UsageStats> usageStatsArray = new ArrayList<UsageStats>();
if(queryUsageStats.size() != 0) {
Collections.sort(queryUsageStats, new LastTimeLaunchedComparatorDesc());
for (int i = 0; i < COUNT; i++) {
usageStatsArray.add(queryUsageStats.get(i));
}
}
return usageStatsArray;
}
private class LastTimeLaunchedComparatorDesc implements Comparator<UsageStats> {
@Override
public int compare(UsageStats left, UsageStats right) {
return Long.compare(right.getLastTimeUsed(), left.getLastTimeUsed());
}
}
public static void setServiceAlarm(Context context, boolean isOn) {
Log.i(TAG_NAME, "setServiceAlarm "+isOn);
Intent intent = new Intent(context, StatisticService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)
context.getSystemService(ALARM_SERVICE);
if (isOn){
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis()
,POLL_INTERVAL, pi);
}else {
alarmManager.cancel(pi);
pi.cancel();
}
}
public static boolean isServiceAlarmOn(Context context) {
Intent intent = new Intent(context, StatisticService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent
,PendingIntent.FLAG_NO_CREATE);
return pi != null;
}
}
<file_sep>package ua.semeniuk.artem.statistic;
import java.util.ArrayList;
/**
* Created by semen_000 on 9/3/2016.
*/
public class GroupItemModel {
long group_title;
ArrayList<ListItemModel> child_items;
public GroupItemModel(long group_title, ArrayList<ListItemModel> child_items) {
this.group_title = group_title;
this.child_items = child_items;
}
public long getGroup_title() {
return group_title;
}
public ArrayList<ListItemModel> getChild_items() {
return child_items;
}
}
| f70c04a8cd1e724dbb2d1a8a06d98b7e0aca1602 | [
"Java"
] | 2 | Java | olorin3000/Statistic | 584b8fe0897ce95dfbd8ceeb3112adc98618c1d9 | ee33a50e8cabdfffd7c6e8bc51cda905cc03fec3 |
refs/heads/main | <repo_name>blakdragon39/fullstackopen2020-part5<file_sep>/README.md
https://fullstackopen.com/en/part5/login_in_frontend#exercises-5-1-5-4<file_sep>/src/components/blogs/BlogPage.js
import React from 'react'
import { useParams } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import { likeBlog } from '../../reducers/blogReducer'
import Comments from './Comments'
const BlogPage = () => {
const dispatch = useDispatch()
const id = useParams().id
const blog = useSelector(store => store.blogs.find(blog => blog.id === id))
// const deleteButtonStyle = {
// display: blog.user && blog.user.id === localStorage.getUser().id ? '' : 'none'
// }
const addLike = () => dispatch(likeBlog(blog))
// const confirmDelete = () => {
// const confirmDelete = window.confirm(`Really delete ${blog.title}?`)
//
// if (confirmDelete) {
// dispatch(deleteBlog(blog))
// }
// }
if (blog) {
return (
<div>
<div>
<h2>{blog.title}</h2>
<div><a href={blog.url}>{blog.url}</a></div>
<div>Likes: {blog.likes} <button onClick={addLike}>Like</button></div>
<div>{blog.author}</div>
{/*<div style={deleteButtonStyle}> <button onClick={confirmDelete}>Delete</button></div>*/}
</div>
<Comments blog={blog}/>
</div>
)
} else {
return null
}
}
export default BlogPage
<file_sep>/src/reducers/blogReducer.js
import blogService from '../services/blogs'
import { addNotification } from './notificationReducer'
export const getBlogs = () => {
return async (dispatch) => {
try {
const blogs = await blogService.getAll()
dispatch({
type: 'blogs.get',
data: {
blogs
}
})
} catch (e) {
console.error(e)
dispatch(addNotification(e.response.data.error, true))
}
}
}
export const addBlog = (blog) => {
return async (dispatch) => {
try {
const newBlog = await blogService.addBlog(blog)
dispatch({
type: 'blogs.add',
data: {
blog: newBlog
}
})
} catch (e) {
console.error(e)
dispatch(addNotification(e.response.data.error, true))
}
}
}
export const likeBlog = (blog) => {
return async (dispatch) => {
try {
const newBlog = await blogService.addLike(blog)
dispatch({
type: 'blogs.update',
data: {
blog: newBlog
}
})
} catch (e) {
console.error(e)
dispatch(addNotification(e.response.data.error, true))
}
}
}
export const deleteBlog = (blog) => {
return async (dispatch) => {
try {
await blogService.deleteBlog(blog)
dispatch({
type: 'blogs.delete',
data: {
blog: blog
}
})
} catch (e) {
console.error(e)
dispatch(addNotification(e.response.data.error, true))
}
}
}
const blogReducer = (state = [], action) => {
switch (action.type) {
case 'blogs.get':
return action.data.blogs
case 'blogs.add':
return state.concat(action.data.blog)
case 'blogs.update': {
const updatedId = action.data.blog.id
return state.map(blog => blog.id === updatedId ? action.data.blog : blog)
}
case 'blogs.delete':
return state.filter(blog => blog.id !== action.data.blog.id)
default:
return state
}
}
export default blogReducer
<file_sep>/src/reducers/notificationReducer.js
export const addNotification = (message, isError = false, timeoutSeconds = 5) => {
return async (dispatch) => {
const id = Math.floor(Math.random() * 10000)
dispatch({
type: 'notification.add',
data: {
id,
message,
isError
}
})
setTimeout(() => dispatch({
type: 'notification.remove',
data: {
id
}
}), timeoutSeconds * 1000)
}
}
const notificationReducer = (state = [], action) => {
switch (action.type) {
case 'notification.add':
return state.concat(action.data)
case 'notification.remove':
return state.filter(notification => notification.id !== action.data.id)
default:
return state
}
}
export default notificationReducer
<file_sep>/src/services/blogs.js
import axios from 'axios'
const baseUrl = 'http://localhost:3001/api/blogs'
let token
const setToken = (newToken) => token = newToken
const header = () => {
return {
Authorization: token
}
}
const headerConfig = () => {
return {
headers: header()
}
}
const getAll = async () => {
const response = await axios.get(baseUrl)
return response.data
}
const addBlog = async (newBlog) => {
const response = await axios.post(baseUrl, newBlog, headerConfig())
return response.data
}
const deleteBlog = async (blog) => {
await axios.delete(`${baseUrl}/${blog.id}`, headerConfig())
}
const addLike = async (blog) => {
const body = { likes: blog.likes + 1 }
const response = await axios.put(`${baseUrl}/${blog.id}`, body, headerConfig())
return response.data
}
const getComments = async (blog) => {
const response = await axios.get(`${baseUrl}/${blog.id}/comments`)
return response.data
}
const addComment = async (blog, text) => {
const response = await axios.post(`${baseUrl}/${blog.id}/comments`, { text }, headerConfig())
return response.data
}
const blogService = {
setToken,
getAll,
addBlog,
deleteBlog,
addLike,
getComments,
addComment
}
export default blogService
<file_sep>/src/components/users/UserPage.js
import React from 'react'
import { useParams } from 'react-router-dom'
import { useSelector } from 'react-redux'
const UserPage = () => {
const id = useParams().id
const user = useSelector(store => store.users.find(user => user.id === id))
if (user) {
return (
<div>
<h2>{ user.displayName }</h2>
<h3>Added Blogs</h3>
<ul>
{
user.blogs.map(blog => <li key={blog.id}>{blog.title}</li>)
}
</ul>
</div>
)
} else {
return null
}
}
export default UserPage
<file_sep>/src/components/blogs/BlogsPage.js
import React, { useRef } from 'react'
import Toggleable from '../Toggleable'
import AddBlog from './AddBlog'
import Blogs from './Blogs'
const BlogsPage = () => {
const toggleRef = useRef()
return (
<div>
<Toggleable toggleText='Add Blog' ref={toggleRef}>
<AddBlog
toggleable={toggleRef}/>
</Toggleable>
<Blogs />
</div>
)
}
export default BlogsPage
<file_sep>/src/App.js
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getBlogs } from './reducers/blogReducer'
import { getUsers } from './reducers/userReducer'
import { getLoginUser } from './reducers/loginReducer'
import { BrowserRouter } from 'react-router-dom'
import NavBar from './components/NavBar'
import Login from './components/Login'
import Main from './components/Main'
import Notifications from './components/Notifications'
import blogService from './services/blogs'
const App = () => {
const user = useSelector(store => store.loginUser)
const dispatch = useDispatch()
useEffect(() => dispatch(getLoginUser()), [])
useEffect(() => dispatch(getBlogs()), [])
useEffect(() => dispatch(getUsers()), [])
if (user) {
blogService.setToken(user.token)
}
const body = user === null ? <Login /> : <Main />
return (
<div>
<BrowserRouter>
<NavBar />
<Notifications />
{body}
</BrowserRouter>
</div>
)
}
export default App
<file_sep>/src/components/blogs/Comments.js
import React, { useEffect, useState } from 'react'
import PropType from 'prop-types'
import { useDispatch } from 'react-redux'
import blogService from '../../services/blogs'
import { addNotification } from '../../reducers/notificationReducer'
const Comments = ({ blog }) => {
const [comments, setComments] = useState([])
const [comment, setComment] = useState('')
const dispatch = useDispatch()
useEffect(() => {
if (blog) {
blogService.getComments(blog)
.then(newComments => setComments(newComments))
}
}, [blog])
const submitComment = async (event) => {
event.preventDefault()
try {
const newComment = await blogService.addComment(blog, comment)
setComments(comments.concat(newComment))
setComment('')
} catch (e) {
console.log(e)
dispatch(addNotification(e.response.data.error, true))
}
}
return (
<div>
<h3>Comments</h3>
<form onSubmit={submitComment}>
<input type='text' value={comment} onChange={({ target }) => setComment(target.value)}/>
<button type='submit'>Add Comment</button>
</form>
<ul>
{
comments.map(comment => <li key={comment.id}>{comment.text}</li>)
}
</ul>
</div>
)
}
Comments.propTypes = {
blog: PropType.object.isRequired
}
export default Comments
<file_sep>/src/reducers/userReducer.js
import userService from '../services/users'
import { addNotification } from './notificationReducer'
export const getUsers = () => {
return async (dispatch) => {
try {
const users = await userService.getAll()
dispatch({
type: 'users.get',
data: { users }
})
} catch (e) {
console.log(e)
dispatch(addNotification(e.response.data.error, true))
}
}
}
const userReducer = (state = [], action) => {
switch (action.type) {
case 'users.get':
return action.data.users
default:
return state
}
}
export default userReducer
<file_sep>/src/components/tests/Blog.test.js
import React from 'react'
import '@testing-library/jest-dom/extend-expect'
import { render, fireEvent } from '@testing-library/react'
import Blogs from '../blogs/Blogs'
describe('<Blog/>', () => {
const blog = {
id: 'id',
title: 'Title',
author: 'Author',
url: 'url',
likes: 5
}
const blogs = [ blog ]
let component
let updateBlogMock
let blogServiceMock
let deleteBlogMock
beforeEach(() => {
updateBlogMock = jest.fn()
deleteBlogMock = jest.fn()
blogServiceMock = {}
component = render(
<Blogs
blogs={blogs}
updateBlog={updateBlogMock}
blogService={blogServiceMock}
deleteBlog={deleteBlogMock}/>
)
})
test('renders title', () => {
expect(component.container).toHaveTextContent(blog.title)
})
test('other fields hidden', () => {
const hiddenDiv = component.container.querySelector('.blogBody')
expect(hiddenDiv).toHaveStyle('display: none')
})
test('fields shown when clicked', () => {
const button = component.getByText('View')
fireEvent.click(button)
const hiddenDiv = component.container.querySelector('.blogBody')
expect(hiddenDiv).not.toHaveStyle('display: none')
})
test('delete fires', () => {
const button = component.getByText('Delete')
fireEvent.click(button)
fireEvent.click(button)
expect(deleteBlogMock.mock.calls).toHaveLength(2)
})
})
<file_sep>/src/components/NavBar.js
import React from 'react'
import { Link } from 'react-router-dom'
import LoginUser from './LoginUser'
const NavBar = () => {
const navBarStyle = {
padding: 8,
backgroundColor: '#afafaf',
marginBottom: 16
}
const linkStyle = {
marginRight: 12
}
return (
<div style={navBarStyle}>
<Link to='/' style={linkStyle}>Blogs</Link>
<Link to='/users' style={linkStyle}>Users</Link>
<LoginUser />
</div>
)
}
export default NavBar
| 379e42a84ed8b15d262113e31cac543edb0d153f | [
"Markdown",
"JavaScript"
] | 12 | Markdown | blakdragon39/fullstackopen2020-part5 | a948a5fdeab3754db26044eac75cced4a6055899 | 868972e302dc5e43016493817fb672f0dab78659 |
refs/heads/master | <repo_name>aritraanish/caesar-cipher<file_sep>/README.md
# caesar-cipher
A Simple Caesar Cipher Code
<file_sep>/Caesar Cipher.py
#Created By AK
print("What do you want to do?")
print("1. ENCRYPT")
print("2. DECRYPT")
print("3. QUIT")
print("Choose the corresponding number.")
print("")
incorrect = True
retry = True
while(retry == True):
choice = str(input("Enter choice number:- "))
if (choice=="1"):
inp = str(input("Enter the string:- "))
k = int(input("Enter the Caesar Key:- "))
print("")
#---------Encryption Algorithm--------------
for i in range(0, len(inp)):
a = ord(inp[i])
for j in range (0, k):
a = a + 1
if (a>122):
a = 97
print(chr(a), end="")
#---------Encryption Algorithm End-----------
print("")
print("")
while (incorrect == True):
print("Do you want to try again?")
print("1. Yes")
print("2. No")
y=str(input())
if (y=="1" or y=="y" or y=="Y" or y=="yes" or y=="Yes"):
retry = True
incorrect = False
elif (y=="2" or y=="n" or y=="N" or y=="no" or y=="No"):
retry = False
incorrect = False
else:
incorrect = True
elif (choice=="2"):
inp = str(input("Enter the string:-"))
k = int(input("Enter the Caesar Key:- "))
print("")
#----------Decryption ALgorithm---------------
for i in range(0, len(inp)):
a = ord(inp[i])
for o in range (0, k):
a = a - 1
if (a<97):
a = 122
print(chr(a), end="")
#-----------Decryption Algorithm Ends----------
print("")
print("")
incorrect = True
while (incorrect == True):
print("Do you want to try again?")
print("1. Yes")
print("2. No")
y=str(input())
if (y=="1" or y=="y" or y=="Y" or y=="yes" or y=="Yes"):
retry = True
incorrect = False
elif (y=="2" or y=="n" or y=="N" or y=="no" or y=="No"):
retry = False
incorrect = False
else:
incorrect = True
elif (choice=="3"):
retry = False
else:
print("Wrong Choice")
| 9bda517ddec42c6ab0b958c8ce71b77beb2be83d | [
"Markdown",
"Python"
] | 2 | Markdown | aritraanish/caesar-cipher | 256d95f644a7c73d1fecedf828e82757630558ca | 269bc1b29072458613778c12f58867c7af965bce |
refs/heads/master | <repo_name>yvonneyanghangzhou/vueTemplate<file_sep>/src/config.js
/*
请求接口地址
devServerUrl 开发使用 也是默认情况下
proServerUrl 生成使用
*/
const devServerUrl = 'http://192.168.240.59:8001';
const proServerUrl = 'http://192.168.240.59:8090';
const testServerUrl = 'http://192.168.240.59:8002';
// 开发
let serverUrl = devServerUrl;
// 生产
if (process.env.NODE_ENV === 'production') {
serverUrl = proServerUrl;
} else if (process.env.NODE_ENV == 'testing') {
// 测试
serverUrl = testServerUrl;
}
/*
系统配置项
*/
export default {
//系统访问地址的path
pathName: '',
// 系统名称
sysName: '创高软件',
//接口地址
serverUrl,
//关闭权限检查 true 关闭 false 打开
closeCheck: true,
pageSizeOpts: [10, 20, 50, 100, 200],
// 合法的图片格式
legalImgType: ['gif', 'png', 'jpg', 'jpeg'],
// 合法的文件格式
legalFile: ['gif', 'png', 'jpg', 'jpeg', 'xls', 'xlsx', 'doc', 'docx', 'pdf', 'txt'],
appSecret: ['YzY', '0MG', 'Nh', 'Mz', 'k', 'yY2', 'Q0N', 'WZ', 'iM2E1', 'NWIw', 'MGE2M2', 'E4', 'NmM2M', 'Tg='],
appKey: ['=<KEY> <KEY> <KEY>'],
loginKey: ['53', '120', '991', '6a1', 'a11e', '999', '280', '05', '056', 'a53', 'c1c'].join('')
};
<file_sep>/src/router/routers.js
export default [
{
path: '/',
name: 'Index',
component: () => import('@/components/index'),
meta: {
title: '首页',
noCheckRule: true
}
},
{
path: '/menu',
name: 'Menu',
component: () => import('@/components/sysData/menu/menu.vue'),
meta: {
title: '菜单管理'
}
},
{
path: '/user',
name: 'User',
component: () => import('@/components/sysData/user/user.vue'),
meta: {
title: '用户管理'
}
},
{
path: '/user/:id',
name: 'UserEdit',
component: () => import('@/components/sysData/user/user-edit.vue'),
meta: {
title: '编辑用户',
breadcrumb: {
name: '用户管理',
url: '/user'
}
}
},
{
path: '*',
name: 'Error',
component: () => import('@/components/common/404.vue'),
meta: {
title: '没有找到页面',
noCheckRule: true
}
},
{
path: '/407',
name: 'noRule',
component: () => import('@/components/common/407.vue'),
meta: {
title: '权限限制',
noCheckRule: true
}
},
{
path: '/login',
name: 'Login',
component: () => import('@/components/login.vue'),
meta: {
title: '登录',
noCheckRule: true,
fullScreen: true,
noLogin: true
}
},
{
path: '/code',
name: 'Code',
component: () => import('@/components/sysData/code/code.vue'),
meta: {
title: '公共代码管理'
}
},
{
path: '/role',
name: 'Role',
component: () => import('@/components/sysData/role/role.vue'),
meta: {
title: '用户组权限管理'
}
},
{
path: '/sysSetting',
name: 'SysSetting',
component: () => import('@/components/sysData/sysSetting.vue'),
meta: {
title: '系统设置'
}
},
{
path: '/cache',
name: 'Cache',
component: () => import('@/components/sysData/cache.vue'),
meta: {
title: '缓存刷新'
}
}
];
<file_sep>/src/vuex/state.js
export default{
loading: false,
menu_list: [],
user_list: [],
sysSetting: {},
breadcrumb: [],
tags: [],
modal: {
show: false,
title: '系统提示',
content: '',
onOk: function () {
return false;
}
}
};
<file_sep>/src/assets/js/custom.js
/* 一些自定义的方法 */
import Vue from 'vue';
import iView from 'iview';
import cryptoJS from 'crypto-js';
import config from '../../config';
var { $http } = require('./cgHttp');
Vue.use(iView);
const appSecret = getBase64(config.appSecret.join(''));
const appString = config.appKey.join('');
const ROUTE_NAME = getLocalData('dataTwo', true, '').split(','); //拥有的页面name
/*
使用axios发起网络请求
*/
function emitAjax(opts) {
/*
处理参数
删除不要的参数
参数字符串前后去空
*/
if (opts.data) {
for (const key in opts.data) {
if (opts.data.hasOwnProperty(key)) {
const value = opts.data[key];
opts.data[key] = formatData(value);
}
}
}
//合并默认的参数
const opt = Object.assign(
{},
{
path: '', //请求地址
type: 'GET', //请求方式 大写
data: null,
dataType: 'common', //文件上传还是普通数据交互 值为file是上传文件
headers: null,
responseType: null, //文件下载 值一般blob
async: true, //true异步 false 同步
success: function() {}, //code200执行的函数
error: function() {}, //不是code200 执行的函数
progress: null
},
opts
);
const timestamp = Date.parse(new Date());
//传一个时间戳 消除get请求服务器缓存
if (opt.type == 'GET') {
opt.data = opt.data ? opt.data : {};
opt.data.nocache = timestamp;
}
const data = Object.assign({}, opt.data, {
gmtCreate: null,
gmtModified: null,
id: null,
_index: null,
_rowKey: null
});
// 生成签证,合并请求头
const appKey = getBase64(
appString
.split('')
.reverse()
.join('')
);
const sign = setSign(timestamp, opt.path, data);
// 组织请求头信息
let headers = {
'app-key': appKey,
timestamp,
sign
};
const Authorization = getLocalData('dataSix', false, '');
if (Authorization) {
headers.Authorization = Authorization;
}
headers = Object.assign({}, headers, opt.headers);
//发送请求
$http({
url: config.serverUrl + opt.path,
type: opt.type.toLocaleUpperCase(),
headers,
async: opt.async,
data,
dataType: opt.dataType,
responseType: opt.responseType ? opt.responseType : null,
progress: opt.progress || null,
success: function(response) {
const code = response.code || 0;
if (getTypeOf(response) === 'blob') {
opt.success(response);
} else if (code == 200) {
opt.success(response.data);
} else if (code == 101) {
//token过期
errorTip(response, () => {
delLocalData('all');
window.location.href = config.pathName + '/login';
});
} else if (code == 408) {
errorTip(response, function() {
window.history.back();
});
} else {
//401 登录失败 250 服务器抛出错误
errorTip(response, opt.error);
}
},
error: function(error) {
errorTip(error, opt.error);
}
});
}
//网络错误处理函数
function errorTip(response, callback) {
if (response.message) {
iView.Modal.error({
title: '系统提示',
content: response.message,
onOk: () => {
callback && callback(response);
}
});
} else {
callback && callback(response);
}
}
//签证
function setSign(timestamp, path, opt) {
let keyArray = [];
let signString = appSecret + path;
if (typeof opt == 'object') {
for (const key in opt) {
if (opt.hasOwnProperty(key)) {
keyArray.push(key);
}
}
keyArray.sort();
for (let index = 0; index < keyArray.length; index++) {
const key = keyArray[index];
if (opt[key] !== null && opt[key] !== undefined && typeof opt[key] != 'object') {
signString += key + opt[key];
}
}
}
signString += timestamp + ' ' + appSecret;
return cryptoJS.MD5(signString).toString();
}
//设置本地缓存
function setLocalData(data) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const value = data[key];
localStorage.setItem(key, value);
}
}
}
//获取本地缓存 ispassword是否是加密过的数据 defaultData如果没有找到数据返回的值
function getLocalData(key, ispassword, defaultData) {
const value = localStorage.getItem(key);
if (value) {
return ispassword ? keyGetPassword(value) || defaultData : value;
}
return defaultData;
}
//删除缓存
function delLocalData(array) {
if (array == 'all') {
const rememberMe = localStorage.getItem('rememberMe');
localStorage.clear();
delCookie('dataEight');
rememberMe && localStorage.setItem('rememberMe', rememberMe);
} else {
for (let index = 0; index < array.length; index++) {
const key = array[index];
localStorage.removeItem(key);
}
}
}
//请求参数处理函数
function formatData(opt) {
if (typeof opt == 'string') {
return opt.replace(/(^\s*)|(\s*$)/g, '');
}
return opt;
}
function getCookie(name) {
const cookie = document.cookie;
if (cookie.length > 0) {
//查询cookie开始位置
let start = cookie.indexOf(name + '=');
if (start >= 0) {
//=号后面的位置为开始位置
start = start + name.length + 1;
//从name开始第一个;的位置
let end = cookie.indexOf(';', start);
if (end < 0) {
end = cookie.length;
}
//cookie是否经过转码
return unescape(cookie.substring(start, end));
}
}
return '';
}
function setCookie(name, value, date) {
let now = Date.parse(new Date());
let expiresTime = '';
if (date) {
//多少小时
expiresTime = new Date(now + date * 3600000);
}
const expires = date ? ';expires=' + expiresTime.toGMTString() : '';
document.cookie = name + '=' + escape(value) + expires + ';path=/';
}
function delCookie(name) {
setCookie(name, '', -1);
}
//aes加密
function keySetPassword(word) {
if (['undefined', 'null'].indexOf(getTypeOf(word)) >= 0) {
return false;
}
const key = cryptoJS.enc.Utf8.parse(['c1h', '2i', '5n6g', '2o', '2k', '4a7'].join(''));
const iv = cryptoJS.enc.Utf8.parse(['C2', 'H3', 'I4N', '5G2O', '3K', '1E4'].join(''));
const srcs = typeof word === 'object' ? JSON.stringify(word) : word.toString();
const keyword = cryptoJS.enc.Utf8.parse(srcs);
return cryptoJS.AES.encrypt(keyword, key, {
iv: iv,
mode: cryptoJS.mode.CBC,
padding: cryptoJS.pad.Pkcs7
}).ciphertext.toString();
}
//aes解密
function keyGetPassword(word) {
if (['undefined', 'null'].indexOf(getTypeOf(word)) >= 0) {
return false;
}
const key = cryptoJS.enc.Utf8.parse(['c1h', '2i', '5n6g', '2o', '2k', '4a7'].join(''));
const iv = cryptoJS.enc.Utf8.parse(['C2', 'H3', 'I4N', '5G2O', '3K', '1E4'].join(''));
const srcs = cryptoJS.enc.Base64.stringify(cryptoJS.enc.Hex.parse(word));
return cryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: cryptoJS.mode.CBC,
padding: cryptoJS.pad.Pkcs7
}).toString(cryptoJS.enc.Utf8);
}
function setBase64(string) {
return cryptoJS.enc.Base64.stringify(cryptoJS.enc.Utf8.parse(string));
}
function getBase64(string) {
return cryptoJS.enc.Base64.parse(string).toString(cryptoJS.enc.Utf8);
}
//文件流下载
function downFile(blob, fileName) {
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, fileName);
} else {
const fileUrl = window.URL.createObjectURL(blob);
const BODY = document.getElementsByTagName('body')[0];
let a = document.createElement('a');
a.href = fileUrl;
a.download = fileName;
BODY.appendChild(a);
a.click();
BODY.removeChild(a);
window.URL.revokeObjectURL(fileUrl);
}
}
//判断数组是否存在value这个值 如果数组的成员是对象,key值则是对比的值
function arrayIndexOf(array, value, key) {
for (let index = 0; index < array.length; index++) {
const item = array[index];
if (key && item[key] == value) {
return index;
}
if (!key && item == value) {
return index;
}
}
return -1;
}
//获取数据类型
function getTypeOf(data) {
const result = Object.prototype.toString.call(data).match(/\[object (.+)\]/);
return result[1].toLocaleLowerCase();
}
//登录成功执行的方法
function loginSuccess(response, callback) {
const time = Date.parse(new Date());
setCookie('dataEight', keySetPassword(config.loginKey + time));
setLocalData({
dataTwo: keySetPassword(response.routeName),
dataThree: keySetPassword(
response.userInfo || {
name: response.name,
role: response.role,
gender: response.gender,
username: response.username
}
),
dataFour: keySetPassword(response.ruleList),
dataFive: keySetPassword(response.menus),
dataSix: response.token.access_token
});
localStorage.removeItem('tags');
callback && callback();
window.location.href = config.pathName;
}
//是否登录
function hasLogin() {
const hasLogin = getCookie('dataEight');
return hasLogin && keyGetPassword(hasLogin).search(config.loginKey) >= 0;
}
//判断是否有操作权限
function hasHanderRule(rule) {
return config.closeCheck || ROUTE_NAME.indexOf(rule) >= 0;
}
//手机号验证
function isPhone(phone) {
return /^1[34578]\d{9}$/.test(phone);
}
//邮箱验证
function isMail(mail) {
return /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/.test(mail);
}
/**
* 防抖
*/
function antiShake(callback, timeout) {
const that = this;
let timer = null;
return function() {
const arg = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
callback.apply(that, arg);
}, timeout || 400);
};
}
export default {
emitAjax,
setLocalData,
getLocalData,
delLocalData,
formatData,
setSign,
getCookie,
setCookie,
delCookie,
keySetPassword,
keyGetPassword,
downFile,
arrayIndexOf,
getTypeOf,
loginSuccess,
setBase64,
getBase64,
hasLogin,
hasHanderRule,
MD5: cryptoJS.MD5,
isPhone,
isMail,
antiShake
};
<file_sep>/src/main.js
import Vue from 'vue';
import Main from './main.vue';
import router from './router';
import iView from 'iview';
import store from './vuex';
import './assets/js/dataset';
import config from './config';
import commonMethods from './assets/js/custom';
import './assets/css/iview.less';
import './assets/css/common.css';
import Button from './components/common/button.vue';
import Upload from './components/common/upload.vue';
Vue.component('ListButton', Button);
Vue.component('UploadFile', Upload);
Vue.config.productionTip = false;
Vue.use(iView);
Vue.prototype.config = config;
Vue.prototype.commonMethods = commonMethods;
Vue.prototype.userInfo = JSON.parse(commonMethods.getLocalData('dataThree', true, '{}'));
iView.LoadingBar.config({
color: '#f90',
failedColor: '#ed3f14',
height: 4
});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(Main),
store
});
<file_sep>/.eslintrc.js
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
rules:{ //前往./eslintrc.js 查看完整的配置规则 0 禁用 1 开启并警告 2 开启并报错
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
//一些空格配置
"space-after-keywords": [0, "always"],//关键字后面是否要空一格
"space-before-blocks": [0, "always"],//不以新行开始的块{前面要不要有空格
"space-before-function-paren": [0, "always"],//函数定义时括号前面要不要有空格
"space-in-parens": [0, "never"],//小括号里面要不要有空格
"space-infix-ops": 0,//中缀操作符周围要不要有空格
"space-return-throw-case": 0,//return throw case后面要不要加空格
"space-unary-ops": [0, { "words": true, "nonwords": false }],//一元运算符的前/后要不要加空格
"spaced-comment": 0,//注释风格要不要有空格什么的
'semi': ["error", "always"], //必须使用分号
'eqeqeq' : 0, //不强制使用全等
},
}
<file_sep>/README.md
[文档链接](https://yanying119.github.io/chingo-docs/docs/)
| c67c53d6e055e9aad52bcdaac6e961048c2e036b | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | yvonneyanghangzhou/vueTemplate | ff862a73f106cc69870f87b76a9d19dc6e5c6123 | d91793782939bd18620f0fe84d10204f6b7e2ce9 |
refs/heads/master | <file_sep>package chapter07;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-11 15:55
*/
public class Exercise07_09 {
public static void main(String[] args) {
System.out.print("Enter ten numbers: ");
double[] nums = new double[10];
Scanner input = new Scanner(System.in);
for(int i = 0; i < 10; i++){
nums[i] = input.nextDouble();
}
System.out.println("The minimum number is: " + min(nums));
}
public static double min(double[] array){
double result = Double.MAX_VALUE;
for(int i = 0; i < array.length; i++){
if(array[i] <= result){
result = array[i];
}
}
return result;
}
}
<file_sep>package chapter05;
import javax.xml.stream.events.Characters;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-10 10:46
*/
public class Exercise05_49 {
public static void main(String[] args) {
System.out.print("Enter a string: ");
Scanner input = new Scanner(System.in);
String s = input.nextLine();
int countVowels = 0;
int countConsonants = 0;
for(int i = 0; i < s.length(); i++){
char ch = Character.toUpperCase(s.charAt(i));
if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
countVowels++;
}else if(Character.isLetter(ch)){
countConsonants++;
}
}
System.out.println("The number of vowels is " + countVowels);
System.out.println("The number of consonants is " + countConsonants);
}
}
<file_sep>package chapter07;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-11 15:47
*/
public class Exercise07_08 {
public static void main(String[] args) {
System.out.print("Enter ten numbers: ");
Scanner input = new Scanner(System.in);
double[] numsOfDouble = new double[10];
for(int i = 0; i < 10; i++){
numsOfDouble[i] = input.nextDouble();
}
System.out.println(average(numsOfDouble));
}
public static int average(int[] array){
int result = 0;
for(int i = 0; i < array.length; i++){
result += array[i];
}
int averageOfInteger = result / array.length;
return averageOfInteger;
}
public static double average(double[] array){
double result = 0;
for(int i = 0; i < array.length; i++){
result += array[i];
}
double averageOdDouble = result / array.length;
return averageOdDouble;
}
}
<file_sep>package chapter05;
/**
* @author WangMingMing
* @creat 2020-02-10 11:42
*/
public class Exercise05_40 {
public static void main(String[] args) {
int count1 = 0;//正面
int count2 = 0;//反面
for(int i = 0; i < 1000000; i++){
int num = (int)(Math.random() * 2);
if(num == 0){
count1++;
}else{
count2++;
}
}
System.out.println("正面次数: " + count1);
System.out.println("反面次数: " + count2);
}
}
<file_sep>package chapter07;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-13 22:14
*/
public class Exercise07_28 {
public static void main(String[] args) {
final int NUMBER = 10;
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
int[] list = new int[NUMBER];
for(int i = 0; i < NUMBER; i++){
list[i] = input.nextInt();
}
for(int i = 0; i < NUMBER; i++){
for(int j = i + 1; j < NUMBER; j++){
System.out.println("(" + list[i] + "," + list[j] + ")");
}
}
}
}
<file_sep>package chapter05;
/**
* @author WangMingMing
* @creat 2020-02-09 12:27
*/
public class Exercise05_19 {
public static void main(String[] args) {
for(int row = 1; row <= 8; row++){
for(int cap = 1; cap <= 8 - row; cap++){
System.out.print(" ");
}
int num = 1;
for(int colrow = 1; colrow <= row; colrow++){
System.out.printf("%4d",num);
num *= 2;
}
num /= 4;
for(int colrow = 1; colrow <= row - 1; colrow++){
System.out.printf("%4d",num);
num /= 2;
}
System.out.println();
}
}
}
<file_sep>package chapter05;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-10 15:55
*/
public class Exercise05_31 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the initial deposit amount: ");
double deposit = input.nextDouble();//输入总金额
System.out.print("Enter annual percentage yield: ");
double annualInterestRate = input.nextDouble();//年利率
double monthlyInterestRate = annualInterestRate / 1200;//月利率
System.out.print("Enter maturity period (number of months): ");
double numberOfMonths = input.nextInt();//月数
System.out.print("Month\t\tCD Value\n");
double currentValue = deposit;
for(int i = 1; i <= numberOfMonths; i++){
currentValue = currentValue * (1 + monthlyInterestRate);
System.out.printf("%-5d%15.2f\n", i, currentValue);
}
}
}
<file_sep>package chapter08;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-14 13:30
*/
public class Exercise08_01 {
public static void main(String[] args) {
System.out.println("Enter a 3-by-4 matrix row by row: ");
Scanner input = new Scanner(System.in);
double[][] nums = new double[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
nums[i][j] = input.nextDouble();
}
}
for(int i = 0; i < 4; i++){
System.out.println("Sum of the elements at column " + i + " is " + sumColumn(nums, i));
}
}
public static double sumColumn(double[][] m, int columnIndex){
double result = 0;
for(int i = 0; i < m.length; i++){
result = result + m[i][columnIndex];
}
return result;
}
}
<file_sep>package chapter05;
/**
* @author WangMingMing
* @creat 2020-02-10 11:37
*/
public class Exercise05_43 {
public static void main(String[] args) {
int count = 0;
for(int i = 1; i <= 7; i++){
for(int j = i + 1; j <= 7; j++){
System.out.println(i + " " + j);
count++;
}
}
System.out.println("The total number of all combinations is " + count);
}
}
<file_sep>package chapter05;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-09 16:04
*/
public class Exercise05_22 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Enter loan amount
System.out.print("Enter loan amount, for example 120000.95: ");
double loanAmount = input.nextDouble();
System.out.print("Enter number of years as an integer, for example 5: ");
int numOfYears = input.nextInt();
System.out.print("Enter yearly interest rate, for example 8.25: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = annualInterestRate/1200;
double monthlyPayment = loanAmount*monthlyInterestRate /
(1 - (Math.pow(1 / (1 + monthlyInterestRate), numOfYears * 12)));
double balance = loanAmount;
double interest;
double principal;
System.out.println("Monthly Payment: " + (int)(monthlyPayment * 100) / 100.0 );
System.out.println("Total Payment: " + (int)(monthlyPayment * 12 * numOfYears * 100) / 100.0 + "\n" );
System.out.println("Payment#\tInterest\tPrincipal\tBalance");
for (int i = 1; i <= numOfYears * 12; i++) {
interest = (int)(monthlyInterestRate * balance * 100) / 100.0;
principal = (int)((monthlyPayment - interest) * 100) / 100.0;
balance = (int)((balance - principal) * 100) / 100.0;
System.out.println(i + "\t\t" + interest + "\t\t" + principal + "\t\t" + balance);
}
}
}
<file_sep>package chapter05;
/**
* @author WangMingMing
* @creat 2020-02-10 15:44
*/
public class Exercise05_33 {
public static void main(String[] args) {
for(int i = 1; i <= 10000; i++){
int sum = 0;
for(int j = 1; j < i; j++){
if(i % j == 0 && i != j){
sum += j;
}
}
if(sum == i){
System.out.println(i);
}
}
}
}
<file_sep>package chapter06;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-11 10:24
*/
public class Exercise06_37 {
public static void main(String[] args) {
System.out.print("Enter a number and width: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
int width = input.nextInt();
System.out.println(format(number, width));
}
public static String format(int number, int width){
String str = Integer.toString(number);
if(str.length() >= width){
return str;
}
while(str.length() < width){
str = "0" + str;
}
return str;
}
}
<file_sep>package chapter06;
/**
* @author WangMingMing
* @creat 2020-02-10 21:42
*/
public class Exercise06_24 {
public static void main(String[] args) {
}
}
<file_sep>package chapter07;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-11 13:45
*/
public class Exercise07_02 {
public static void main(String[] args) {
System.out.print("Enter 10 numbers: ");
Scanner input = new Scanner(System.in);
int[] nums = new int[10];
for(int i = 9; i >= 0; i--){
nums[i] = input.nextInt();
}
System.out.print("Reverse numbers of the input is: ");
for(int i = 0; i < 10; i++){
System.out.print(nums[i] + " ");
}
System.out.println();
}
}
<file_sep>package chapter06;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-10 20:57
*/
public class Exercise06_20 {
public static void main(String[] args) {
System.out.println("Enter a String: ");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
System.out.println("The number of Letters is : " + countLetters(str));
}
public static int countLetters(String s){
int count = 0;
for(int i = 0; i < s.length(); i++){
if(Character.isLetter(s.charAt(i))){
count++;
}
}
return count;
}
}
<file_sep>package chapter07;
import sun.security.krb5.internal.tools.Klist;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-13 22:56
*/
public class Exercise07_31 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter list1: ");
int numberOfList1 = input.nextInt();
int[] list1 = new int[numberOfList1];
for(int i = 0; i < numberOfList1; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list2: ");
int numberOfList2 = input.nextInt();
int[] list2 = new int[numberOfList2];
for(int i = 0; i < numberOfList2; i++){
list2[i] = input.nextInt();
}
int[] result = merge(list1, list2);
System.out.print("The merge list is ");
for(int i = 0; i < list1.length + list2.length; i++){
System.out.print(result[i] + " ");
}
}
public static int[] merge(int[] list1, int[] list2){
int i = 0;
int j = 0;
int k = 0;
int[] result = new int[list1.length + list2.length];
while(i < list1.length && j < list2.length){
if(list1[i] < list2[j]){
result[k] = list1[i];
k++;
i++;
}else{
result[k] = list2[j];
k++;
j++;
}
}
if(i < list1.length){
for(int m = k; m < list1.length + list2.length; m++, i++){
result[m] = list1[i];
}
}
if(j < list2.length){
for(int m = k; m < list1.length + list2.length; m++, j++){
result[m] = list2[j];
}
}
return result;
}
}
<file_sep>package chapter07;
import java.util.Arrays;
/**
* @author WangMingMing
* @creat 2020-02-11 18:03
*/
public class Exercise07_16 {
public static void main(String[] args) {
int[] nums = new int[100000];
for(int i = 0; i < 100000; i++){
nums[i] = (int)(Math.random() * 100000);
}
int key = (int)(Math.random() * 100000);
long startTime = System.currentTimeMillis();
System.out.println(linearSearch(nums, key));
long endTime = System.currentTimeMillis();
long executionTime = startTime - endTime;
System.out.println(executionTime);
Arrays.sort(nums);
startTime = System.currentTimeMillis();
System.out.println(binarySearch(nums, key));
endTime = System.currentTimeMillis();
executionTime = startTime - endTime;
System.out.println(executionTime);
}
public static int linearSearch(int[] list, int key){
for(int i = 0; i < list.length; i++){
if(key == list[i]){
return i;
}
}
return -1;
}
public static int binarySearch(int[] list, int key){
int low = 0;
int high = list.length - 1;
while(high >= low){
int mid = (low + high) / 2;
if(key < list[mid]){
high = mid - 1;
}else if(key > list[mid]){
low = mid + 1;
}else{
return mid;
}
}
return -low - 1;
}
}
<file_sep>package chapter05;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-10 15:51
*/
public class Exercise05_32 {
public static void main(String[] args) {
int first = (int)(Math.random() * 10);
int second = (int)(Math.random() * 10);
while(second == first){
second = (int)(Math.random() * 10);
}
System.out.print("Enter your two digits lottery pick: ");
Scanner input = new Scanner(System.in);
int guess = input.nextInt();
if(guess / 10 == first && guess % 10 == second){
System.out.println("Exact match: you win $10,000");
}else if(guess / 10 == second && guess % 10 == first){
System.out.println("Match all digits: you win $3,000");
}else if(guess / 10 == first || guess / 10 == second || guess % 10 == first || guess % 10 == second){
System.out.println("Match one digit: you win $1,000");
}else{
System.out.println("Sorry, no match");
}
System.out.println("Lottery is " + first + second);
}
}
<file_sep>package chapter07;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-11 16:50
*/
public class Exercise07_12 {
public static void main(String[] args) {
System.out.print("Enter ten numbers: ");
Scanner input = new Scanner(System.in);
int[] nums = new int[10];
for(int i = 0; i < 10; i++){
nums[i] = input.nextInt();
}
nums = reverse(nums);
for(int i = 0; i < nums.length; i++){
System.out.print(nums[i] + " ");
}
}
public static int[] reverse(int[] list){
for(int i = 0, j = list.length - 1; i < j; i++, j--){
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
return list;
}
}
<file_sep>package chapter07;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-11 16:00
*/
public class Exercise07_10 {
public static void main(String[] args) {
double[] nums = new double[10];
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
for(int i = 0; i < 10; i++){
nums[i] = input.nextDouble();
}
System.out.println("The smallest number's index is: " + indexOfSmallestElement(nums));
}
public static int indexOfSmallestElement(double[] array){
double min = Double.MAX_VALUE;
int index = -1;
for(int i = 0; i < array.length; i++){
if(array[i] < min){
min = array[i];
index = i;
}
}
return index;
}
}
<file_sep>package chapter06;
/**
* @author WangMingMing
* @creat 2019-12-14 20:34
*/
public class Exercise06_14 {
public static void main(String[] args) {
System.out.printf("%-20s%-20s\n", "i", "m(i)");
for (int i = 1; i <= 1000; i += 100)
System.out.printf("%-20d%-20.4f\n", i, m(i));
}
public static double m(int n){
double pi = 0;
double sign = 1;
for(int i = 1; i <= n; i++){
pi += sign / (2 * i - 1);
sign = -sign;
}
return 4 * pi;
}
}
<file_sep>package chapter02;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2019-11-27 22:13
*/
public class Exercise02_03 {
public static void main(String[] args) {
// Enter foot
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a value for feet: ");
double feet = scanner.nextDouble();
double meter = feet * 0.305;
System.out.println(feet + " feet is " + meter + " meters");
}
}
<file_sep>package chapter06;
/**
* @author WangMingMing
* @creat 2020-02-10 18:48
*/
public class Exercise06_16 {
public static void main(String[] args) {
for(int i = 2000; i <= 2020; i++){
System.out.println(i + "年有" + numberOfDaysInAYear(i) + "天");
}
}
public static int numberOfDaysInAYear(int year){
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){
return 366;
}else{
return 365;
}
}
}
<file_sep>package chapter06;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-10 20:29
*/
public class Exercise06_17 {
public static void main(String[] args) {
System.out.print("Enter n: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
printMatrix(n);
}
public static void printMatrix(int n){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
int num = (int)(Math.random() * 2);
System.out.printf("%2d", num);
}
System.out.println();
}
}
}
<file_sep>package chapter06;
/**
* @author WangMingMing
* @creat 2020-02-10 22:17
*/
public class Exercise06_26 {
public static void main(String[] args) {
int count = 0;
for(int i = 2; true; i++){
if(isPrim(i) && isReverse(i)){
count++;
System.out.print((count % 10 != 0) ? i + " " : i + "\n");
if(count == 100){
break;
}
}
}
}
public static boolean isPrim(int num){
for(int i = 2; i <= num / 2; i++){
if(num % i == 0){
return false;
}
}
return true;
}
public static int isEqual(int num){
int result = 0;
while(num != 0){
int digit = num % 10;
result = result * 10 + digit;
num /= 10;
}
return result;
}
public static boolean isReverse(int number){
return number == isEqual(number);
}
}
<file_sep>package chapter06;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2019-12-14 16:58
*/
public class Exercise06_02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int value = input.nextInt();
System.out.println("The sum of digits for " + value + " is " + sumDigits(value));
}
public static int sumDigits(long n) {
long temp = (long)Math.abs(n);
int result = 0;
while(temp != 0){
int digit = (int)(temp % 10);
result += digit;
temp /= 10;
}
return result;
}
}
<file_sep># Introduction-to-Java-Programming
Java语言程序设计(基础篇)梁勇著课后习题编程练习<br>
**src**文件夹里面是每个章节后面的习题答案<br>
** 持续更新 **
<file_sep>package chapter05;
/**
* @author WangMingMing
* @creat 2020-02-08 21:54
*/
public class Exercise05_13 {
public static void main(String[] args) {
int i = 1;
while (i * i * i < 12000) {
i++;
}
// i^3 >= 12000
// (i-1)^3 < 12000
System.out.println("This number is " + (i - 1));
}
}
<file_sep>package chapter07;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-11 17:07
*/
public class Exercise07_14 {
public static void main(String[] args) {
System.out.print("Enter five numbers: ");
Scanner input = new Scanner(System.in);
int[] nums = new int[5];
for(int i = 0; i < 5; i++){
nums[i] = input.nextInt();
}
System.out.println(gcd(nums));
}
public static int gcd(int number1, int number2){
int gcd = 1;
int k = 1;
while(k <= number1 && k <= number2){
if(number1 % k == 0 && number2 % k == 0){
gcd = k;
}
k++;
}
return gcd;
}
public static int gcd(int... numbers){
int gcd = numbers[0];
for(int i = 0; i < numbers.length; i++){
gcd = gcd(gcd, numbers[i]);
}
return gcd;
}
}
<file_sep>package chapter05;
import java.util.Scanner;
/**
* @author WangMingMing
* @creat 2020-02-10 11:00
*/
public class Exercise05_47 {
public static void main(String[] args) {
System.out.print("Enter the first 12-digit of an ISBN number as a string: ");
Scanner input = new Scanner(System.in);
String s = input.nextLine();
if(s.length() != 12){
System.out.print(s + " is an invalid input");
System.exit(1);
}
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(i % 2 == 0){
sum = sum + (s.charAt(i) - '0');
}else{
sum = sum + (s.charAt(i) - '0') * 3;
}
}
int checkSum = 10 - sum % 10;
System.out.print("The ISBN number is ");
System.out.print((checkSum == 10) ? s + 0 : s + checkSum);
}
}
| c7bfbfc23a13734bc5a438de83b65c5d879eb58b | [
"Markdown",
"Java"
] | 30 | Java | GithubHfx/Introduction-to-Java-Programming | 41a2d51b86eec5e0d94363890a673da89984ab8a | cfbe52fecaf811837e89e35f0913dfe2cc2e2363 |
refs/heads/master | <repo_name>fatanugraha/pepehug-bot<file_sep>/readme.md
# pepe hug bot
<file_sep>/utils.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
)
func getProfileImage(userID string) (*ProfileAPIResult, error) {
apiURL := fmt.Sprintf("https://slack.com/api/users.profile.get?token=%s&user=%s", tokenAPI, userID)
resp, err := http.Get(apiURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
res, _ := ioutil.ReadAll(resp.Body)
result := &ProfileAPIResult{}
if err := json.Unmarshal(res, &result); err != nil {
panic(err)
}
return result, err
}
func postResponseImage(responseURL string, title string, imageURL string) error {
payload := ResponsePayload{
Attachments: &[]Attachment{
Attachment{
Title: "Here's a hug for you",
Pretext: title,
ImageURL: imageURL,
ThumbURL: imageURL,
},
},
ResponseType: "in_channel",
}
serialized, err := json.Marshal(payload)
_, err = http.Post(responseURL, "application/json", bytes.NewBuffer(serialized))
return err
}
func postResponseText(responseURL string, text string) error {
payload := ResponsePayload{Text: text}
serialized, err := json.Marshal(payload)
_, err = http.Post(responseURL, "application/json", bytes.NewBuffer(serialized))
return err
}
func downloadImage(filepath string, url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
func processImage(userID string) {
dir, _ := os.Getwd()
photoPath := fmt.Sprintf("/app/tmp/%s.jpg", userID)
photoResizedPath := fmt.Sprintf("/app/tmp/%s_200.png", userID)
backgroundPath := fmt.Sprintf("%s/assets/back.png", dir)
handPath := fmt.Sprintf("%s/assets/top.png", dir)
resultPath := fmt.Sprintf("%s/static/%s.png", dir, userID)
exec.Command("convert", photoPath, "-resize", "160", photoResizedPath).Run()
exec.Command("convert", "-background", "rgba(0,0,0,0)", "-rotate", "335", photoResizedPath, photoResizedPath).Run()
exec.Command("composite", "-geometry", "+40+260", photoResizedPath, backgroundPath, resultPath).Run()
exec.Command("composite", "-gravity", "center", handPath, resultPath, resultPath).Run()
}
<file_sep>/main.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
)
var slackSecret = os.Getenv("SLACK_SECRET")
var tokenAPI = os.Getenv("SLACK_API_TOKEN")
var domain = os.Getenv("DOMAIN")
func IsLetter(s string) bool {
for _, r := range s {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') {
return false
}
}
return true
}
func doHug(user string, responseURL string) {
userParts := strings.Split(user, "|")
userID := userParts[0][2:]
if !IsLetter(userID) || len(userID) != 9 {
postResponseText(responseURL, "usage: /pepe hug @person")
return
}
profile, _ := getProfileImage(userID)
downloadImage(fmt.Sprintf("/app/tmp/%s.jpg", userID), profile.Profile.Image512)
processImage(userID)
imageURL := fmt.Sprintf("%s/static/%s.png", domain, userID)
postResponseImage(responseURL, fmt.Sprintf("relax %s, everything will be alright", user), imageURL)
}
func webhookClientHandler(w http.ResponseWriter, r *http.Request) {
text := r.FormValue("text")
parts := strings.Split(text, " ")
responseURL := r.FormValue("response_url")
if parts[0] == "hug" {
if len(parts) == 1 {
postResponseText(responseURL, "you need to tag someone")
return
}
go doHug(parts[1], responseURL)
} else {
postResponseText(responseURL, "command unrecognized")
}
}
func main() {
port, found := os.LookupEnv("PORT")
if !found {
port = "8000"
}
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc(fmt.Sprintf("/slack-webhook/%s", slackSecret), webhookClientHandler)
connStr := fmt.Sprintf("0.0.0.0:%s", port)
log.Printf("Listening on %s", connStr)
if err := http.ListenAndServe(connStr, nil); err != nil {
log.Fatalf("Can't listen in port %s", port)
}
}
<file_sep>/Dockerfile
FROM golang:alpine as builder
RUN apk add --no-cache dep
ADD . /go/src/build/
WORKDIR /go/src/build
RUN dep ensure
RUN go build -o main .
FROM alpine
RUN adduser -S -D -H -h /app appuser
RUN apk add --no-cache imagemagick
COPY --from=builder /go/src/build/main /app/
COPY --from=builder /go/src/build/assets /app/assets
RUN mkdir /app/tmp && \
mkdir /app/static && \
chown -R appuser /app && \
chmod 755 /app
WORKDIR /app
ENV PORT 5000
EXPOSE 5000
USER appuser
CMD ["./main"]
<file_sep>/structs.go
package main
type Profile struct {
DisplayName string `json:"display_name"`
Image512 string `json:"image_512"`
}
type ProfileAPIResult struct {
Ok bool `json:"ok"`
Profile Profile `json:"profile"`
}
type Attachment struct {
Title string `json:"title"`
Pretext string `json:"pretext"`
ImageURL string `json:"image_url"`
ThumbURL string `json:"thumb_url"`
Footer string `json:"footer"`
}
type ResponsePayload struct {
Attachments *[]Attachment `json:"attachments"`
Text string `json:"text"`
ResponseType string `json:"response_type"`
}
| 421bc0d2e880c0b3652461275366102656112b39 | [
"Markdown",
"Go",
"Dockerfile"
] | 5 | Markdown | fatanugraha/pepehug-bot | e23fae217773180197f0a3098c211d43f6d64e32 | 16fbf27c3f6df1e15082bc47a580a60eb848bd62 |
refs/heads/master | <repo_name>doowsing/rediuse<file_sep>/result.go
package rediuse
import (
"encoding/json"
"errors"
"fmt"
"github.com/gomodule/redigo/redis"
"reflect"
"strconv"
)
type RdbResultInterface interface {
Interface() (interface{}, error)
This() *RdbResult
}
type RdbHashResultInterface interface {
RdbResultInterface
ScanMapByMergeArgs(interface{}) error
ScanMap(interface{}) error
}
type RdbResult struct {
args []interface{} // 命令参数
data interface{}
err error
}
func NewErrRdbResult(format string, a ...interface{}) *RdbResult {
return &RdbResult{
data: nil,
err: errors.New(fmt.Sprintf(format, a...)),
}
}
func (opt *RdbResult) Error() error {
return opt.err
}
func (opt *RdbResult) Data() interface{} {
return opt.data
}
func (opt *RdbResult) This() *RdbResult {
return opt
}
func (opt *RdbResult) SetResult(data interface{}, err error) {
opt.data = data
opt.err = err
}
func (opt *RdbResult) Bytes() ([]byte, error) {
return redis.Bytes(opt.data, opt.err)
}
func (opt *RdbResult) ByteSlices() ([][]byte, error) {
return redis.ByteSlices(opt.data, opt.err)
}
func (opt *RdbResult) String() (string, error) {
return redis.String(opt.data, opt.err)
}
func (opt *RdbResult) StringSlices() ([]string, error) {
return redis.Strings(opt.data, opt.err)
}
func (opt *RdbResult) Int() (int, error) {
return redis.Int(opt.data, opt.err)
}
func (opt *RdbResult) IntSlices() ([]int, error) {
return redis.Ints(opt.data, opt.err)
}
func (opt *RdbResult) Float64() (float64, error) {
return redis.Float64(opt.data, opt.err)
}
func (opt *RdbResult) Float64Slices() ([]float64, error) {
return redis.Float64s(opt.data, opt.err)
}
func (opt *RdbResult) Bool() (bool, error) {
return redis.Bool(opt.data, opt.err)
}
func (opt *RdbResult) IntMap() (map[string]int, error) {
return redis.IntMap(opt.data, opt.err)
}
func (opt *RdbResult) StringMap() (map[string]string, error) {
return redis.StringMap(opt.data, opt.err)
}
func (opt *RdbResult) Interface() (interface{}, error) {
return opt.data, opt.err
}
func (opt *RdbResult) Values() ([]interface{}, error) {
return redis.Values(opt.data, opt.err)
}
func (opt *RdbResult) Struct(s interface{}) error {
bytes, err := opt.Bytes()
if err != nil {
return err
}
err = json.Unmarshal(bytes, s)
if err != nil {
return err
}
return nil
}
var errScanMapValue = errors.New("rediuse.ScanMap: value must be non-nil pointer to a map")
// 将 hgetall 的结果转化为 map[T]T
func (opt *RdbResult) ScanMap(s interface{}) error {
src, err := opt.Values()
if err != nil {
return err
}
return opt.scanMap(s, src)
}
// 将 hmget 的结果转化为 map[T]T
func (opt *RdbResult) ScanMapByMergeArgs(s interface{}) error {
src, err := opt.Values()
if err != nil {
return err
}
newSrc := make([]interface{}, len(src)*2)
for i := 0; i < len(src); i++ {
newSrc[2*i] = opt.args[i+1]
newSrc[2*i+1] = src[i]
}
return opt.scanMap(s, newSrc)
}
func (opt *RdbResult) scanMap(s interface{}, src []interface{}) error {
var err error
defer func() {
_err := recover()
if _err != nil {
fmt.Printf("scanMap error:%s\n", _err)
}
}()
d := reflect.ValueOf(s)
if d.Kind() != reflect.Ptr || d.IsNil() {
return errScanMapValue
}
d = d.Elem()
if d.Kind() != reflect.Map {
return errScanMapValue
}
t := d.Type()
if len(src)%2 != 0 {
return errors.New("rediuse.ScanMap: number of mgethash'result not a multiple of 2")
}
// key处理函数,map.key的类型固定,因此循环中的处理过程都是确定的,这里应该写成多个命名函数的,但是偷懒了一点
var ktHandle func(key string, kv *reflect.Value) error
kt := t.Key()
switch {
case kt.Kind() == reflect.String:
ktHandle = func(key string, kv *reflect.Value) error {
*kv = reflect.ValueOf(key).Convert(kt)
return nil
}
default:
switch kt.Kind() {
case reflect.Float32, reflect.Float64:
ktHandle = func(key string, kv *reflect.Value) error {
s := string(key)
n, err := strconv.ParseFloat(s, 64)
if err != nil || reflect.Zero(kt).OverflowFloat(n) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return errors.New("number " + s + " convert failed. Unmarshal Type(float) err:" + errMsg)
}
*kv = reflect.ValueOf(n).Convert(kt)
return nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
ktHandle = func(key string, kv *reflect.Value) error {
s := string(key)
n, err := strconv.ParseInt(s, 10, 64)
if err != nil || reflect.Zero(kt).OverflowInt(n) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return errors.New("number " + s + " convert failed. Unmarshal Type(int) err:" + errMsg)
}
*kv = reflect.ValueOf(n).Convert(kt)
return nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
ktHandle = func(key string, kv *reflect.Value) error {
s := string(key)
n, err := strconv.ParseUint(s, 10, 64)
if err != nil || reflect.Zero(kt).OverflowUint(n) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return errors.New("number " + s + " convert failed. Unmarshal Type(uint) err:" + errMsg)
}
*kv = reflect.ValueOf(n).Convert(kt)
return nil
}
default:
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return fmt.Errorf("convert failed. Unmarshal Type(%t) err:"+errMsg, kt.Kind())
}
}
// value处理函数,map.value的类型固定,因此循环中的处理过程都是确定的,这里应该写成多个命名函数的,但是偷懒了一点
var vtHandle func(data []byte, vv *reflect.Value) error
elemType := t.Elem()
switch elemTypekind := elemType.Kind(); elemTypekind {
case reflect.Ptr, reflect.Struct, reflect.Slice, reflect.Map:
elemTypekind = elemType.Elem().Kind()
switch elemTypekind {
case reflect.Struct, reflect.Slice, reflect.Map:
vtHandle = func(data []byte, elemv *reflect.Value) error {
err = json.Unmarshal(data, (*elemv).Interface())
return err
}
break
default:
return fmt.Errorf("can't handle type:%s\n", elemType.Kind())
}
case reflect.String:
vtHandle = func(key []byte, kv *reflect.Value) error {
(*kv).Set(reflect.ValueOf(key).Convert(elemType))
return nil
}
case reflect.Float32, reflect.Float64:
vtHandle = func(key []byte, kv *reflect.Value) error {
s := string(key)
n, err := strconv.ParseFloat(s, 64)
if err != nil || reflect.Zero(elemType).OverflowFloat(n) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return errors.New("number " + s + " convert failed. Unmarshal Type(float) err:" + errMsg)
}
(*kv).Set(reflect.ValueOf(n).Convert(elemType))
return nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
vtHandle = func(key []byte, kv *reflect.Value) error {
s := string(key)
n, err := strconv.ParseInt(s, 10, 64)
//fmt.Printf("scan map[int]int value s:%s, v:%d\n", s, n)
if err != nil || reflect.Zero(elemType).OverflowInt(n) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return errors.New("number " + s + " convert failed. Unmarshal Type(int) err:" + errMsg)
}
(*kv).Set(reflect.ValueOf(n).Convert(elemType))
//*kv = reflect.ValueOf(n).Convert(elemType)
return nil
}
case reflect.Bool:
vtHandle = func(key []byte, kv *reflect.Value) error {
s := string(key)
n, err := strconv.ParseInt(s, 10, 64)
if err != nil || reflect.Zero(elemType).OverflowInt(n) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return errors.New("number " + s + " convert failed. Unmarshal Type(bool) err:" + errMsg)
}
boolV := false
if n > 0 {
boolV = true
}
(*kv).Set(reflect.ValueOf(boolV).Convert(elemType))
return nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
vtHandle = func(key []byte, kv *reflect.Value) error {
s := string(key)
n, err := strconv.ParseUint(s, 10, 64)
if err != nil || reflect.Zero(elemType).OverflowUint(n) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
return errors.New("number " + s + " convert failed. Unmarshal Type(uint) err:" + errMsg)
}
(*kv).Set(reflect.ValueOf(n).Convert(elemType))
return nil
}
default:
return fmt.Errorf("can't handle type:%s\n", elemType.Kind())
}
for i := 0; i < len(src); i += 2 {
// 处理key
name, ok := src[i].([]byte)
if !ok {
name = []byte(getString(src[i]))
//return fmt.Errorf("rediuse.ScanMap: key %d not a bulk string value", i)
}
key := name
// 代码片段取自 /encoding/json/decode.go:661 func (d *decodeState) object(v reflect.Value) error
var kv reflect.Value
err = ktHandle(string(key), &kv)
if err != nil {
return err
}
// 处理value
valueData, ok := src[i+1].([]byte)
if !ok {
if src[i+1] == nil || reflect.ValueOf(src[i+1]).IsNil() {
continue
}
return fmt.Errorf("rediuse.ScanStruct: key %d not a bulk string value", i)
}
data := valueData
var subv reflect.Value
if !subv.IsValid() {
subv = reflect.New(elemType).Elem()
} else {
subv.Set(reflect.Zero(elemType))
}
if err = vtHandle(data, &subv); err != nil {
return err
}
if kv.IsValid() {
d.SetMapIndex(kv, subv)
}
}
return nil
}
<file_sep>/README.md
# rediuse
简化对redigo包的操作,将redigo包操作后的结果进行封装,以便更加方便的获取想要的数据格式。
可转换的数据格式包括:int,bool,float64,string,[]byte,以及各种常用类型的slice,结构体。
对传入的结构体、切片、字典会自动做进行json编码。
可使用单机与集群,详情见example文件夹。
## Example
```go
package main
import (
"fmt"
"github.com/gomodule/redigo/redis"
"github.com/doowsing/rediuse"
"time"
)
// redis 连接池
var pool *redis.Pool
//根据配置初始化打开redis连接
func init() {
pool = &redis.Pool{
MaxIdle: 20,
MaxActive: 30,
IdleTimeout: 60 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
return nil, err
}
//TODO 不加有时候池子链接失败
// 线上环境redis配置密码, 则需要加上这句AUTH
//_,err = c.Do("AUTH","<EMAIL>")
return c, err
},
//testOnBorrow 向资源池借用连接时是否做连接有效性检测(ping),无效连接会被移除 默认值 false 业务量很大时候建议设置为false(多一次ping的开销)。
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
}
fmt.Printf("redis start on 6379\n")
}
func GetRedisPool() *redis.Pool {
return pool
}
// 获取redis全局实例
func GetR() redis.Conn {
return pool.Get()
}
var rdbHandler = rediuse.NewRdbHandler(GetR)
type User struct {
Id int
Name string
}
func main() {
rdbHandler.Set("id", 1)
id, err := rdbHandler.Get("id").Int()
if err != nil {
log.Printf("get id err:%s\n", err)
}
idFlag, err := rdbHandler.Hget("flag", id).Bool()
if err != nil {
log.Printf("idFlag 1 is %s!", idFlag)
}
user := &User{
Id: 1,
Name: "张三",
}
rdbHandler.Set("user", user)
user1 := &User{}
err = rdbHandler.Get("user").Struct(user1)
log.Printf("user name:%s\n", user1.Name)
}
```
使用获得redis.Conn的函数进行初始化。
[redis单机连接库](https://github.com/gomodule/redigo/redis)
[redis集群连接库](https://github.com/mna/redisc)
两个库的接口是一样的,便于开发和线上切换
目前加入的redis使用函数有限,可自行添加<file_sep>/example/single/main.go
package main
import (
"github.com/doowsing/rediuse"
"log"
)
var rdbHandler = rediuse.NewRdbHandler(GetR)
type User struct {
Id int
Name string
}
func main() {
rdbHandler.Set("id", 1)
id, err := rdbHandler.Get("id").Int()
if err != nil {
log.Printf("get id err:%s\n", err)
}
idFlag, err := rdbHandler.Hget("flag", id).Bool()
if err != nil {
log.Printf("idFlag 1 is %s!", idFlag)
}
user := &User{
Id: 1,
Name: "张三",
}
rdbHandler.Set("user", user)
user1 := &User{}
err = rdbHandler.Get("user").Struct(user1)
log.Printf("user name:%s\n", user1.Name)
}
<file_sep>/go.mod
module github.com/doowsing/rediuse
go 1.13
require (
github.com/gomodule/redigo v2.0.0+incompatible
github.com/mna/redisc v1.1.7
github.com/stretchr/testify v1.5.1 // indirect
github.com/unknwon/com v1.0.1
)
<file_sep>/handler.go
package rediuse
import (
"encoding/json"
"fmt"
"github.com/gomodule/redigo/redis"
"github.com/unknwon/com"
"reflect"
"strconv"
)
type RdbHandler struct {
getConn func() redis.Conn
}
func NewRdbHandler(getConn func() redis.Conn) *RdbHandler {
return &RdbHandler{getConn: getConn}
}
func (handler *RdbHandler) DoCommand(commandName string, args ...interface{}) *RdbResult {
conn := handler.getConn()
defer conn.Close()
result := &RdbResult{}
result.args = args
result.SetResult(conn.Do(commandName, args...))
return result
}
func (handler *RdbHandler) Get(key string) *RdbResult {
return handler.DoCommand("GET", key)
}
func (handler *RdbHandler) Set(key string, value interface{}) *RdbResult {
value, err := marshal(value)
if err != nil {
return &RdbResult{err: err}
}
return handler.DoCommand("SET", key, value)
}
func (handler *RdbHandler) SetEx(key string, value interface{}, second int) *RdbResult {
value, err := marshal(value)
if err != nil {
return &RdbResult{err: err}
}
return handler.DoCommand("SET", key, value, "EX", second)
}
func (handler *RdbHandler) Expire(key string, second int) *RdbResult {
return handler.DoCommand("EXPIRE", key, second)
}
func (handler *RdbHandler) Exists(key string) *RdbResult {
return handler.DoCommand("Exists", key)
}
func (handler *RdbHandler) Delete(key string) *RdbResult {
return handler.DoCommand("DEL", key)
}
func (handler *RdbHandler) Hget(key string, field interface{}) *RdbResult {
return handler.DoCommand("HGET", key, getString(field))
}
func (handler *RdbHandler) Hset(key string, field interface{}, value interface{}) *RdbResult {
value, err := marshal(value)
if err != nil {
return &RdbResult{err: err}
}
return handler.DoCommand("HSET", key, getString(field), value)
}
func (handler *RdbHandler) Hdel(key string, field interface{}) *RdbResult {
return handler.DoCommand("HDEL", key, getString(field))
}
func (handler *RdbHandler) Hexist(key string, field interface{}) *RdbResult {
return handler.DoCommand("HEXIST", key, getString(field))
}
func (handler *RdbHandler) HgetAll(key string) RdbHashResultInterface {
return handler.DoCommand("HGETALL", key)
}
func (handler *RdbHandler) Hmget(key string, fields ...interface{}) RdbHashResultInterface {
return handler.DoCommand("HMGET", redis.Args{}.Add(key).AddFlat(fields)...)
}
func (handler *RdbHandler) Hmset(key string, filed2data interface{}) *RdbResult {
// 第一种方法,但是这种方法没有过滤 传参的类型
//args := redis.Args{}.AddFlat(key).AddFlat(filed2data)
// 第二种方法,复制redis.Args{}..AddFlat()方法,并过滤参数类型
rv := reflect.ValueOf(filed2data)
var args = []interface{}{key}
switch rv.Kind() {
case reflect.Slice:
rvLen := rv.Len()
if rvLen%2 == 1 {
rvLen--
}
var isKey = true
for i := 0; i < rvLen; i++ {
if isKey {
args = append(args, rv.Index(i).Interface())
} else {
vJson, err := marshal(rv.Index(i).Interface())
if err != nil {
return NewErrRdbResult("批量序列化失败")
} else {
args = append(args, vJson)
}
}
isKey = !isKey
}
case reflect.Map:
for _, k := range rv.MapKeys() {
vJson, err := marshal(rv.MapIndex(k).Interface())
if err != nil {
return NewErrRdbResult("批量序列化失败")
} else {
args = append(args, getString(k.Interface()), vJson)
}
}
default:
return NewErrRdbResult("非 map or slice,无法写入redis hash队列")
}
// 第三种方法,限定了redis只能传 map[string]interface
//var args = []interface{}{key}
//for i, v := range filed2data {
// vJson, err := marshal(v)
// if err != nil {
// return NewErrRdbResult("批量序列化失败")
// } else {
// args = append(args, i, vJson)
// }
//}
//fmt.Printf("hmset args:%v\n", args)
return handler.DoCommand("HMSET", args...)
}
func (handler *RdbHandler) RPush(key string, field interface{}) *RdbResult {
return handler.DoCommand("RPUSH", key, getString(field))
}
func (handler *RdbHandler) LPush(key string, field interface{}) *RdbResult {
return handler.DoCommand("LPUSH", key, getString(field))
}
func (handler *RdbHandler) LLen(key string) *RdbResult {
return handler.DoCommand("LLEN", key)
}
func (handler *RdbHandler) LRange(key string, start, stop int) *RdbResult {
return handler.DoCommand("LRANGE", key, start, stop)
}
func (handler *RdbHandler) LTrim(key string, start, stop int) *RdbResult {
return handler.DoCommand("LTRIM", key, start, stop)
}
func (handler *RdbHandler) SCARD(key string) *RdbResult {
return handler.DoCommand("SCARD", key)
}
func (handler *RdbHandler) SADD(key string, field interface{}) *RdbResult {
return handler.DoCommand("SADD", key, getString(field))
}
func (handler *RdbHandler) HScan(key string, cursor int, match string, count int) (int, map[string]string, error) {
var args []interface{}
args = append(args, key, cursor)
if match != "" {
args = append(args, "match", match)
}
if count > 0 {
args = append(args, "count", count)
}
result, err := handler.DoCommand("HSCAN", args...).Interface()
mapResult := make(map[string]string)
if err == nil {
_datas := result.([]interface{})
nextCursor := string(_datas[0].([]byte))
datas := _datas[1].([]interface{})
cursor = com.StrTo(nextCursor).MustInt()
//fmt.Println(nextCursor)
for i := 0; i < len(datas)/2; i++ {
mapResult[string(datas[i*2].([]byte))] = mapResult[string(datas[i*2+1].([]byte))]
}
}
return cursor, mapResult, err
}
func (handler *RdbHandler) Scan(cursor int, match string, count int) (int, []string, error) {
var args []interface{}
args = append(args, cursor)
if match != "" {
args = append(args, "match", match)
}
if count > 0 {
args = append(args, "count", count)
}
result, err := handler.DoCommand("SCAN", args...).Interface()
mapResult := []string{}
if err == nil {
_datas := result.([]interface{})
nextCursor := string(_datas[0].([]byte))
datas := _datas[1].([]interface{})
//fmt.Println(nextCursor)
cursor, err = com.StrTo(nextCursor).Int()
if err != nil {
fmt.Printf("返回游标非整数,%s\n", nextCursor)
}
for i := 0; i < len(datas); i++ {
mapResult = append(mapResult, string(datas[i].([]byte)))
}
}
return cursor, mapResult, err
}
func getString(field interface{}) string {
trueField := ""
switch field.(type) {
case int:
trueField = strconv.Itoa(field.(int))
break
case string:
trueField = field.(string)
break
default:
trueField = fmt.Sprintf("%s", field)
}
return trueField
}
func marshal(v interface{}) (interface{}, error) {
switch t := v.(type) {
case string, []byte, int, int64, float64, bool, nil, redis.Argument:
return v, nil
default:
return json.Marshal(t)
}
}
<file_sep>/example/test/main.go
package main
import (
"fmt"
"github.com/doowsing/rediuse"
)
var rdbHandler = rediuse.NewRdbHandler(GetRedisConn)
func hashOperation() {
type Petime struct {
Name string
}
rdbHandler.Delete("test_id_petime")
id2petime := make(map[int]*Petime)
id2petime[1] = &Petime{"mask1"}
id2petime[2] = &Petime{"mask2"}
id2petime[3] = &Petime{"mask3"}
var err error
err = rdbHandler.Hmset("test_id_petime", id2petime).Error()
//getResult := rdbHandler.HgetAll("test_id_id")
//id2petimeget := make(map[int]int)
//err = getResult.ScanMap(&id2petimeget)
//fmt.Printf("id2petimeget:%v\n",id2petimeget)
//fmt.Printf("err:%v\n",err)
id2petimeget := make(map[int]*Petime)
getResult := rdbHandler.HgetAll("test_id_petime")
getResult.This()
err = getResult.ScanMap(&id2petimeget)
_ = err
//fmt.Printf("ifce:%v\n",ifce)
fmt.Printf("id2petime:%s\n", id2petime)
fmt.Printf("id2petimeget:%s\n", id2petimeget)
fmt.Printf("err:%v\n", err)
}
func main() {
hashOperation()
}
<file_sep>/example/exps/hash.go
package exps
func Hget() {
key := "test_hget"
type Petime struct {
Id int
Name string
}
petimes := []Petime{
{1, "M"},
{2, "S"},
}
for _, pt := range petimes {
rdbHandler.Hset(key, pt.Id, pt.Name)
}
}
<file_sep>/example/exps/conn.go
package exps
import (
"github.com/doowsing/rediuse"
"github.com/gomodule/redigo/redis"
"github.com/mna/redisc"
"log"
"time"
)
var cluster *redisc.Cluster
func init() {
cluster = &redisc.Cluster{
StartupNodes: []string{":7000", ":7001", ":7002"},
DialOptions: []redis.DialOption{redis.DialConnectTimeout(5 * time.Second)},
CreatePool: createPool,
}
cluster.Stats()
if err := cluster.Refresh(); err != nil {
log.Fatalf("Refresh failed: %v", err)
}
}
func createPool(addr string, opts ...redis.DialOption) (*redis.Pool, error) {
return &redis.Pool{
MaxIdle: 500,
MaxActive: 1000,
IdleTimeout: time.Minute,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", addr, opts...)
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}, nil
}
func GetRedisCluster() *redisc.Cluster {
return cluster
}
func GetRedisConn() redis.Conn {
return cluster.Get()
}
var rdbHandler = rediuse.NewRdbHandler(GetRedisConn)
<file_sep>/example/test/main_test.go
package main
import "testing"
func BenchmarkHashOperation(b *testing.B) {
type Petime struct {
Name string
}
id2petime := make(map[int]Petime)
var err error
err = rdbHandler.Hmset("test_id_petime1", id2petime).Error()
id2petimeget := make(map[float64]Petime)
getResult := rdbHandler.Hmget("test_id_petime1", 5, 2)
for i := 0; i < b.N; i++ {
//getResult := rdbHandler.HgetAll("test_id_id")
//id2petimeget := make(map[int]int)
//err = getResult.ScanMap(&id2petimeget)
//fmt.Printf("id2petimeget:%v\n",id2petimeget)
//fmt.Printf("err:%v\n",err)
err = getResult.ScanMapByMergeArgs(&id2petimeget)
_ = err
}
}
| e8129db2d3d2765474365f5ce4c8ffcb2c8328b9 | [
"Markdown",
"Go Module",
"Go"
] | 9 | Go | doowsing/rediuse | 8b5085519d15b744dd24feb276e8a1b67a6db946 | 8f74c0c03f53f4e7760b25e2076a77f4197b6f00 |
refs/heads/master | <file_sep># global variables will be assigned here
# can be imported in any module to make life easier.
from userbot.config import Config
LOGGER = Config.PRIVATE_GROUP_BOT_API_ID
BLACKLIST = Config.UB_BLACK_LIST_CHAT
SYNTAX = {}
SUDO_USERS = Config.SUDO_USERS
COUNT_MSG = 0
USERS = {}
COUNT_PM = {}
LASTMSG = {}
CMD_HELP = {}
ISAFK = False
AFKREASON = None
BUILD = "Plus+"
<file_sep>import asyncio
from uniborg.util import admin_cmd
DEL_TIMEOUT = 5
@borg.on(admin_cmd(pattern="gn"))
async def gn(event):
await event.edit("。♥。・゚♡゚・。♥。・。・。・。♥。・\n╱╱╱╱╱╱╱╭╮╱╱╱╭╮╱╭╮╭╮\n╭━┳━┳━┳╯┃╭━┳╋╋━┫╰┫╰╮\n┃╋┃╋┃╋┃╋┃┃┃┃┃┃╋┃┃┃╭┫\n┣╮┣━┻━┻━╯╰┻━┻╋╮┣┻┻━╯\n╰━╯╱╱╱╱╱╱╱╱╱╱╰━╯\n。♥。・゚♡゚・。♥° ♥。・゚♡゚・")
await asyncio.sleep(DEL_TIMEOUT)
await event.delete()
@borg.on(admin_cmd(pattern="gm"))
async def gm(event):
await event.edit("。♥。・゚♡゚・。♥。・。・。・。♥。・。♥。・゚♡゚・\n╱╱╱╱╱╱╱╭╮╱╱╱╱╱╱╱╱╱╱╭╮\n╭━┳━┳━┳╯┃╭━━┳━┳┳┳━┳╋╋━┳┳━╮\n┃╋┃╋┃╋┃╋┃┃┃┃┃╋┃╭┫┃┃┃┃┃┃┃╋┃\n┣╮┣━┻━┻━╯╰┻┻┻━┻╯╰┻━┻┻┻━╋╮┃\n╰━╯╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╰━╯\n。♥。・゚♡゚・。♥。・。・。・。♥。・。♥。・゚♡゚・")
await asyncio.sleep(DEL_TIMEOUT)
await event.delete()
@borg.on(admin_cmd(pattern="like"))
async def like(event):
await event.edit("👍🏿👇🏿👇🏿👇🏿👇🏿👇🏿👇🏿👇🏿👇🏿👇🏿👍🏿\n👉🏿👍🏾👇🏾👇🏾👇🏾👇🏾👇🏾👇🏾👇🏾👍🏾👈🏿\n👉🏿👉🏾👍🏽👇🏽👇🏽👇🏽👇🏽👇🏽👍🏽👈🏾👈🏿\n👉🏿👉🏾👉🏽👍🏼👇🏼👇🏼👇🏼👍🏼👈🏽👈🏾👈🏿\n👉🏿👉🏾👉🏽👉🏼👍🏻👇🏻👍🏻👈🏼👈🏽👈🏾👈🏿\n👉🏿👉🏾👉🏽👉🏼👉🏻❤👈🏻👈🏼👈🏽👈🏾👈🏿\n👉🏿👉🏾👉🏽👉🏼👍🏻👆🏻👍🏻👈🏼👈🏽👈🏾👈🏿\n👉🏿👉🏾👉🏽👍🏼👆🏼👆🏼👆🏼👍🏼👈🏽👈🏾👈🏿\n👉🏿👉🏾👍🏽👆🏽👆🏽👆🏽👆🏽👆🏽👍🏽👈🏾👈🏿\n👉🏿👍🏾👆🏾👆🏾👆🏾👆🏾👆🏾👆🏾👆🏾👍🏾👈🏿\n👍🏿👆🏿👆🏿👆🏿👆🏿👆🏿👆🏿👆🏿👆🏿👆🏿👍🏿")
await asyncio.sleep(DEL_TIMEOUT)
await event.delete()
<file_sep>""" Userbot module for having some fun with people. """
from asyncio import sleep
from random import choice, getrandbits, randint
from re import sub
import time
from collections import deque
import requests
from userbot.events import register
@register(pattern=r"^\.scam(?: |$)(.*)", outgoing=True)
async def scam(event):
"""
Just a small command to fake chat actions for fun !!
Available Actions: typing, contact, game, location, voice, round, video, photo, document, cancel
"""
options = [
'typing', 'contact', 'game', 'location', 'voice', 'round', 'video',
'photo', 'document', 'cancel'
]
input_str = event.pattern_match.group(1)
args = input_str.split()
if len(args) == 0: # Let bot decide action and time
scam_action = choice(options)
scam_time = randint(30, 60)
elif len(args) == 1: # User decides time/action, bot decides the other.
try:
scam_action = str(args[0]).lower()
scam_time = randint(30, 60)
except ValueError:
scam_action = choice(options)
scam_time = int(args[0])
elif len(args) == 2: # User decides both action and time
scam_action = str(args[0]).lower()
scam_time = int(args[1])
else:
await event.edit("`Invalid Syntax !!`")
return
try:
if (scam_time > 0):
await event.delete()
async with event.client.action(event.chat_id, scam_action):
await sleep(scam_time)
except BaseException:
return
<file_sep># Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
# Usage:- .picspam <count> <pic link>
import asyncio
from asyncio import wait, sleep
from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP
from userbot.events import register
@register(outgoing=True, pattern="^.picspam")
async def tiny_pic_spam(e):
message = e.text
text = message.split()
counter = int(text[1])
link = str(text[2])
await e.delete()
for i in range(1, counter):
await e.client.send_file(e.chat_id, link)
if BOTLOG:
await e.client.send_message(
BOTLOG_CHATID, "#PICSPAM\n"
"PicSpam was executed successfully")
CMD_HELP.update({
"spam":
".picspam <count> <link to image/gif>\
\nUsage: As if text spam was not enough !!\""
})
<file_sep>"""Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you."""
import asyncio
from telethon import events, version
from telethon.tl.types import ChannelParticipantsAdmins
from platform import python_version, uname
from userbot import ALIVE_NAME
from userbot.utils import admin_cmd
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "No name set yet."
@borg.on(admin_cmd(pattern="alive"))
async def amireallyalive(alive):
""" For .alive command, check if the bot is running. """
await alive.edit(" **MADE IN 🇮🇳 , MADE FOR 🗺️** \n\n"
"`"
f" 🔸 Telethon : {version.__version__} \n 🔹 Python: {python_version()} \n"
"`"
f"` 🔸 Fork by:` {DEFAULTUSER} \n "
"`🔹 Bot creator:` [//•𝙺𝚞𝚖𝚊𝚛•𝙰𝚖𝚒𝚝•//](tg://user?id=667805879)\n"
"` 🔸 Database Status:` **All OK 👌!** \n"
f"` 🔹 My owner:` {DEFAULTUSER} \n"
"` 🔸 Join` @xtratgplus `For Help` \n\n"
" [Deploy✔️](https://dashboard.heroku.com/new?button-url=https%3A%2F%2Fgithub.com%2Famitsharma123234%2FX-tra-TG-plus&template=https%3A%2F%2Fgithub.com%2Famitsharma123234%2FX-tra-TG-plus) \n\n ")
@borg.on(admin_cmd(pattern="sudo", allow_sudo=True))
async def amireallyalive(alive):
""" For .alive command, check if the bot is running. """
await alive.reply(" **MADE IN 🇮🇳 , MADE FOR 🗺️** \n\n"
"`"
f" 🔸 Telethon : {version.__version__} \n 🔹 Python: {python_version()} \n"
"`"
f"` 🔸 Fork by:` {DEFAULTUSER} \n "
"`🔹 Bot creator:` [//•𝙺𝚞𝚖𝚊𝚛•𝙰𝚖𝚒𝚝•//](tg://user?id=667805879)\n"
"` 🔸 Database Status:` **All OK 👌!** \n"
f"` 🔹 My owner:` {DEFAULTUSER} \n"
"` 🔸 Join` @xtratgplus `For Help` \n\n"
" [Deploy✔️](https://dashboard.heroku.com/new?button-url=https%3A%2F%2Fgithub.com%2Famitsharma123234%2FX-tra-TG-plus&template=https%3A%2F%2Fgithub.com%2Famitsharma123234%2FX-tra-TG-plus) \n\n", link_preview=False
)
| 4b99648a785e91ac9029e4ec4c619fbc5e1c70cd | [
"Python"
] | 5 | Python | ItzSjDude/X-tra-TG-plus | 4f64b5fe8e0b012738d9dfcfc9f907c6a10eb34c | e8f4cbebda42d3a35b97feb3c862a67df2c0d8fa |
refs/heads/master | <repo_name>andersk/homeworld<file_sep>/build-kubernernetes/build.sh
#!/bin/bash
set -e -u
cd $(dirname $0)
ROOT=$(pwd)
rm -rf go/
mkdir -p go/src/k8s.io/kubernetes
cd go/src/k8s.io/kubernetes
echo "extracting..."
tar -xf ${ROOT}/kubernetes-src-v1.6.4.tar.xz
echo "extracted!"
export GOPATH=${ROOT}/go
make
cp _output/local/bin/linux/amd64/kubectl ${ROOT}/../binaries/
cd ${ROOT}
./package.sh
echo "built kubernetes binaries!"
<file_sep>/deployment/wrappers/launch-scheduler.sh
#!/bin/bash
set -e -u
# use known apiserver
SRVOPT="--kubeconfig=/etc/hyades/kubeconfig"
SRVOPT="$SRVOPT --leader-elect"
exec /usr/bin/hyperkube kube-scheduler $SRVOPT
<file_sep>/build-flannel/build.sh
#!/bin/bash
set -e -u
cd $(dirname $0)
ROOT=$(pwd)
rm -rf go/
mkdir -p go/src/github.com/coreos/
cd go/src/github.com/coreos/
echo "extracting..."
tar -xf ${ROOT}/flannel-0.7.1.tar.xz flannel-0.7.1/
echo "extracted!"
export GOPATH=${ROOT}/go
mv flannel-0.7.1/ flannel/
cd flannel/
CGO_ENABLED=1 make dist/flanneld
cd ${ROOT}
./package.sh
echo "built flannel binaries!"
<file_sep>/deployment/wrappers/start-master.sh
#!/bin/bash
set -e -u
echo "starting master services..."
systemctl daemon-reload
systemctl start etcd
systemctl enable etcd
systemctl start flannel
systemctl enable flannel
systemctl start rkt-api
systemctl enable rkt-api
systemctl start kubelet
systemctl enable kubelet
systemctl start kube-proxy
systemctl enable kube-proxy
systemctl start apiserver
systemctl enable apiserver
systemctl start kube-ctrlmgr
systemctl enable kube-ctrlmgr
systemctl start kube-scheduler
systemctl enable kube-scheduler
echo "services started and enabled!"
<file_sep>/deployment/build-package.sh
#!/bin/bash
set -e -u
VERSION=0.1.3
# basic structure
FPMOPT="-s dir -t deb"
# name and version
FPMOPT="$FPMOPT -n hyades-services -v ${VERSION} --iteration 1"
# packager
FPMOPT="$FPMOPT --maintainer '<EMAIL>'"
# metadata
# TODO: better metadata
FPMOPT="$FPMOPT --license MIT -a x86_64 --url https://sipb.mit.edu/"
# dependencies
FPMOPT="$FPMOPT -d hyades-rkt -d hyades-etcd -d hyades-flannel -d hyades-hyperkube"
# get binary
FPMOPT="$FPMOPT wrappers/=/usr/lib/hyades/ services/=/usr/lib/systemd/system/"
fpm --vendor 'MIT SIPB Hyades Project' $FPMOPT
cp hyades-services_${VERSION}-1_amd64.deb ../binaries
<file_sep>/deployment/config/compile-config.py
#!/usr/bin/env python3
# takes in setup.conf and certificates.conf in the current directory
# and spits out a folder cluster-config/ with the generated configuration
import os
import sys
setup = "setup.conf"
certificates_in = "certificates.conf"
certificates_out = "certificates.list"
output = "cluster-config/"
cluster_config = "cluster.conf"
if os.path.exists(output):
for file in os.listdir(output):
os.remove(os.path.join(output, file))
else:
os.mkdir(output)
def parse_setup(f):
lines = [line.strip() for line in f if line.strip()]
config = {}
nodes = []
for line in lines:
if line[0] == '#':
continue
elif "=" in line:
k, v = line.split("=")
config[k] = v
elif line[:7] in ("master ", "worker "):
kind, hostname, ip = line.split()
nodes.append((kind == "master", hostname, ip))
else:
raise Exception("Unrecognized line: %s" % line)
return config, nodes
def generate_etcd_info(nodes):
cluster = []
endpoints = []
for is_master, hostname, ip in nodes:
if not is_master: continue
cluster.append("{hostname}=https://{ip}:2380".format(hostname=hostname, ip=ip))
endpoints.append("https://{ip}:2379".format(ip=ip))
return ",".join(cluster), ",".join(endpoints)
with open(setup, "r") as f:
config, nodes = parse_setup(f)
masters = [(hostname, ip) for ismaster, hostname, ip in nodes if ismaster]
workers = [(hostname, ip) for ismaster, hostname, ip in nodes if not ismaster]
config["ETCD_CLUSTER"], config["ETCD_ENDPOINTS"] = generate_etcd_info(nodes)
config["APISERVER_COUNT"] = len(masters)
print("TODO: use more than one apiserver for direct requests")
config["APISERVER"] = "https://{ip}:443".format(ip=masters[0][1])
with open(os.path.join(output, cluster_config), "w") as f:
f.write("# generated from setup.conf automatically by compile-config.py\n")
for kv in sorted(config.items()):
f.write("%s=%s\n" % kv)
for ismaster, hostname, ip in nodes:
with open(os.path.join(output, "node-%s.conf" % hostname), "w") as f:
f.write("""# generated from setup.conf automatically by compile-config.py
HOST_NODE={hostname}
HOST_DNS={hostname}.{DOMAIN}
HOST_IP={ip}
SCHEDULE_WORK={schedule_work}
""".format(hostname=hostname, ip=ip, DOMAIN=config['DOMAIN'],
schedule_work=('false' if ismaster else 'true')))
with open(certificates_in, "r") as fin:
with open(os.path.join(output, certificates_out), "w") as fout:
fout.write("# generated from certificates.conf and setup.conf automatically by compile-config.py\n")
nodelists = {"master": masters, "worker": workers, "all": masters + workers}
for line in fin:
line = line.strip()
if not line or line[0] == '#':
fout.write("\n")
elif line.startswith("authority ") or line.startswith("shared-key "):
fout.write(line + "\n")
else:
fout.write("# " + line + "\n")
components = line.split(" ")
needs_default_names = components[0] == "certificate"
nodes_to_include = nodelists[components[1]] # must be master, worker, all
for hostname, ip in nodes_to_include:
ncomp = components[:]
ncomp[1] = "%s.%s" % (hostname, config["DOMAIN"])
if needs_default_names:
ncomp.append("ip:%s" % ip)
ncomp.append("dns:%s" % hostname)
ncomp.append("dns:%s.%s" % (hostname, config["DOMAIN"]))
fout.write(" ".join(ncomp) + "\n")
with open(os.path.join(output, "spin-up-all.sh"), "w") as f:
f.write("#!/bin/bash\nset -e -u\n")
f.write("# generated from setup.conf automatically by compile-config.py\n")
f.write("cd $(dirname $0)\n")
for ismaster, hostname, ip in nodes:
f.write("./spin-up.sh {host}\n".format(host=hostname))
f.write("echo 'spun up all nodes!'\n")
os.chmod(os.path.join(output, "spin-up-all.sh"), 0o755)
with open(os.path.join(output, "spin-up.sh"), "w") as f:
f.write("#!/bin/bash\nset -e -u\n")
f.write("# generated from setup.conf automatically by compile-config.py\n")
f.write("cd $(dirname $0)\n")
f.write("HOST=$1\n")
f.write('if [ ! -e node-$HOST.conf ]; then echo "could not find node config for $HOST"; exit 1; fi\n')
f.write("echo \"uploading to $HOST...\"\n")
f.write("scp node-$HOST.conf root@$HOST.{domain}:/etc/hyades/local.conf\n".format(domain=config["DOMAIN"]))
f.write("scp cluster.conf root@$HOST.{domain}:/etc/hyades/cluster.conf\n".format(domain=config["DOMAIN"]))
f.write("echo \"uploaded to $HOST!\"\n")
os.chmod(os.path.join(output, "spin-up.sh"), 0o755)
with open(os.path.join(output, "pkg-install-all.sh"), "w") as f:
f.write("#!/bin/bash\nset -e -u\n")
f.write("# generated from setup.conf automatically by compile-config.py\n")
f.write("cd $(dirname $0)\n")
for ismaster, hostname, ip in nodes:
f.write("./pkg-install.sh {host} $*\n".format(host=hostname))
f.write("echo 'deployed to all nodes!'\n")
os.chmod(os.path.join(output, "pkg-install-all.sh"), 0o755)
with open(os.path.join(output, "pkg-install.sh"), "w") as f:
f.write("#!/bin/bash\nset -e -u\n")
f.write("# generated from setup.conf automatically by compile-config.py\n")
f.write("cd $(dirname $0)\n")
f.write("HOST=$1\n")
f.write("shift 1\n")
f.write("echo \"deploying to $HOST...\"\n")
f.write("ssh root@$HOST.{domain} 'rm -rf /root/staging-pkg && mkdir /root/staging-pkg && mkdir -p /usr/lib/hyades/images/'\n".format(domain=config["DOMAIN"]))
f.write("scp $* root@$HOST.{domain}:/root/staging-pkg/\n".format(domain=config["DOMAIN"]))
f.write("ssh root@$HOST.{domain} 'if [ -e /root/staging-pkg/*.deb ]; then dpkg -i /root/staging-pkg/*.deb; fi'\n".format(domain=config["DOMAIN"]))
f.write("ssh root@$HOST.{domain} 'if [ -e /root/staging-pkg/*.aci ]; then cp -f /root/staging-pkg/*.aci /usr/lib/hyades/images/; fi'\n".format(domain=config["DOMAIN"]))
f.write("ssh root@$HOST.{domain} 'rm -rf /root/staging-pkg'\n".format(domain=config["DOMAIN"]))
f.write("echo \"deployed to $HOST!\"\n")
f.write("echo 'TODO: START SYSTEMD SERVICES'\n")
os.chmod(os.path.join(output, "pkg-install.sh"), 0o755)
print("Generated!")
<file_sep>/auth/build.sh
#!/bin/bash
set -e
cd $(dirname $0)
rm -rf goroot
mkdir goroot
(cd goroot && tar -xf ../golang-x-crypto-5ef0053f77724838734b6945dd364d3847e5de1d.tar.xz src)
GOPATH=$(pwd)/goroot go build hyauth.go
./package.sh
echo "Build complete!"
<file_sep>/deploy.md
# How to deploy a Homeworld cluster
## Building Software
* Install go, acbuild, and ruby. See trust.txt for signatures.
* Install fpm from the gems in build-rkt.
* Build hyauth, etcd, and flannel with the ./build.sh scripts.
* Make sure you have these installed:
git build-essential zlib1g-dev libxml2 libxml2-dev libreadline-dev
libssl-dev zlibc automake squashfs-tools libacl1-dev libsystemd-dev
libcap-dev libglib2.0-dev libpcre3-dev libpcrecpp0 libpixman-1-dev
pkg-config realpath flex bison
* For rkt, run ./build.sh.
You may need to tweak the removal of stage1/usr_from_kvm/kernel/patches/0002-for-debian-gcc.patch if you get '-no-pie' problems.
* For kubernetes, run ./build.sh
You may need to allocate additional memory to your build environment.
* ./build-package.sh on deployment
## Set up the authentication server
* Request a keytab from accounts@, if necessary.
* Provision yourself a Debian Stretch machine. Choose SSH Server.
* Establish SSH access somehow (i.e. ssh keys)
* Generate ssh user CA locally; save it somewhere safe.
* Rotate the keytab locally (k5srvutil -f <keytab> change); save it somewhere safe.
* Run auth/deploy.sh on <host> <keytab> auth-login <user-ca>
* Run req-cert and see if it works.
TODO: improve cryptographic strength of keytab (see note on sipb page)
## Initial server setup
* Provision yourself new Debian Stretch machines. Choose SSH Server only.
* Launch an admission server from a trusted machine. Copy up the relevant files.
* Admit the server according to the instructions. Verify all hashes carefully.
* Make sure to add the CA key for the server into your known_hosts.
@cert-authority eggs-benedict.mit.edu,huevos-rancheros.mit.edu,[...] ssh-rsa ...
* Confirm that you can ssh into the server as root.
## Configuration and SSL setup and package installation
* Install openssl, curl, and ca-certificates on each server
* Modify config/setup.conf
* Run ./compile-config.py
* Run ./compile-certificates cluster-config/certificates.list <secrets-directory>
* Run authority-gen.sh
* Run authority-upload.sh
* Run private-gen.sh
* Run shared-gen.sh
* Run shared-upload.sh
* Run certificate-gen-csrs.sh
* Run certificate-sign-csrs.sh
* Run certificate-upload-certs.sh
* Run spin-up-all.sh
* Run pkg-install-all.sh on the latest packages and etcd-current-linux-amd64.aci
DO NOT INCLUDE hyades-authserver IN THIS INSTALLATION!
## Starting everything
* Manually start etcd on each master node
* Run init-flannel.sh on one master node
* Run start-master.sh on all master nodes
* Run start-worker.sh on all worker nodes
* Run kubectl and make sure things work (you may need to generate certs for this)
## Core cluster services
* kubectl create -f dns-addon.yml
<file_sep>/build-etcd/build.sh
#!/bin/bash
set -e -u
VERSION=3.1.7
cd $(dirname $0)
HYBIN=$(pwd)/../binaries/
mkdir -p ${HYBIN}
tar -xf etcd-${VERSION}.tar.xz etcd-${VERSION}/
cd etcd-${VERSION}
./build
../build-aci ${VERSION}
cp bin/etcdctl ${HYBIN}/
cp bin/etcd-${VERSION}-linux-amd64.aci ${HYBIN}/
rm -f ${HYBIN}/etcd-current-linux-amd64.aci
ln -s etcd-${VERSION}-linux-amd64.aci ${HYBIN}/etcd-current-linux-amd64.aci
FPMOPT="-s dir -t deb"
FPMOPT="$FPMOPT -n hyades-etcd -v ${VERSION} --iteration 1"
FPMOPT="$FPMOPT --maintainer '<EMAIL>'"
FPMOPT="$FPMOPT --license APLv2 -a x86_64 --url https://github.com/coreos/etcd/"
FPMOPT="$FPMOPT ${HYBIN}/etcd-${VERSION}-linux-amd64.aci=/usr/lib/hyades/ ${HYBIN}/etcd-current-linux-amd64.aci=/usr/lib/hyades/ ${HYBIN}/etcdctl=/usr/bin/etcdctl"
fpm --vendor 'MIT SIPB Hyades Project' $FPMOPT
cp hyades-etcd_${VERSION}-1_amd64.deb ${HYBIN}/
echo "etcd built!"
<file_sep>/deployment/wrappers/init-flannel.sh
#!/bin/bash
set -e -u
source /etc/hyades/cluster.conf
AUTHOPT="--ca-file /etc/hyades/certs/kube/etcd-ca.pem --cert-file /etc/hyades/certs/kube/etcd-cert.pem --key-file /etc/hyades/certs/kube/local-key.pem"
export ETCDCTL_API=2
/usr/bin/etcdctl --endpoints ${ETCD_ENDPOINTS} ${AUTHOPT} set /coreos.com/network/config "{ \"network\": \"${CLUSTER_CIDR}\" }"
<file_sep>/pull-upstream.sh
#!/bin/bash
set -e -u
# git clone <EMAIL>:sipb/homeworld-upstream.git
if [ -e "upstream" ]
then
(cd upstream && git pull)
else
git clone https://github.com/sipb/homeworld-upstream.git upstream
fi
cd upstream
sha512sum --check ../SHA512SUM.UPSTREAM || (echo "CHECKSUM MISMATCH" && false)
<file_sep>/admission/setup.sh
#!/bin/bash
set -e -u
SSH_DIR=/etc/ssh/
cat >server-tmp.cert <<EOCERTIFICATE_HERE
{{SERVER CERTIFICATE}}
EOCERTIFICATE_HERE
for type in ecdsa ed25519 rsa
do
pub=${SSH_DIR}/ssh_host_${type}_key.pub
certtemp=${SSH_DIR}/ssh_host_${type}_cert.tmp
cert=${SSH_DIR}/ssh_host_${type}_cert
echo "===================== VERIFY WITH ====================="
sha256sum ${pub} | cut -d " " -f 1
echo "===================== VERIFY WITH ====================="
rm -f -- ${certtemp}
wget -nv --tries=1 --ca-certificate=server-tmp.cert "https://{{SERVER IP}}/sign/$(cat ${pub})" -O ${certtemp}
mv -- ${certtemp} ${cert}
done
echo "Installing static details..."
rm -f ${SSH_DIR}/ssh_user_ca.pub.tmp
cat >${SSH_DIR}/ssh_user_ca.pub.tmp <<EOSSH_USER_CA_HERE
{{SSH CA}}
EOSSH_USER_CA_HERE
mv ${SSH_DIR}/ssh_user_ca.pub.tmp ${SSH_DIR}/ssh_user_ca.pub
rm -f ${SSH_DIR}/sshd_config.tmp
cat >${SSH_DIR}/sshd_config.tmp <<EOSSHD_CONFIG_HERE
{{SSHD CONFIG}}
EOSSHD_CONFIG_HERE
mv ${SSH_DIR}/sshd_config.tmp ${SSH_DIR}/sshd_config
wget -nv --tries=1 --ca-certificate=server-tmp.cert "https://{{SERVER IP}}/finish" -O /dev/null
rm -f server-tmp.cert $0
systemctl restart ssh
echo "Done!"
<file_sep>/build-rkt/build.sh
#!/bin/bash
set -e -u
cd $(dirname $0)
rm -rf rkt-1.27.0/
tar -xf rkt-1.27.0.tar.xz rkt-1.27.0/
patch -p0 <rkt.patch
if gcc --version | grep -q 'Debian 4.9'
then
rm rkt-1.27.0/stage1/usr_from_kvm/kernel/patches/0002-for-debian-gcc.patch
fi
sha512sum --check <<EOF
85adf3715cba4a457efea8359ebed34413ac63ee58fe920c5713501dec1e727e167416e9d67a9e2d9430aa9f3a53ad0ac26a4f749984bc5a3f3c37ac504f75de linux-4.9.2.tar.xz
10e3fcd515b746be2af55636a6dd9334706cc21ab2bb8b2ba38fe342ca51b072890fd1ae2cd8777006036b0a08122a621769cb5903ab16cfbdcc47c9444aa208 qemu-2.8.1.1.tar.xz
EOF
cp coreos_restructured.cpio.gz rkt-1.27.0/coreos_production_pxe_image.cpio.gz
mkdir -p rkt-1.27.0/build-rkt-1.27.0/tmp/usr_from_kvm/kernel/
cp linux-4.9.2.tar.xz rkt-1.27.0/build-rkt-1.27.0/tmp/usr_from_kvm/kernel/linux-4.9.2.tar.xz
mkdir -p rkt-1.27.0/build-rkt-1.27.0/tmp/usr_from_kvm/qemu/
cp qemu-2.8.1.1.tar.xz rkt-1.27.0/build-rkt-1.27.0/tmp/usr_from_kvm/qemu/qemu-2.8.1.1.tar.xz
cd rkt-1.27.0/
./autogen.sh
./configure \
--disable-tpm --prefix=/usr \
--with-stage1-flavors=coreos,kvm \
--with-stage1-default-flavor=kvm \
--with-coreos-local-pxe-image-path=coreos_production_pxe_image.cpio.gz \
--with-coreos-local-pxe-image-systemd-version=v231 \
--with-stage1-default-images-directory=/usr/lib/rkt/stage1-images \
--with-stage1-default-location=/usr/lib/rkt/stage1-images/stage1-kvm.aci
# make manpages
# make bash-completion
make -j4
cd ..
BUILDDIR=rkt-1.27.0/build-rkt-1.27.0/
BUILDDIR=${BUILDDIR} ./build-pkgs.sh 1.27.0
cp ${BUILDDIR}/target/bin/hyades-rkt_1.27.0-1_amd64.deb ../binaries/
<file_sep>/deployment/wrappers/launch-etcd.sh
#!/bin/bash
set -e -u
source /etc/hyades/cluster.conf
source /etc/hyades/local.conf
TLS_MOUNTPOINT=/etc/hyades/certs/etcd/
TLS_STORAGE=/etc/hyades/certs/etcd/
PERSISTENT_DATA=/var/lib/etcd
ETCD_IMAGE=/usr/lib/hyades/images/etcd-current-linux-amd64.aci
mkdir -p ${PERSISTENT_DATA}
# our image is stored on disk -- better hope that's safe!
HOSTOPT="--insecure-options=image"
# provide data directory for etcd to store persistent data
HOSTOPT="$HOSTOPT --volume data-dir,kind=host,source=${PERSISTENT_DATA}"
# provide directory for etcd TLS certificates
HOSTOPT="$HOSTOPT --volume etcd-certs,kind=host,readOnly=true,source=${TLS_STORAGE} --mount volume=etcd-certs,target=${TLS_MOUNTPOINT}"
# bind ports to public interface
HOSTOPT="$HOSTOPT --port=client:2379 --port=peer:2380"
# etcd node name
ETCDOPT="--name=${HOST_NODE}"
# public advertisement URLs
ETCDOPT="$ETCDOPT --advertise-client-urls=https://${HOST_IP}:2379 --initial-advertise-peer-urls=https://${HOST_IP}:2380"
# listening URLs
ETCDOPT="$ETCDOPT --listen-client-urls=https://0.0.0.0:2379 --listen-peer-urls=https://0.0.0.0:2380"
# initial cluster setup
ETCDOPT="$ETCDOPT --initial-cluster=${ETCD_CLUSTER} --initial-cluster-token=${ETCD_TOKEN} --initial-cluster-state=new"
# client-to-server TLS certs
ETCDOPT="$ETCDOPT --cert-file=${TLS_MOUNTPOINT}/etcd-self.pem --key-file=${TLS_MOUNTPOINT}/etcd-self-key.pem --client-cert-auth --trusted-ca-file=${TLS_MOUNTPOINT}/etcd-ca-client.pem"
# server-to-server TLS certs
ETCDOPT="$ETCDOPT --peer-cert-file=${TLS_MOUNTPOINT}/etcd-self.pem --peer-key-file=${TLS_MOUNTPOINT}/etcd-self-key.pem --peer-client-cert-auth --peer-trusted-ca-file=${TLS_MOUNTPOINT}/etcd-ca.pem"
exec rkt run $HOSTOPT ${ETCD_IMAGE} -- $ETCDOPT
<file_sep>/admin/ectl
#!/bin/bash
exec etcdctl --endpoints "$(cat ~/.etcd/etcd.conf)" --ca-file ~/.etcd/ca.pem --key-file ~/.etcd/etcli-key.pem --cert-file ~/.etcd/etcli.pem $*
<file_sep>/admission/admit.py
#!/usr/bin/env python3
import sys
import tempfile
import threading
import subprocess
import os
import socket
import hashlib
import base64
import http.server
import ssl
if len(sys.argv) < 5:
print("Usage: admit.sh <hostname> <host_ca-key> <user_ca-pubkey> <sshd_config>", file=sys.stderr)
sys.exit(1)
hostname, host_ca, user_ca, sshd_config = sys.argv[1:5]
assert not host_ca.endswith(".pub")
assert user_ca.endswith(".pub")
assert os.path.basename(sshd_config) == "sshd_config"
if not os.path.exists(host_ca):
print("Host certificate authority does not exist.", file=sys.stderr)
sys.exit(1)
if not os.path.exists(user_ca):
print("User certificate authority does not exist.", file=sys.stderr)
sys.exit(1)
if not os.path.exists(sshd_config):
print("sshd configuration does not exist.", file=sys.stderr)
sys.exit(1)
with open(os.path.join(os.path.dirname(__file__), "setup.sh"), "rb") as f:
setup_script = f.read()
def get_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.8', 1)) # doesn't actually send anything
return s.getsockname()[0]
finally:
s.close()
local_ip = get_local_ip()
secure_token = base64.b64encode(os.urandom(10)).rstrip(b"=")
def stop_soon(server):
print("will stop")
threading.Timer(0.1, lambda: (server.shutdown(), print("perform stop"))).start()
class InitialRequestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.client_address[0] != socket.gethostbyname(hostname):
print("Got connection from wrong client", self.client_address)
self.send_error(403)
return
if self.path == "/setup":
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.send_header("Content-length", len(setup_script))
self.send_header("Last-Modified", self.date_time_string())
self.end_headers()
self.wfile.write(setup_script)
stop_soon(self.server)
else:
self.send_error(404)
class SecondaryRequestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.client_address[0] != socket.gethostbyname(hostname):
print("Got connection from wrong client", self.client_address)
self.send_error(403)
return
if self.path.startswith("/sign/"):
pubkey_to_sign = self.path[len("/sign/"):].replace("%20"," ").encode() + b"\n"
print("======================= VERIFY ========================")
print(hashlib.sha256(pubkey_to_sign).hexdigest())
print("======================= VERIFY ========================")
if input("Correct? (y/n) ").strip()[:1].lower() == "y":
with tempfile.NamedTemporaryFile(suffix=".pub") as pubkey:
pubkey.write(pubkey_to_sign)
pubkey.flush()
subprocess.check_call(["ssh-keygen", "-s", host_ca, "-h", "-I", "hyades_host_" + hostname, "-Z", hostname, "-V", "-1w:+30w", pubkey.name])
# TODO: more secure tempfile handling
certname = pubkey.name[:-4] + "-cert.pub"
try:
with open(certname, "rb") as cert:
certdata = cert.read()
finally:
os.remove(certname)
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.send_header("Content-length", len(certdata))
self.send_header("Last-Modified", self.date_time_string())
self.end_headers()
self.wfile.write(certdata)
else:
self.send_error(403)
elif self.path == "/finish":
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.send_header("Content-length", len("stopping...\n"))
self.send_header("Last-Modified", self.date_time_string())
self.end_headers()
self.wfile.write(b"stopping...\n")
stop_soon(self.server)
else:
self.send_error(404)
PORT=20557
with tempfile.NamedTemporaryFile() as privatekey:
with tempfile.NamedTemporaryFile() as certificate:
subprocess.check_call(["openssl", "genrsa", "-out", privatekey.name, "2048"])
subprocess.check_call(["openssl", "req", "-new", "-x509", "-key", privatekey.name, "-out", certificate.name, "-days", "1", "-subj", "/CN=" + local_ip])
setup_script = setup_script.replace(b"{{SERVER CERTIFICATE}}", certificate.read())
setup_script = setup_script.replace(b"{{SERVER IP}}", ("%s:%d" % (local_ip, PORT)).encode())
with open(user_ca, "rb") as f:
setup_script = setup_script.replace(b"{{SSH CA}}", f.read())
with open(sshd_config, "rb") as f:
setup_script = setup_script.replace(b"{{SSHD CONFIG}}", f.read())
assert setup_script.count(b"_HERE") == 6 # avoid confusion of terminators
setup_hash = hashlib.sha256(setup_script).hexdigest()
print("Run on the target system:")
print(" $ wget {ip}:{port}/setup".format(ip=local_ip, port=PORT))
print(" $ sha256sum setup")
print(" {hash} setup".format(hash=setup_hash))
print(" $ # after verifying hash")
print(" $ bash setup")
print(" # and compare the output to our output ...")
# first, without SSL, to let them download /setup
httpd = http.server.HTTPServer(('', PORT), InitialRequestHandler)
httpd.serve_forever(poll_interval=0.1)
httpd.server_close()
print("/setup downloaded; moving to phase two")
# then again, with SSL, to receive the request from the script
httpd = http.server.HTTPServer(('', PORT), SecondaryRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=certificate.name, keyfile=privatekey.name, server_side=True, ciphers="TLSv1.2")
httpd.serve_forever(poll_interval=0.1)
httpd.server_close()
<file_sep>/auth/deploy.sh
#!/bin/bash
if [ "$1" = "" -o "$2" = "" -o "$3" = "" -o "$4" = "" ]
then
echo "Usage: $0 <host> <keytab> <acl> <ca> [package]" 1>&2
echo " NOTE: The keytab is not automatically rotated!" 1>&2
exit 1
fi
set -e -u
HOST=$1
KEYTAB=$2
ACL=$3
CA=$4
PACKAGE=${5:-$(dirname $0)/hyades-authserver_0.1.4-1_amd64.deb}
if [ ! -e $KEYTAB ]
then
echo "Could not find keytab." 1>&2
exit 1
fi
if [ ! -e $ACL ]
then
echo "Could not find acl." 1>&2
exit 1
fi
if [ ! -e $CA -o ! -e $CA.pub ]
then
echo "Could not find ca and ca.pub." 1>&2
exit 1
fi
if [ ! -e $PACKAGE ]
then
echo "Could not find package." 1>&2
exit 1
fi
if ssh root@${HOST} test ! -e /etc/krb5.keytab
then
echo "Uploading keytab..."
scp $KEYTAB root@${HOST}:/etc/krb5.keytab
else
echo "Keytab already exists -- skipping."
fi
scp ${PACKAGE} root@${HOST}:/root/hyauth-pkg-install.deb
scp ${ACL} root@${HOST}:/root/.k5login
ssh root@${HOST} 'apt-get install krb5-user && dpkg -i /root/hyauth-pkg-install.deb && rm /root/hyauth-pkg-install.deb'
scp ${ACL} root@${HOST}:/home/kauth/.k5login
scp ${CA} root@${HOST}:/home/kauth/ca_key
scp ${CA}.pub root@${HOST}:/home/kauth/ca_key.pub
ssh root@${HOST} chown kauth /home/kauth/ca_key
ssh root@${HOST} systemctl restart ssh
echo "Finished!"
<file_sep>/build-kubernernetes/package.sh
#!/bin/bash
set -e -u
# basic structure
FPMOPT="-s dir -t deb"
# name and version
FPMOPT="$FPMOPT -n hyades-hyperkube -v 1.6.4 --iteration 1"
# packager
FPMOPT="$FPMOPT --maintainer '<EMAIL>'"
# metadata
FPMOPT="$FPMOPT --license APLv2 -a x86_64 --url https://kubernetes.io/"
# get binary
FPMOPT="$FPMOPT --prefix /usr/bin --chdir go/src/k8s.io/kubernetes/_output/local/bin/linux/amd64/ hyperkube"
rm -f hyades-hyperkube_1.6.4-1_amd64.deb
fpm --vendor 'MIT SIPB Hyades Project' $FPMOPT
cp hyades-hyperkube_1.6.4-1_amd64.deb ../binaries
<file_sep>/build-flannel/package.sh
#!/bin/bash
set -e -u
# basic structure
FPMOPT="-s dir -t deb"
# name and version
FPMOPT="$FPMOPT -n hyades-flannel -v 0.7.1 --iteration 2"
# packager
FPMOPT="$FPMOPT --maintainer '<EMAIL>'"
# metadata
FPMOPT="$FPMOPT --license APLv2 -a x86_64 --url https://github.com/coreos/flannel/"
# get binary
FPMOPT="$FPMOPT go/src/github.com/coreos/flannel/dist/flanneld=/usr/bin/flanneld 10-containernet.conf=/etc/rkt/net.d/10-containernet.conf"
fpm --vendor 'MIT SIPB Hyades Project' $FPMOPT
cp hyades-flannel_0.7.1-2_amd64.deb ../binaries
<file_sep>/auth/package.sh
#!/bin/bash
set -e -u
VERSION=0.1.4
cd $(dirname $0)
HERE=$(pwd)
HYBIN=$(pwd)/../binaries/
mkdir -p ${HYBIN}
FPMOPT="-s dir -t deb"
FPMOPT="$FPMOPT -n hyades-authserver -v ${VERSION} --iteration 1"
FPMOPT="$FPMOPT --maintainer '<EMAIL>'"
FPMOPT="$FPMOPT --license MIT -a x86_64"
FPMOPT="$FPMOPT --depends krb5-user"
FPMOPT="$FPMOPT --after-install auth.postinstall --after-remove auth.postremove --before-install auth.preinstall"
FPMOPT="$FPMOPT hyauth=/usr/bin/hyauth sshd_config=/etc/ssh/sshd_config.hyades-new"
fpm --vendor 'MIT SIPB Hyades Project' $FPMOPT
echo "authserver package built!"
<file_sep>/deployment/wrappers/launch-flannel.sh
#!/bin/bash
set -e -u
source /etc/hyades/cluster.conf
source /etc/hyades/local.conf
# allow verification of etcd certs
FLANOPT="--etcd-cafile /etc/hyades/certs/kube/etcd-ca.pem"
# authenticate to etcd servers
FLANOPT="$FLANOPT --etcd-certfile /etc/hyades/certs/kube/etcd-cert.pem --etcd-keyfile /etc/hyades/certs/kube/local-key.pem"
# endpoints
FLANOPT="$FLANOPT --etcd-endpoints ${ETCD_ENDPOINTS}"
FLANOPT="$FLANOPT --iface ${HOST_IP}" # the IP
FLANOPT="$FLANOPT --ip-masq"
FLANOPT="$FLANOPT --public-ip ${HOST_IP}" # the IP
exec /usr/bin/flanneld $FLANOPT
<file_sep>/build-rkt/restrip-coreos.sh
#!/bin/bash
set -e -u
cd $(dirname $0)
cat $(find rkt-1.27.0/ -name *.manifest | grep amd64) | sort -u >coreos-manifest.txt
zcat coreos_production_pxe_image.cpio.gz | cpio -i --to-stdout usr.squashfs >coreos_squashfs
rm -rf coreos_minimal_dir
unsquashfs -d coreos_minimal_dir -e coreos-manifest.txt coreos_squashfs
rm coreos_squashfs
cd coreos_minimal_dir
mksquashfs ./ ../coreos_resquash -root-owned -noappend
cd ..
rm -rf coreos_minimal_dir
mkdir -p coreos_ncpio/etc
cd coreos_ncpio
mv ../coreos_resquash usr.squashfs
(echo .; echo etc; echo usr.squashfs) | cpio -o | gzip -c >../coreos_restructured.cpio.gz
cd ..
rm -rf coreos_ncpio
rm coreos-manifest.txt
| 4d6bf8a6c24964b6f5f1d59a4e35cec4052fcabf | [
"Markdown",
"Python",
"Shell"
] | 22 | Shell | andersk/homeworld | fad390adaca74e09559e53ede08486e2a0a8c1b7 | 91f05cb901adee6479898a52418ef91429e41a70 |
refs/heads/main | <repo_name>zhongkangjk/beast_python<file_sep>/README.md
# beast_python
兽音译者 python
<file_sep>/兽音译者.py
bd = ['嗷', '呜', '啊', '~']
def str2hex(text: str):
ret = ""
for x in text:
charHexStr = hex(ord(x))[2:]
if len(charHexStr) == 3:
charHexStr = "0" + charHexStr
elif len(charHexStr) == 2:
charHexStr = "00" + charHexStr
ret += charHexStr
return ret
def hex2str(text: str):
ret = ""
for i in range(0, len(text), 4):
unicodeHexStr = text[i:i + 4]
charStr = chr(int(unicodeHexStr, 16))
ret += charStr
return ret
def toBeast(rawStr):
tfArray = list(str2hex(rawStr))
beast = ""
n = 0
for x in tfArray:
k = int(x, 16) + n % 16
if k >= 16:
k -= 16
beast += bd[int(k / 4)] + bd[k % 4]
n += 1
return "~呜嗷" + beast + "啊"
def fromBeast(decoratedBeastStr):
beastStr = decoratedBeastStr[3:-1]
beastCharArr = list(beastStr)
unicodeHexStr = ""
for i in range(0, len(beastCharArr), 2):
pos1 = bd.index(beastCharArr[i])
pos2 = bd.index(beastCharArr[i + 1])
k = ((pos1 * 4) + pos2) - (int(i / 2) % 16)
if k < 0:
k += 16
unicodeHexStr += hex(k)[2:]
return hex2str(unicodeHexStr)
if __name__ == '__main__':
print(toBeast("https://www.baidu.com"))
print(
fromBeast(
"~呜嗷嗷嗷嗷呜啊嗷啊~呜嗷呜呜~呜啊~啊嗷啊呜嗷呜~~~嗷~呜呜呜~~嗷嗷嗷呜啊呜呜啊呜嗷呜呜啊呜嗷呜啊嗷啊呜~嗷啊啊~嗷~呜嗷嗷~啊嗷嗷嗷呜啊呜啊啊呜嗷呜呜~呜~啊啊嗷啊呜嗷呜嗷啊~嗷~呜嗷嗷~呜嗷嗷嗷呜啊嗷呜呜呜嗷呜呜~嗷啊嗷啊嗷啊呜嗷嗷呜嗷~嗷~呜呜嗷嗷~嗷嗷嗷呜啊呜啊嗷呜嗷呜呜啊嗷呜呜啊嗷啊呜嗷嗷~啊~嗷~呜呜嗷~啊嗷嗷嗷呜啊嗷嗷嗷啊"
))
| 58f7b791480bcfabccd50138734e3471c6b50227 | [
"Markdown",
"Python"
] | 2 | Markdown | zhongkangjk/beast_python | 277e013273c819c4eb73648ad77484506fc44756 | 7df737064734323bba8eff4c3c65e5e525612568 |
refs/heads/master | <file_sep>using HomeBrew;
using System;
using System.Collections.Generic;
using System.Text;
namespace HomeBrewCLI
{
public class Menu
{
private HomeBrewCalculator _hBCalc = null;
public Menu (HomeBrewCalculator hBCalc)
{
_hBCalc = hBCalc;
}
public void MainMenu()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Capstone.Classes
{
public class SnackItem
{
public string sLocation { get; }
public string sName { get; }
public decimal dPrice { get; }
public string sType { get; }
public int nAmount { get; set; }
public SnackItem(string[] saData)
{
sLocation = saData[0];
sName = saData[1];
dPrice = decimal.Parse(saData[2]);
sType = saData[3];
nAmount = 5;
}
}
}
<file_sep>using System;
namespace HomeBrewCalculators
{
class Program
{
static void Main(string[] args)
{
AVBCalc abvCalc = new AVBCalc();
DMECalc dmeCalc = new DMECalc();
bool mainMenuTrue = true;
while (mainMenuTrue == true)
{
Console.Clear();
Console.WriteLine("\nWhich Calculation would you like to do?");
Console.WriteLine("=======================================\n");
Console.WriteLine("1.) ABV Calculator");
Console.WriteLine("2.) DME Calculator");
Console.WriteLine("3.) Sparge Water Calculator");
Console.WriteLine("4.) Boil Off Rate Calculator");
Console.WriteLine("5.) IBU Calculator");
Console.WriteLine("6.) Yeast Pitch Calculator\n");
Console.Write("Selection: ");
string selection = Console.ReadLine();
if (selection == "1")
{
abvCalc.ABVMenu();
}
if (selection == "2")
{
dmeCalc.DMEMenu();
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CarRepairService.Models
{
[Serializable]
public class ItemizedIncidentLine : Item
{
public int IncidentId { get; set; }
public string Description { get; set; }
public Decimal Cost { get; set; }
public int TimeHours { get; set; }
public bool Approved { get; set; }
public bool Declined { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CarRepairService.Models
{
[Serializable]
public class Vehicle : Item
{
public string Vin { get; set; }
public int UserId { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string Color { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CarRepairWebApi.Models
{
public class RepairLineViewModel
{
[Required]
public int IncidentId { get; set; }
[Required]
public string Description { get; set; }
[Required]
public Decimal Cost { get; set; }
[Required]
public int TimeHours { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CarRepairService.BusinessLogic;
using CarRepairService.DAOs;
using CarRepairService.Models;
using CarRepairWebApi.Models;
using CarRepairWebApi.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CarRepairWebApi.Controllers
{
[Route("api/account")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly ITokenGenerator _tokenGenerator;
private readonly ICarRepairDAO _db;
/// <summary>
/// Creates a new account controller.
/// </summary>
/// <param name="tokenGenerator">A token generator used when creating auth tokens.</param>
/// <param name="db">Access to the BuddyBux database.</param>
public AccountController(ITokenGenerator tokenGenerator, ICarRepairDAO db)
{
_tokenGenerator = tokenGenerator;
_db = db;
}
#region Basic
/// <summary>
/// Registers a user and provides a bearer token.
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost("register")]
public IActionResult Register(RegisterViewModel model)
{
IActionResult result = null;
// Does user already exist
try
{
if (ModelState.IsValid)
{
// Generate a password hash
var pwdMgr = new PasswordManager(model.Password);
var roleMgr = new RoleManager(_db);
// Create a user object
var user = new User
{
Hash = pwdMgr.Hash,
Salt = pwdMgr.Salt,
RoleId = roleMgr.CustomerRoleId,
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
Username = model.Username,
PhoneNumber = model.PhoneNumber,
};
// Save the user account
_db.AddUser(user);
roleMgr.User = _db.GetUserByEmailOrUsername(model.Username);
// Generate a token
var token = _tokenGenerator.GenerateToken(roleMgr.User.Username, roleMgr.RoleName);
result = Ok(token);
}
else
{
result = BadRequest(new { Message = "Required fields not filled out correctly" });
}
}
catch (Exception)
{
result = BadRequest(new { Message = "Username or Email has already been taken." });
}
// Return the token
return result;
}
/// <summary>
/// Authenticates the user and provides a bearer token.
/// </summary>
/// <param name="model">An object including the user's credentials.</param>
/// <returns></returns>
[HttpPost("login")]
public IActionResult Login([FromBody] LoginViewModel model)
{
// Assume the user is not authorized
IActionResult result = Unauthorized();
try
{
if (ModelState.IsValid)
{
var roleMgr = new RoleManager(_db);
roleMgr.User = _db.GetUserByEmailOrUsername(model.LoginCredentials);
// Generate a password hash
var pwdMgr = new PasswordManager(model.Password, roleMgr.User.Salt);
if (pwdMgr.Verify(roleMgr.User.Hash))
{
// Create an authentication token
var token = _tokenGenerator.GenerateToken(roleMgr.User.Username, roleMgr.RoleName);
// Switch to 200 OK
result = Ok(token);
}
}
else
{
result = BadRequest(new { Message = "Required fields not filled out correctly" });
}
}
catch (Exception)
{
result = BadRequest(new { Message = "Username or password is invalid." });
}
return result;
}
#endregion
#region Admin
/// <summary>
/// Add a new User or Admin if poster is Admin.
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost("register/employee")]
[Authorize(Roles = "Administrator")]
public IActionResult AddEmployeeOrAdim([FromBody] EmployeeAdminRegisterViewModel model)
{
IActionResult result = null;
try
{
//pick role number by name (dropdown) and return the value
if(ModelState.IsValid)
{
// Generate a password hash
var pwdMgr = new PasswordManager(model.Password);
var roleMgr = new RoleManager(_db);
// Create a user object
var user = new User
{
Hash = pwdMgr.Hash,
Salt = pwdMgr.Salt,
RoleId = roleMgr.GetIdForRole(model.RoleName),
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
Username = model.Username,
PhoneNumber = model.PhoneNumber,
};
// Save the user account
_db.AddUser(user);
// Generate a token
var token = _tokenGenerator.GenerateToken(user.Username, roleMgr.RoleName);
result = Ok(token);
}
else
{
result = BadRequest(new { Message = "Required fields not filled out correctly" });
}
}
catch (Exception)
{
result = BadRequest(new { Message = "Username or Email has already been taken." });
}
// Return the token
return result;
}
/// <summary>
/// Retrieves customer by id to get their information for displaying on incident.
/// </summary>
/// <param name="customerId">id to find customer by</param>
/// <returns>basic customer information</returns>
[HttpGet("user/{customerId}")]
[Authorize]
public IActionResult GetCustomerbyUserID(int customerId)
{
IActionResult result = null;
try
{
User model = _db.GetUserById(customerId);
// Only let the information we want leave, void the rest
model.Hash = null;
model.Salt = null;
model.RoleId = -1;
result = Ok(model);
}
catch (Exception ex)
{
result = BadRequest(new { Message = "Failed to retrieve customer." });
}
return result;
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Capstone.Classes;
using System.IO;
namespace Capstone.Classes
{
class VendingMachineCLI
{
public void GenerateDisplayItemsMenu(Dictionary<string, SnackItem> Snacks, VendingMachine Vend, bool bMainMenu = true)
{
Console.Clear();
List<string> sListOfKeys = new List<string>();
foreach (string s in Snacks.Keys)
{
sListOfKeys.Add(s);
}
string[] saKeys = sListOfKeys.ToArray();
decimal dBalanceOverride = Vend.Balance;
if (dBalanceOverride > 999.99m)
{
dBalanceOverride = 999.99m;
}
string sLine = "_______________________________________________\n" +
"|| _ _ _ _ _ _ _ _ _ _ ||\n" +
"|| / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ ||\n" +
"|| ( V | E | N | D | O | M | A | T | I | C ) ||\n" +
"|| \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ ||\n" +
"||___________________________________________||\n" +
"|| || || || || ||\n" +
$"|| A1 || A2 || A3 || A4 || Balance ||\n" +
$"|| || || || || ${string.Format("{0:000.00}", dBalanceOverride)} ||\n" +
$"|| || || || || ||\n" +
$"|| || || || || [A] [B] ||\n" +
$"|| B1 || B2 || B3 || B4 || [C] [D] ||\n" +
$"|| || || || || ||\n" +
$"|| || || || || [1] [2] ||\n" +
$"|| || || || || [3] [4] ||\n" +
$"|| C1 || C2 || C3 || C4 || ||\n" +
$"|| || || || || ||\n" +
$"|| || || || || ||\n" +
$"|| || || || || ||\n" +
$"|| D1 || D2 || D3 || D4 || ||\n" +
$"|| || || || || ||\n" +
$"|| || || || || ||\n" +
$"|| || || || || ||\n" +
"||______________________________|| ||\n" +
"|| || ||\n" +
"|| || ||\n" +
"||______________________________||___________||\n\n";
string[] newStringArray = sLine.Split('\n');
foreach (string s in newStringArray)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine(s);
Console.ResetColor();
}
int n = 0;
sLine = "";
foreach (string s in saKeys)
{
if (Snacks[saKeys[n]].nAmount <= 0)
{
sLine += "**SOLD OUT**\n";
}
else
{
sLine += $"{ Snacks[saKeys[n]].sLocation} - { Snacks[saKeys[n]].sName} - ${ Snacks[saKeys[n]].dPrice}\n";
}
n++;
}
Console.WriteLine(sLine);
Console.ForegroundColor = ConsoleColor.White;
if (bMainMenu)
{
Console.WriteLine("1). Insert Money");
Console.WriteLine("2). Select Product");
Console.WriteLine("3). Finish Transaction");
Console.WriteLine("4). Exit");
}
}
public void PromptInsertMoney(VendingMachine VendoMatic600, string sLogPath)
{
Console.WriteLine("How many Dollars do you want to insert into the machine?");
bool bIsValidAmount = int.TryParse(Console.ReadLine(), out int nAmount);
while (!bIsValidAmount)
{
Console.WriteLine("Please enter a valid number of Dollar Bills.");
bIsValidAmount = int.TryParse(Console.ReadLine(), out nAmount);
}
VendoMatic600.InsertMoney(nAmount);
GenerateDisplayItemsMenu(VendoMatic600.GetSnackItems(), VendoMatic600, false);
using (StreamWriter newSW = new StreamWriter(sLogPath, true))
{
//write Date & Time
newSW.Write(DateTime.Now.ToString() + " ");
//write amount entered
newSW.Write($"FEED MONEY: ${string.Format("{0:0.00}", (double)nAmount)} ");
//write balance
newSW.Write($"${string.Format("{0:0.00}", VendoMatic600.Balance)}\n");
}
}
public void RunTransaction(VendingMachine VendoMatic600, string sLogPath)
{
Console.WriteLine("Ending Transaction... Returning Change...");
string sLine = VendoMatic600.GetChangeMessage(VendoMatic600.Balance);
Console.WriteLine(sLine);
using (StreamWriter newSW = new StreamWriter(sLogPath, true))
{
//write Date & Time
newSW.Write(DateTime.Now.ToString() + " ");
//write transaction amount
newSW.Write("GIVE CHANGE: $" + VendoMatic600.Balance + " ");
VendoMatic600.Balance = 0;
//write balance
newSW.Write($"${string.Format("{0:0.00}", VendoMatic600.Balance)}\n");
}
Console.ReadKey();
}
public void RunPurchase(VendingMachine VendoMatic600, string sLogPath)
{
Console.Write("Please Select Your Product by ID: ");
bool bIsValidProductNumber = false;
bool bIsValidProductLetter = false;
string sInput = Console.ReadLine();
bIsValidProductNumber = int.TryParse(sInput.Substring(1, 1), out int nNumber);
bIsValidProductLetter = sInput.Substring(0, 1).ToUpper() == "A" ||
sInput.Substring(0, 1).ToUpper() == "B" ||
sInput.Substring(0, 1).ToUpper() == "C" ||
sInput.Substring(0, 1).ToUpper() == "D";
while (!bIsValidProductNumber || !bIsValidProductLetter || nNumber < 1 || nNumber > 4)
{
Console.WriteLine("Please enter a valid Product ID... Format : LetterNumber");
sInput = Console.ReadLine();
bIsValidProductNumber = int.TryParse(sInput.Substring(1, 1), out nNumber);
bIsValidProductLetter = sInput.Substring(0, 1).ToUpper() == "A" ||
sInput.Substring(0, 1).ToUpper() == "B" ||
sInput.Substring(0, 1).ToUpper() == "C" ||
sInput.Substring(0, 1).ToUpper() == "D";
}
sInput = sInput.Substring(0, 1).ToUpper() + sInput.Substring(1, 1);
if (VendoMatic600.GetSnackItems()[sInput].nAmount > 0)
{
VendoMatic600.Balance -= VendoMatic600.GetSnackItems()[sInput].dPrice;
VendoMatic600.DecrementAmountOfSnack(VendoMatic600.GetSnackItems()[sInput], 1);
Console.WriteLine(VendoMatic600.DispenseItem(VendoMatic600.GetSnackItems()[sInput]));
Console.ReadKey();
}
else
{
Console.WriteLine("We Don't Have Any More, Go Away.");
}
using (StreamWriter newSW = new StreamWriter(sLogPath, true))
{
//write Date & Time
newSW.Write(DateTime.Now.ToString() + " ");
//write amount entered
newSW.Write(VendoMatic600.GetSnackItems()[sInput].sName + " ");
newSW.Write(VendoMatic600.GetSnackItems()[sInput].sLocation + " ");
newSW.Write("$" + string.Format("{0:0.00}", VendoMatic600.GetSnackItems()[sInput].dPrice) + " ");
//write balance
newSW.Write($"${string.Format("{0:0.00}", VendoMatic600.Balance)}\n");
}
}
public void Start(VendingMachine VendoMatic600, string sLogPath)
{
bool bFinished = false;
while (!bFinished)
{
GenerateDisplayItemsMenu(VendoMatic600.GetSnackItems(), VendoMatic600);
bool bValidSelection = int.TryParse(Console.ReadLine(), out int nSelection);
while (!bValidSelection || nSelection > 4 || nSelection < 1)
{
GenerateDisplayItemsMenu(VendoMatic600.GetSnackItems(), VendoMatic600);
Console.WriteLine("Please Enter a valid selection.");
bValidSelection = int.TryParse(Console.ReadLine(), out nSelection);
}
switch (nSelection)
{
case 1:
{
Console.Clear();
GenerateDisplayItemsMenu(VendoMatic600.GetSnackItems(), VendoMatic600, false);
PromptInsertMoney(VendoMatic600, sLogPath);
}
break;
case 2:
{
if (!VendoMatic600.IsAllowedToPurchase())
{
Console.WriteLine("You cannot afford anything.");
Console.ReadKey();
break;
}
Console.Clear();
GenerateDisplayItemsMenu(VendoMatic600.GetSnackItems(), VendoMatic600, false);
RunPurchase(VendoMatic600, sLogPath);
}
break;
case 3:
{
Console.Clear();
RunTransaction(VendoMatic600, sLogPath);
}
break;
case 4:
{
bFinished = true;
}
break;
}
}
}
public void DisplayMainMenuOptions()
{
Console.WriteLine("1). Insert Money");
Console.WriteLine("2). Select Product");
Console.WriteLine("3). Finish Transaction");
Console.WriteLine("4). Exit");
}
}
}
<file_sep>using CarRepairService.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace CarRepairService.DAOs
{
public interface ICarRepairDAO
{
#region User
int AddUser(User model);
User GetUserById(int userId);
User GetUserByEmailOrUsername(string searchCredential);
int GetUserIdByUsername(string username);
int NumberOfUsersByRole(int roleId);
#endregion
#region Role
List<Role> GetRoles();
#endregion
#region Incident
/// <summary>
/// Saves a new Incident to the system.
/// </summary>
/// <param name="newIncident"></param>
/// <returns></returns>
int AddIncident(Incident newIncident);
List<Incident> GetIncidentsByUser(int userId);
void IncidentPaid(int incidentId);
void IncidentComplete(int incidentId);
void AddPickUpDate(int incidentId, DateTime pickUpDate);
List<Incident> GetIncidents();
Incident GetIncidentById(int incidentId);
#endregion
#region ItemizedLine
List<ItemizedIncidentLine> GetItemizedLines(int incidentId);
ItemizedIncidentLine GetItemizedLineById(int lineId);
int AddItemizedLine(ItemizedIncidentLine model);
void ApproveLineItem(int itemLineId);
void DeclineLineItem(int itemLineId);
int EditLineItem(ItemizedIncidentLine model);
#endregion
#region Vehicle
/// <summary>
/// Saves a new Incident to the system.
/// </summary>
/// <param name="newVehicle"></param>
/// <returns></returns>
int AddVehicleItems(Vehicle newVehicle);
Vehicle GetVehicleByVin(string vehicleVin);
Vehicle GetVehicleByID(int id);
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace HomeBrewCalculators
{
class AVBCalc
{
public void ABVMenu()
{
bool repeatMethod = true;
double resultABV = 0.0;
string oGravity = "";
string fGravity = "";
while (repeatMethod)
{
Console.Clear();
Console.Write("Welcome to the ABV Calculator!!\n" +
"Use This Calculator to determine the Alcohol By Volome in your brew. \n" +
"===============================\n" +
"Please enter Original Gravity (1.000 - 1.130): ");
oGravity = Console.ReadLine();
Console.Write("Please Enter Final Gravity (1.000 - 1.130): ");
fGravity = Console.ReadLine();
//Convert user string inputs to doubles
double oGDouble = Convert.ToDouble(oGravity);
double oFDouble = Convert.ToDouble(fGravity);
//Calculates ABV
resultABV = (oGDouble - oFDouble) * 131.25;
Console.WriteLine($"Your Brew's ABV is {string.Format("{0:0.00}", resultABV)} \n" +
"===============================\n" +
"New Calculation or Return to Main Menu?\n" +
"1.) New Calculation\n" +
"2.) Main Menu");
Console.Write("Selection: ");
string selection = Console.ReadLine();
if (selection == "1")
{
repeatMethod = true;
}
else if (selection == "2")
{
repeatMethod = false;
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Capstone.Classes
{
public class VendingMachine
{
public decimal Balance { get; private set; } = 0.0M;
Dictionary<string, SnackItem> VendItems = new Dictionary<string, SnackItem>();
public void FillMyMachine(string sFilePath)
{
//List<string> sList = new List<string>();
using (StreamReader newSR = new StreamReader(sFilePath))
{
while (!newSR.EndOfStream)
{
string sLine = newSR.ReadLine();
string[] saStringArray = sLine.Split('|');
SnackItem siSnack = new SnackItem(saStringArray);
AddItemToMachine(siSnack);
}
}
}
public void AddItemToMachine(SnackItem Snack)
{
VendItems.Add(Snack.sLocation, Snack);
}
public void IncrementAmountOfSnack(SnackItem Snack, int nAmount)
{
Snack.nAmount += nAmount;
}
public void DecrementAmountOfSnack(SnackItem Snack, int nAmount)
{
Snack.nAmount -= nAmount;
}
public Dictionary<string, SnackItem> GetSnackItems()
{
return VendItems;
}
public void InsertMoney(decimal dAmount)
{
Balance += dAmount;
}
public void DecreaseMoney(decimal dAmount)
{
Balance -= dAmount;
}
public bool IsAllowedToPurchase()
{
bool result = true;
decimal dCheapest = GetCheapestPrice(VendItems);
if (Balance < dCheapest)
{
result = false;
}
return result;
}
public decimal GetCheapestPrice(Dictionary<string, SnackItem> Snacks)
{
decimal dCheapest = -1.0m;
foreach (string snack in Snacks.Keys)
{
if (dCheapest == -1.0m)
{
dCheapest = Snacks[snack].dPrice;
}
if (Snacks[snack].dPrice <= dCheapest)
{
dCheapest = Snacks[snack].dPrice;
}
}
return dCheapest;
}
public string GetChangeMessage(decimal balance)
{
string result = "";
decimal iOriginalBalance = balance;
string sQuarters = "Quarter";
string sDimes = "Dime";
string sNickles = "Nickel";
int iQuarters = (int)(balance / 0.25m);
if (iQuarters > 0)
{
balance -= 0.25m * iQuarters;
}
int iDimes = (int)(balance / 0.1m);
if (iDimes > 0)
{
balance -= 0.10m * iDimes;
}
int iNickels = (int)(balance / 0.05m);
if (iNickels > 0)
{
balance -= 0.05m * iNickels;
}
if (iQuarters != 1)
{
sQuarters = "Quarters";
}
if (iDimes != 1)
{
sDimes = "Dimes";
}
if (iNickels != 1)
{
sNickles = "Nickels";
}
result = $"Change = {iQuarters} {sQuarters}, {iDimes} {sDimes}, and {iNickels} {sNickles} for a total of ${string.Format("{0:0.00}", iOriginalBalance)}";
return result;
}
public string DispenseItem(SnackItem Snack)
{
string result = "";
switch (Snack.sType)
{
case "Chip": result = "Crunch Crunch, Yum!\n" + ".~~~~~. \n" +
"|-----|\n" +
"|CHIPS|\n" +
"|-----|\n" +
"|_____|\n";
break;
case "Candy": result = "Munch Munch, Yum!\n" + " \n" +
" .---. \n" +
"(CANDY)\n" +
" '---' \n" +
" ";
break;
case "Drink": result = "Glug Glug, Yum!\n" + " ____ \n"+
"[____] \n" +
"|SODA| \n" +
"|____| \n"+
"[____] ";
break;
case "Gum": result = "Chew Chew, Yum!\n" + " \n"+
" .---. \n"+
"| GUM |\n"+
"'-----'\n"+
" ";
break;
}
return result;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace HomeBrewCalculators
{
class SpargeCalc
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace HomeBrewCalculators
{
class DMECalc
{
public void DMEMenu()
{
bool repeatMethod = true;
double originalDME = 0.0;
double resultDME = 0.0;
double resultDMEOunces = 0.0;
double resultDMEGrams = 0.0;
string oGravity = "";
string gallons = "";
string targetGravity = "";
double targetDME = 0.0;
while (repeatMethod)
{
Console.Clear();
Console.Write("Welcome to the DME Calculator!!\n" +
"Use This Calculator to determine the Dry Malt Extract needed for your brew. \n" +
"===============================\n" +
"Please enter Original Gravity (1.020 - 1.130): ");
oGravity = Console.ReadLine();
Console.Write("Please Enter volume of Gallons: ");
gallons = Console.ReadLine();
Console.Write("Please Enter Target Gravity (1.020 - 1.150): ");
targetGravity = Console.ReadLine();
//Convert user string inputs to doubles
double oGDouble = Convert.ToDouble(oGravity);
double gallonDouble = Convert.ToDouble(gallons);
double targetGravityDouble = Convert.ToDouble(targetGravity);
//Calculates DME
originalDME = oGDouble * gallonDouble;
targetDME = targetGravityDouble * gallonDouble;
resultDME = (originalDME / targetDME) ;
resultDMEOunces = resultDME * 16;
resultDMEGrams = resultDME * 453.592;
Console.WriteLine($"Your Brew's Required DME is {String.Format("{0:0.00}", resultDME)} Lbs \n" +
$"or {String.Format("{0:0.00}", resultDMEOunces)} Ounces \n" +
$"or {String.Format("{0:0.00}", resultDMEGrams)} Grams \n" +
"===============================\n" +
"New Calculation or Return to Main Menu?\n" +
"1.) New Calculation\n" +
"2.) Main Menu");
Console.Write("Selection: ");
string selection = Console.ReadLine();
if (selection == "1")
{
repeatMethod = true;
}
else if (selection == "2")
{
repeatMethod = false;
}
}
}
}
}
<file_sep>using ParkGeek.DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ParkGeekMVC.Models
{
public class SurveyResultViewModel
{
public int SurveyID { get; set; }
public string ParkCode { get; set; }
public string Email { get; set; }
public string State { get; set; }
public string ActivityLevel { get; set; }
public IList<SurveyResultModel> survey { get; set; }
public IList<ParkModel> Parks { get; set; } = new List<ParkModel>();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CarRepairWebApi.Models
{
public class ApproveRepairViewModel
{
[Required]
public int LineId { get; set; }
}
}
<file_sep>using ParkGeekMVC.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace ParkGeek.DAL
{
public interface ISurveyResultDAO
{
IList<SurveyResultModel> GetAllSurveys();
int PostSurvey(SurveyResultModel SurveyModel);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CarRepairService.Models
{
[Serializable]
public class User : Item
{
public int RoleId { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Hash { get; set; }
public string Salt { get; set; }
}
}<file_sep>using ParkGeekMVC.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace ParkGeek.DAL.Scripts
{
public interface IWeatherDAO
{
IList<WeatherModel>GetWeather(string parkCode);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ParkGeek.DAL.Models
{
public class ParkModel
{
public string ParkCode { get; set; }
public string ParkName { get; set; }
public string State { get; set; }
public int Acerage { get; set; }
public int ElevationFeet { get; set; }
public int MilesOfTrails { get; set; }
public int NumOfCampsites { get; set; }
public string Climate { get; set; }
public int YearFounded { get; set; }
public string Quote { get; set; }
public string QuoteSource { get; set; }
public int AnnualVisitorCount { get; set; }
public string ParkDescription { get; set; }
public int EntryFee { get; set; }
public int NumOfAnimalSpecies { get; set; }
}
}
<file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Dashboard from '@/views/Dashboard.vue'
import About from '@/views/About.vue'
import NewIncident from '@/views/NewIncident.vue'
import IncidentDetails from '@/views/IncidentDetails.vue'
import auth from '@/shared/auth'
import AddEmployeeOrAdmin from '@/views/AddEmployeeOrAdmin.vue'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/home',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About
},
{
path: "/login",
name: "login",
component: Login
},
{
path: "/register",
name: "register",
component: Register
},
{
path: "/",
name: "dashboard",
component: Dashboard
},
{
path: "/incident/new",
name: "new-incident",
component: NewIncident
},
{
path: "/incident/:incident",
name: "incident-details",
component: IncidentDetails
},
{
path: "/employee/add",
name: "add-employee",
component: AddEmployeeOrAdmin
}
]
});
router.beforeEach((to, from, next) => {
// redirect to login page if not logged in and trying to access a restricted page
const publicPages = ['/login', '/register', '/home', '/about'];
const authRequired = !publicPages.includes(to.path);
const loggedIn = auth.getUser();
if (authRequired && !loggedIn) {
return next('/home');
}
next();
});
export default router
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarRepairService.DAOs;
using CarRepairWebApi.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.Swagger;
namespace CarRepairWebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//Configures Swagger to look at the XmlComments above our methods
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Car Repair API", Version = "v1" });
});
// Add CORS policy allowing any origin
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
// Enables automatic authentication token.
// The token is expected to be included as a bearer authentication token.
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// The rules for token validation
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false, // issuer not required
ValidateAudience = false, // audience not required
ValidateLifetime = true, // token must not have expired
ValidateIssuerSigningKey = true, // token signature must match so as not to be tampered with
NameClaimType = System.Security.Claims.ClaimTypes.NameIdentifier, // allows us to use sub for username
RoleClaimType = "rol", // allows us to put the role in rol
IssuerSigningKey = new SymmetricSecurityKey( // each token is signed with a private key so as to ensure its validity
Encoding.UTF8.GetBytes(Configuration["JwtSecret"]))
};
});
string connectionString = Configuration.GetConnectionString("CarRepairConnection");
services.AddScoped<ICarRepairDAO, CarRepairDAO>(m => new CarRepairDAO(connectionString));
services.AddScoped<ITokenGenerator, JwtGenerator>(m => new JwtGenerator(Configuration["JwtSecret"]));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// Enables the middleware to check the incoming request headers.
app.UseAuthentication();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CarRepair API v1");
});
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
<file_sep>using ParkGeek.DAL.Models;
using ParkGeekMVC.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace ParkGeek.DAL
{
public class ParkGeekDAO : IParkGeekDAO
{
private string _connectionString;
public ParkGeekDAO(string connectionString)
{
_connectionString = connectionString;
}
public IList<ParkModel> GetParks()
{
List<ParkModel> parks = new List<ParkModel>();
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM park;", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
parks.Add(MapRowToPark(reader));
}
}
return parks;
}
public ParkModel GetPark(string parkCode)
{
ParkModel park = new ParkModel();
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM park WHERE parkCode = @parkName;", conn);
cmd.Parameters.AddWithValue("@parkName", parkCode);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
park = MapRowToPark(reader);
}
}
return park;
}
private ParkModel MapRowToPark(SqlDataReader reader)
{
ParkModel result = new ParkModel();
result.ParkCode = Convert.ToString(reader["parkCode"]);
result.ParkName = Convert.ToString(reader["parkName"]);
result.ParkDescription = Convert.ToString(reader["parkDescription"]);
result.Acerage = Convert.ToInt32(reader["acreage"]);
result.State = Convert.ToString(reader["state"]);
result.ElevationFeet = Convert.ToInt32(reader["elevationInFeet"]);
result.MilesOfTrails = Convert.ToInt32(reader["milesOfTrail"]);
result.NumOfCampsites = Convert.ToInt32(reader["numberOfCampsites"]);
result.Climate = Convert.ToString(reader["climate"]);
result.YearFounded = Convert.ToInt16(reader["yearFounded"]);
result.Quote = Convert.ToString(reader["inspirationalQuote"]);
result.QuoteSource = Convert.ToString(reader["inspirationalQuoteSource"]);
result.AnnualVisitorCount = Convert.ToInt32(reader["annualVisitorCount"]);
result.EntryFee = Convert.ToInt16(reader["entryFee"]);
result.NumOfAnimalSpecies = Convert.ToInt32(reader["numberOfAnimalSpecies"]);
return result;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CarRepairWebApi.Models
{
public class LoginViewModel
{
/// <summary>
/// The user's login username or email.
/// </summary>
[Required]
public string LoginCredentials { get; set; }
/// <summary>
/// The user's password.
/// </summary>
[Required]
public string Password { get; set; }
}
}
<file_sep>using CarRepairService.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace CarRepairService.DAOs
{
public class CarRepairDAO : ICarRepairDAO
{
#region Variables
private const string _getLastIdSQL = "SELECT CAST(SCOPE_IDENTITY() as int);";
private readonly string _connectionString = "";
#endregion
public CarRepairDAO(string connectionString)
{
_connectionString = connectionString;
}
#region User
/// <summary>
/// Adds a user to the database.
/// </summary>
/// <param name="model"></param>
/// <returns>Id of the newly generated user</returns>
public int AddUser(User model)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
const string sql = "INSERT [user] (username, first_name, last_name, email, phone_number, hash, salt, role_id) " +
"VALUES(@username, @first_name, @last_name, @email, @phone_number, @hash, @salt, @role_id)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql + _getLastIdSQL, conn);
cmd.Parameters.AddWithValue("@username", model.Username);
cmd.Parameters.AddWithValue("@first_name", model.FirstName);
cmd.Parameters.AddWithValue("@last_name", model.LastName);
cmd.Parameters.AddWithValue("@email", model.Email);
cmd.Parameters.AddWithValue("@phone_number", model.PhoneNumber);
cmd.Parameters.AddWithValue("@hash", model.Hash);
cmd.Parameters.AddWithValue("@salt", model.Salt);
cmd.Parameters.AddWithValue("@role_id", model.RoleId);
model.Id = (int)cmd.ExecuteScalar();
}
return model.Id;
}
/// <summary>
/// Finds the UserId of a provided username.
/// </summary>
/// <param name="username">Username to find Id by</param>
/// <returns>User Id</returns>
public int GetUserIdByUsername(string username)
{
int userId = -1;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
const string sql = "SELECT id FROM [user] WHERE username = @username;";
conn.Open();
SqlCommand cmd = new SqlCommand(sql + _getLastIdSQL, conn);
cmd.Parameters.AddWithValue("@username", username);
userId = (int)cmd.ExecuteScalar();
}
return userId;
}
/// <summary>
/// Retrieves user from database by id.
/// </summary>
/// <param name="userId">Id to search user by</param>
/// <returns>User</returns>
public User GetUserById(int userId)
{
User user = null;
const string sql = "SELECT * From [User] WHERE Id = @Id;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Id", userId);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
user = GetUserFromReader(reader);
}
}
if (user == null)
{
throw new Exception("User does not exist.");
}
return user;
}
/// <summary>
/// Searchs for an existing user in the database by username or email.
/// </summary>
/// <param name="searchCredential">search parameter</param>
/// <returns>found user item</returns>
public User GetUserByEmailOrUsername(string searchCredential)
{
User user = null;
const string sql = "SELECT * FROM [user] " +
"WHERE username = @search OR email = @search;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@search", searchCredential);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
user = GetUserFromReader(reader);
}
}
if (user == null)
{
throw new Exception("User does not exist.");
}
return user;
}
/// <summary>
/// Saves reader data to a role item.
/// </summary>
/// <param name="reader">Reader line with data</param>
/// <returns>New User item</returns>
private User GetUserFromReader(SqlDataReader reader)
{
User item = new User
{
Id = Convert.ToInt32(reader["id"]),
FirstName = Convert.ToString(reader["first_name"]),
LastName = Convert.ToString(reader["last_name"]),
Username = Convert.ToString(reader["username"]),
Email = Convert.ToString(reader["email"]),
PhoneNumber = Convert.ToString(reader["phone_number"]),
Salt = Convert.ToString(reader["salt"]),
Hash = Convert.ToString(reader["hash"]),
RoleId = Convert.ToInt32(reader["role_id"])
};
return item;
}
/// <summary>
/// Gets list of all users from database
/// </summary>
/// <returns>list of users</returns>
public List<User> GetUserItems()
{
List<User> user = new List<User>();
const string sql = "Select * From [User];";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
user.Add(GetUserFromReader(reader));
}
}
return user;
}
/// <summary>
/// Deletes all users in the user table. *USED FOR TESTING ONLY*
/// </summary>
public void DeleteAllUsers()
{
const string sql = "Delete FROM [User];";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Checks the database for the current number of users by role.
/// </summary>
/// <returns>Count of current users of that role</returns>
public int NumberOfUsersByRole(int roleId)
{
int result = 0;
const string sql = "SELECT COUNT(role_id) FROM [user] WHERE role_id = @role_id;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql + _getLastIdSQL, conn);
cmd.Parameters.AddWithValue("@role_id", roleId);
result = (int)cmd.ExecuteScalar();
}
return result;
}
#endregion
#region Role
/// <summary>
/// Gets all roles from the database.
/// </summary>
/// <returns>List of roles</returns>
public List<Role> GetRoles()
{
List<Role> roles = new List<Role>();
const string sql = "Select * From Role;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
roles.Add(GetRoleFromReader(reader));
}
}
return roles;
}
/// <summary>
/// Saves reader data to a role item.
/// </summary>
/// <param name="reader">Reader line with data</param>
/// <returns>New Role item</returns>
private Role GetRoleFromReader(SqlDataReader reader)
{
Role item = new Role
{
Id = Convert.ToInt32(reader["Id"]),
Name = Convert.ToString(reader["Name"])
};
return item;
}
#endregion
#region Incident
/// Adds an incident to the database.
/// </summary>
/// <param name="model"></param>
/// <returns>Id of the newly generated incident</returns>
public int AddIncident(Incident model)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
const string sql = "INSERT [incident] (vehicle_id, description, submitted_date, paid, completed) " +
"VALUES(@vehicle_id, @description, @submitted_date, @paid, @completed)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql + _getLastIdSQL, conn);
cmd.Parameters.AddWithValue("@vehicle_id", model.VehicleId);
cmd.Parameters.AddWithValue("@description", model.Description);
cmd.Parameters.AddWithValue("@submitted_date", model.SubmittedDate);
cmd.Parameters.AddWithValue("@paid", model.Paid);
cmd.Parameters.AddWithValue("@completed", model.Completed);
model.Id = (int)cmd.ExecuteScalar();
}
return model.Id;
}
/// <summary>
/// Used to get incident by passing in ID. Built for integration tests.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public Incident GetIncidentById(int incidentId)
{
Incident incident = null;
const string sql = "SELECT * From [incident] WHERE Id = @Id;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Id", incidentId);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
incident = GetIncidentFromReader(reader);
}
}
if (incident == null)
{
throw new Exception("Incident does not exist.");
}
return incident;
}
/// <summary>
/// Retrieves a list of a users incidents, searching by Id.
/// </summary>
/// <param name="userId">User Id to find incidents by</param>
/// <returns>List of incidents for user</returns>
public List<Incident> GetIncidentsByUser(int userId)
{
List<Incident> incidents = new List<Incident>();
const string sql = "SELECT * FROM [incident] JOIN vehicle on incident.vehicle_id = vehicle.id WHERE vehicle.user_id = @user_id; ";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@user_id", userId);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
incidents.Add(GetIncidentFromReader(reader));
}
}
if (incidents == null)
{
throw new Exception("Incident does not exist.");
}
return incidents;
}
/// <summary>
/// Updates incident to mark it as paid.
/// </summary>
/// <param name="incidentId"></param>
/// <returns>Whether it succeded or not</returns>
public void IncidentPaid(int incidentId)
{
const string sql = "UPDATE incident " +
"SET paid = 1 WHERE id = @incident_id";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@incident_id", incidentId);
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Failed to mark paid.");
}
}
}
/// <summary>
/// Updates incident to mark it as complete.
/// </summary>
/// <param name="incidentId"></param>
/// <returns>Whether it succeded or not</returns>
public void IncidentComplete(int incidentId)
{
const string sql = "UPDATE incident " +
"SET completed = 1 WHERE id = @incident_id";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@incident_id", incidentId);
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Failed to mark complete.");
}
}
}
/// <summary>
/// Updates incident to add pick up date for completed repair.
/// </summary>
/// <param name="incidentId">Id of incident to update</param>
/// <param name="pickUpDate">Date of pickup</param>
/// <returns></returns>
public void AddPickUpDate(int incidentId, DateTime pickUpDate)
{
const string sql = "UPDATE incident " +
"SET pickup_date = @date WHERE id = @incident_id";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@incident_id", incidentId);
cmd.Parameters.AddWithValue("@date", pickUpDate);
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Failed to add pickup date.");
}
}
}
/// <summary>
/// Gets all incidents from database.
/// </summary>
/// <returns>List of incidents</returns>
public List<Incident> GetIncidents()
{
List<Incident> incident = new List<Incident>();
const string sql = "Select * From [incident];";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
incident.Add(GetIncidentFromReader(reader));
}
}
return incident;
}
/// <summary>
/// Used to delete incdients **FOR INTEGRATION TESTS ONLY**
/// </summary>
public void DeleteAllIncidents()
{
const string sql = "Delete FROM [incident];";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Saves reader data to a incident item.
/// </summary>
/// <param name="reader">Reader line with data</param>
/// <returns>New vehicle item</returns>
private Incident GetIncidentFromReader(SqlDataReader reader)
{
Incident incident = new Incident();
incident.Id = Convert.ToInt32(reader["id"]);
incident.VehicleId = Convert.ToInt32(reader["vehicle_id"]);
incident.Description = Convert.ToString(reader["description"]);
incident.Paid = Convert.ToBoolean(reader["paid"]);
incident.Completed = Convert.ToBoolean(reader["completed"]);
incident.SubmittedDate = Convert.ToDateTime(reader["submitted_date"]);
if (reader["pickup_date"] != DBNull.Value)
{
incident.PickupDate = Convert.ToDateTime(reader["pickup_date"]);
}
return incident;
}
#endregion
#region ItemizedLine
/// <summary>
/// Adds an incident by line item to the database.
/// </summary>
/// <param name="model">New itemized line to add</param>
/// <returns>Id of the newly generated incident by line item</returns>
public int AddItemizedLine(ItemizedIncidentLine model)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
const string sql = "INSERT [incident_itemizated] (incident_id, description, cost, time_hours, approved, declined) " +
"VALUES(@incident_id, @description, @cost, @time_hours, @approved, @declined)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql + _getLastIdSQL, conn);
cmd.Parameters.AddWithValue("@incident_id", model.IncidentId);
cmd.Parameters.AddWithValue("@description", model.Description);
cmd.Parameters.AddWithValue("@cost", model.Cost);
cmd.Parameters.AddWithValue("@time_hours", model.TimeHours);
cmd.Parameters.AddWithValue("@approved", model.Approved);
cmd.Parameters.AddWithValue("@declined", model.Declined);
model.Id = (int)cmd.ExecuteScalar();
}
return model.Id;
}
/// <summary>
/// Gets list of all itemized lines from an incident, searching by incident ID.
/// </summary>
/// <returns>list of itemzided incident lines</returns>
public List<ItemizedIncidentLine> GetItemizedLines(int incidentId)
{
List<ItemizedIncidentLine> itemizedIncidentLine = new List<ItemizedIncidentLine>();
const string sql = "Select * From [incident_itemizated] WHERE incident_id = @incident_id;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@incident_id", incidentId);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
itemizedIncidentLine.Add(GetItemizedIncidentLineFromReader(reader));
}
}
return itemizedIncidentLine;
}
/// <summary>
/// Retrieves the line item that
/// </summary>
/// <param name="lineId">id of line to return</param>
/// <returns></returns>
public ItemizedIncidentLine GetItemizedLineById(int lineId)
{
ItemizedIncidentLine line = null;
const string sql = "SELECT * FROM incident_itemizated WHERE id = @line_id;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@line_id", lineId);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
line = GetItemizedIncidentLineFromReader(reader);
}
}
if (line == null)
{
throw new Exception("Repair line does not exist.");
}
return line;
}
/// <summary>
/// Updates and Item line to aprrove it for repair.
/// </summary>
/// <param name="itemLineId"></param>
/// <returns>Whether it succeded or not</returns>
public void ApproveLineItem(int itemLineId)
{
const string sql = "UPDATE incident_itemizated " +
"SET approved = 1 WHERE id = @line_id";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@line_id", itemLineId);
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Failed to approve line.");
}
}
}
/// <summary>
/// Updates and Item line to decline it for repair.
/// </summary>
/// <param name="itemLineId"></param>
/// <returns>Whether it succeded or not</returns>
public void DeclineLineItem(int itemLineId)
{
const string sql = "UPDATE incident_itemizated " +
"SET declined = 1 WHERE id = @line_id";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@line_id", itemLineId);
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Failed to decline line.");
}
}
}
/// <summary>
/// Saves reader data to an itemized incident line item.
/// </summary>
/// <param name="reader">Reader line with data</param>
/// <returns>New ItemizedIncidentLine item</returns>
private ItemizedIncidentLine GetItemizedIncidentLineFromReader(SqlDataReader reader)
{
ItemizedIncidentLine itemizedIncidentLine = new ItemizedIncidentLine();
itemizedIncidentLine.Id = Convert.ToInt32(reader["id"]);
itemizedIncidentLine.IncidentId = Convert.ToInt32(reader["incident_id"]);
itemizedIncidentLine.Description = Convert.ToString(reader["description"]);
itemizedIncidentLine.Cost = Convert.ToDecimal(reader["cost"]);
itemizedIncidentLine.TimeHours = Convert.ToInt32(reader["time_hours"]);
itemizedIncidentLine.Approved = Convert.ToBoolean(reader["approved"]);
itemizedIncidentLine.Declined = Convert.ToBoolean(reader["declined"]);
return itemizedIncidentLine;
}
/// <summary>
/// Edits fields in the line item then sets line item to unapproved.
/// </summary>
/// <param name="itemLineId"></param>
/// <returns>Whether it succeded or not</returns>
public int EditLineItem(ItemizedIncidentLine model)
{
//pass in new view model and keep the same line id
const string sql = "UPDATE incident_itemizated " +
"SET description = @description, cost = @cost, time_hours = @time_hours, approved = null, declined = null" +
"WHERE incident_id = model.IncidentId ";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql + _getLastIdSQL, conn);
cmd.Parameters.AddWithValue("@incident_id", model.IncidentId);
cmd.Parameters.AddWithValue("@description", model.Description);
cmd.Parameters.AddWithValue("@cost", model.Cost);
cmd.Parameters.AddWithValue("@time_hours", model.TimeHours);
model.Id = (int)cmd.ExecuteScalar();
return model.Id;
}
}
#endregion
#region Vehicle
/// Adds an vehicle to the database.
/// </summary>
/// <param name="model"></param>
/// <returns>Id of the newly generated vehicle</returns>
public int AddVehicleItems(Vehicle model)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
const string sql = "INSERT [vehicle] (vin, user_id, make, model, year, color) " +
"VALUES(@vin, @user_id, @make, @model, @year, @color)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql + _getLastIdSQL, conn);
cmd.Parameters.AddWithValue("@vin", model.Vin);
cmd.Parameters.AddWithValue("@user_id", model.UserId);
cmd.Parameters.AddWithValue("@make", model.Make);
cmd.Parameters.AddWithValue("@model", model.Model);
cmd.Parameters.AddWithValue("@year", model.Year);
cmd.Parameters.AddWithValue("@color", model.Color);
model.Id = (int)cmd.ExecuteScalar();
}
return model.Id;
}
/// <summary>
/// Gets a vehicle by it's ID.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public Vehicle GetVehicleByID(int id)
{
Vehicle vehicle = null;
const string sql = "SELECT * From [Vehicle] WHERE id = @id;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@id", id);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
vehicle = GetVehicleFromReader(reader);
}
}
return vehicle;
}
/// <summary>
/// Gets all vehicles from database.
/// </summary>
/// <returns>list of vehicles</returns>
public List<Vehicle> GetVehicles()
{
List<Vehicle> vehicle = new List<Vehicle>();
const string sql = "Select * From vehicle;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
vehicle.Add(GetVehicleFromReader(reader));
}
}
return vehicle;
}
/// <summary>
/// Saves reader data to a vehicle item.
/// </summary>
/// <param name="reader">Reader line with data</param>
/// <returns>New vehicle item</returns>
private Vehicle GetVehicleFromReader(SqlDataReader reader)
{
Vehicle vehicle = new Vehicle
{
Id = Convert.ToInt32(reader["id"]),
Vin = Convert.ToString(reader["vin"]),
UserId = Convert.ToInt32(reader["user_id"]),
Make = Convert.ToString(reader["make"]),
Model = Convert.ToString(reader["model"]),
Year = Convert.ToInt32(reader["year"]),
Color = Convert.ToString(reader["color"]),
};
return vehicle;
}
/// <summary>
/// Retrieves vehicle from database by id.
/// </summary>
/// <param name="userId">Id to search user by</param>
/// <returns>User</returns>
public Vehicle GetVehicleByVin(string vehicleVin)
{
Vehicle vehicle = null;
const string sql = "SELECT * From [Vehicle] WHERE Vin = @Vin;";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Vin", vehicleVin);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
vehicle = GetVehicleFromReader(reader);
}
}
return vehicle;
}
/// <summary>
/// Deletes all vehicles in the vehicle table. *USED FOR TESTING ONLY*
/// </summary>
public void DeleteAllVehicles()
{
const string sql = "Delete FROM [Vehicle];";
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteNonQuery();
}
}
#endregion
}
}
<file_sep>using HomeBrew;
using System;
namespace HomeBrewCLI
{
class Program
{
static void Main(string[] args)
{
HomeBrewCalculator hBCalc = new HomeBrewCalculator();
Menu menu = new Menu(hBCalc);
menu.MainMenu();
}
}
}
<file_sep>using ParkGeek.DAL.Models;
using ParkGeekMVC.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace ParkGeek.MVC.Models
{
public class ParkViewModel
{
public string ParkCode { get; set; }
public string ParkName { get; set; }
public string State { get; set; }
public int Acerage { get; set; }
public int ElevationFeet { get; set; }
public int MilesOfTrails { get; set; }
public int NumOfCampsites { get; set; }
public string Climate { get; set; }
public int YearFounded { get; set; }
public string Quote { get; set; }
public string QuoteSource { get; set; }
public int AnnualVisitorCount { get; set; }
public string ParkDescription { get; set; }
public int EntryFee { get; set; }
public int NumOfAnimalSpecies { get; set; }
public int FiveDayForecastValue { get; set; }
public int LowTemp { get; set; }
public int HighTemp { get; set; }
public string ForeCast { get; set; }
public ParkModel Park { get; set; }
public IList<WeatherModel> Weather { get; set; }
public IList<ParkModel> Parks { get; set; } = new List<ParkModel>();
public int Convert(int temp)
{
int finalTemp = 0;
int first = temp - 32;
int second = first * 5;
finalTemp = second / 9;
return finalTemp;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CarRepairWebApi.Models
{
public class VehicleIncidentViewModel
{
[Required]
[StringLength(17, ErrorMessage = "Vin numbers can be more than 17 characters")]
public string Vin { get; set; }
[Required]
public string Make { get; set; }
[Required]
public string Model { get; set; }
[Required]
public int Year { get; set; }
[Required]
public string Color { get; set; }
[Required]
public string Description { get; set; }
}
}
<file_sep>using ParkGeekMVC.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace ParkGeek.DAL
{
public class SurveyResultDAO: ISurveyResultDAO
{
private string _connectionString;
public SurveyResultDAO(string connectionString)
{
_connectionString = connectionString;
}
public IList<SurveyResultModel> GetAllSurveys()
{
List<SurveyResultModel> surveys = new List<SurveyResultModel>();
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT parkCode, COUNT(*) AS numVotes FROM survey_result GROUP BY parkCode ORDER BY numVotes DESC", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
SurveyResultModel rm = new SurveyResultModel();
rm.ParkCode = Convert.ToString(reader["parkCode"]);
rm.NumVotes = Convert.ToInt32(reader["numVotes"]);
surveys.Add(rm);
}
}
return surveys;
}
private SurveyResultModel MapRowToSurveys(SqlDataReader reader)
{
return new SurveyResultModel()
{
SurveyID = Convert.ToInt32(reader["surveyId"]),
ParkCode = Convert.ToString(reader["parkCode"]),
Email = Convert.ToString(reader["email"]),
State = Convert.ToString(reader["state"]),
ActivityLevel = Convert.ToString(reader["activityLevel"]),
NumVotes = Convert.ToInt32(reader["numVotes"])
};
}
public int PostSurvey(SurveyResultModel surveyModel)
{
int result = 0;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO survey_result (parkCode, emailAddress, state, activityLevel) " +
"VALUES ( @parkCode, @emailAddress, @state, @activityLevel) SELECT CAST(SCOPE_IDENTITY() as int)", conn);
cmd.Parameters.AddWithValue("@parkCode", surveyModel.ParkCode);
cmd.Parameters.AddWithValue("@emailAddress", surveyModel.Email);
cmd.Parameters.AddWithValue("@state", surveyModel.State);
cmd.Parameters.AddWithValue("@activityLevel", surveyModel.ActivityLevel);
result = (int)cmd.ExecuteScalar();
}
return result;
}
}
}
<file_sep>using ParkGeek.DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ParkGeekMVC.Models
{
public class FavoritesViewModel
{
public string ParkCode { get; set; }
public string ParkName { get; set; }
public int NumVotes { get; set; }
public string ParkDesc { get; set; }
public IList<ParkModel> FavParks { get; set; } = new List<ParkModel>();
public IList<SurveyResultModel> surveys { get; set; } = new List<SurveyResultModel>();
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using Capstone.Classes;
using Capstone;
using System.Collections.Generic;
namespace CapstoneTests
{
[TestClass]
public class CapstoneTests
{
[TestMethod]
public void TestSnackSlot() //Test Snack slot is set correctly.
{
SnackItem Snack = new SnackItem(new string[] { "Z2", "Foobar", "7.89", "Ass" });
Assert.AreEqual("Z2", Snack.sLocation);
}
[TestMethod]
public void TestSnackName() //Test Snack Name is set correctly.
{
SnackItem Snack = new SnackItem(new string[] { "Z2", "Foodbar", "7.89", "Pretzel" });
Assert.AreEqual("Foodbar", Snack.sName);
}
[TestMethod]
public void TestSnackPrice() //Test Snack Cost is set correctly.
{
SnackItem Snack = new SnackItem(new string[] { "Z2", "Foobar", "7.89", "Horesdeovaries" });
Assert.AreEqual(7.89m, Snack.dPrice);
}
[TestMethod]
public void TestSnackType() //Test Snack Type is set correctly.
{
SnackItem Snack = new SnackItem(new string[] { "Z2", "Foobar", "7.89", "Hat" });
Assert.AreEqual("Hat", Snack.sType);
}
[TestMethod]
public void TestSnackAmountEqualsFive() //Test default amount is 5
{
SnackItem Snack = new SnackItem(new string[] { "Z2", "Foobar", "7.89", "Beer" });
Assert.AreEqual(5, Snack.nAmount);
}
[TestMethod]
public void TestSnackChangeIsCorrect1() //Test Quarters Multiple and Dime/Nickel Singular, and Change is Correct.
{
VendingMachine VendeezNuts = new VendingMachine();
Assert.AreEqual("Change = 12 Quarters, 1 Dime, and 1 Nickel for a total of $3.15", VendeezNuts.GetChangeMessage(3.15m));
}
[TestMethod]
public void TestSnackChangeIsCorrect2() //Test Quarter Singular and Dimes is 0 and Change is Correct.
{
VendingMachine VendeezNuts = new VendingMachine();
Assert.AreEqual("Change = 1 Quarter, 0 Dimes, and 1 Nickel for a total of $0.30", VendeezNuts.GetChangeMessage(0.30m));
}
[TestMethod]
public void TestSnackChangeIsCorrect3() //Additional Change is Correct with larger input.
{
VendingMachine TestVendor = new VendingMachine();
Assert.AreEqual("Change = 67 Quarters, 1 Dime, and 0 Nickels for a total of $16.85", TestVendor.GetChangeMessage(16.85m));
}
[TestMethod]
public void TestDispenseItemChip() // Test if correct dispense message is sent.
{
VendingMachine TestVendor = new VendingMachine();
SnackItem snak = new SnackItem(new string[] { "d4", "CheeseCar", "2.00", "Chip" });
Assert.AreEqual("Crunch Crunch, Yum!", TestVendor.DispenseItem(snak));
; }
[TestMethod]
public void TestDispenseItemGum() // Test if correct dispense message is sent.
{
VendingMachine TestVendor = new VendingMachine();
SnackItem snak = new SnackItem(new string[] { "d4", "CheeseCar", "2.00", "Gum" });
Assert.AreEqual("Chew Chew, Yum!", TestVendor.DispenseItem(snak));
}
[TestMethod]
public void TestDispenseItemDrink() // Test if correct dispense message is sent.
{
VendingMachine TestVendor = new VendingMachine();
SnackItem snak = new SnackItem(new string[] { "d4", "CheeseCar", "2.00", "Drink" });
Assert.AreEqual("Glug Glug, Yum!", TestVendor.DispenseItem(snak));
}
[TestMethod]
public void TestDispenseItemCandy() // Test if correct dispense message is sent.
{
VendingMachine TestVendor = new VendingMachine();
SnackItem snak = new SnackItem(new string[] { "d4", "CheeseCar", "2.00", "Candy" });
Assert.AreEqual("Munch Munch, Yum!", TestVendor.DispenseItem(snak));
}
[TestMethod]
public void TestInsertMoney()// Test if valid entry for values inserted to machine
{
VendingMachine TestVendor = new VendingMachine();
TestVendor.InsertMoney(12);
Assert.AreEqual(12.00M, TestVendor.Balance);
}
[TestMethod]
public void TestInventoryAddSnack()// Test if item exists in dictionary after adding
{
VendingMachine TestVendor = new VendingMachine();
SnackItem snak = new SnackItem(new string[] { "d4", "CheeseCar", "2.00", "Candy" });
TestVendor.AddItemToMachine(snak);
Assert.AreEqual(snak, TestVendor.GetSnackItems()["d4"]);
}
[TestMethod]
public void TestCheapestSnack()// Tests if correct cheapest price is returned.
{
VendingMachine TestVendor = new VendingMachine();
SnackItem snak1 = new SnackItem(new string[] { "d1", "Dinger", "2.50", "Candy" });
SnackItem snak2 = new SnackItem(new string[] { "b3", "HooHoo", "1.35", "Chip" });
SnackItem snak3 = new SnackItem(new string[] { "a2", "<NAME>", "0.45", "Soda" });
TestVendor.AddItemToMachine(snak1);
TestVendor.AddItemToMachine(snak2);
TestVendor.AddItemToMachine(snak3);
Assert.AreEqual(0.45m, TestVendor.GetCheapestPrice(TestVendor.GetSnackItems()));
}
[TestMethod]
public void TestGetSnackItems()//Test if corrected dictionary is retrieved.
{
VendingMachine TestVendor = new VendingMachine();
SnackItem snak1 = new SnackItem(new string[] { "d1", "Dinger", "2.50", "Candy" });
SnackItem snak2 = new SnackItem(new string[] { "b3", "HooHoo", "1.35", "Chip" });
SnackItem snak3 = new SnackItem(new string[] { "a2", "<NAME>", "0.45", "Soda" });
TestVendor.AddItemToMachine(snak1);
TestVendor.AddItemToMachine(snak2);
TestVendor.AddItemToMachine(snak3);
Dictionary<string, SnackItem> TestDict = new Dictionary<string, SnackItem>()
{
{snak1.sLocation, snak1},
{snak2.sLocation, snak2},
{snak3.sLocation, snak3}
};
CollectionAssert.AreEquivalent(TestDict, TestVendor.GetSnackItems());
}
[TestMethod]
public void TestBalance() // Tests if Balance is correct for entered values.
{
VendingMachine TestVendor = new VendingMachine();
TestVendor.InsertMoney(12);
TestVendor.InsertMoney(15);
Assert.AreEqual(27.00M, TestVendor.Balance);
}
[TestMethod]
public void TestIsAllowedToPurchaseFalse()// Test if balance is enough to make a purchase.
{
VendingMachine TestVendor = new VendingMachine();
TestVendor.InsertMoney(1);
SnackItem snak1 = new SnackItem(new string[] { "d1", "Dinger", "2.50", "Candy" });
SnackItem snak2 = new SnackItem(new string[] { "b3", "HooHoo", "1.35", "Chip" });
TestVendor.AddItemToMachine(snak1);
TestVendor.AddItemToMachine(snak2);
Assert.IsFalse(TestVendor.IsAllowedToPurchase());
}
[TestMethod]
public void TestIsAllowedToPurchaseTrue()// Test if balance is enough to make a purchase.
{
VendingMachine TestVendor = new VendingMachine();
TestVendor.InsertMoney(2);
SnackItem snak1 = new SnackItem(new string[] { "d1", "Dinger", "2.50", "Candy" });
SnackItem snak2 = new SnackItem(new string[] { "b3", "HooHoo", "1.35", "Chip" });
TestVendor.AddItemToMachine(snak1);
TestVendor.AddItemToMachine(snak2);
Assert.IsTrue(TestVendor.IsAllowedToPurchase());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ParkGeek;
using ParkGeek.DAL;
using ParkGeek.DAL.Models;
using ParkGeek.DAL.Scripts;
using ParkGeek.MVC.Models;
using ParkGeekMVC.Models;
using Security.DAO;
namespace ParkGeekMVC.Controllers
{
public class ParkController : AuthenticationController
{
private IWeatherDAO _weatherDAO = null;
private IParkGeekDAO _parkDAO = null;
private ISurveyResultDAO _surveyDAO = null;
private IUserSecurityDAO _userSecurity = null;
public ParkController(IUserSecurityDAO db, IParkGeekDAO parkDAO, IWeatherDAO weatherDAO, ISurveyResultDAO surveyDAO, IHttpContextAccessor httpContext) : base(db, httpContext)
{
_parkDAO = parkDAO;
_weatherDAO = weatherDAO;
_surveyDAO = surveyDAO;
_userSecurity = db;
}
public IActionResult Index()
{
//get list of parks
var parks = _parkDAO.GetParks();
//pass list to VIEW as parameter in get auth view below it
return GetAuthenticatedView("Index", parks);
//on the view, bind the type passed in
//use to build razer
}
[HttpGet]
public IActionResult Details(string parkCode)
{
ParkViewModel parkSp = new ParkViewModel();
//parkSp.ParkCode = parkCode;
parkSp.Park =_parkDAO.GetPark(parkCode);
parkSp.Weather = _weatherDAO.GetWeather(parkCode);
return GetAuthenticatedView("Details", parkSp);
}
[HttpGet]
public IActionResult Survey()
{
SurveyResultViewModel SurveyVM = new SurveyResultViewModel();
SurveyVM.Parks = _parkDAO.GetParks();
return GetAuthenticatedView("Survey", SurveyVM);
}
[HttpPost]
public IActionResult Survey(SurveyResultModel RM)
{
_surveyDAO.PostSurvey(RM);
return RedirectToAction("Favorites");
}
[HttpGet]
public IActionResult Favorites()
{
IList<FavoritesViewModel> vmList = new List<FavoritesViewModel>();
IList<SurveyResultModel> rmList = new List<SurveyResultModel>();
rmList = _surveyDAO.GetAllSurveys();
foreach(SurveyResultModel RM in rmList)
{
FavoritesViewModel vm = new FavoritesViewModel();
ParkModel park = _parkDAO.GetPark(RM.ParkCode);
vm.NumVotes = RM.NumVotes;
vm.ParkCode = RM.ParkCode;
vm.ParkName = park.ParkName;
vm.ParkDesc = park.ParkDescription;
vmList.Add(vm);
}
return View("Favorites", vmList);
}
[HttpGet]
public IActionResult Weather(string parkCode)
{
ParkViewModel parkSp = new ParkViewModel();
parkSp.Weather = _weatherDAO.GetWeather(parkCode);
return GetAuthenticatedView("Weather", parkSp);
}
//[HttpGet]
//public IActionResult Survey()
//{
// SurveyResultViewModel surveySp = new SurveyResultViewModel();
// surveySp.ParkCode = parkCode;
// surveySp.survey = _surveyDAO.GetAllSurveys(parkCode);
// return GetAuthenticatedView("Survey", surveySp);
//}
//[HttpPost]
//public IActionResult Survey(string parkCode)
//{
// SurveyResultViewModel surveySp = new SurveyResultViewModel();
// surveySp.ParkCode = parkCode;
// surveySp.survey = _surveyDAO.GetAllSurveys(parkCode);
// return GetAuthenticatedView("Survey", surveySp);
//}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using CarRepairService.Models;
using CarRepairService.DAOs;
using System.Data.SqlClient;
namespace CarRepairTests.DAO_Tests
{
[TestClass]
public class CarRepairServiceTests
{
/// <summary>
/// The transaction for each test.
/// </summary>
private TransactionScope transaction;
protected string ConnectionString { get; } = "Data Source=.\\SQLEXPRESS;Initial Catalog=CarRepairTracker;Integrated Security=True";
#region Test Initialize and Cleanup
[TestInitialize]
public void Setup()
{
// Begin the transaction
transaction = new TransactionScope();
}
[TestCleanup]
public void Cleanup()
{
// Roll back the transaction
transaction.Dispose();
}
#endregion
#region Methods for Tests
private User CreateFirstTestUser()
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
User user = new User();
user.RoleId = 3;
user.Username = "K.Schott";
user.FirstName = "Kevin";
user.LastName = "Schott";
user.Email = "<EMAIL>";
user.PhoneNumber = "1-513-555-6666";
user.Hash = "hash";
user.Salt = "salt";
return user;
}
private User CreateSecondTestUser()
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
User user2 = new User();
user2.RoleId = 3;
user2.Username = "K.Schott2";
user2.FirstName = "Kevin";
user2.LastName = "Schott";
user2.Email = "<EMAIL>";
user2.PhoneNumber = "1-513-555-6666";
user2.Hash = "hash";
user2.Salt = "salt";
return user2;
}
private Incident CreateFirstTestIncident(int vehicleId)
{
Incident incident = new Incident();
incident.VehicleId = vehicleId;
incident.Description = "Car is Broken";
incident.SubmittedDate = new DateTime(2012, 11, 15);
incident.Paid = true;
return incident;
}
private Incident CreateSecondTestIncident(int vehicleId)
{
Incident incident = new Incident();
incident.VehicleId = vehicleId;
incident.Description = "Car is Broken";
incident.SubmittedDate = new DateTime(2012, 11, 15);
incident.Paid = true;
return incident;
}
private Vehicle CreateTestVehicle(int newUserID)
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
Vehicle vehicle = new Vehicle();
vehicle.Vin = "VinTest";
vehicle.UserId = newUserID;
vehicle.Make = "MakeTest";
vehicle.Model = "Model Test";
vehicle.Year = 1990;
vehicle.Color = "ColorTest";
return vehicle;
}
#endregion
#region User Tests
[TestMethod]
public void AddUserTest()
{
//// Arrange
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
User user = CreateFirstTestUser();
int newId = dao.AddUser(user);
var newUser = dao.GetUserById(newId);
Assert.AreEqual(newId, newUser.Id, "ID does not match, check GetUserItemByIdMethod");
Assert.AreEqual(user.RoleId, newUser.RoleId, "Role ID does not match");
Assert.AreEqual(user.Username, newUser.Username, "UserName does not match");
Assert.AreEqual(user.FirstName, newUser.FirstName, "FirstName does not match");
Assert.AreEqual(user.LastName, newUser.LastName, "LastName does not match");
Assert.AreEqual(user.Email, newUser.Email, "Email does not match");
Assert.AreEqual(user.PhoneNumber, newUser.PhoneNumber, "PhoneNumber does not match");
Assert.AreEqual(user.Hash, newUser.Hash, "Hash does not match");
Assert.AreEqual(user.Salt, newUser.Salt, "Salt does not match");
}
[TestMethod]
public void GetUserItemsTest()
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
//delete entire table
dao.DeleteAllVehicles();
dao.DeleteAllUsers();
//create new users
User user = CreateFirstTestUser();
int newUserID = dao.AddUser(user);
User user2 = CreateSecondTestUser();
int newUser2ID = dao.AddUser(user2);
List<User> userList = new List<User>();
userList = dao.GetUserItems();
Assert.AreEqual(userList.Count, 2, "2 users were not returned");
Assert.AreEqual(userList[0].Id, newUserID, "First user's ID does not match first user in list");
Assert.AreEqual(userList[1].Id, newUser2ID, "Second user's ID does not match second user in list");
}
#endregion
#region Role Tests
[TestMethod]
public void GetRolesTest()
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
List<Role> RolesList = new List<Role>();
RolesList = dao.GetRoles();
Assert.AreEqual(RolesList[0].Id, 1, "Administrator ID does not equal 1");
Assert.AreEqual(RolesList[0].Name, "Administrator", "ID 1 is not named Administrator");
Assert.AreEqual(RolesList[1].Id, 2, "Employee ID does not equal 2");
Assert.AreEqual(RolesList[1].Name, "Employee", "ID 2 is not named Employee");
Assert.AreEqual(RolesList[2].Id, 3, "Customer ID does not equal 3");
Assert.AreEqual(RolesList[2].Name, "Customer", "ID 1 is not named Customer");
}
#endregion
#region Incidents Tests
[TestMethod]
public void AddIncidentTest()
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
//add user
User user = CreateFirstTestUser();
int userId = dao.AddUser(user);
//add vehicle and set incident to that id
Vehicle vehicle = CreateTestVehicle(userId);
int vehicleId = dao.AddVehicleItems(vehicle);
Incident incident = CreateFirstTestIncident(vehicleId);
int newId = dao.AddIncident(incident);
var newUser = dao.GetIncidentById(newId);
Assert.AreEqual(newId, newUser.Id, "ID does not match, check GetIncidentById Method");
Assert.AreEqual(incident.VehicleId, newUser.VehicleId, "Vehicle ID does not match");
Assert.AreEqual(incident.Description, newUser.Description, "Description does not match");
Assert.AreEqual(incident.SubmittedDate, newUser.SubmittedDate, "SubmittedDate does not match");
Assert.AreEqual(incident.Paid, newUser.Paid, "Paid bool does not match");
}
[TestMethod]
public void GetIncidentsTest()
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
dao.DeleteAllIncidents();
User user = CreateFirstTestUser();
int userId = dao.AddUser(user);
Vehicle vehicle = CreateTestVehicle(userId);
int vehicleId = dao.AddVehicleItems(vehicle);
Incident incident1 = CreateFirstTestIncident(vehicleId);
int newIncidentID = dao.AddIncident(incident1);
Incident incident2 = CreateSecondTestIncident(vehicleId);
int newIncidentID2 = dao.AddIncident(incident2);
List<Incident> incidentList = new List<Incident>();
incidentList = dao.GetIncidents();
Assert.AreEqual(incidentList.Count, 2, "2 users were not returned");
Assert.AreEqual(incidentList[0].Id, newIncidentID, "First user's ID does not match first user in list");
Assert.AreEqual(incidentList[1].Id, newIncidentID2, "Second user's ID does not match second user in list");
}
[TestMethod]
public void GetIncidentsByUserTest()
{
CarRepairDAO dao = new CarRepairDAO(ConnectionString);
List<Incident> incidentsList = new List<Incident>();
//delete all vehicles
dao.DeleteAllVehicles();
//delete users
dao.DeleteAllUsers();
//delete incidents
dao.DeleteAllIncidents();
//delete all vehicles
dao.DeleteAllVehicles();
//add user and return id
User user = CreateFirstTestUser();
int newUserID = dao.AddUser(user);
//add vehicle
Vehicle vehicle = CreateTestVehicle(newUserID);
int vehicleId = dao.AddVehicleItems(vehicle);
//add incidents with new user id
Incident incident1 = CreateFirstTestIncident(vehicleId);
int newIncidentID = dao.AddIncident(incident1);
Incident incident2 = CreateSecondTestIncident(vehicleId);
int newIncidentID2 = dao.AddIncident(incident2);
//call get method and add to incidents list
incidentsList = dao.GetIncidentsByUser(newUserID);
Assert.AreEqual(incidentsList.Count, 2, "2 incidents were not returned");
Assert.AreEqual(incidentsList[0].VehicleId, vehicleId, "First incidents vehicle ID does not match");
Assert.AreEqual(incidentsList[1].VehicleId, vehicleId, "Second incidents vehicle ID does not match");
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CarRepairWebApi.Models
{
public class RegisterViewModel
{
[Required]
[StringLength(32, ErrorMessage = "First Name must be 32 charcters or less")]
public string FirstName { get; set; }
[Required]
[StringLength(32, ErrorMessage = "Last Name must be 32 charcters or less")]
public string LastName { get; set; }
[Required]
[StringLength(32, ErrorMessage = "Last Name must be 32 charcters or less")]
public string Username { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Invalid Email")]
public string Email { get; set; }
[Required]
[MinLength(4, ErrorMessage = "Password must be at least 4 characters")]
public string Password { get; set; }
[Required]
[Compare("Password", ErrorMessage = "Passwords do not match")]
public string ConfirmPassword { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
public string PhoneNumber { get; set; }
}
}
<file_sep>using CarRepairService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CarRepairWebApi.Models
{
public class DisplayIncidentsViewModel
{
public Incident Incident { get; set; }
public Vehicle Vehicle { get; set; }
public string Status { get; set; }
}
}
<file_sep>using ParkGeek.DAL.Models;
using ParkGeek.DAL.Scripts;
using ParkGeekMVC.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace ParkGeek.DAL
{
public class WeatherDAO : IWeatherDAO
{
private string _connectionString;
public WeatherDAO(string connectionString)
{
_connectionString = connectionString;
}
public IList<WeatherModel> GetAllWeather()
{
List<WeatherModel> weather = new List<WeatherModel>();
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM weather;", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
weather.Add(MapRowToWeather(reader));
}
}
return weather;
}
public IList <WeatherModel> GetWeather(string parkCode)
{
List<WeatherModel> weather = new List<WeatherModel>();
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM weather WHERE parkCode = @parkCode ORDER BY fiveDayForecastValue;", conn);
cmd.Parameters.AddWithValue("@parkCode", parkCode);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
weather.Add (MapRowToWeather(reader));
}
}
return weather;
}
private WeatherModel MapRowToWeather(SqlDataReader reader)
{
return new WeatherModel()
{
ParkCode = Convert.ToString(reader["parkCode"]),
FiveDayForecastValue = Convert.ToInt32(reader["fiveDayForecastValue"]),
LowTemp = Convert.ToInt32(reader["low"]),
HighTemp = Convert.ToInt32(reader["high"]),
ForeCast = Convert.ToString(reader["forecast"]),
};
}
}
}
<file_sep>using CarRepairService.DAOs;
using CarRepairService.Models;
using System.Collections.Generic;
namespace CarRepairService.BusinessLogic
{
/// <summary>
/// Holds a user and manages their permissions
/// </summary>
public class RoleManager
{
public const string ADMINISTRATOR = "Administrator";
public const string EMPLOYEE = "Employee";
public const string CUSTOMER = "Customer";
public const string UNKOWN = "Unkown";
private Dictionary<int, Role> _roles = new Dictionary<int, Role>();
/// <summary>
/// The user to manage permissions for
/// </summary>
public User User { get; set; }
/// <summary>
/// The name of the user's role
/// </summary>
public string RoleName
{
get
{
return User != null ? _roles[User.RoleId].Name : UNKOWN;
}
}
public int AdministratorRoleId
{
get
{
return GetIdForRole(ADMINISTRATOR);
}
}
public int EmployeeRoleId
{
get
{
return GetIdForRole(EMPLOYEE);
}
}
public int CustomerRoleId
{
get
{
return GetIdForRole(CUSTOMER);
}
}
/// <summary>
/// Constructor for the role manager. Create this everytime a user changes.
/// </summary>
/// <param name="user">The user to get the permissions for</param>
public RoleManager(ICarRepairDAO db)
{
if(_roles.Count == 0)
{
var roles = db.GetRoles();
foreach(var role in roles)
{
_roles.Add(role.Id, role);
}
}
}
public int GetIdForRole(string roleName)
{
int result = Role.InvalidId;
foreach(var role in _roles)
{
if(role.Value.Name == roleName)
{
result = role.Key;
}
}
return result;
}
/// <summary>
/// Specifies if the user has administrator permissions
/// </summary>
public bool IsAdministrator
{
get
{
return RoleName == ADMINISTRATOR;
}
}
/// <summary>
/// Specifies if the user has employee permissions
/// </summary>
public bool IsEmployee
{
get
{
return RoleName == EMPLOYEE;
}
}
/// <summary>
/// Specifies if the user has customer permissions
/// </summary>
public bool IsCustomer
{
get
{
return RoleName == CUSTOMER;
}
}
/// <summary>
/// Specifies if the user has unknown permissions
/// </summary>
public bool IsUnknown
{
get
{
return RoleName == UNKOWN;
}
}
}
}
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using Capstone.Classes;
using System.Text;
namespace Capstone
{
class Program
{
static void Main(string[] args)
{
VendingMachine VendoMatic600 = new VendingMachine();
VendingMachineCLI VCLI = new VendingMachineCLI();
VendoMatic600.FillMyMachine(@"..\..\..\..\VendingMachine.txt");
VCLI.Start(VendoMatic600, @"..\..\..\..\Log.txt");
}
}
}
<file_sep>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CarRepairService.DAOs;
using CarRepairService.Models;
using CarRepairWebApi.Models;
using Microsoft.AspNetCore.Authorization;
namespace CarRepairWebApi.Controllers
{
[Route("api/incident")]
[ApiController]
public class IncidentController : ControllerBase
{
private readonly ICarRepairDAO _db;
/// <summary>
/// Creates a new Incident controller.
/// </summary>
/// <param name="dao">DAO the controller requires.</param>
public IncidentController(ICarRepairDAO dao)
{
_db = dao;
}
#region Incident
/// <summary>
/// Adds a new incident to the database from input of the front end.
/// </summary>
/// <param name="model">Inputs for the new incident</param>
/// <returns></returns>
[HttpPost("new")]
[Authorize(Roles = "Customer")]
public IActionResult AddIncident([FromBody] VehicleIncidentViewModel model)
{
IActionResult result = null;
try
{
if (ModelState.IsValid)
{
Vehicle vehicle = new Vehicle
{
Color = model.Color,
Make = model.Make,
Model = model.Model,
UserId = _db.GetUserIdByUsername(User.Identity.Name),
Vin = model.Vin,
Year = model.Year,
};
Incident incident = new Incident
{
Description = model.Description
};
incident.VehicleId = _db.AddVehicleItems(vehicle);
_db.AddIncident(incident);
result = Ok();
}
else
{
result = BadRequest(new { Message = "Required fields are not filled out properly" });
}
}
catch
{
result = BadRequest(new { Message = "Adding incident failed." });
}
return result;
}
/// <summary>
/// Returns a list of all the incidents for that user.
/// </summary>
/// <param name="username">Username to pull the incidents for</param>
/// <returns></returns>
[HttpGet("{username}")]
[Authorize]
public IActionResult GetIncidentsByUser(string username)
{
IActionResult result = Unauthorized();
List<DisplayIncidentsViewModel> model = new List<DisplayIncidentsViewModel>();
try
{
int userId = _db.GetUserIdByUsername(username);
List<Incident> userIncidents = _db.GetIncidentsByUser(userId);
foreach (var incident in userIncidents)
{
DisplayIncidentsViewModel modelLine = new DisplayIncidentsViewModel();
modelLine.Incident = incident;
modelLine.Vehicle = _db.GetVehicleByID(incident.VehicleId);
List<ItemizedIncidentLine> repairLines = _db.GetItemizedLines(incident.Id);
modelLine.Status = incident.GetStatus(repairLines);
model.Add(modelLine);
}
result = Ok(model);
}
catch (Exception ex)
{
result = BadRequest(new { Message = "Failed to retrieve incidents." });
}
return result;
}
/// <summary>
/// Retrieves list of all incidents.
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorize(Roles = "Employee, Administrator")]
public IActionResult GetIncidents()
{
// Check if user is employee or admin
IActionResult result = Unauthorized();
List<DisplayIncidentsViewModel> model = new List<DisplayIncidentsViewModel>();
try
{
List<Incident> incidents = _db.GetIncidents();
foreach (var incident in incidents)
{
DisplayIncidentsViewModel modelLine = new DisplayIncidentsViewModel();
modelLine.Incident = incident;
modelLine.Vehicle = _db.GetVehicleByID(incident.VehicleId);
List<ItemizedIncidentLine> repairLines = _db.GetItemizedLines(incident.Id);
modelLine.Status = incident.GetStatus(repairLines);
model.Add(modelLine);
}
result = Ok(model);
}
catch (Exception ex)
{
result = BadRequest(new { Message = "Failed to retrieve incidents." });
}
return result;
}
/// <summary>
/// Updates database to reflect the customer has paid for the incident.
/// </summary>
/// <param name="incidentId"> Incident id that was paid for.</param>
/// <returns></returns>
[HttpPut("paid")]
[Authorize(Roles = "Employee, Administrator")]
public IActionResult IncidentPaid([FromBody] PayIncidentViewModel model)
{
IActionResult result = Unauthorized();
try
{
if (ModelState.IsValid)
{
_db.IncidentPaid(model.IncidentId);
_db.AddPickUpDate(model.IncidentId, model.CompletedByDate);
result = Ok();
}
else
{
result = BadRequest(new { Message = "Required fields are not filled out properly" });
}
}
catch
{
result = BadRequest(new { Message = "Failed to mark incident paid." });
}
return result;
}
/// <summary>
/// Updates database to reflect the repair has been completed.
/// </summary>
/// <param name="incidentId"> Incident id that was completed.</param>
/// <returns></returns>
[HttpPut("complete")]
[Authorize(Roles = "Employee, Administrator")]
public IActionResult IncidentComplete([FromBody] CompleteIncidentViewModel model)
{
IActionResult result = Unauthorized();
try
{
if (ModelState.IsValid)
{
_db.IncidentComplete(model.IncidentId);
result = Ok();
}
else
{
result = BadRequest(new { Message = "Required fields are not filled out properly" });
}
}
catch
{
result = BadRequest(new { Message = "Failed to mark incident complete." });
}
return result;
}
#endregion
#region LineItem
/// <summary>
/// Pulls the repair lines of the incident to display.
/// </summary>
/// <param name="incidentId">Incient to pull repair lines for</param>
/// <returns></returns>
[HttpGet("repairlines/{incidentId}")]
[Authorize]
public IActionResult GetRepairItems(int incidentId)
{
IActionResult result = Unauthorized();
List<ItemizedIncidentLine> incidentDetailsViewModel = new List<ItemizedIncidentLine>();
try
{
var repairLinesItems = _db.GetItemizedLines(incidentId);
result = Ok(repairLinesItems);
}
catch (Exception ex)
{
result = BadRequest(new { Message = "Get repair Lines failed." });
}
return result;
}
/// <summary>
/// Adds a new line item to a incident.
/// </summary>
/// <param name="model">Details for the line to be added</param>
/// <returns></returns>
[HttpPost("line/add")]
[Authorize(Roles = "Employee, Administrator")]
public IActionResult AddNewItemizedLine([FromBody] RepairLineViewModel model)
{
IActionResult result = Unauthorized();
try
{
if (ModelState.IsValid)
{
ItemizedIncidentLine itemizedIncidentLine = new ItemizedIncidentLine
{
Cost = model.Cost,
Description = model.Description,
TimeHours = model.TimeHours,
IncidentId = model.IncidentId,
Approved = false,
Declined = false
};
//Check if incidents exists
Incident existingIncident = _db.GetIncidentById(model.IncidentId);
//if vehicle does exist, add incident to vehicle
if (existingIncident != null)
{
itemizedIncidentLine.IncidentId = existingIncident.Id;
itemizedIncidentLine.Id = _db.AddItemizedLine(itemizedIncidentLine);
result = Ok(itemizedIncidentLine);
}
}
else
{
result = BadRequest(new { Message = "Incident does not Exist." });
}
}
catch
{
result = BadRequest(new { Message = "Adding new repair line failed." });
}
return result;
}
/// Updates database to approve the item customer marks as accepted.
/// </summary>
/// <param name="lineId">line item to approve</param>
/// <returns></returns>
[HttpPut("line/approve")]
[Authorize(Roles = "Customer")]
public IActionResult ApproveLineItem([FromBody] ApproveRepairViewModel model)
{
IActionResult result = Unauthorized();
try
{
ItemizedIncidentLine line = _db.GetItemizedLineById(model.LineId);
if (!line.Declined)
{
_db.ApproveLineItem(model.LineId);
result = Ok();
}
else
{
result = BadRequest(new { Message = "Line declined already, can't approve now." });
}
}
catch
{
result = BadRequest(new { Message = "Approving repair line failed." });
}
return result;
}
/// <summary>
/// Updates database to approve the item customer marks as declined.
/// </summary>
/// <param name="model">line item to approve</param>
/// <returns></returns>
[HttpPut("line/decline")]
[Authorize(Roles = "Customer")]
public IActionResult DeclineLineItem([FromBody] ApproveRepairViewModel model)
{
IActionResult result = Unauthorized();
try
{
ItemizedIncidentLine line = _db.GetItemizedLineById(model.LineId);
if (!line.Approved)
{
_db.DeclineLineItem(model.LineId);
result = Ok();
}
else
{
result = BadRequest(new { Message = "Line approved already, can't decline now." });
}
}
catch
{
result = BadRequest(new { Message = "Declining repair line failed." });
}
return result;
}
[HttpPut("line/edit")]
[Authorize(Roles = "Employee, Administrator")]
public IActionResult EditLineItem(UpdateRepairItemViewModel model)
{
IActionResult result = Unauthorized();
try
{
ItemizedIncidentLine line = _db.GetItemizedLineById(model.LineId);
line.Description = model.Description;
line.Cost = model.Cost;
line.TimeHours = model.TimeHours;
_db.EditLineItem(line);
}
catch
{
result = BadRequest(new { Message = "Unable to update Incident Line." });
}
return result;
}
#endregion
}
}
<file_sep>import axios from 'axios';
import auth from "@/shared/auth";
export class APIService {
constructor() {
}
async login(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/account/login`;
let response;
try {
response = await axios.post(url, data);
} catch (error) {
if (error.response.status != 200) {
throw "Your username and/or password is invalid";
}
}
return response.data;
}
async register(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/account/register`;
let res = await axios.post(url, data);
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
async registerEmployee(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/account/register/employee`;
let res = await axios.post(url, data, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
});
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
getUserById(userId) {
const url = `${process.env.VUE_APP_REMOTE_API}/account/user/${userId}`;
return axios.get(url, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
}).then(response => response.data);
}
async postIncident(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/new`;
let res = await axios.post(url, data, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
});
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
async putPayIncident(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/paid`;
let res = await axios.put(url, data, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
});
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
async markIncidentComplete(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/complete`;
let res = await axios.put(url, data, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
});
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
getUserIncidents() {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/${auth.getUser().sub}`;
return axios.get(url, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
}).then(response => response.data);
}
getIncidents() {
const url = `${process.env.VUE_APP_REMOTE_API}/incident`;
return axios.get(url, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
}).then(response => response.data);
}
getRepairLines(incidentId) {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/repairlines/${incidentId}`;
return axios.get(url, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
}).then(response => response.data);
}
async addRepairLine(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/line/add`;
let res = await axios.post(url, data, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
});
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
async approveRepairLine(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/line/approve`;
let res = await axios.put(url, data, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
});
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
async declineRepairLine(data) {
const url = `${process.env.VUE_APP_REMOTE_API}/incident/line/decline`;
let res = await axios.put(url, data, {
headers: {
Authorization: "Bearer " + auth.getToken()
}
});
if (res.status === 400) {
throw res.data.message;
}
return res.data;
}
}<file_sep>using ParkGeek.DAL.Models;
using System;
using System.Collections.Generic;
namespace ParkGeek
{
public interface IParkGeekDAO
{
ParkModel GetPark(string parkCode);
IList<ParkModel> GetParks();
}
}
<file_sep>using System;
namespace HomeBrew
{
public class HomeBrewCalculator
{
const string ABV_MENU = "Welcome to the ABV Calculator!!\n" +
"Use This Calculator to determine the Alcohol By Volome in your brew. \n" +
"===============================\n";
const string CONST_REQUEST_ORIGINALGRAVITY = "Please enter Original Gravity (1.000 - 1.130): ";
const string CONST_REQUEST_FINALGRAVITY = "Please Enter Final Gravity (1.000 - 1.130): ";
public void AbvCalcOpenMenu()
{
bool repeatMethod = true;
while (repeatMethod)
{
Console.Clear();
Console.Write(ABV_MENU);
Console.Write(CONST_REQUEST_ORIGINALGRAVITY);
string oGravity = Console.ReadLine();
Console.Write(CONST_REQUEST_FINALGRAVITY);
string fGravity = Console.ReadLine();
double resultABV = RunABVCalc(oGravity, fGravity);
Console.WriteLine($"Your Brew's ABV is {string.Format("{0:0.00}", resultABV)} \n" +
"===============================\n" +
"New Calculation or Return to Main Menu?\n" +
"1.) New Calculation\n" +
"2.) Main Menu");
Console.Write("Selection: ");
string selection = Console.ReadLine();
if (selection == "1")
{
repeatMethod = true;
}
else if (selection == "2")
{
repeatMethod = false;
}
}
}
private double RunABVCalc(string oGravity, string fGravity)
{
double resultABV = 0.0;
//Convert user string inputs to doubles
double oGDouble = Convert.ToDouble(oGravity);
double oFDouble = Convert.ToDouble(fGravity);
//Calculates ABV
resultABV = (oGDouble - oFDouble) * 131.25;
return resultABV;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace CarRepairService.Models
{
[Serializable]
public class Incident : Item
{
private const string COMPLETED = "Completed";
private const string REPAIRING = "In Progress";
private const string EVALUATION = "Awaiting Evaluation";
private const string NEEDPAYMENT = "Awaiting Payment";
private const string NEEDAPPROVAL = "Awaiting Approval";
public int VehicleId { get; set; }
public string Description { get; set; }
public DateTime SubmittedDate { get; set; } = DateTime.Now;
public DateTime? PickupDate { get; set; } = null;
public bool Paid { get; set; } = false;
public bool Completed { get; set; } = false;
/// <summary>
/// Returns the status of the incident based on its state and the state
/// of it's repair lines.
/// </summary>
/// <param name="repairLines">Repairlines to check status off</param>
/// <returns></returns>
public string GetStatus(List<ItemizedIncidentLine> repairLines)
{
string status = "Submitted";
int pendingLines = 0;
// Check if there are any pending repair lines.
foreach (var repairLine in repairLines)
{
if ( !(repairLine.Approved || repairLine.Declined) )
{
pendingLines++;
}
}
if (Completed)
{
status = COMPLETED;
}
else if (PickupDate != null && Paid)
{
status = REPAIRING;
}
else if (repairLines.Count == 0)
{
status = EVALUATION;
}
else if (pendingLines != 0)
{
status = NEEDAPPROVAL;
}
else if (!Paid)
{
status = NEEDPAYMENT;
}
return status;
}
}
} | 14d3b62f96616d98f7f48293a49b50197ea731f6 | [
"JavaScript",
"C#"
] | 42 | C# | jessefoltz1/Portfolio | f4e34e27ec35a64364f54ea6ffeda5367dbbf745 | 552caeec7e719672d9a30e13b5d20d5a142d45f7 |
refs/heads/master | <repo_name>sohardforaname/TongJi-University-DataStructure-Design<file_sep>/String.cpp
#include "String.h"
const size_t newSize = 16;
String::String()
{
this->size = newSize;
this->buffer = new char[newSize];
}
String::String(const char* str_)
{
this->size = strlen(str_);
buffer = new char[this->size + 1];
strcpy(this->buffer, str_);
buffer[this->size] = 0;
}
String::String(const char* str_, size_t size_)
{
this->size = std::min(size_, strlen(str_));
buffer = new char[this->size + 1];
memcpy(this->buffer, str_, this->size);
buffer[this->size] = 0;
}
String::String(const char ch_, size_t size_)
{
this->size = size_;
buffer = new char[this->size + 1];
buffer[this->size] = 0;
memset(buffer, ch_, size_);
}
String::String(const String& str_)
{
this->size = str_.size;
buffer = new char[this->size + 1];
strcpy(this->buffer, str_.buffer);
buffer[this->size] = 0;
}
String::~String()
{
delete[]this->buffer;
}
size_t String::GetSize() const
{
return this->size;
}
void String::Append(const String& str_)
{
char* buffer = new char[this->size + str_.size + 1];
strcpy(buffer, this->buffer);
strcpy(buffer + this->size, str_.buffer);
this->size += str_.size;
buffer[this->size] = 0;
delete[]this->buffer;
this->buffer = buffer;
}
void String::Append(const char* str_)
{
size_t size_ = strlen(str_);
char* buffer = new char[this->size + size_ + 1];
strcpy(buffer, this->buffer);
strcpy(buffer + this->size, str_);
this->size += size_;
buffer[this->size] = 0;
delete[]this->buffer;
this->buffer = buffer;
}
void String::Append(const char* str_, size_t size_)
{
size_t size = std::min(strlen(str_), size_);
char* buffer = new char[this->size + size + 1];
strcpy(buffer, this->buffer);
strcpy(buffer + this->size, str_);
this->size += size;
buffer[this->size] = 0;
delete[]this->buffer;
this->buffer = buffer;
}
void String::Append(const char ch_)
{
char* buffer = new char[this->size + 2];
strcpy(buffer, this->buffer);
buffer[this->size] = ch_;
buffer[++this->size] = 0;
delete[]this->buffer;
this->buffer = buffer;
}
const char* String::GetCstr() const
{
return this->buffer;
}
char& String::operator[](size_t index_)
{
if (index_ >= this->size || index_ < 0)
throw std::out_of_range("index out of range");
return buffer[index_];
}
const char& String::operator[](size_t index_) const
{
if (index_ >= this->size || index_ < 0)
throw std::out_of_range("index out of range");
return buffer[index_];
}
String operator+(const String& str1_, const String& str2_)
{
String str(str1_);
str.Append(str2_);
return str;
}
String operator+(const String& str1_, const char* str2_)
{
String str(str1_);
str.Append(str2_);
return str;
}
String operator+(const String& str1_, const char ch2_)
{
String str(str1_);
str.Append(ch2_);
return str;
}
String operator+(const char* str1_, const String& str2_)
{
String str(str1_);
str.Append(str2_);
return str;
}
String operator+(const char ch1_, const String& str2_)
{
String str(ch1_, 1);
str.Append(str2_);
return str;
}
bool String::operator==(const String& str_) const
{
return this->size == str_.size && !strcmp(this->buffer, str_.buffer);
}<file_sep>/List.hpp
#pragma once
#include <stdexcept>
template<class T>
struct ListNode
{
ListNode* next;
ListNode* prev;
T* dat;
ListNode() : next(nullptr), prev(nullptr), dat(nullptr) {}
ListNode(const T& dat_) : next(nullptr), prev(nullptr), dat(new T(dat_)) {}
~ListNode() { delete dat; }
};
template<class T>
class List
{
private:
ListNode<T> head;
size_t size;
public:
List() : head(), size(0)
{
this->head.next = &this->head;
this->head.prev = &this->head;
}
List(const List& list_) : size(list_.size)
{
this->head.next = &this->head;
this->head.prev = &this->head;
ListNode<T>* newHead = &this->head, * newPtr = this->head.next;
const ListNode<T>* oldHead = &(list_.head), * oldPtr = (list_.head).next;
while (oldPtr != oldHead)
{
newPtr = new ListNode<T>();
newPtr->dat = new T(*(oldPtr->dat));
newPtr->prev = newHead;
newHead->next = newPtr;
newPtr = newPtr->next;
newHead = newHead->next;
oldPtr = oldPtr->next;
}
this->head.prev = newHead;
newHead->next = &(this->head);
}
~List()
{
ListNode<T>* ptr = this->head.next, * cur;
while (ptr != &(this->head))
{
cur = ptr;
ptr = ptr->next;
delete cur;
}
}
void PushBack(const T& val_)
{
ListNode<T>* ptr = new ListNode<T>(val_);
this->head.prev->next = ptr;
ptr->prev = this->head.prev;
this->head.prev = ptr;
ptr->next = &(this->head);
++this->size;
}
void PushFront(const T& val_)
{
ListNode<T>* ptr = new ListNode<T>(val_);
this->head.next->prev = ptr;
ptr->next = this->head.next;
this->head.next = ptr;
ptr->prev = &(this->head);
++this->size;
}
void PopBack()
{
if (!this->size)
throw std::out_of_range("no element to be popped");
ListNode<T>* ptr = this->head.prev;
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
delete ptr;
}
void PopFront()
{
if (!this->size)
throw std::out_of_range("no element to be popped");
ListNode<T>* ptr = this->head.next;
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
delete ptr;
}
template<class Ty1, class EqualFunc>
ListNode<T>* FindNode(const Ty1& ty1_, const EqualFunc& func)
{
ListNode<T>* ptr = this->head.next;
while (ptr != &(this->head))
{
if (func(ty1_, *(ptr->dat)))
return ptr;
ptr = ptr->next;
}
return nullptr;
}
void Erase(ListNode<T>* ptr_)
{
if (!ptr_)
throw std::runtime_error("Nullptr");
ptr_->prev->next = ptr_->next;
ptr_->next->prev = ptr_->prev;
--this->size;
delete ptr_;
}
};<file_sep>/Vector.hpp
#pragma once
#include <stdexcept>
const size_t newSize = 16;
template<class T>
class Vector
{
private:
T* dat;
size_t size, capacity;
private:
void Reserve(size_t capacity_)
{
if (this->capacity >= capacity_)
return;
//T* dat_ = reinterpret_cast<T*>(malloc(sizeof(T) * capacity_));
T* dat_ = (T*)malloc(sizeof(T) * capacity_);
for (size_t i = 0; i < this->size; ++i)
new (dat_ + i) T(dat[i]);
for (size_t i = 0; i < this->size; ++i)
this->dat[i].~T();
free(dat);
dat = dat_;
this->capacity = capacity_;
}
public:
Vector()
{
this->size = 0;
this->capacity = newSize;
dat = (T*)malloc(sizeof(T) * this->capacity);
}
Vector(size_t size_)
{
this->size = size_;
this->capacity = std::max(size_, newSize);
dat = (T*)malloc(sizeof(T) * this->capacity);
for (size_t i = 0; i < this->size; ++i)
new (dat + i) T();
}
Vector(size_t size_, const T& dat_)
{
this->size = size_;
this->capacity = std::max(size_, newSize);
dat = (T*)malloc(sizeof(T) * this->capacity);
for(size_t i =0 ;i<this->size; ++i)
new (dat + i) T(dat_);
}
Vector(const Vector& vec_)
{
this->size = vec_.size;
this->capacity = vec_.capacity;
dat = (T*)malloc(sizeof(T) * this->capacity);
for (size_t i = 0; i < this->size; ++i)
new (dat + i) T(vec_.dat[i]);
}
~Vector()
{
for (size_t i = 0; i < this->size; ++i)
;//this->dat[i].~T();
free(dat);
}
size_t GetSize() const
{
return this->size;
}
size_t GetCapacity()
{
return this->capacity;
}
void Resize(size_t size_)
{
Reserve(size_ + (size_ >> 1));
if (this->size <= size_)
for (size_t i = this->size; i < size_; ++i)
new(dat + size++) T();
else
for (size_t i = this->size; i > size_; --i)
PopBack();
this->size = size_;
}
void PushBack(const T& dat_)
{
if (this->size == this->capacity)
Reserve(this->capacity + (this->capacity >> 1));
new(dat + size++) T(dat_);
}
void PopBack()
{
--this->size;
if (this->size < (this->capacity >> 2))
Reserve(this->capacity >> 1);
}
void Append(const Vector& vec_)
{
if (this->capacity < this->size + vec_.size)
Reserve(this->size + vec_.size);
for (size_t i = 0; i < vec_.size; ++i)
this->dat[i + this->size] = vec_.dat[i];
this->size += vec_.size;
}
void Erase(const size_t& index_)
{
if (index_ >= this->size)
throw std::out_of_range("index out of range");
for (size_t i = index_; i < this->size - 1; ++i)
{
dat[i].~T();
new (dat + i) T(dat[i + 1]);
}
--this->size;
if (this->size < (this->capacity >> 2))
Reserve(this->capacity >> 1);
}
T& At(size_t index_)
{
if (index_ >= this->size)
throw std::out_of_range("index out of range");
return dat[index_];
}
T& operator[](size_t index_)
{
return At(index_);
}
const T& At(size_t index_) const
{
if (index_ >= this->size)
throw std::out_of_range("index out of range");
return dat[index_];
}
const T& operator[](size_t index_) const
{
return At(index_);
}
bool operator==(const Vector& vec_)
{
if (this->size != vec_.size)
return false;
for (size_t i = 0; i < this->size; ++i)
if (!(this->dat[i] == vec_.dat[i]))
return false;
return true;
}
bool operator!=(const Vector& vec_)
{
return !(*this == vec_);
}
};<file_sep>/Trie.hpp
#pragma once
#include "HashTable.hpp"
#include "Hash.h"
template<class K, class Ar, class V>
class Trie
{
private:
Vector<HashTable<K, size_t>> buffer;
HashTable<size_t, V>indexTable;
public:
Trie() : buffer(1) {}
Trie(const Trie& trie_)
: buffer(trie_.buffer), indexTable(trie_.indexTable) {}
~Trie() {}
void Insert(const Ar& array_, const V& val_)
{
size_t root = 0;
for (size_t i = 0; i < array_.GetSize(); ++i)
{
const K& nxt = array_[i];
auto ptr = buffer[root].Find(nxt);
if (!ptr)
{
buffer[root].Insert(nxt, buffer.GetSize());
root = buffer.GetSize();
buffer.PushBack(HashTable<K, size_t>());
}
else
root = *ptr;
}
indexTable[root] = val_;
}
void Erase(const Ar& array_)
{
size_t root = 0;
for (size_t i = 0; i < array_.GetSize(); ++i)
{
const K& nxt = array_[i];
auto ptr = buffer[root].Find(nxt);
if (!ptr)
return;
root = *ptr;
}
indexTable.Erase(root);
}
V* Find(const Ar& array_)
{
size_t root = 0;
for (size_t i = 0; i < array_.GetSize(); ++i)
{
const K& nxt = array_[i];
auto ptr = buffer[root].Find(nxt);
if (!ptr)
return nullptr;
root = *ptr;
}
return indexTable.Find(root);
}
V* operator[](const Ar& array_)
{
return Find(array_);
}
size_t GetSize() const
{
return indexTable.GetSize();
}
};
<file_sep>/Hash.h
#pragma once
const size_t cBeginVal = 998244353;
const size_t mulFactor = 16777619;
template<class T>
struct hash
{
static size_t GetHash(const unsigned char* valPtr, const size_t& size)
{
size_t beginVal = cBeginVal;
for (size_t i = 0; i < size; ++i)
beginVal = (beginVal ^ valPtr[i]) * mulFactor;
return beginVal;
}
size_t operator()(const T& key)
{
return this->GetHash(reinterpret_cast<const unsigned char*>(&key), sizeof(T));
}
};<file_sep>/singlefile.cpp
#include <algorithm>
#include <cstring>
#include <stdexcept>
class String
{
private:
char *buffer;
size_t size;
public:
String();
String(const char *str_);
String(const char *str_, size_t size_);
String(const char ch_, size_t size_);
String(const String &str_);
~String();
size_t GetSize() const;
void Append(const String &str_);
void Append(const char *str_);
void Append(const char *str_, size_t size_);
void Append(const char ch_);
const char *GetCstr() const;
const char &operator[](size_t index_) const;
char &operator[](size_t index_);
bool operator==(const String &str_) const;
};
String operator+(const String &str1_, const String &str2_);
String operator+(const String &str1_, const char *str2_);
String operator+(const String &str1_, const char ch2_);
String operator+(const char *str1_, const String &str2_);
String operator+(const char ch1_, const String &str2_);
const size_t newSize = 16;
String::String()
{
this->size = newSize;
this->buffer = new char[newSize];
}
String::String(const char *str_)
{
this->size = strlen(str_);
buffer = new char[this->size + 1];
strcpy(this->buffer, str_);
buffer[this->size] = 0;
}
String::String(const char *str_, size_t size_)
{
this->size = std::min(size_, strlen(str_));
buffer = new char[this->size + 1];
memcpy(this->buffer, str_, this->size);
buffer[this->size] = 0;
}
String::String(const char ch_, size_t size_)
{
this->size = size_;
buffer = new char[this->size + 1];
buffer[this->size] = 0;
memset(buffer, ch_, size_);
}
String::String(const String &str_)
{
this->size = str_.size;
buffer = new char[this->size + 1];
strcpy(this->buffer, str_.buffer);
buffer[this->size] = 0;
}
String::~String()
{
delete[] this->buffer;
}
size_t String::GetSize() const
{
return this->size;
}
void String::Append(const String &str_)
{
char *buffer = new char[this->size + str_.size + 1];
strcpy(buffer, this->buffer);
strcpy(buffer + this->size, str_.buffer);
this->size += str_.size;
buffer[this->size] = 0;
delete[] this->buffer;
this->buffer = buffer;
}
void String::Append(const char *str_)
{
size_t size_ = strlen(str_);
char *buffer = new char[this->size + size_ + 1];
strcpy(buffer, this->buffer);
strcpy(buffer + this->size, str_);
this->size += size_;
buffer[this->size] = 0;
delete[] this->buffer;
this->buffer = buffer;
}
void String::Append(const char *str_, size_t size_)
{
size_t size = std::min(strlen(str_), size_);
char *buffer = new char[this->size + size + 1];
strcpy(buffer, this->buffer);
strcpy(buffer + this->size, str_);
this->size += size;
buffer[this->size] = 0;
delete[] this->buffer;
this->buffer = buffer;
}
void String::Append(const char ch_)
{
char *buffer = new char[this->size + 2];
strcpy(buffer, this->buffer);
buffer[this->size] = ch_;
buffer[++this->size] = 0;
delete[] this->buffer;
this->buffer = buffer;
}
const char *String::GetCstr() const
{
return this->buffer;
}
char &String::operator[](size_t index_)
{
if (index_ >= this->size || index_ < 0)
throw std::out_of_range("index out of range");
return buffer[index_];
}
const char &String::operator[](size_t index_) const
{
if (index_ >= this->size || index_ < 0)
throw std::out_of_range("index out of range");
return buffer[index_];
}
String operator+(const String &str1_, const String &str2_)
{
String str(str1_);
str.Append(str2_);
return str;
}
String operator+(const String &str1_, const char *str2_)
{
String str(str1_);
str.Append(str2_);
return str;
}
String operator+(const String &str1_, const char ch2_)
{
String str(str1_);
str.Append(ch2_);
return str;
}
String operator+(const char *str1_, const String &str2_)
{
String str(str1_);
str.Append(str2_);
return str;
}
String operator+(const char ch1_, const String &str2_)
{
String str(ch1_, 1);
str.Append(str2_);
return str;
}
bool String::operator==(const String &str_) const
{
return this->size == str_.size && !strcmp(this->buffer, str_.buffer);
}
template <class T>
class Vector
{
private:
T *dat;
size_t size, capacity;
private:
void Reserve(size_t capacity_)
{
if (this->capacity >= capacity_)
return;
//T* dat_ = reinterpret_cast<T*>(malloc(sizeof(T) * capacity_));
T *dat_ = (T *)malloc(sizeof(T) * capacity_);
for (size_t i = 0; i < this->size; ++i)
new (dat_ + i) T(dat[i]);
for (size_t i = 0; i < this->size; ++i)
this->dat[i].~T();
free(dat);
dat = dat_;
this->capacity = capacity_;
}
public:
Vector()
{
this->size = 0;
this->capacity = newSize;
dat = (T *)malloc(sizeof(T) * this->capacity);
}
Vector(size_t size_)
{
this->size = size_;
this->capacity = std::max(size_, newSize);
dat = (T *)malloc(sizeof(T) * this->capacity);
for (size_t i = 0; i < this->size; ++i)
new (dat + i) T();
}
Vector(size_t size_, const T &dat_)
{
this->size = size_;
this->capacity = std::max(size_, newSize);
dat = (T *)malloc(sizeof(T) * this->capacity);
for (size_t i = 0; i < this->size; ++i)
new (dat + i) T(dat_);
}
Vector(const Vector &vec_)
{
this->size = vec_.size;
this->capacity = vec_.capacity;
dat = (T *)malloc(sizeof(T) * this->capacity);
for (size_t i = 0; i < this->size; ++i)
new (dat + i) T(vec_.dat[i]);
}
~Vector()
{
for (size_t i = 0; i < this->size; ++i)
; //this->dat[i].~T();
free(dat);
}
size_t GetSize() const
{
return this->size;
}
size_t GetCapacity()
{
return this->capacity;
}
void Resize(size_t size_)
{
Reserve(size_ + (size_ >> 1));
if (this->size <= size_)
for (size_t i = this->size; i < size_; ++i)
new (dat + size++) T();
else
for (size_t i = this->size; i > size_; --i)
PopBack();
this->size = size_;
}
void PushBack(const T &dat_)
{
if (this->size == this->capacity)
Reserve(this->capacity + (this->capacity >> 1));
new (dat + size++) T(dat_);
}
void PopBack()
{
--this->size;
if (this->size < (this->capacity >> 2))
Reserve(this->capacity >> 1);
}
void Append(const Vector &vec_)
{
if (this->capacity < this->size + vec_.size)
Reserve(this->size + vec_.size);
for (size_t i = 0; i < vec_.size; ++i)
this->dat[i + this->size] = vec_.dat[i];
this->size += vec_.size;
}
void Erase(const size_t &index_)
{
if (index_ >= this->size)
throw std::out_of_range("index out of range");
for (size_t i = index_; i < this->size - 1; ++i)
{
dat[i].~T();
new (dat + i) T(dat[i + 1]);
}
--this->size;
if (this->size < (this->capacity >> 2))
Reserve(this->capacity >> 1);
}
T &At(size_t index_)
{
if (index_ >= this->size)
throw std::out_of_range("index out of range");
return dat[index_];
}
T &operator[](size_t index_)
{
return At(index_);
}
const T &At(size_t index_) const
{
if (index_ >= this->size)
throw std::out_of_range("index out of range");
return dat[index_];
}
const T &operator[](size_t index_) const
{
return At(index_);
}
bool operator==(const Vector &vec_)
{
if (this->size != vec_.size)
return false;
for (size_t i = 0; i < this->size; ++i)
if (!(this->dat[i] == vec_.dat[i]))
return false;
return true;
}
bool operator!=(const Vector &vec_)
{
return !(*this == vec_);
}
};
template <class T>
struct ListNode
{
ListNode *next;
ListNode *prev;
T *dat;
ListNode() : next(nullptr), prev(nullptr), dat(nullptr) {}
ListNode(const T &dat_) : next(nullptr), prev(nullptr), dat(new T(dat_)) {}
~ListNode() { delete dat; }
};
template <class T>
class List
{
private:
ListNode<T> head;
size_t size;
public:
List() : head(), size(0)
{
this->head.next = &this->head;
this->head.prev = &this->head;
}
List(const List &list_) : size(list_.size)
{
this->head.next = &this->head;
this->head.prev = &this->head;
ListNode<T> *newHead = &this->head, *newPtr = this->head.next;
const ListNode<T> *oldHead = &(list_.head), *oldPtr = (list_.head).next;
while (oldPtr != oldHead)
{
newPtr = new ListNode<T>();
newPtr->dat = new T(*(oldPtr->dat));
newPtr->prev = newHead;
newHead->next = newPtr;
newPtr = newPtr->next;
newHead = newHead->next;
oldPtr = oldPtr->next;
}
this->head.prev = newHead;
newHead->next = &(this->head);
}
~List()
{
ListNode<T> *ptr = this->head.next, *cur;
while (ptr != &(this->head))
{
cur = ptr;
ptr = ptr->next;
delete cur;
}
}
void PushBack(const T &val_)
{
ListNode<T> *ptr = new ListNode<T>(val_);
this->head.prev->next = ptr;
ptr->prev = this->head.prev;
this->head.prev = ptr;
ptr->next = &(this->head);
++this->size;
}
void PushFront(const T &val_)
{
ListNode<T> *ptr = new ListNode<T>(val_);
this->head.next->prev = ptr;
ptr->next = this->head.next;
this->head.next = ptr;
ptr->prev = &(this->head);
++this->size;
}
void PopBack()
{
if (!this->size)
throw std::out_of_range("no element to be popped");
ListNode<T> *ptr = this->head.prev;
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
delete ptr;
}
void PopFront()
{
if (!this->size)
throw std::out_of_range("no element to be popped");
ListNode<T> *ptr = this->head.next;
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
delete ptr;
}
template <class Ty1, class EqualFunc>
ListNode<T> *FindNode(const Ty1 &ty1_, const EqualFunc &func)
{
ListNode<T> *ptr = this->head.next;
while (ptr != &(this->head))
{
if (func(ty1_, *(ptr->dat)))
return ptr;
ptr = ptr->next;
}
return nullptr;
}
void Erase(ListNode<T> *ptr_)
{
if (!ptr_)
throw std::runtime_error("Nullptr");
ptr_->prev->next = ptr_->next;
ptr_->next->prev = ptr_->prev;
--this->size;
delete ptr_;
}
};
const size_t cBeginVal = 998244353;
const size_t mulFactor = 16777619;
template <class T>
struct hash
{
static size_t GetHash(const unsigned char *valPtr, const size_t &size)
{
size_t beginVal = cBeginVal;
for (size_t i = 0; i < size; ++i)
beginVal = (beginVal ^ valPtr[i]) * mulFactor;
return beginVal;
}
size_t operator()(const T &key)
{
return this->GetHash(reinterpret_cast<const unsigned char *>(&key), sizeof(T));
}
};
#include <utility>
template <class K, class V, class HashFunc = hash<K>>
class HashTable
{
private:
Vector<List<std::pair<K, V>>> buffer;
size_t size;
private:
static bool cmp(const K &key_, const std::pair<K, V> &node_)
{
return key_ == node_.first;
}
ListNode<std::pair<K, V>> *_Find(const K &key_)
{
return this->buffer
.At(HashFunc()(key_) % buffer.GetSize())
.FindNode(key_, HashTable::cmp);
}
void Rehash()
{
// todo: adjust hash table size
}
public:
HashTable() : size(0), buffer(newSize >> 1) {}
HashTable(const HashTable &table_) : size(table_.size), buffer(table_.buffer) {}
~HashTable() {}
V *Find(const K &key_)
{
auto ptr = _Find(key_);
return ptr ? &(ptr->dat->second) : nullptr;
}
void Insert(const K &key_, const V &value_)
{
auto ptr = _Find(key_);
if (!ptr)
{
this->buffer.At(HashFunc()(key_) % buffer.GetSize())
.PushFront({key_, value_});
++size;
}
else
ptr->dat->second = value_;
}
void Erase(const K &key_)
{
auto ptr = _Find(key_);
if (!ptr)
return;
this->buffer.At(HashFunc()(key_) % buffer.GetSize()).Erase(ptr);
--size;
}
V &operator[](const K &key_)
{
auto ptr = Find(key_);
if (ptr != nullptr)
return *ptr;
Insert(key_, V());
return *Find(key_);
}
size_t GetSize() const
{
return this->size;
}
};
template <class K, class Ar, class V>
class Trie
{
private:
Vector<HashTable<K, size_t>> buffer;
HashTable<size_t, V> indexTable;
public:
Trie() : buffer(1) {}
Trie(const Trie &trie_)
: buffer(trie_.buffer), indexTable(trie_.indexTable) {}
~Trie() {}
void Insert(const Ar &array_, const V &val_)
{
size_t root = 0;
for (size_t i = 0; i < array_.GetSize(); ++i)
{
const K &nxt = array_[i];
auto ptr = buffer[root].Find(nxt);
if (!ptr)
{
buffer[root].Insert(nxt, buffer.GetSize());
root = buffer.GetSize();
buffer.PushBack(HashTable<K, size_t>());
}
else
root = *ptr;
}
indexTable[root] = val_;
}
void Erase(const Ar &array_)
{
size_t root = 0;
for (size_t i = 0; i < array_.GetSize(); ++i)
{
const K &nxt = array_[i];
auto ptr = buffer[root].Find(nxt);
if (!ptr)
return;
root = *ptr;
}
indexTable.Erase(root);
}
V *Find(const Ar &array_)
{
size_t root = 0;
for (size_t i = 0; i < array_.GetSize(); ++i)
{
const K &nxt = array_[i];
auto ptr = buffer[root].Find(nxt);
if (!ptr)
return nullptr;
root = *ptr;
}
return indexTable.Find(root);
}
V *operator[](const Ar &array_)
{
return Find(array_);
}
size_t GetSize() const
{
return indexTable.GetSize();
}
};
template <class T>
class Heap
{
private:
Vector<T> buffer;
void HeapAdjustUp(size_t index_)
{
size_t cur = index_;
size_t par = (cur - 1) / 2;
T tmp = buffer[index_];
while (cur > 0)
{
if (!(buffer[par] < tmp))
break;
buffer[cur] = buffer[par];
cur = par;
par = (par - 1) / 2;
}
buffer[cur] = tmp;
}
void HeapAdjustDown(size_t beg_, size_t end_)
{
size_t cur = beg_;
size_t lc = (beg_ << 1) + 1;
T tmp = buffer[beg_];
while (lc <= end_)
{
if (lc < end_ && buffer[lc] < buffer[lc + 1])
++lc;
if (!(tmp < buffer[lc]))
break;
buffer[cur] = buffer[lc];
cur = lc;
lc = (lc << 1) + 1;
}
buffer[cur] = tmp;
}
public:
Heap() {}
Heap(const Heap &heap_) : buffer(heap_.buffer) {}
~Heap() {}
size_t GetSize()
{
return buffer.GetSize();
}
void Push(const T &val_)
{
buffer.PushBack(val_);
HeapAdjustUp(buffer.GetSize() - 1);
}
void Pop()
{
if (!buffer.GetSize())
throw std::out_of_range("empty heap");
std::swap(buffer[0], buffer[buffer.GetSize() - 1]);
buffer.PopBack();
if (buffer.GetSize())
HeapAdjustDown(0, buffer.GetSize() - 1);
}
const T &GetTop()
{
return buffer[0];
}
};
#include <cstdio>
struct Edge
{
size_t w, to;
Edge() {}
Edge(const size_t &_w, const size_t &_to) : w(_w), to(_to) {}
bool operator<(const Edge &e) const
{
return w > e.w;
}
};
Vector<Vector<Edge>> G;
size_t edgeCount;
size_t nodeCount;
Vector<size_t> dis, pre;
Vector<bool> vis, exist;
Heap<Edge> q;
size_t dijkstra(const size_t &s, const size_t &t, Vector<int> &path)
{
dis.Resize(G.GetSize());
pre.Resize(G.GetSize());
vis.Resize(G.GetSize());
for (size_t i = 0; i < dis.GetSize(); ++i)
dis[i] = INT_MAX;
for (size_t i = 0; i < vis.GetSize(); ++i)
vis[i] = 0;
dis[s] = 0;
q.Push(Edge(0, s));
while (q.GetSize())
{
Edge e = q.GetTop();
q.Pop();
if (vis[e.to])
continue;
int u = e.to;
vis[u] = 1;
for (size_t i = 0; i < G[u].GetSize(); ++i)
{
int v = G[e.to][i].to, w = G[e.to][i].w;
if (dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
pre[v] = u;
q.Push(Edge(dis[v], v));
}
}
}
path.Resize(0);
size_t cur = t;
while (cur != s)
{
path.PushBack(cur);
cur = pre[cur];
}
path.PushBack(cur);
return dis[t];
}
Trie<char, String, int> mpStrToInt;
Vector<String> mpIntToStr;
void PrintPath(const Vector<int> &path)
{
printf("path: \n");
for (size_t i = path.GetSize() - 1; int(i) >= 0; --i)
printf("%s%s", mpIntToStr[path[i]].GetCstr(), i ? " -> " : "\n");
}
bool LoadGraph(const char *filePath)
{
char *buffer = new char[1 << 10];
FILE *fp = fopen(filePath, "r");
if (!fp)
return printf("Can't load graph from: %s\n", filePath), false;
fscanf(fp, "%u", &nodeCount);
for (size_t i = 0; i < nodeCount; ++i)
{
fscanf(fp, "%s", buffer);
mpStrToInt.Insert(String(buffer), i);
mpIntToStr.PushBack(String(buffer));
}
exist.Resize(nodeCount);
for (size_t i = 0; i < exist.GetSize(); ++i)
exist[i] = true;
;
G.Resize(nodeCount);
fscanf(fp, "%u", &edgeCount);
for (size_t i = 0; i < edgeCount; ++i)
{
fscanf(fp, "%s", buffer);
int u = *mpStrToInt.Find(String(buffer));
fscanf(fp, "%s", buffer);
int v = *mpStrToInt.Find(String(buffer));
size_t w;
fscanf(fp, "%u", &w);
G[u].PushBack(Edge(w, v));
//G[v].PushBack(Edge(w, u));
}
fclose(fp);
delete[] buffer;
return true;
}
void StoreGraph(const char *filePath)
{
FILE *fp = fopen(filePath, "w");
fprintf(fp, "%u\n", mpStrToInt.GetSize());
for (size_t i = 0; i < mpIntToStr.GetSize(); ++i)
if (exist[i])
fprintf(fp, "%s\n", mpIntToStr[i].GetCstr());
fprintf(fp, "%u\n", edgeCount);
for (size_t i = 0; i < G.GetSize(); ++i)
for (size_t j = 0; exist[i] && j < G[i].GetSize(); ++j)
fprintf(fp, "%s %s %u\n", mpIntToStr[i].GetCstr(),
mpIntToStr[G[i][j].to].GetCstr(), G[i][j].w);
fclose(fp);
}
void AddPoint(const String &point)
{
auto ptr1 = mpStrToInt.Find(point);
if (ptr1)
return;
nodeCount++;
mpStrToInt.Insert(point, mpIntToStr.GetSize());
exist.PushBack(true);
mpIntToStr.PushBack(point);
G.PushBack(Vector<Edge>());
}
void DeletePoint(const String &point)
{
const auto ptr1 = mpStrToInt.Find(point);
if (!ptr1)
return;
for (size_t i = 0; i < G.GetSize(); ++i)
{
if (i == *ptr1)
continue;
Vector<int> v;
for (size_t j = 0; j < G[i].GetSize(); ++j)
if (G[i][j].to == *ptr1)
v.PushBack(j);
for (int j = v.GetSize() - 1; j >= 0; --j)
G[i].Erase(v[j]);
edgeCount -= v.GetSize();
}
edgeCount -= G[*ptr1].GetSize();
--nodeCount;
exist[*ptr1] = false;
mpStrToInt.Erase(point);
}
void AddEdge(const String &from, const String &to, size_t w)
{
AddPoint(from);
AddPoint(to);
G[*mpStrToInt[from]].PushBack(Edge(w, *mpStrToInt[to]));
}
void DeleteEdge(const String &from, const String &to)
{
auto ptr1 = mpStrToInt.Find(from);
if (!ptr1)
return;
auto ptr2 = mpStrToInt.Find(to);
if (!ptr2)
return;
for (size_t i = 0; i < G[*ptr1].GetSize(); ++i)
if (G[*ptr1][i].to == *ptr2)
{
G[*ptr1].Erase(i);
break;
}
--edgeCount;
}
char op[10], buf1[1 << 4], buf2[1 << 4];
size_t w;
void PrintMenu()
{
printf("What do you want to do?\n");
printf("1. Load Graph\n");
printf("2. Store Graph\n");
printf("3. Add an edge\n");
printf("4. Delete an edge\n");
printf("5. Add a point\n");
printf("6. Delete a point\n");
printf("7. Get the shortest path\n");
printf("press number to choose, 0 to exit\n");
}
Vector<int> p;
int main()
{
while (1)
{
PrintMenu();
scanf("%s", op);
printf("\n");
if (op[0] == '0')
break;
switch (op[0] - '0')
{
case 1:
printf("Input the path of the file\n");
scanf("%s", buf1);
LoadGraph(buf1);
break;
case 2:
printf("Input the path of the file\n");
scanf("%s", buf1);
StoreGraph(buf1);
break;
case 3:
printf("Input the point from ans point to and weight\n");
scanf("%s%s%u", buf1, buf2, &w);
AddEdge(buf1, buf2, w);
break;
case 4:
printf("Input the point from ans point to\n");
scanf("%s%s", buf1, buf2);
DeleteEdge(buf1, buf2);
break;
case 5:
printf("Input the point\n");
scanf("%s", buf1);
AddPoint(buf1);
break;
case 6:
printf("Input the point\n");
scanf("%s", buf1);
DeletePoint(buf1);
break;
case 7:
printf("Input the point from ans point to\n");
scanf("%s%s", buf1, buf2);
{
auto ptr1 = mpStrToInt[buf1];
auto ptr2 = mpStrToInt[buf2];
if (!ptr1 || !ptr2)
{
printf("not such point on the graph\n");
break;
}
printf("%u\n", dijkstra(
*ptr1, *ptr2, p));
PrintPath(p);
break;
}
default:
printf("Order not found\n");
}
system("pause");
system("cls");
}
return 0;
}<file_sep>/String.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <stdexcept>
#include <algorithm>
//class String;
class String
{
private:
char* buffer;
size_t size;
public:
String();
String(const char* str_);
String(const char* str_, size_t size_);
String(const char ch_, size_t size_);
String(const String& str_);
~String();
size_t GetSize() const;
void Append(const String& str_);
void Append(const char* str_);
void Append(const char* str_, size_t size_);
void Append(const char ch_);
const char* GetCstr() const;
const char& operator[](size_t index_) const;
char& operator[](size_t index_);
bool operator==(const String& str_) const;
};
String operator+(const String& str1_, const String& str2_);
String operator+(const String& str1_, const char* str2_);
String operator+(const String& str1_, const char ch2_);
String operator+(const char* str1_, const String& str2_);
String operator+(const char ch1_, const String& str2_);<file_sep>/README.md
# TongJi-University-DataStructure-Design
A Simple implementation of vector, list, hash table, trie using template for learning the STL
Just for learning, so iterators and traits are not implemented.
<file_sep>/Heap.hpp
#pragma once
#include "Vector.hpp"
template<class T>
class Heap
{
private:
Vector<T>buffer;
void HeapAdjustUp(size_t index_)
{
size_t cur = index_;
size_t par = (cur - 1) / 2;
T tmp = buffer[index_];
while (cur > 0)
{
if (!(buffer[par] < tmp))
break;
buffer[cur] = buffer[par];
cur = par;
par = (par - 1) / 2;
}
buffer[cur] = tmp;
}
void HeapAdjustDown(size_t beg_, size_t end_)
{
size_t cur = beg_;
size_t lc = (beg_ << 1) + 1;
T tmp = buffer[beg_];
while (lc <= end_)
{
if (lc < end_ && buffer[lc] < buffer[lc + 1])
++lc;
if (!(tmp < buffer[lc]))
break;
buffer[cur] = buffer[lc];
cur = lc;
lc = (lc << 1) + 1;
}
buffer[cur] = tmp;
}
public:
Heap() {}
Heap(const Heap& heap_) : buffer(heap_.buffer) {}
~Heap() {}
size_t GetSize()
{
return buffer.GetSize();
}
void Push(const T& val_)
{
buffer.PushBack(val_);
HeapAdjustUp(buffer.GetSize() - 1);
}
void Pop()
{
if (!buffer.GetSize())
throw std::out_of_range("empty heap");
std::swap(buffer[0], buffer[buffer.GetSize() - 1]);
buffer.PopBack();
if (buffer.GetSize())
HeapAdjustDown(0, buffer.GetSize() - 1);
}
const T& GetTop()
{
return buffer[0];
}
};<file_sep>/HashTable.hpp
#pragma once
#include "List.hpp"
#include "Vector.hpp"
#include <utility>
template<class K, class V, class HashFunc = hash<K>>
class HashTable
{
private:
Vector<List<std::pair<K, V>>> buffer;
size_t size;
private:
static bool cmp(const K& key_, const std::pair<K, V>& node_)
{
return key_ == node_.first;
}
ListNode<std::pair<K, V>>* _Find(const K& key_)
{
return this->buffer
.At(HashFunc()(key_) % buffer.GetSize())
.FindNode(key_, HashTable::cmp);
}
void Rehash()
{
// todo: adjust hash table size
}
public:
//HashTable() : size(0), buffer() { buffer.Resize(newSize >> 1); }
HashTable() : size(0), buffer(newSize >> 1) {}
HashTable(const HashTable& table_) : size(table_.size), buffer(table_.buffer) {}
~HashTable() {}
V* Find(const K& key_)
{
auto ptr = _Find(key_);
return ptr ? &(ptr->dat->second) : nullptr;
}
void Insert(const K& key_, const V& value_)
{
auto ptr = _Find(key_);
if (!ptr)
{
this->buffer.At(HashFunc()(key_) % buffer.GetSize())
.PushFront({ key_, value_ });
++size;
}
else
ptr->dat->second = value_;
}
void Erase(const K& key_)
{
auto ptr = _Find(key_);
if (!ptr)
return;
this->buffer.At(HashFunc()(key_) % buffer.GetSize()).Erase(ptr);
--size;
}
V& operator[](const K& key_)
{
auto ptr = Find(key_);
if (ptr != nullptr)
return *ptr;
Insert(key_, V());
return *Find(key_);
}
size_t GetSize() const
{
return this->size;
}
};<file_sep>/main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "HashTable.hpp"
#include "Trie.hpp"
#include "String.h"
#include "Heap.hpp"
#include <cstdio>
struct Edge
{
size_t w, to;
Edge() {}
Edge(const size_t& _w, const size_t& _to) :
w(_w), to(_to) {}
bool operator<(const Edge& e) const
{
return w > e.w;
}
};
Vector<Vector<Edge>>G;
size_t edgeCount;
size_t nodeCount;
Vector<size_t> dis, pre;
Vector<bool> vis, exist;
Heap<Edge>q;
size_t dijkstra(const size_t& s, const size_t& t, Vector<int>& path)
{
dis.Resize(G.GetSize());
pre.Resize(G.GetSize());
vis.Resize(G.GetSize());
for (size_t i = 0; i < dis.GetSize(); ++i)
dis[i] = INT_MAX;
for (size_t i = 0; i < vis.GetSize(); ++i)
vis[i] = 0;
dis[s] = 0;
q.Push(Edge(0, s));
while (q.GetSize())
{
Edge e = q.GetTop();
q.Pop();
if (vis[e.to])
continue;
int u = e.to;
vis[u] = 1;
for (size_t i = 0; i < G[u].GetSize(); ++i)
{
int v = G[e.to][i].to, w = G[e.to][i].w;
if (dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
pre[v] = u;
q.Push(Edge(dis[v], v));
}
}
}
path.Resize(0);
size_t cur = t;
while (cur != s)
{
path.PushBack(cur);
cur = pre[cur];
}
path.PushBack(cur);
return dis[t];
}
Trie<char, String, int>mpStrToInt;
Vector<String> mpIntToStr;
void PrintPath(const Vector<int>& path)
{
printf("path: \n");
for (size_t i = path.GetSize() - 1; int(i) >= 0; --i)
printf("%s%s", mpIntToStr[path[i]].GetCstr(), i ? " -> " : "\n");
}
bool LoadGraph(const char* filePath)
{
char* buffer = new char[1 << 10];
FILE* fp = fopen(filePath, "r");
if (!fp)
return printf("Can't load graph from: %s\n", filePath), false;
fscanf(fp, "%u", &nodeCount);
for (size_t i = 0; i < nodeCount; ++i)
{
fscanf(fp, "%s", buffer);
mpStrToInt.Insert(String(buffer), i);
mpIntToStr.PushBack(String(buffer));
}
exist.Resize(nodeCount);
for (size_t i = 0; i < exist.GetSize(); ++i)
exist[i] = true;;
G.Resize(nodeCount);
fscanf(fp, "%u", &edgeCount);
for (size_t i = 0; i < edgeCount; ++i)
{
fscanf(fp, "%s", buffer);
int u = *mpStrToInt.Find(String(buffer));
fscanf(fp, "%s", buffer);
int v = *mpStrToInt.Find(String(buffer));
size_t w;
fscanf(fp, "%u", &w);
G[u].PushBack(Edge(w, v));
//G[v].PushBack(Edge(w, u));
}
fclose(fp);
delete[]buffer;
return true;
}
void StoreGraph(const char* filePath)
{
FILE* fp = fopen(filePath, "w");
fprintf(fp, "%u\n", mpStrToInt.GetSize());
for (size_t i = 0; i < mpIntToStr.GetSize(); ++i)
if (exist[i])
fprintf(fp, "%s\n", mpIntToStr[i].GetCstr());
fprintf(fp, "%u\n", edgeCount);
for (size_t i = 0; i < G.GetSize(); ++i)
for (size_t j = 0; exist[i] && j < G[i].GetSize(); ++j)
fprintf(fp, "%s %s %u\n", mpIntToStr[i].GetCstr(),
mpIntToStr[G[i][j].to].GetCstr(), G[i][j].w);
fclose(fp);
}
void AddPoint(const String& point)
{
auto ptr1 = mpStrToInt.Find(point);
if (ptr1)
return;
nodeCount++;
mpStrToInt.Insert(point, mpIntToStr.GetSize());
exist.PushBack(true);
mpIntToStr.PushBack(point);
G.PushBack(Vector<Edge>());
}
void DeletePoint(const String& point)
{
const auto ptr1 = mpStrToInt.Find(point);
if (!ptr1)
return;
for (size_t i = 0; i < G.GetSize(); ++i)
{
if (i == *ptr1)
continue;
Vector<int>v;
for (size_t j = 0; j < G[i].GetSize(); ++j)
if (G[i][j].to == *ptr1)
v.PushBack(j);
for (int j = v.GetSize() - 1; j >= 0; --j)
G[i].Erase(v[j]);
edgeCount -= v.GetSize();
}
edgeCount -= G[*ptr1].GetSize();
--nodeCount;
exist[*ptr1] = false;
mpStrToInt.Erase(point);
}
void AddEdge(const String& from, const String& to, size_t w)
{
AddPoint(from);
AddPoint(to);
G[*mpStrToInt[from]].PushBack(Edge(w, *mpStrToInt[to]));
}
void DeleteEdge(const String& from, const String& to)
{
auto ptr1 = mpStrToInt.Find(from);
if (!ptr1)
return;
auto ptr2 = mpStrToInt.Find(to);
if (!ptr2)
return;
for (size_t i = 0; i < G[*ptr1].GetSize(); ++i)
if (G[*ptr1][i].to == *ptr2)
{
G[*ptr1].Erase(i);
break;
}
--edgeCount;
}
char op[10], buf1[1 << 4], buf2[1 << 4];
size_t w;
void PrintMenu()
{
printf("What do you want to do?\n");
printf("1. Load Graph\n");
printf("2. Store Graph\n");
printf("3. Add an edge\n");
printf("4. Delete an edge\n");
printf("5. Add a point\n");
printf("6. Delete a point\n");
printf("7. Get the shortest path\n");
printf("press number to choose, 0 to exit\n");
}
Vector<int> p;
int main()
{
while (1)
{
PrintMenu();
scanf("%s", op);
printf("\n");
if (op[0] == '0')
break;
switch (op[0] - '0')
{
case 1:
printf("Input the path of the file\n");
scanf("%s", buf1);
LoadGraph(buf1);
break;
case 2:
printf("Input the path of the file\n");
scanf("%s", buf1);
StoreGraph(buf1);
break;
case 3:
printf("Input the point from ans point to and weight\n");
scanf("%s%s%u", buf1, buf2, &w);
AddEdge(buf1, buf2, w);
break;
case 4:
printf("Input the point from ans point to\n");
scanf("%s%s", buf1, buf2);
DeleteEdge(buf1, buf2);
break;
case 5:
printf("Input the point\n");
scanf("%s", buf1);
AddPoint(buf1);
break;
case 6:
printf("Input the point\n");
scanf("%s", buf1);
DeletePoint(buf1);
break;
case 7:
printf("Input the point from ans point to\n");
scanf("%s%s", buf1, buf2);
{
auto ptr1 = mpStrToInt[buf1];
auto ptr2 = mpStrToInt[buf2];
if (!ptr1 || !ptr2)
{
printf("not such point on the graph\n");
break;
}
printf("%u\n", dijkstra(
*ptr1, *ptr2, p
));
PrintPath(p);
break;
}
default:
printf("Order not found\n");
}
system("pause");
system("cls");
}
return 0;
} | 19ab0bfd946befa2298acc3a8221cd18da3ed4b9 | [
"Markdown",
"C++"
] | 11 | C++ | sohardforaname/TongJi-University-DataStructure-Design | 04b64e89618141ecc6dd34695d971d220fb9d581 | add27e650aab9f492c513a43f07cc6bf67acc705 |
refs/heads/master | <file_sep>import { EntityService } from './../../shared/helpers/entityService';
import {
OnTurnProperty
} from './../../shared/stateProperties/onTurnProperty';
import {
WaterfallStep,
WaterfallStepContext,
DialogTurnResult
} from 'botbuilder-dialogs';
import {
GetAcountNamePrompt
} from './../../shared/prompts/getAccountNamePrompt';
import {
ComponentDialog,
WaterfallDialog
} from 'botbuilder-dialogs';
import {
StatePropertyAccessor,
ConversationState,
UserState
} from 'botbuilder';
import {
Dialog
} from 'botbuilder-dialogs';
import axios, {
AxiosRequestConfig,
AxiosPromise
} from 'axios';
// This dialog's name. Also matches the name of the intent from ../dispatcher/resources/checkAccountBalance.lu
// LUIS recognizer replaces spaces ' ' with '_'. So intent name 'Who are you' is recognized as 'Who_are_you'.
const CHECK_ACCOUNT_BALANCE = 'check_account_balance';
const CHECK_ACCOUNT_BALANCE_WATERFALL = 'checkAccountBalanceWaterfall';
const GET_LOCATION_DIALOG_STATE = 'getLocDialogState';
const CONFIRM_DIALOG_STATE = 'confirmDialogState';
// Turn.N here refers to all back and forth conversations beyond the initial trigger until the book table dialog is completed or cancelled.
const GET_ACCOUNT_NAME_PROMPT = 'getAccountName';
export class CheckAccountBalanceDialog extends ComponentDialog {
static getName(): string {
return CHECK_ACCOUNT_BALANCE;
}
/**
* Constructor
* // todo adjust params etc
* @param {Object} botConfig bot configuration
* @param {Object} accessor for on turn
* @param {Object} accessor for the dialog
* @param {Object} conversation state object
*/
constructor(private botConfig: any, private onTurnAccessor: StatePropertyAccessor, private entityService: EntityService) {
super(CHECK_ACCOUNT_BALANCE);
// add dialogs
// Water fall book table dialog
this.addDialog(new WaterfallDialog(CHECK_ACCOUNT_BALANCE_WATERFALL, [
this.askForAccountName.bind(this),
this.checkAccountBalance.bind(this)
]));
this.addDialog(new GetAcountNamePrompt(GET_ACCOUNT_NAME_PROMPT,
botConfig,
onTurnAccessor,
entityService
));
}
public async askForAccountName(step: WaterfallStepContext): Promise<DialogTurnResult<any>> {
const onTurnProperty: OnTurnProperty = await this.onTurnAccessor.get(step.context);
let accountNameEntityProperty = onTurnProperty.getEntityByName('Account');
if (accountNameEntityProperty === undefined) {
return await step.prompt(GET_ACCOUNT_NAME_PROMPT, `Van welke account wil je je balans zien?`);
}
else {
let accountName = accountNameEntityProperty.getValue()[0];
if(this.entityService.accountNamesContains(accountName)) {
return await step.next(accountName);
}
else return await step.prompt(GET_ACCOUNT_NAME_PROMPT, `What's the name of the account you want to check?`);
}
}
/**
* Waterfall step to finalize user's response and return the balance of the account
*
* @param {WaterfallStepContext} WaterfallStepContext
*/
async checkAccountBalance(step: WaterfallStepContext): Promise<DialogTurnResult<any>> {
if (step.result) {
const accountName = step.result;
try {
let url = `https://nestjsbackend.herokuapp.com/accounts/${accountName}`;
const res = await axios.get(url);
const amountLeft = res.data;
await step.context.sendActivity(`The balance on ${accountName} is ${amountLeft}`);
} catch (error) {
console.log(error);
await step.context.sendActivity(`something went wrong...`);
}
}
return await step.endDialog();
}
}<file_sep>import {
EntityService
} from './../../shared/helpers/entityService';
import {
OnTurnProperty
} from './../../shared/stateProperties/onTurnProperty';
import {
WaterfallStep,
WaterfallStepContext,
DialogTurnResult
} from 'botbuilder-dialogs';
import {
GetAcountNamePrompt
} from './../../shared/prompts/getAccountNamePrompt';
import {
ComponentDialog,
WaterfallDialog
} from 'botbuilder-dialogs';
import {
StatePropertyAccessor,
ConversationState,
UserState
} from 'botbuilder';
import {
Dialog
} from 'botbuilder-dialogs';
import axios, {
AxiosRequestConfig,
AxiosPromise
} from 'axios';
import {
GetCategoryNameWithABudgetPrompt
} from '../../shared/prompts/getCategoryNameWithABudgetPrompt';
// This dialog's name. Also matches the name of the intent from ../dispatcher/resources/checkAccountBalance.lu
// LUIS recognizer replaces spaces ' ' with '_'. So intent name 'Who are you' is recognized as 'Who_are_you'.
const CHECK_BUDGET = 'check_budget';
const CHECK_BUDGET_WATERFALL = 'checkAccountBalanceWaterfall';
const GET_CATEGORY_NAME_WITH_A_BUDGET_PROMPT = 'getCategoryNameWithABudget';
export class CheckBudgetDialog extends ComponentDialog {
static getName(): string {
return CHECK_BUDGET;
}
/**
* Constructor
* // todo adjust params etc
* @param {Object} botConfig bot configuration
* @param {StatePropertyAccessor} onTurnAccessor turn property accessor
*/
constructor(private botConfig: any, private onTurnAccessor: StatePropertyAccessor, private entityService: EntityService) {
super(CHECK_BUDGET);
// add dialogs
// Water fall book table dialog
this.addDialog(new WaterfallDialog(CHECK_BUDGET_WATERFALL, [
this.askForCategoryNameWithABudget.bind(this),
this.checkBudget.bind(this)
]));
this.addDialog(new GetCategoryNameWithABudgetPrompt(GET_CATEGORY_NAME_WITH_A_BUDGET_PROMPT,
botConfig,
onTurnAccessor,
entityService
));
}
public async askForCategoryNameWithABudget(step: WaterfallStepContext): Promise < DialogTurnResult < any >> {
const onTurnProperty: OnTurnProperty = await this.onTurnAccessor.get(step.context);
let categoryEntityProperty = onTurnProperty.getEntityByName('Category');
if (categoryEntityProperty === undefined) {
return await step.prompt(GET_CATEGORY_NAME_WITH_A_BUDGET_PROMPT, `Van welke category wil je het budget zien?`);
} else {
let categoryName = categoryEntityProperty.getValue()[0];
if (this.entityService.categoryNamesWithABudgetContains(categoryName)) {
return await step.next(categoryName);
} else return await step.prompt(GET_CATEGORY_NAME_WITH_A_BUDGET_PROMPT, `Die category heeft geen budget. Geef opnieuw in`);
}
}
/**
* Waterfall step to finalize user's response and return the balance of the account
*
* @param {WaterfallStepContext} WaterfallStepContext
*/
async checkBudget(step: WaterfallStepContext): Promise < DialogTurnResult < any >> {
if (step.result) {
console.log(step.result);
const categoryName = step.result;
try {
let url = `https://nestjsbackend.herokuapp.com/budget/${categoryName}`;
const res = await axios.get(url);
const {
limitAmount,
currentAmountSpent
} = res.data;
const remaining = limitAmount - currentAmountSpent;
await step.context.sendActivity(`Your remaining budget in ${categoryName} is ${remaining}`);
} catch (error) {
await step.context.sendActivity(`something went wrong...`);
}
}
return await step.endDialog();
}
}<file_sep>import {
EntityProperty
} from './entityProperty';
import {
LuisRecognizer
} from 'botbuilder-ai';
import { RecognizerResult } from 'botbuilder';
export class OnTurnProperty {
/**
* On Turn Property constructor.
*
* @param {String} intent intent name
* @param {EntityProperty []} entities Array of Entities
*/
private intent: string;
private entities: EntityProperty[];
public getIntent(): string {
return this.intent;
}
public getEntityProperties() {
return this.entities;
}
public addEntityProperty(entityProperty: EntityProperty): void{
this.entities.push(entityProperty);
}
constructor(intent ? : string, entities ? : EntityProperty[]) {
this.intent = intent || '';
this.entities = entities || [];
}
public setIntent(intent: string): void{
this.intent = intent;
}
/**
*
* Method to get entity by name, returns EntityProperty or undefined if does not exist
*
* @param {string} entityName
* @returns {EntityProperty} entityProperty or undefined
*/
public getEntityByName(entityName: string): EntityProperty {
let i = this.entities.findIndex((entity: EntityProperty) => entity.name === entityName);
if(i !== -1){
return this.entities[i];
}
return undefined;
}
/**
*
* Static method to create an on turn property object from LUIS results
*
* @param {Object} LUISResults
* @returns {OnTurnProperty}
*/
public static getOnTurnPropertyFromLuisResults(LUISResults: RecognizerResult): OnTurnProperty {
let LUIS_ENTITIES = ['Account', 'Category']; // add more in central helper
let onTurnProperty = new OnTurnProperty();
onTurnProperty.setIntent(LuisRecognizer.topIntent(LUISResults))
// Gather entity values if available. Uses a const list of LUIS entity names.
LUIS_ENTITIES.forEach(luisEntity => {
if (luisEntity in LUISResults.entities) {
onTurnProperty.addEntityProperty(new EntityProperty(luisEntity, LUISResults.entities[luisEntity]));
}
});
return onTurnProperty;
}
//TODO: refactor
/**
*
* Static method to create an on turn property object from card input
*
* @param {Object} cardValue context.activity.value from a card interaction
* @returns {OnTurnProperty}
*/
static fromCardInput(cardValue: Object): OnTurnProperty {
// All cards used by this bot are adaptive cards with the card's 'data' property set to useful information.
let onTurnProperties = new OnTurnProperty();
for (var key in cardValue) {
if (!cardValue.hasOwnProperty(key)) continue;
if (key.toLowerCase().trim() === 'intent') {
onTurnProperties.intent = cardValue[key];
} else {
onTurnProperties.entities.push(new EntityProperty(key, cardValue[key]));
}
}
return onTurnProperties;
}
}<file_sep>import {
Dialog, DialogContext
} from 'botbuilder-dialogs'
import {
CardFactory
} from 'botbuilder';
// Require the adaptive card.
const helpCard = require('./resources/whatCanYouDoCard.json');
// This dialog's name. Also matches the name of the intent from ../dispatcher/resources/cafeDispatchModel.lu
// LUIS recognizer replaces spaces ' ' with '_'. So intent name 'Who are you' is recognized as 'Who_are_you'.
const WHAT_CAN_YOU_DO_DIALOG = 'What_can_you_do';
/**
*
* What can you do dialog.
* Sends the what can you do adaptive card to user.
* Includes a suggested actions of queries users can try. See ../shared/helpers/genSuggestedQueries.js
*
*/
export class WhatCanYouDoDialog extends Dialog {
static getName(): string {
return WHAT_CAN_YOU_DO_DIALOG;
}
constructor() {
super(WHAT_CAN_YOU_DO_DIALOG);
}
/**
* Override dialogBegin.
*
* @param {DialogContext} dialog context
* @param {Object} options
*/
async beginDialog(dc: DialogContext, options) {
await dc.context.sendActivity({
attachments: [CardFactory.adaptiveCard(helpCard)]
});
await dc.context.sendActivity(`Pick a query from the card or you can use the suggestions below.`);
return await dc.endDialog();
}
}<file_sep>import { OnTurnProperty } from './../stateProperties/onTurnProperty';
import {
StatePropertyAccessor
} from 'botbuilder';
import {
TextPrompt,
PromptValidatorContext,
DialogContext
} from "botbuilder-dialogs";
import axios, {
AxiosRequestConfig,
AxiosPromise
} from 'axios';
import { EntityService } from '../helpers/entityService';
export class GetAcountNamePrompt extends TextPrompt {
private accountNames: string[];
/**
* custom prompt for getting an accountName and validating it against the known accounts of the user
* @param {String []} accountNames variable holding accountNames for the validator, gets filled on constructing via a promise
*/
constructor(private dialogId: string, private botConfig: any, private onTurnAccessor: StatePropertyAccessor, private entityService: EntityService) {
super(dialogId, async (prompt: PromptValidatorContext < string > ) => {
const value = prompt.recognized.value.toLowerCase();
if (!entityService.accountNamesContains(value)) {
await prompt.context.sendActivity(`You dont have an account named ${value} please provide correct one`);
return false;
}
return true;
});
if (!dialogId) throw new Error('Need dialog ID');
if (!botConfig) throw new Error('Need bot configuration');
if (!entityService) throw new Error('Need entity service');
if (!onTurnAccessor) throw new Error('Need onturnaccessor');
}
/**
* Override continueDialog.
* The override enables
* recognizing the cancel intent to cancel the dialog
* todo: recognizing other intents and resolving them appropiatly
* ...
* @param {DialogContext} dc context
*/
async continueDialog(dc: DialogContext) {
let turnContext = dc.context;
// let step = dc.activeDialog.state;
const onTurnProperty: OnTurnProperty = await this.onTurnAccessor.get(turnContext);
switch (onTurnProperty.getIntent()) {
case 'Cancel':
await dc.context.sendActivity('ok ill cancel this conversation for you :)');
return await dc.cancelAllDialogs();
case 'None':
return await super.continueDialog(dc);
default:
return await super.continueDialog(dc);
}
}
}<file_sep>export class EntityProperty {
/**
* Entity Property constructor.
*
* @param {String} name entity name
* @param {String} value entity value
*/
constructor(public name, public value) {
if (!name || !value) throw new Error('Need name and value to create an entity');
}
public getValue(): string {
return this.value;
}
public getName(): string {
return this.name;
}
}<file_sep>import { EntityService } from './../../shared/helpers/entityService';
import { CheckBudgetDialog } from './../checkBudget/checkBudgetDialog';
import { CheckAccountBalanceDialog } from './../checkAccountBalance/checkAccountBalanceDialog';
import { OnTurnProperty } from './../../shared/stateProperties/onTurnProperty';
import { WhatCanYouDoDialog } from './../whatCanYouDo/whatCanYouDo';
import {
ComponentDialog, DialogSet, Dialog, DialogContext, DialogTurnStatus, TextPrompt, DialogTurnResult, WaterfallStepContext, WaterfallDialog
} from "botbuilder-dialogs";
import {
StatePropertyAccessor,
UserState,
ConversationState,
MessageFactory
} from "botbuilder";
import { ResourceResponse, Entity } from 'botframework-connector/lib/generated/models/mappers';
// dialog name
const MAIN_DISPATCHER_DIALOG = 'MainDispatcherDialog';
// const for state properties
const USER_PROFILE_PROPERTY = 'userProfile';
const MAIN_DISPATCHER_STATE_PROPERTY = 'mainDispatcherState';
const ACCOUNT_NAME_PROPERTY = 'accountNameProperty'
// todo: cleanup
// const for cancel and none intent names
const NONE_INTENT = 'None';
const CANCEL_INTENT = 'Cancel';
const ACCOUNT_PROMPT = 'accountPrompt';
// Query property from ../whatCanYouDo/resources/whatCanYHouDoCard.json
// When user responds to what can you do card, a query property is set in response.
const QUERY_PROPERTY = 'query';
// end todo
export class MainDispatcher extends ComponentDialog {
static getName() {
return MAIN_DISPATCHER_DIALOG;
}
private userProfileAccessor: StatePropertyAccessor;
private mainDispatcherAccessor: StatePropertyAccessor;
private accountNameAccessor: StatePropertyAccessor;
private entityService: EntityService;
// private dialogs: DialogSet;
/**
* Constructor.
*
* @param {BotConfiguration} botConfig bot configuration
* @param {StatePropertyAccessor} onTurnAccessor
* @param {ConversationState} conversationState
* @param {UserState} userState
* @param {StatePropertyAccessor} accountNameAccessor // sets the accountName string for checking balances
*/
constructor(private botConfig: any, private onTurnAccessor: StatePropertyAccessor, private conversationState: ConversationState, private userState: UserState) {
super(MAIN_DISPATCHER_DIALOG);
if (!botConfig) throw new Error('Missing parameter. Bot Configuration is required.');
if (!onTurnAccessor) throw new Error('Missing parameter. On turn property accessor is required.');
if (!conversationState) throw new Error('Missing parameter. Conversation state is required.');
if (!userState) throw new Error('Missing parameter. User state is required.');
// Create state objects for user, conversation and dialog states.
this.userProfileAccessor = conversationState.createProperty(USER_PROFILE_PROPERTY);
this.mainDispatcherAccessor = conversationState.createProperty(MAIN_DISPATCHER_STATE_PROPERTY);
this.accountNameAccessor = conversationState.createProperty(ACCOUNT_NAME_PROPERTY);
this.entityService = new EntityService();
this.dialogs = new DialogSet(this.mainDispatcherAccessor);
this.addDialog(new WhatCanYouDoDialog());
this.addDialog(new TextPrompt(ACCOUNT_PROMPT));
this.addDialog(new WaterfallDialog('giveAccount', [
this.askForAccountLabel.bind(this),
this.collectAndDisplayAccountLabel.bind(this)
]));
this.addDialog(new CheckAccountBalanceDialog(botConfig, onTurnAccessor, this.entityService))
this.addDialog(new CheckBudgetDialog(botConfig, onTurnAccessor, this.entityService));
}
/// test
async collectAndDisplayAccountLabel(step: WaterfallStepContext): Promise < DialogTurnResult > {
await step.context.sendActivity(`Got it. You want the balance of ${ step.result }`);
return await step.endDialog(step.result);
}
async askForAccountLabel(dc: DialogContext, step) {
// return dc.prompt()
return await dc.prompt(ACCOUNT_PROMPT, `Hmmm without an account that would be hard to check.... Please enter it now`);
}
// end test
/**
* Override onBeginDialog
*
* @param {DialogContext} dc dialog context
* @param {Object} options dialog turn options
*/
async onBeginDialog(dc: DialogContext, options: any) {
// Override default begin() logic with bot orchestration logic
return await this.mainDispatch(dc);
}
/**
* Override onContinueDialog
*
* @param {DialogContext} dc dialog context
*/
async onContinueDialog(dc: DialogContext) {
// Override default continue() logic with bot orchestration logic
return await this.mainDispatch(dc);
}
/**
* Main Dispatch
*
* This method examines the incoming turn property to determine
* 1. If the requested operation is permissible - e.g. if user is in middle of a dialog,
* then an out of order reply should not be allowed.
* 2. Calls any outstanding dialogs to continue
* 3. If results is no-match from outstanding dialog .OR. if there are no outstanding dialogs,
* decide which child dialog should begin and start it
*
* @param {DialogContext} dialog context
*/
async mainDispatch(dc: DialogContext) {
// get on turn property through the property accessor
const onTurnProperty: OnTurnProperty = await this.onTurnAccessor.get(dc.context);
// Evaluate if the requested operation is possible/ allowed.
// const reqOpStatus = await this.isRequestedOperationPossible(dc.activeDialog, onTurnProperty.intent);
// if (!reqOpStatus.allowed) {
// await dc.context.sendActivity(reqOpStatus.reason);
// // Nothing to do here. End main dialog.
// return await dc.endDialog();
// }
// continue outstanding dialogs
let dialogTurnResult = await dc.continueDialog();
// This will only be empty if there is no active dialog in the stack.
// Removing check for dialogTurnStatus here will break successful cancellation of child dialogs.
// E.g. who are you -> cancel -> yes flow.
if (!dc.context.responded && dialogTurnResult !== undefined && dialogTurnResult.status !== DialogTurnStatus.complete) {
// No one has responded so start the right child dialog.
dialogTurnResult = await this.beginChildDialog(dc, onTurnProperty);
}
if (dialogTurnResult === undefined) return await dc.endDialog();
console.log(dialogTurnResult.status);
// Examine result from dc.continue() or from the call to beginChildDialog().
switch (dialogTurnResult.status) {
case DialogTurnStatus.complete: {
// The active dialog finished successfully. Ask user if they need help with anything else.
//await dc.context.sendActivity(MessageFactory.suggestedActions(GenSuggestedQueries(), `Is there anything else I can help you with?`));
await dc.context.sendActivity(`Is there anything else I can help you with?`);
break;
}
case DialogTurnStatus.waiting: {
// The active dialog is waiting for a response from the user, so do nothing
break;
}
case DialogTurnStatus.cancelled: {
// The active dialog's stack has been cancelled
await dc.cancelAllDialogs();
break;
}
}
return dialogTurnResult;
}
/**
* Method to begin appropriate child dialog based on user input
*
* @param {DialogContext} dc
* @param {OnTurnProperty} onTurnProperty
*/
async beginChildDialog(dc: DialogContext, onTurnProperty: OnTurnProperty): Promise<any> {
switch (onTurnProperty.getIntent()) {
case 'checkAccount':
return await dc.beginDialog(CheckAccountBalanceDialog.getName());
//return await dc.endDialog();
// return await this.beginWhatCanYouDoDialog(dc, onTurnProperty);
// return
case 'checkBudget':
return await dc.beginDialog(CheckBudgetDialog.getName());
// case 'Cancel':
// return await dc.context.sendActivity('OK i cancelled');
case NONE_INTENT:
default:
await dc.context.sendActivity(`I'm still learning.. Sorry, I do not know how to help you with that.`);
return await dc.context.sendActivity(`Follow [this link](https://www.bing.com/search?q=${ dc.context.activity.text }) to search the web!`);
}
}
/**
* Method to evaluate if the requested user operation is possible.
* User could be in the middle of a multi-turn dialog where interruption might not be possible or allowed.
*
* @param {String} activeDialog
* @param {String} requestedOperation
* @returns {Object} outcome object
*/
// async isRequestedOperationPossible(activeDialog, requestedOperation) {
// let outcome = { allowed: true, reason: '' };
// // E.g. What_can_you_do is not possible when you are in the middle of Who_are_you dialog
// if (requestedOperation === WhatCanYouDoDialog.Name) {
// if (activeDialog === WhoAreYouDialog.Name) {
// outcome.allowed = false;
// outcome.reason = `Sorry! I'm unable to process that. You can say 'cancel' to cancel this conversation..`;
// }
// } else if (requestedOperation === CANCEL_INTENT) {
// if (activeDialog === undefined) {
// outcome.allowed = false;
// outcome.reason = `Sure, but there is nothing to cancel..`;
// }
// }
// return outcome;
// }
/**
* Helper method to begin what can you do dialog.
*
* @param {DialogContext} dc dialog context
* @param {OnTurnProperty} onTurnProperty
*/
async beginWhatCanYouDoDialog(dc, onTurnProperty) {
// Handle case when user interacted with the what can you do card.
// What can you do card sends a custom data property with intent name, text value and possible entities.
// See ../whatCanYouDo/resources/whatCanYouDoCard.json for card definition.
let queryProperty = (onTurnProperty.entities || []).filter(item => item.entityName === QUERY_PROPERTY);
if (queryProperty.length !== 0) {
let parsedJSON;
try {
parsedJSON = JSON.parse(queryProperty[0].entityValue);
} catch (err) {
return await dc.context.sendActivity(`Choose a query from the card drop down before you click 'Let's talk!'`);
}
if (parsedJSON.text !== undefined) {
dc.context.activity.text = parsedJSON.text;
await dc.context.sendActivity(`You said: '${ dc.context.activity.text }'`);
}
// create a set a new on turn property
// await this.onTurnAccessor.set(dc.context, OnTurnProperty.fromCardInput(parsedJSON));
return await this.beginChildDialog(dc, parsedJSON);
}
return await dc.beginDialog(WhatCanYouDoDialog.getName());
}
}
<file_sep>import { OnTurnProperty } from './shared/stateProperties/onTurnProperty';
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// bot.js is your main bot dialog entry point for handling activity types
// Import required Bot Builder
import {
ActivityTypes,
CardFactory,
ConversationState,
UserState,
StatePropertyAccessor,
TurnContext,
RecognizerResult,
MessageFactory
} from 'botbuilder';
import {
LuisRecognizer,
IntentData
} from 'botbuilder-ai';
import axios, {
AxiosRequestConfig,
AxiosPromise
} from 'axios';
import {
DialogSet,
TextPrompt,
WaterfallDialog,
DialogState,
Dialog,
DialogContext,
DialogTurnResult,
WaterfallStep,
WaterfallStepContext
} from 'botbuilder-dialogs'
import { MainDispatcher } from './dialogs/dispatcher/mainDispatcher';
// LUIS service type entry as defined in the .bot file.
const LUIS_CONFIGURATION: string = 'BasicBotLuisApplication';
// Supported LUIS Intents.
const GREETING_INTENT: string = 'Greeting';
const CANCEL_INTENT: string = 'Cancel';
const HELP_INTENT: string = 'Help';
const NONE_INTENT: string = 'None';
const CHECKACCOUNT_INTENT: string = "checkAccount";
// persistent state properties
const DIALOG_STATE_PROPERTY: string = 'dialogState';
const USER_NAME_PROP: string = 'user_name';
const TURN_COUNTER_PROPERTY = 'turnCounterProperty';
const ON_TURN_PROPERTY = 'onTurnStateProperty';
// dialog references
const WHO_ARE_YOU: string = 'who_are_you';
const HELLO_USER: string = 'hello_user';
const NAME_PROMPT: string = 'name_prompt';
/**
* Demonstrates the following concepts:
* Displaying a Welcome Card, using Adaptive Card technology
* Use LUIS to model Greetings, Help, and Cancel interactions
*/
export class BasicBot {
/**
* @param {BotConfiguration} botConfig contents of the .bot file
* @param {Object} conversationState state store for the conversation (ACCESSOR)
* @param {Object} userState private state store per user (ACCESSOR)
*/
private dialogState: StatePropertyAccessor;
private onTurnAccessor: StatePropertyAccessor;
private userName: StatePropertyAccessor;
private countProperty: StatePropertyAccessor;
private dialogSet: DialogSet;
private luisRecognizer: LuisRecognizer;
private counter: number = 1;
constructor(private botConfig: any, private conversationState: ConversationState, private userState: UserState) {
// creates a new state accessor property. see https://aka.ms/about-bot-state-accessors to learn more about the bot state and state accessors
this.dialogState = this.conversationState.createProperty(DIALOG_STATE_PROPERTY);
this.userName = this.userState.createProperty(USER_NAME_PROP);
this.countProperty = conversationState.createProperty(TURN_COUNTER_PROPERTY);
this.onTurnAccessor = conversationState.createProperty(ON_TURN_PROPERTY);
this.dialogSet = new DialogSet(this.dialogState);
this.dialogSet.add(new TextPrompt(NAME_PROMPT));
//this.dialogSet.add(new TextPrompt('accountNamePrompt')) // TODO: refactor in own pages - per dialog subject (intent)
// this.dialogSet.add(this.askForAccountName.bind(this));
// Create a dialog that asks the user for their name.
this.dialogSet.add(new WaterfallDialog(WHO_ARE_YOU, [
this.askForName.bind(this),
this.collectAndDisplayName.bind(this)
]));
this.dialogSet.add(new WaterfallDialog(HELLO_USER, [
this.displayName.bind(this)
]));
this.dialogSet.add(new MainDispatcher(botConfig, this.onTurnAccessor, conversationState, userState));
if (!botConfig) throw ('Missing parameter. botConfig is required');
// Add the LUIS recognizer.
const luisConfig = botConfig.findServiceByNameOrId(LUIS_CONFIGURATION);
if (!luisConfig || !luisConfig.appId) throw ('Missing LUIS configuration. Please follow README.MD to create required LUIS applications.\n\n');
this.luisRecognizer = new LuisRecognizer({
applicationId: "4576b202-e5a9-4e2b-9b19-961ac2a0e831",
endpoint: "https://westeurope.api.cognitive.microsoft.com/luis/v2.0/apps/4576b202-e5a9-4e2b-9b19-961ac2a0e831?subscription-key=<KEY>&timezoneOffset=60&q=",
endpointKey: "<KEY>"
});
}
async askForName(dc: DialogContext, step) {
// return dc.prompt()
return await dc.prompt(NAME_PROMPT, `Hello and welcome, what is your name?`);
}
async askForAccountName(dc: DialogContext, userName: string): Promise < DialogTurnResult > {
// return dc.prompt()
return await dc.prompt('accountNamePrompt', `what account would you like to check ${userName} ?`);
}
// The second step in this waterfall collects the response, stores it in
// the state accessor, then displays it.
async collectAndDisplayName(step: WaterfallStepContext): Promise < DialogTurnResult > {
await this.userName.set(step.context, step.result);
await step.context.sendActivity(`Got it. You are ${ step.result }. How may I help you?`);
return await step.endDialog();
}
// This step loads the user's name from state and displays it.
async displayName(step: WaterfallStepContext): Promise < DialogTurnResult > {
const userName = await this.userName.get(step.context);
await step.context.sendActivity(`Your name is ${ userName }.`);
return await step.endDialog();
}
/**
* Driver code that does one of the following:
* 1. Use LUIS to recognize intents for incoming user message
*
* @param {Context} context turn context from the adapter
*/
async onTurn(turnContext: TurnContext) {
// Handle Message activity type, which is the main activity type for shown within a conversational interface
// Message activities may contain text, speech, interactive cards, and binary or unknown attachments.
// see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types
this.counter++;
if (turnContext.activity.type === ActivityTypes.Message) {
// Create dialog context
const dc: DialogContext = await this.dialogSet.createContext(turnContext);
// Continue the current dialog
// If the bot hasn't yet responded, try to continue any active dialog
// Process on turn input (card or NLP) and gather new properties
// OnTurnProperty object has processed information from the input message activity.
let onTurnProperties = await this.detectIntentAndEntities(turnContext);
//console.log(onTurnProperties);
if (onTurnProperties === undefined) return;
// Set the state with gathered properties (intent/ entities) through the onTurnAccessor
await this.onTurnAccessor.set(turnContext, onTurnProperties);
if (!turnContext.responded) {
await dc.continueDialog();
}
let username = await this.userName.get(dc.context)
// prevent calling luis on just a username
// todo: find more elegant solution
if (username !== turnContext.activity.text) {
await dc.beginDialog(MainDispatcher.getName());
}
}
// Handle ConversationUpdate activity type, which is used to indicates new members add to
// the conversation.
// see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types
else if (turnContext.activity.type === ActivityTypes.ConversationUpdate) {
// Do we have any new members added to the conversation?
if (turnContext.activity.membersAdded.length !== 0) {
// Iterate over all new members added to the conversation
for (var idx in turnContext.activity.membersAdded) {
// Greet anyone that was not the target (recipient) of this message
// the 'bot' is the recipient for events from the channel,
// context.activity.membersAdded == context.activity.recipient.Id indicates the
// bot was added to the conversation.
if (turnContext.activity.membersAdded[idx].id !== turnContext.activity.recipient.id) {
// Welcome user.
// When activity type is "conversationUpdate" and the member joining the conversation is the bot
// we will send our Welcome Adaptive Card. This will only be sent once, when the Bot joins conversation
// To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
// const welcomeCard = CardFactory.adaptiveCard(WelcomeCard);
// await context.sendActivity({
// attachments: [welcomeCard]
// });
let dc: DialogContext = await this.dialogSet.createContext(turnContext);
await dc.beginDialog(WHO_ARE_YOU);
}
}
}
}
// only at the end of the turn
await this.userState.saveChanges(turnContext);
// End this turn by saving changes to the conversation state.
await this.conversationState.saveChanges(turnContext);
}
/**
* Async helper method to get on turn properties from cards or NLU using https://LUIS.ai
*
* - All cards for this bot -
* 1. Are adaptive cards. See https://adaptivecards.io to learn more.
* 2. All cards include an 'intent' field under 'data' section and can include entities recognized.
* - Bot also uses a dispatch LUIS model that includes trigger intents for all dialogs.
* See ./dialogs/dispatcher/resources/cafeDispatchModel.lu for a description of the dispatch model.
*
* @param {TurnContext} turn context object
*
*/
async detectIntentAndEntities(turnContext: TurnContext) {
// Handle card input (if any), update state and return.
if (turnContext.activity.value !== undefined) {
return OnTurnProperty.fromCardInput(turnContext.activity.value);
}
// Acknowledge attachments from user.
if (turnContext.activity.attachments && turnContext.activity.attachments.length !== 0) {
await turnContext.sendActivity(`Thanks for sending me that attachment. I'm still learning to process attachments.`);
return undefined;
}
// Nothing to do for this turn if there is no text specified.
if (turnContext.activity.text === undefined || turnContext.activity.text.trim() === '') {
return;
}
// Call to LUIS recognizer to get intent + entities
const LUISResults = await this.luisRecognizer.recognize(turnContext);
// Return new instance of on turn property from LUIS results.
// Leverages static fromLUISResults method
return OnTurnProperty.getOnTurnPropertyFromLuisResults(LUISResults);
}
/**
* Async helper method to welcome all users that have joined the conversation.
*
* @param {TurnContext} context conversation context object
*
*/
async welcomeUser(turnContext: TurnContext): Promise<void> {
// Do we have any new members added to the conversation?
if (turnContext.activity.membersAdded.length !== 0) {
// Iterate over all new members added to the conversation
for (var idx in turnContext.activity.membersAdded) {
// Greet anyone that was not the target (recipient) of this message
// the 'bot' is the recipient for events from the channel,
// turnContext.activity.membersAdded == turnContext.activity.recipient.Id indicates the
// bot was added to the conversation.
if (turnContext.activity.membersAdded[idx].id !== turnContext.activity.recipient.id) {
// Welcome user.
await turnContext.sendActivity(`Hello, I am the Contoso Cafe Bot!`);
await turnContext.sendActivity(`I can help book a table and more..`);
// Send welcome card.
//await turnContext.sendActivity(MessageFactory.attachment(CardFactory.adaptiveCard(WelcomeCard)));
}
}
}
}
// dialogs.add('BalanceDialog', [
// async function(dc){
// let balance = Math.floor(Math.random() * Math.floor(100));
// await dc.context.sendActivity(`Your balance is £${balance}.`);
// await dc.continue();
// },
// async function(dc){
// await dc.context.sendActivity(`OK, we're done here. What is next?`);
// await dc.continue();
// },
// async function(dc){
// await dc.end();
// }
// ]);
// dialogs.add('TransferDialog', [
// async function(dc) {
// const state = convoState.get(dc.context);
// if (state.AccountLabel) {
// await dc.continue();
// } else {
// await dc.prompt('textPrompt', `Which account do you want to transfer from? For example Joint, Current, Savings etc`);
// }
// },
// async function(dc, accountLabel) {
// const state = convoState.get(dc.context);
// // Save accountLabel
// if (!state.AccountLabel) {
// state.AccountLabel = accountLabel;
// }
// //continue
// await dc.continue();
// },
// async function(dc) {
// const state = convoState.get(dc.context);
// await dc.context.sendActivity(`AccountLabel: ${state.AccountLabel}`);
// //continue
// await dc.continue();
// },
// async function(dc){
// await dc.context.sendActivity(`OK, we're done here. What is next?`);
// await dc.continue();
// },
// async function(dc){
// await dc.end();
// }
// ]);
}
// let account = entities[0];
// let accountLabel = results.entities["Account"];
// if (accountLabel === undefined) {
// // ask with dialogprompt
// // let accountLabel = await dc.prompt('accountNamePrompt', `what account would you like to check ?`);
// // let url = `https://nestjsbackend.herokuapp.com/accounts/${accountLabel}`;
// // const res = await axios.get(url);
// // const amountLeft = res.data;
// // await context.sendActivity(`The balance of ${accountLabel} is ${amountLeft}`);
// }
// if (accountLabel !== undefined) {
// let url = `https://nestjsbackend.herokuapp.com/accounts/${accountLabel}`;
// const res = await axios.get(url);
// const amountLeft = res.data;
// await context.sendActivity(`The balance of ${accountLabel} is ${amountLeft}`);
// }<file_sep>import axios, {
AxiosRequestConfig,
AxiosPromise
} from 'axios';
export class EntityService {
private entityNames: string[];
private categoryNames: string[];
private categoryNamesWithABudget: string[];
private accountNames: string[];
constructor() {
this.setCategoryNamesWithABudget();
this.setEntityNames();
this.setAccountNames();
}
private setEntityNames(): void {
this.entityNames = ['Account', 'Category'];
}
private async setCategoryNames(): Promise < void > {
let url = `https://nestjsbackend.herokuapp.com/category/`;
let res = await axios.get(url);
this.categoryNames = res.data;
}
private async setAccountNames() {
let url = `https://nestjsbackend.herokuapp.com/accounts/`;
const {
data
} = await axios.get(url);
this.accountNames = data;
}
private async setCategoryNamesWithABudget(): Promise < void > {
let url = `https://nestjsbackend.herokuapp.com/budget/`;
let res = await axios.get(url);
this.categoryNamesWithABudget = res.data;
}
public getCategoryNamesWithABudget(): string[] {
return this.categoryNamesWithABudget;
}
public getEntityNames(): string[] {
return this.entityNames;
}
public categoryNamesWithABudgetContains(categoryName: string) {
return (this.categoryNamesWithABudget.findIndex(cat => cat === categoryName) !== -1);
}
public accountNamesContains(accountName: string) {
return (this.accountNames.findIndex(acc => acc === accountName) !== -1);
}
}<file_sep>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// See https://github.com/microsoft/botbuilder-samples for a more comprehensive list of samples.
// Import required pckages
import * as path from 'path';
import * as restify from 'restify';
// Import required bot services. See https://aka.ms/bot-services to learn more about the different parts of a bot.
import {BotFrameworkAdapter, MemoryStorage, ConversationState, UserState} from 'botbuilder';
// Import required bot configuration.
import {BotConfiguration} from 'botframework-config';
import { BasicBot } from './bot';
// This bot's main dialog.
// Read botFilePath and botFileSecret from .env file
// Note: Ensure you have a .env file and include botFilePath and botFileSecret.
const ENV_FILE = path.join(__dirname, '.env');
const env = require('dotenv').config({ path: ENV_FILE });
// Get the .bot file path
// See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.
const BOT_FILE = path.join(__dirname, (process.env.botFilePath || ''));
let botConfig;
try {
// Read bot configuration from .bot file.
botConfig = BotConfiguration.loadSync(BOT_FILE, process.env.botFileSecret);
} catch (err) {
console.error(`\nError reading bot file. Please ensure you have valid botFilePath and botFileSecret set for your environment.`);
console.error(`\n - The botFileSecret is available under appsettings for your Azure Bot Service bot.`);
console.error(`\n - If you are running this bot locally, consider adding a .env file with botFilePath and botFileSecret.`);
console.error(`\n - See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.\n\n`);
process.exit();
}
// For local development configuration as defined in .bot file
const DEV_ENVIRONMENT = 'development';
// bot name as defined in .bot file or from runtime
const BOT_CONFIGURATION = (process.env.NODE_ENV || DEV_ENVIRONMENT);
// Get bot endpoint configuration by service name
const endpointConfig = botConfig.findServiceByNameOrId(BOT_CONFIGURATION);
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about .bot file its use and bot configuration .
const adapter = new BotFrameworkAdapter({
appId: endpointConfig.appId || process.env.microsoftAppID,
appPassword: endpointConfig.appPassword || <PASSWORD>,
openIdMetadata: process.env.BotOpenIdMetadata
});
// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
// This check writes out errors to console log
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError]: ${ error }`);
// Send a message to the user
context.sendActivity(`Oops. Something went wrong!`);
};
// Define a state store for your bot. See https://aka.ms/about-bot-state to learn more about using MemoryStorage.
// A bot requires a state store to persist the dialog and user state between messages.
let conversationState, userState;
// For local development, in-memory storage is used.
// CAUTION: The Memory Storage used here is for local bot debugging only. When the bot
// is restarted, anything stored in memory will be gone.
const memoryStorage = new MemoryStorage();
conversationState = new ConversationState(memoryStorage);
userState = new UserState(memoryStorage);
// CAUTION: You must ensure your product environment has the NODE_ENV set
// to use the Azure Blob storage or Azure Cosmos DB providers.
// const { BlobStorage } = require('botbuilder-azure');
// Storage configuration name or ID from .bot file
// const STORAGE_CONFIGURATION_ID = '<STORAGE-NAME-OR-ID-FROM-BOT-FILE>';
// // Default container name
// const DEFAULT_BOT_CONTAINER = 'botstate';
// // Get service configuration
// const blobStorageConfig = botConfig.findServiceByNameOrId(STORAGE_CONFIGURATION_ID);
// const blobStorage = new BlobStorage({
// containerName: (blobStorageConfig.container || DEFAULT_BOT_CONTAINER),
// storageAccountOrConnectionString: blobStorageConfig.connectionString,
// });
// conversationState = new ConversationState(blobStorage);
// userState = new UserState(blobStorage);
// Create the main dialog.
let bot;
try {
bot = new BasicBot(botConfig, conversationState, userState);
} catch (err) {
console.error(`[botInitializationError]: ${ err }`);
process.exit();
}
// Create HTTP server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
console.log(`\n${ server.name } listening to`);
console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
console.log(`\nTo talk to your bot, open basic-bot.bot file in the Emulator`);
});
// Listen for incoming activities and route them to your bot main dialog.
server.post('/api/messages', (req, res) => {
// Route received a request to adapter for processing
adapter.processActivity(req, res, async (turnContext) => {
// route to bot activity handler.
await bot.onTurn(turnContext);
});
});
<file_sep># LuisAgent-NodeJS
Testing the Microsoft bot framework v4 using NodeJS in preparation of internship at Stardekk.
| 52812020b7a3ff2a32724dd12fba73ab501af230 | [
"Markdown",
"TypeScript"
] | 11 | TypeScript | DM-be/LuisAgent-NodeJS | 7d800c2128731fbb9e1de81feb7911097e56d55c | 9ea6604195f89bb0021ca56937b6050cb476e7e1 |
refs/heads/master | <file_sep>import os
import random
from itertools import chain
import numpy as np
import torch
import torch.utils.data as data
from data_utils import load_task, vectorize_data
from six.moves import range, reduce
class bAbIDataset(data.Dataset):
def __init__(self, dataset_dir, task_id=1, memory_size=50, train=True):
self.train = train
self.task_id = task_id
self.dataset_dir = dataset_dir
train_data, test_data = load_task(self.dataset_dir, task_id)
data = train_data + test_data
self.vocab = set()
for story, query, answer in data:
self.vocab = self.vocab | set(list(chain.from_iterable(story))+query+answer)
self.vocab = sorted(self.vocab)
word_idx = dict((word, i+1) for i, word in enumerate(self.vocab))
self.max_story_size = max([len(story) for story, _, _ in data])
self.query_size = max([len(query) for _, query, _ in data])
self.sentence_size = max([len(row) for row in \
chain.from_iterable([story for story, _, _ in data])])
self.memory_size = min(memory_size, self.max_story_size)
# Add time words/indexes
for i in range(self.memory_size):
word_idx["time{}".format(i+1)] = "time{}".format(i+1)
self.num_vocab = len(word_idx) + 1 # +1 for nil word
self.sentence_size = max(self.query_size, self.sentence_size) # for the position
self.sentence_size += 1 # +1 for time words
self.word_idx = word_idx
self.mean_story_size = int(np.mean([ len(s) for s, _, _ in data ]))
if train:
story, query, answer = vectorize_data(train_data, self.word_idx,
self.sentence_size, self.memory_size)
else:
story, query, answer = vectorize_data(test_data, self.word_idx,
self.sentence_size, self.memory_size)
self.data_story = torch.LongTensor(story)
self.data_query = torch.LongTensor(query)
self.data_answer = torch.LongTensor(np.argmax(answer, axis=1))
def __getitem__(self, idx):
return self.data_story[idx], self.data_query[idx], self.data_answer[idx]
def __len__(self):
return len(self.data_story)
<file_sep># MemN2N_Experiments
Class project for DS-GA 1008 at NYU to investigate ways to improve MemN2N performance on bAbI tasks.
Baseline code is from https://github.com/nmhkahn/MemN2N-pytorch.
**Test accuracy**
#### Baseline results:
mean, std, min
0.33420000000000005 0.06544585548375084 0.236
#### Ensemble with regularization:
ensemble accuracy: 0.453
mean, std, min
0.35007999999999995 0.05676172654174642 0.246
#### Ensemble with regularization and squared cross entropy loss
ensemble_accuracy_so_far 0.443
mean, std, min
0.34629000000000004 0.061368443845351 0.247
<file_sep>import os
import time
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from dataset import bAbIDataset
from model import MemN2N
import pdb
class Trainer():
def __init__(self, config):
self.train_data = bAbIDataset(config.dataset_dir, config.task)
self.train_loader = DataLoader(self.train_data,
batch_size=config.batch_size,
num_workers=1,
shuffle=True)
self.test_data = bAbIDataset(config.dataset_dir, config.task, train=False)
self.test_loader = DataLoader(self.test_data,
batch_size=config.batch_size,
num_workers=1,
shuffle=False)
settings = {
"use_cuda": config.cuda,
"num_vocab": self.train_data.num_vocab,
"embedding_dim": 20,
"sentence_size": self.train_data.sentence_size,
"max_hops": config.max_hops
}
print("Longest sentence length", self.train_data.sentence_size)
print("Longest story length", self.train_data.max_story_size)
print("Average story length", self.train_data.mean_story_size)
print("Number of vocab", self.train_data.num_vocab)
self.mem_n2n = MemN2N(settings)
self.ce_fn = nn.CrossEntropyLoss(size_average=False)
self.opt = torch.optim.SGD(self.mem_n2n.parameters(), lr=config.lr, weight_decay=1e-5)
print(self.mem_n2n)
if config.cuda:
self.ce_fn = self.ce_fn.cuda()
self.mem_n2n = self.mem_n2n.cuda()
self.start_epoch = 0
self.config = config
def fit(self):
config = self.config
best_acc = 0
for epoch in range(self.start_epoch, config.max_epochs):
loss = self._train_single_epoch(epoch)
lr = self._decay_learning_rate(self.opt, epoch)
if (epoch+1) % 10 == 0:
train_acc = self.evaluate("train")
test_acc = self.evaluate("test")
print(epoch+1, loss, train_acc, test_acc)
if test_acc > best_acc:
best_acc = test_acc
print(train_acc, test_acc)
return best_acc
def load(self, directory):
pass
def evaluate(self, data="test", ensemble = False):
correct = 0
pred_prob_all = np.zeros((0, 85))
answers = np.zeros(0)
loader = self.train_loader if data == "train" else self.test_loader
for step, (story, query, answer) in enumerate(loader):
story = Variable(story)
query = Variable(query)
answer = Variable(answer)
if self.config.cuda:
story = story.cuda()
query = query.cuda()
answer = answer.cuda()
pred_prob = self.mem_n2n(story, query)[1]
if ensemble:
pred_prob_all = np.concatenate((pred_prob_all, pred_prob.data), 0)
answers = np.concatenate((answers, answer.data), 0)
pred = pred_prob.data.max(1)[1] # max func return (max, argmax)
correct += pred.eq(answer.data).cpu().sum()
acc = correct / len(loader.dataset)
if ensemble:
return acc, correct, pred_prob_all, answers
return acc
def _train_single_epoch(self, epoch):
config = self.config
num_steps_per_epoch = len(self.train_loader)
for step, (story, query, answer) in enumerate(self.train_loader):
story = Variable(story)
query = Variable(query)
answer = Variable(answer)
if config.cuda:
story = story.cuda()
query = query.cuda()
answer = answer.cuda()
self.opt.zero_grad()
loss = self.ce_fn(self.mem_n2n(story, query)[0], answer)
loss.backward()
self._gradient_noise_and_clip(self.mem_n2n.parameters(),
noise_stddev=1e-3, max_clip=config.max_clip)
self.opt.step()
return loss.data[0]
def _gradient_noise_and_clip(self, parameters,
noise_stddev=1e-3, max_clip=40.0):
parameters = list(filter(lambda p: p.grad is not None, parameters))
nn.utils.clip_grad_norm(parameters, max_clip)
for p in parameters:
noise = torch.randn(p.size()) * noise_stddev
if self.config.cuda:
noise = noise.cuda()
p.grad.data.add_(noise)
def _decay_learning_rate(self, opt, epoch):
decay_interval = self.config.decay_interval
decay_ratio = self.config.decay_ratio
decay_count = max(0, epoch // decay_interval)
lr = self.config.lr * (decay_ratio ** decay_count)
for param_group in opt.param_groups:
param_group["lr"] = lr
return lr
<file_sep>import argparse
import trainer
import numpy as np
import pdb
def parse_config():
parser = argparse.ArgumentParser()
parser.add_argument("--cuda", action="store_true")
parser.add_argument("--dataset_dir", type=str, default="bAbI/tasks_1-20_v1-2/en/")
parser.add_argument("--task", type=int, default=3)
parser.add_argument("--max_hops", type=int, default=3)
parser.add_argument("--batch_size", type=int, default=32)
parser.add_argument("--max_epochs", type=int, default=100)
parser.add_argument("--lr", type=float, default=0.01)
parser.add_argument("--decay_interval", type=int, default=25)
parser.add_argument("--decay_ratio", type=float, default=0.5)
parser.add_argument("--max_clip", type=float, default=40.0)
return parser.parse_args()
def main(config):
accs = []
models = []
accs_ensemble = []
correct_ensemble = []
pred_prob_ensemble = []
answer_ensemble = []
for _ in range(100):
t = trainer.Trainer(config)
acc = t.fit()
accs.append(acc)
print(np.array(accs).mean())
models.append(t)
accs_individual, correct, pred_prob, answer = t.evaluate('test', ensemble = True)
accs_ensemble.append(accs_individual)
correct_ensemble.append(correct)
pred_prob_ensemble.append(pred_prob)
answer_ensemble.append(answer)
init_prob = np.ones_like(pred_prob_ensemble[0])
for p in pred_prob_ensemble:
init_prob = init_prob * p
guess = init_prob.argmax(1)
ensemble_total_accuracy = (guess == answer_ensemble[0]).mean()
print('ensemble_accuracy_so_far', ensemble_total_accuracy)
pred_prob_ensemble[0].argmax(1) == answer_ensemble[0]
#pdb.set_trace()
npaccs = np.array(accs)
print(npaccs.mean(),npaccs.std(),npaccs.min())
if __name__ == "__main__":
config = parse_config()
main(config)
| 13316bb53b653420ee0f10566e7c176f39907027 | [
"Markdown",
"Python"
] | 4 | Python | jts550/MemN2N_Experiments | b7bfa683dad962f2b78f0371c84783a716fbc716 | 59aeaf1889cc3d7d138325849069c43c9d930ccb |
refs/heads/master | <repo_name>ppkinev/Fast-Aid-Bot-NodeJS<file_sep>/utils/Twinery2JSON/compare.js
'use strict';
const fs = require('fs');
function grabEditedText(origFile, editedFile, callback) {
let source = require(origFile),
edited = require(editedFile);
let counter = 0;
for (let line in source) {
if (source.hasOwnProperty(line)) {
if (edited[line]) {
let rLength = source[line]['replies']['choices'].length;
for (var i = 0; i < rLength; i++) {
let orig = source[line]['replies']['choices'][i],
edit = edited[line]['replies']['choices'][i];
if (!orig || !edit) continue;
let sourceChoice = orig['message'],
editedChoice = edit['message'];
if (sourceChoice !== editedChoice) {
counter++;
orig['message'] = editedChoice;
}
}
}
}
}
fs.writeFile(origFile, JSON.stringify(source), 'utf8', () => {
console.log(`File ${origFile}`);
console.log(`Done - ${counter} lines were changed`);
console.log('##########################');
if (callback) callback();
});
}
module.exports = {
start: grabEditedText
};<file_sep>/telegram_bot/helpers/string-constants.js
console.logger('Init: String Constants');
var system = {
allaCode: 'Алла ждет код. Введите его'
};
var wrongAnswers = [
'<b>Сообщение не было доставлено. Выберите ответ из предложенных вариантов</b>'
];
var wrongAnswersEng = [
'<b>Message delivery failed. Please, select one of the options below.</b>'
];
var waitingAnswers = {
0: [
'Пожалуйста, ответь! Мне правда нужна твоя помощь',
'Выходи на связь!',
'У меня садится терминал, осталось мало времени',
'Да, не торопись с ответом, я тут всего лишь умираю',
'Не оставляй меня тут одну!',
'Мне начинает казаться, что сообщения от тебя это просто жестокая шутка. Ответь, пожалуйста.',
'Ты получаешь мои сообщения? Кажется я схожу с ума.',
'{user_name}? Ты тут?',
'Шщщшщщ… Алла вызывает {user_name}. Шщщщшщ… Как слышно?',
'Дорогой дневник, я провожу чудесную неделю. Меня похители, я чудом еще жива, а единственный человек, с которым у меня есть связь это {user_name}. И этот человек меня игнорирует.',
'Алла умерла… Ладно, еще нет, но мы к этому близки. Пожалуйста, помоги!',
'Мне кажется это конец. Мне очень нужен твой совет!',
'ПОМОГИ! Я СЛЫШУ ОЧЕНЬ СТРАННЫЕ ЗВУКИ!',
'Я замерзаю и живот сводит от голода. Прошу, поторопись',
'Эй! Ты где там?',
'Не будь таким безразличным!',
'Еще пара минут и я сделаю все сама!!',
'Что говоришь? Как у меня дела? О! Превосходно! Я же медленно умираю и никак не дождусь сообщений от единственного человека, с которым есть связь'
],
1: [
'{user_name}, я уже заждалась :)',
'Напомню, что у нас проходит экскурсия по Одессе.',
'{user_name}? Может продолжим?',
'Я не тороплю, просто тихонько напомню о себе.',
'{user_name}, нас ждет еще столько интересного! Вернемся к экскурсии?',
'Впереди так много интересно и так мало времени :)',
'{user_name}, мне не терпится вернуться к нашему общению.',
'Интересно, у девушек растет щетина на лице, если они долго ждут? :)',
'Привет, {user_name}! Я все еще жду!',
'У нас осталось немного времени. Давайте продолжим.',
'{user_name}, я уже заждалась :)',
'Ку-ку, {user_name}. Это я, Ева, ваш экскурсовод.',
'Мой фитнес треккер говорит, что мы долго стоим на месте.',
'{user_name}, вы знали, что знаменитую марку Timberland, создал сапожник из Одессы? Возвращайтесь, нас ждет много интересного.',
'{user_name}, уже хочется есть и я вспомнила интересный факт. Знамениты конфеты "Стрела" были изобретены в Одессе на кондитерской фабрике имени Розы Люксембург. Современное название- "Одесса Люкс"'
],
2: [
'Пожалуйста, ответь! Мне правда нужна твоя помощь'
]
};
var comeBackMessage = {
0: [
'Ну, наконец-то!',
'Я уже думала, придется все делать самой',
'Спасибо, что ты со мной',
'Я уже начала волноваться, что ты не вернешься',
'Пожалуйста, не оставляй меня тут одну надолго',
'Уф. Я уже начала думать, что сошла сума и придумала тебя',
'Ты здесь! Наконец-то!',
'Ура, ты снова со мной!',
'Ох, я уже начала беспокоиться, что наше соединение разорвалось',
'{user_name}, я испугалась, что осталась тут совершенно одна',
'О, это чудесный звук входящего сообщения! Когда я вела экскурсии он меня жутко бесил.',
'А, это ты! Тут уже такое начало мерещиться. Вздрагиваю от каждого шороха',
'Слушай, {user_name}, я понимаю, это не похоже на экскурсию, но я очень благодарна, что не бросаешь меня',
'Давай продолжим меня спасать',
'Ура! {user_name} со мной! Я нашла дохлую крысу и почти готова была ее съесть. Помоги поскорее выбраться',
'{user_name} снова на связи! Не думала, что буду так рада клиенту Look Right.'
],
1: [
'Спасибо, что вы с нами :)',
'Я уже начала комплексовать, что из меня плохой и скучный гид :)',
'Тогда вперед и только вперед!',
'Отлично, продолжим!',
'Наша экскурсия продолжается.',
'Продолжим открывать новые грани прекрасной Одессы.'
],
2: [
'Я уже начала волноваться, что ты не вернешься'
]
};
var numpadInputs = {
notIntegerInput: [
'Так не получится, только цифры подходят',
'Я уже говорила, что тут цифровой код?',
'Как считаешь, почему я пробовала ввести известные даты? Тут только цифры ввести можно',
'Так каши с тобой мы не сварим. Давай попробуем цифры',
'Ээээ... Это точно цифры?'
],
longInput: [
'Тут код на 4 цифры всего, есть еще варианты?',
'Четырех цифр достаточно. Давай еще раз',
'Нет, так не подходит. Больше не значит лучше. Нужно 4-ре цифры',
'Слушай, а ты не торопись, это же моя жизнь зависит от 4-х цифр. Ударение на слово 4-х'
]
};
var isTyping = {
terminal: '...',
alla: '...',
eva: '...'
};
// It's not a hyphen, a long dash symbol
// Type by "Alt + Shift + -" (OSX)
// You can check it in editor, it will be highlighted as syntax error, if used
var needToLeave = {
leave: '— Мне нужно отойти —',
cameBack: '— Давай продолжим —',
leaveReplies: ['Да, конечно. Я подожду.', 'Без проблем.', 'Надеюсь не потому, что скучно :) Жду!', 'Я буду здесь.', 'Ой, только не очень долго, пожалуйста.'],
cameBackReplies: ['Ура! Идем дальше.', 'Да, продолжим.', 'Отлично!', 'Отлично, а то я уже начала беспокоиться.', 'Тогда полный вперед!']
};
// ** ** ** ** ** ** ** ** ** ** ** ** **
var miniGames = {
guessMusic: {
genres: ['Классическая', 'Рок-музыка', 'Поп-музыка'],
backToGenres: '— Другой стиль —',
startGame: 'Давай начнём'
},
guessManiac: {
startGame: 'Давай начнём'
},
sendInRange: {
startGame: 'Я готов'
}
};
module.exports = {
skipDelay: 'Не хочу ждать!',
reminders: waitingAnswers,
wrongInput: wrongAnswers,
wrongInputEng: wrongAnswersEng,
numpadInputs: numpadInputs,
comeBackMessage: comeBackMessage,
system: system,
needToLeave: needToLeave,
isTyping: isTyping,
miniGames: miniGames
};<file_sep>/telegram_bot/helpers/messaging.js
console.logger('Init: Messaging Logic');
var User = require('./user');
var Scheduler = require('./user-scheduler');
var sendMessage = require('./send-messages');
var storyHelper = require('./story-helpers');
var analytics = require('./analytics');
var utils = require('./utils');
var config = require('../config');
var str = require('./string-constants');
var DBUsers = require('./db').dbUsers;
var miniGames = require('./minigames');
var getStory = function (file, lang) {
switch (file) {
case 'file1':
case 0:
case '0':
if (/ru/gi.test(lang)) return require('../../scenarios/FirstAid_rookie.json');
return require('../../scenarios/FirstAid_rookie_en.json');
case 'file2':
case 1:
case '1':
if (/ru/gi.test(lang)) return require('../../scenarios/FirstAid_pro.json');
return require('../../scenarios/FirstAid_pro_en.json');
}
};
var getPath2Media = function (type, media) {
switch (type) {
case 'gif':
return media ? media : null;
break;
default:
return media ? '..' + media : null;
}
};
var checkReply = function (curUser, input) {
input = input.trim();
var curBlock = curUser.progress.block;
var nextBlock;
var story = getStory(curUser.progress.game, curUser.locale);
var userId = curUser['_id'];
var lang = curUser['locale'];
function checkPatternAndGetNextBlock() {
var index = -1;
var type = story[curBlock]['replies']['type'];
var choices = story[curBlock]['replies']['choices'];
if (type === 'numpad') {
return storyHelper.checkAllaNumberOnInput(curUser, input);
}
if (type === 'guess-music' || type === 'guess-music-block') {
return miniGames.guessMusic(curUser, input);
}
if (type === 'guess-maniac' || type === 'guess-maniac-block') {
return miniGames.guessManiac(curUser, input);
}
if (type === 'send-in-range' || type === 'send-in-range-block') {
return miniGames.sendInRange(curUser, input);
}
if (input === str.needToLeave.leave) {
return storyHelper.needToLeave.leave(curUser);
}
if (input === str.needToLeave.cameBack) {
return storyHelper.needToLeave.cameBack(curUser);
}
story[curBlock]['replies']['choices'].forEach(function (r, i) {
if (sendMessage.checkReplyLength(r.message).check.trim() === input.trim()) {
index = i;
}
});
if (story[curBlock]['replies']['type'] === 'system') {
story[curBlock]['replies']['choices'].forEach(function (r, i) {
if (r.block.trim() === input.trim()) {
index = i;
}
});
}
if (index !== -1) {
console.logger(curUser['_id'], ' user has clicked: ', choices[index]['message']);
console.logger(curUser['_id'], ' next block is ', choices[index]['block']);
return choices[index]['block'];
} else {
return null;
}
}
// Last seen parameter on all user inputs, if replies are allowed
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']}, {'$set': {'lastSeen': utils.getNow()}},
function () {
console.logger(curUser['_id'] + ' lastSeen parameter was updated');
db.close()
}
);
});
nextBlock = checkPatternAndGetNextBlock();
if (nextBlock !== null) { // Next block is found and can be used
var comeback = null;
if (curUser.reminders.active > 0) { // removing reminders if there were some
comeback = utils.getRandomItem(str.comeBackMessage[curUser.progress.game], curUser.name.first);
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']}, {'$set': {'reminders.active': 0}},
function () {
console.logger(curUser['_id'] + ' all active reminders were reset');
db.close()
}
);
});
}
if (nextBlock === 'stop-main-dialogs') return; // if blocks are handled separately, like numpad
analytics.sendPageView(userId, 'messageBlock=' + curUser.progress.block, 'Block: ' + curUser.progress.block);
// working with the next block
curUser.progress.block = nextBlock;
curUser.actions.replyAllowed = false;
curUser.progress.line = 0;
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']},
{
'$set': {
'progress.block': curUser.progress.block,
'actions.replyAllowed': curUser.actions.replyAllowed,
'progress.line': curUser.progress.line
}
},
function () {
console.logger(curUser['_id'] + ' moved to the next block -> ' + curUser.progress.block);
Scheduler.add({
delay: .1, uid: curUser['_id'], event: function () {
dialogQueue(curUser, null, comeback);
}
});
db.close();
}
);
});
} else {
// Unsupported answer was given, show some message (logic later?)
curUser.progress.line = curUser.progress.line > 0 ? curUser.progress.line - 1 : 0;
dialogQueue(curUser, utils.getRandomItem(/ru/gi.test(lang) ? str.wrongInput : str.wrongInputEng, curUser.name.first));
sendMessage.sendToChat(curUser, input);
}
};
var dialogQueue = function (curUser, wrongAnswerText, comeback) {
var story = getStory(curUser.progress.game, curUser.locale);
var currentBlock = story[curUser.progress.block];
if (!currentBlock['messages']) throw 'no messages in ' + currentBlock;
var currentLineNum = curUser.progress.line || 0,
blockLength = currentBlock['messages'].length,
currentLine = currentBlock['messages'][currentLineNum],
answer = currentBlock['replies'];
var lastLine = currentLineNum >= blockLength - 1;
var delay = 0;
var canSkip = false;
var parseTextVars = function (text) {
var varReg = /\{([^}]*)}/g;
var result = varReg.exec(text);
if (result) {
if (result[1] === 'guideNumber') {
text = text.replace(/\{([^}]*)}/g, curUser.progress.guideNumber);
}
}
return text;
};
var text;
if (config.env === 'local') {
delay = config.delayLimit ? Math.min(currentLine.delay, config.delayLimit) : currentLine.delay;
var pauseText = '\n(' + currentLine.delay.toFixed(2) + ' | ' + delay.toFixed(2) + ' сек)';
text = 'Block: "' + curUser.progress.block + '"\n' + parseTextVars(currentLine.text) + ((!lastLine) ? pauseText : '');
} else {
if (!lastLine || (currentBlock['final'] && lastLine)) {
delay = config.delayLimit ? Math.min(currentLine.delay, config.delayLimit) : currentLine.delay;
}
text = parseTextVars(currentLine.text);
}
if (!lastLine && delay >= config.skipDelayThreshold) {
canSkip = true;
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']},
{
'$set': {
'actions.canSkip': canSkip,
'progress.line': currentLineNum
}
},
function () {
console.logger(curUser['_id'] + ' can skip block "' + currentBlock + '" on line - ' + currentLineNum);
db.close();
}
);
});
}
if (!wrongAnswerText) {
var nextDelay = 0;
if (comeback) {
sendMessage.send({
id: curUser['_id'],
chapter: curUser.progress.game,
answer: answer,
text: comeback,
link: currentLine.link,
speaker: currentLine.speaker,
type: 'text'
});
nextDelay = 4;
}
Scheduler.add({
delay: nextDelay, uid: curUser['_id'], event: function () {
sendMessage.send({
id: curUser['_id'],
chapter: curUser.progress.game,
answer: answer,
text: text,
link: currentLine.link,
status: currentLine.status,
speaker: currentLine.speaker,
image: (config.platform === 'telegram') ? getPath2Media(currentLine.type, currentLine.image) : currentLine.image,
video: (config.platform === 'telegram') ? getPath2Media(currentLine.type, currentLine.video) : currentLine.video,
audio: (config.platform === 'telegram') ? getPath2Media(currentLine.type, currentLine.audio) : currentLine.audio,
caption: currentLine.caption || text,
type: currentLine.type,
lastLine: lastLine,
canSkip: canSkip
}, callback);
}
});
} else {
sendMessage.send({
id: curUser['_id'],
chapter: curUser.progress.game,
answer: answer,
text: wrongAnswerText,
link: currentLine.link,
speaker: currentLine.speaker,
image: null,
video: null,
caption: null,
type: 'text',
lastLine: true
});
}
function callback() {
curUser.progress.line = currentLineNum + 1;
if (!lastLine) {
Scheduler.add({
delay: delay, uid: curUser['_id'], event: function () {
dialogQueue(curUser);
}
});
} else {
if (!currentBlock['final']) {
if (currentBlock['messages'].some(function (m) {
return m.type === 'image' || m.type === 'video' || m.type === 'audio'
})) {
// looking for media block
if (!curUser.progress.media[curUser.progress.game]) {
curUser.progress.media[curUser.progress.game] = [];
}
curUser.progress.media[curUser.progress.game].push(Number(currentBlock['serial']));
}
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']},
{
'$set': {
'actions.replyAllowed': true,
'actions.systemAllowed': answer['type'] === 'system',
'progress.answer': answer,
'progress.speaker': currentLine.speaker,
'progress.media': curUser.progress.media
}
},
function () {
console.logger(curUser['_id'] + ' waiting for an answer');
db.close();
}
);
});
} else {
// if (!isNaN(Number(currentBlock['final']))) {
// curUser.progress.game = Number(currentBlock['final']);
// }
curUser.progress.game = currentBlock['final'];
if (currentBlock['final'] == '3') {
curUser.progress.game = '0';
}
curUser.progress.line = 0;
curUser.progress.block = 'Start';
curUser.actions.systemAllowed = true;
sendMessage.sendToChat(curUser, '<b>Started the chapter - </b>' + curUser.progress.game);
if (curUser.progress.game == 0) {
curUser.actions.systemAllowed = true;
}
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']},
{
'$set': {
'progress.game': curUser.progress.game,
'progress.line': curUser.progress.line,
'progress.block': curUser.progress.block,
'actions.systemAllowed': curUser.actions.systemAllowed
}
},
function () {
console.logger(curUser['_id'] + ' final block');
Scheduler.add({
delay: delay, uid: curUser['_id'], event: function () {
dialogQueue(curUser);
}
});
db.close();
}
);
});
}
}
}
};
module.exports = {
checkReply: checkReply,
dialogQueue: dialogQueue
};<file_sep>/telegram_bot/helpers/db.js
console.logger('Init: MongoDB');
var config = require('../config');
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/' + config.platform + '-' + config.env;
var dbUsers = function (callback) {
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
var collection = db.collection('users');
if (callback) callback(db, collection);
});
};
var dbGifs = function (callback) {
MongoClient.connect('mongodb://localhost:27017/gif-links', function (err, db) {
assert.equal(null, err);
var collection = db.collection('gifs');
if (callback) callback(db, collection);
});
};
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.logger('Connected successfully to server');
db.close();
});
module.exports = {
client: MongoClient,
test: assert,
url: url,
dbUsers: dbUsers,
dbGifs: dbGifs
};<file_sep>/telegram_bot/helpers/user.js
console.logger('Init: Users');
var DB = require('./db');
var utils = require('./utils');
var users = [];
var useDB = function(callback){
DB.client.connect(DB.url, function(err, db){
DB.test.equal(null, err);
var collection = db.collection('users');
if (callback) callback(db, collection);
});
};
module.exports = {
blueprint: function(user){
return {
_id: user['_id'],
name: {
first: user['first_name'] || '',
last: user['last_name'] || ''
},
username: user['username'] || null,
sex: user['sex'] || null,
age: user['age'] || null,
email: user['email'] || null,
profile_pic: user['profile_pic'] || null,
locale: user['locale'] || null,
timezone: user['timezone'] || null,
lastSeen: utils.getNow(),
createdOn: utils.getNow(),
reminders: {
active: 0,
overall: 0
},
progress: {
media: {},
game: 'file1',
line: 0,
guideNumber: String(utils.randomFixedInteger(4)),
guideNumberTry: '',
speaker: null,
answer: null,
miniGames: {
musicGuess: {
set: null,
songs: []
},
maniacGuess: [],
sendInRange: null
},
block: 'Start'
// block: 'Вот им и подсвети себе'
},
actions: {
replyAllowed: false,
systemAllowed: false,
canSkip: false
}
}
},
set: function(user, callback){
user = this.blueprint(user);
users.push(user);
console.logger(user['_id'] + ' set user');
console.logger(user['_id'] + ' set allaCode: ' + user['progress']['guideNumber']);
useDB(function(db, collection){
collection.insertOne(user, function(err, response){
DB.test.equal(null, err);
DB.test.equal(1, response.insertedCount);
console.logger(user['_id'] + ' user was set successfully');
if (callback && response) callback(response.ops[0]);
db.close();
});
});
},
get: function(id, callback){
var user;
useDB(function(db, collection){
collection.find({'_id': id}).toArray(function(err, docs){
DB.test.equal(null, err);
user = docs.length > 0 ? docs[0] : null;
if (callback) callback(user);
console.logger(user ? user['_id'] : null, ' get user result successfully');
db.close();
});
});
},
update: function(user, callback){
user.lastSeen = utils.getNow();
useDB(function(db, collection){
collection.updateOne({'_id': user['_id']}, user, {'upsert': true, 'w': 1}, function(err, docs){
DB.test.equal(null, err);
if (docs.result.ok) {
console.logger(user['_id'], ' user updated ', user.progress.block);
if (callback) callback(user);
}
});
});
},
removeUser: function(id, callback) {
useDB(function(db, collection) {
collection.remove({'_id': id},
function() {
if (callback) callback();
db.close();
});
});
}
};<file_sep>/telegram_bot/helpers/utils.js
var randomFixedInteger = function (length) {
return Math.floor(Math.pow(10, length - 1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length - 1) - 1));
};
var getNow = function () {
return (new Date).getTime();
};
(function () {
function addZero(num) {
return num < 10 ? '0' + num : num;
}
Date.prototype.getStringDate = function () {
return addZero(this.getDate()) + '.' + addZero(this.getMonth()) + '.' + addZero(this.getFullYear()) + ' ' +
addZero(this.getHours()) + ':' + addZero(this.getMinutes()) + ':' + addZero(this.getSeconds());
};
console.logger = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift('=> ' + (new Date()).getStringDate() + ' - ');
console.log.apply(console, args);
};
})();
var getRandomItem = function (array, name) {
var text = array[Math.floor(Math.random() * array.length)];
if (name) text = text.replace(/\{user_name}/gmi, name);
return text;
};
var getUserMap = function (user, text) {
var message = '<b>Карта пользователя:</b>\n' +
'<b>ID:</b> ' + user['_id'] + '\n' +
(user['username'] ? ('<b>Username:</b> @' + user['username'] + '\n') : '') +
'<b>Name:</b> ' + user['name']['first'] + ' ' + user['name']['last'] + '\n' +
'<b>Chapter: </b>' + user['progress']['game'] + '\n' +
'<b>Block:</b> ' + user['progress']['block'] + '\n';
if (text) message += (text + '\n');
return message;
};
console.logger('Init: Utils');
module.exports = {
randomFixedInteger: randomFixedInteger,
getNow: getNow,
getRandomItem: getRandomItem,
getUserMap: getUserMap
};<file_sep>/utils/Twinery2JSON/check-media.js
'use strict';
const fs = require('fs');
const path = require('path');
const baseDir = '../_Media';
function fileExists(filePath) {
function fileExistsWithCaseSync(filepath) {
var dir = path.dirname(filepath);
if (dir === '/' || dir === '.') return true;
var filenames = fs.readdirSync(dir);
if (filenames.indexOf(path.basename(filepath)) === -1) {
return false;
}
return fileExistsWithCaseSync(dir);
}
filePath = baseDir + filePath;
return fileExistsWithCaseSync(filePath)
}
function checkMedia(files, callback) {
let chapters = files;
let overallErrors = 0;
chapters.forEach((chapter, index) => {
let errors = 0;
for (let block in chapter) {
if (chapter.hasOwnProperty(block)) {
if (chapter[block].messages.length > 0) {
chapter[block].messages.forEach((bubble) => {
let path = null,
result = null;
switch (bubble.type) {
case 'image':
path = bubble.image;
break;
case 'video':
path = bubble.video;
break;
case 'audio':
path = bubble.audio;
break;
case 'gif':
//path = bubble.text;
break;
}
if (path) {
result = fileExists(path);
if (result) {
// console.log('OK: ' + path);
} else {
errors++;
console.log(`=> ERROR: ${bubble.type} - ${path}`);
}
}
});
}
}
}
if (errors === 0) {
console.log('OK: All files are in place');
console.log('##########################');
}
overallErrors += errors;
});
if (overallErrors === 0) {
console.log('Testing MEDIA is finished');
console.log('##########################\n');
if (callback) callback();
}
}
module.exports = {
start: checkMedia
};<file_sep>/telegram_bot/helpers/analytics.js
console.logger('Init: Analytics');
var config = require('../config');
var ga = require('./ga');
var sendPageView = function(userid, pagename, label){
var visitor = ga.ua(ga.gaId, userid, {strictCidFormat: false});
visitor.pageview({
dp: '/' + config.platform + '/' + pagename,
dt: label,
dh: config.hostname
}, function(err){
if (err) console.logger(err);
});
};
module.exports = {
sendPageView: sendPageView
};<file_sep>/telegram_bot/helpers/send-messages.js
console.logger('Init: Sending Messages');
var Utils = require('./utils');
var bot = require('../bot');
var caching = require('./file-caching');
var config = require('../config');
var DBGifs = require('./db').dbGifs;
// var miniGames = require('./minigames');
var str = require('./string-constants');
var checkReplyLength = function (text) {
var pattern = /==\/==/gmi;
var result;
text = text.trim();
if (pattern.test(text)) {
result = text.split(pattern);
return {
check: result[0],
text: result[0] + '\n' + result[1]
}
}
return {
check: text,
text: text
};
};
var sendMessage = function (message, callback) {
var keyboardType, keyboardMarkup;
var cachingName;
var answerLines = [];
var LINK_RGXP = /(<a href.*<\/a>)/;
if (message.text) {
if (message.speaker === 'terminal') {
LINK_RGXP.lastIndex = 0;
if (LINK_RGXP.test(message.text)) {
var link = LINK_RGXP.exec(message.text)[0];
message.text = message.text.replace(LINK_RGXP, '');
message.text = '<b>' + message.text + '</b>';
message.text += link;
} else {
message.text = '<b>' + message.text + '</b>';
}
}
}
if (message.lastLine) {
if (message.answer.type === 'numpad') {
//keyboardType = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['0']];
keyboardType = [[str.system.allaCode]];
} else if (message.answer.type === 'system') {
keyboardMarkup = {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[
{
text: message.answer.choices[0]['message'],
callback_data: message.answer.choices[0]['block']
}
]
]
}
};
} else if (message.answer.type === 'guess-music-block') {
answerLines.push([str.miniGames.guessMusic.startGame]);
keyboardType = answerLines;
} else if (message.answer.type === 'guess-maniac-block') {
answerLines.push([str.miniGames.guessManiac.startGame]);
keyboardType = answerLines;
} else if (message.answer.type === 'send-in-range-block') {
answerLines.push([str.miniGames.sendInRange.startGame]);
keyboardType = answerLines;
} else {
message.answer.choices.forEach(function (choice) {
answerLines.push([checkReplyLength(choice.message).text]);
});
// if (message.answer.choices.length > 0
// && checkReplyLength(message.answer.choices[0].message).text !== str.needToLeave.cameBack
// && message.answer.type !== 'guess-music'
// && message.answer.type !== 'guess-maniac'
// && message.answer.type !== 'send-in-range'
// ) {
// answerLines.push([str.needToLeave.leave]);
// }
keyboardType = answerLines;
}
} else {
keyboardType = [];
if (!message.status) {
if (message.speaker === 'terminal') {
keyboardType.push([str.isTyping.terminal]);
} else if (message.speaker === 'alla') {
keyboardType.push([str.isTyping.alla]);
} else {
keyboardType.push([str.isTyping.eva]);
}
} else {
keyboardType.push([message.status]);
}
// if (message.canSkip) keyboardType.push([str.skipDelay]);
}
keyboardMarkup = !keyboardMarkup ? {
parse_mode: 'HTML',
reply_markup: {
caption: message.caption,
force_reply: false,
keyboard: keyboardType,
one_time_keyboard: false,
resize_keyboard: true
}
} : keyboardMarkup;
if (!message.lastLine) {
keyboardMarkup['disable_notification'] = true;
}
function sendVideoDirect() {
bot.sendVideo(message.id, message.video, keyboardMarkup).then(
function (value) {
caching.cacheFile(cachingName, message.video, value['video']['file_id']);
if (callback) callback();
bot.sendMessage(message.id, '<b>Видео отправлено</b>', keyboardMarkup);
},
function (reason) {
var err = JSON.parse(/({.*})/.exec(reason)[1]);
// console.log(err.description)
if (callback) callback();
console.log(err);
bot.sendMessage(message.id, '<b>Ошибка при отправке видео</b> - ' + message.video, keyboardMarkup);
}
);
}
function sendPhotoDirect() {
bot.sendPhoto(message.id, message.image, keyboardMarkup).then(
function (value) {
if (Object.prototype.toString.call(value['photo']) === '[object Array]') {
caching.cacheFile(cachingName, message.image, value['photo'][value['photo'].length - 1]['file_id']);
} else {
caching.cacheFile(cachingName, message.image, value['photo']['file_id']);
}
if (callback) callback();
bot.sendMessage(message.id, '<b>Фото отправлено</b>', keyboardMarkup);
},
function () {
callback && callback();
bot.sendMessage(message.id, '<b>Ошибка при отправке фото</b> - ' + message.image, keyboardMarkup);
}
);
}
function sendAudioDirect() {
bot.sendVoice(message.id, message.audio, keyboardMarkup).then(
function (value) {
caching.cacheFile(cachingName, message.audio, value['voice']['file_id']);
if (callback) callback();
bot.sendMessage(message.id, '<b>Аудио отправлено</b>', keyboardMarkup);
},
function (err) {
console.log(message.audio);
console.log(err);
callback && callback();
bot.sendMessage(message.id, '<b>Ошибка при отправке аудио</b> - ' + message.audio, keyboardMarkup);
}
);
}
switch (message.type) {
case 'text':
bot.sendMessage(message.id, message.text, keyboardMarkup).then(
function () {
callback && callback()
},
function () {
callback && callback()
}
);
break;
case 'link':
sendLink({
id: message.id,
text: message.text,
url: message.link,
keyboard: keyboardMarkup,
lastLine: message.lastLine,
callback: callback
});
break;
case 'gif':
DBGifs(function (db, collection) {
collection.find({url: message.image}).toArray(function (err, docs) {
if (!err && docs.length > 0) {
message.image = config.gifService + docs[0]['name'];
}
bot.sendMessage(message.id, message.image, keyboardMarkup).then(
function () {
callback && callback()
},
function () {
callback && callback()
}
);
db.close();
});
});
break;
case 'image' || 'photo':
cachingName = message.chapter + message.image.substring(message.image.lastIndexOf('/'), message.image.length);
caching.getFileId(cachingName, function (cachingId) {
if (cachingId) {
bot.sendPhoto(message.id, cachingId, keyboardMarkup).then(
function () {
if (callback) callback();
bot.sendMessage(message.id, '<b>Фото отправлено</b>', keyboardMarkup);
},
function () {
sendPhotoDirect()
}
)
} else {
sendPhotoDirect()
}
});
break;
case 'video':
cachingName = message.chapter + message.video.substring(message.video.lastIndexOf('/'), message.video.length);
caching.getFileId(cachingName, function (cachingId) {
if (cachingId) {
bot.sendVideo(message.id, cachingId, keyboardMarkup).then(
function () {
if (callback) callback();
bot.sendMessage(message.id, '<b>Видео отправлено</b>', keyboardMarkup);
},
function (reason) {
var err = JSON.parse(/({.*})/.exec(reason)[1]);
// Send an error to analytics
console.logger(err.description);
sendVideoDirect();
}
)
} else {
sendVideoDirect()
}
});
break;
case 'audio':
cachingName = message.chapter + message.audio.substring(message.audio.lastIndexOf('/'), message.audio.length);
caching.getFileId(cachingName, function (cachingId) {
if (cachingId) {
bot.sendVoice(message.id, cachingId, keyboardMarkup).then(
function () {
if (callback) callback();
bot.sendMessage(message.id, '<b>Аудио отправлено</b>', keyboardMarkup);
},
function () {
sendAudioDirect()
}
)
} else {
sendAudioDirect()
}
});
break;
case 'sticker':
bot.sendSticker(message.id, message.sticker);
break;
}
};
var openStats = function (id) {
sendLink({id: id, text: 'Хотите узнать, чего уже достигли?', url: 'https://lookright.net/user/telegram/' + id});
};
var sendLink = function (params) {
var id = params.id,
text = params.text,
url = params.url,
keyboardMarkup = params.keyboard,
lastline = params.lastLine,
callback = params.callback;
if (url.indexOf('http') === -1) {
keyboardMarkup = lastline ? keyboardMarkup : {parse_mode: 'HTML'};
bot.sendMessage(id, '<b>Внутренняя ошибка Look Right: ссылка не может быть отправлена</b>', keyboardMarkup);
if (callback) callback();
} else {
console.log(url);
var keyboard = {
parse_mode: 'HTML',
disable_notification: true,
reply_markup: {
inline_keyboard: [
[
{
text: 'Открыть страницу',
url: url
}
]
]
}
};
bot.sendMessage(id, text, keyboard).then(function (res) {
if (lastline) bot.sendMessage(id, '<b>Ссылка отправлена</b>', keyboardMarkup);
if (callback) callback();
}).catch(function (err) {
console.logger(err);
if (lastline) bot.sendMessage(id, '<b>Ссылка не может быть отправлена</b>', keyboardMarkup);
if (callback) callback();
});
}
};
var sendToChat = function(user, input){
// var CHAT_ID = '-196933883';
// var message = Utils.getUserMap(user, input ? ('<b>Message:</b> ' + input) : null);
//
// if (config.env !== 'local' && config.env !== 'test') {
// bot.sendMessage(CHAT_ID, message, {
// parse_mode: 'HTML'
// }).then(function () {
// bot.sendMessage(CHAT_ID, '/botsend ' + user['_id'] + ' "<b>YOUR_MESSAGE_HERE</b>"\n');
// });
// }
};
module.exports = {
send: sendMessage,
checkReplyLength: checkReplyLength,
stats: openStats,
sendToChat: sendToChat
};<file_sep>/utils/Twinery2JSON/reducer.js
'use strict';
const fs = require('fs');
const fileName = 'Chapter 1 eng.json';
const path = '../Twines/Jsons/';
const file = require(path + fileName);
function replacer(key, value) {
if (value === null) return undefined;
return value;
}
fs.writeFile(path + fileName, JSON.stringify(file, replacer, '\t'), 'utf-8', () => {
console.log('Done');
});<file_sep>/telegram_bot/inline_specific/first_aid_responses.js
var ambulance = {
ru: [
'Позовите окружающих людей на помощь.',
'Вызовите скорую или попросите кого-то это сделать.',
'Сообщите скорой: Что случилось. Где случилось. Примерный возраст пострадавшего. Пол пострадавшего. Ответьте на вопросы диспетчера. Диспетчер должен повесить трубку первым.',
'Позаботьтесь, чтобы скорую было кому встретить.'
],
en: [
'Shout out for others to help.',
'Call the ambulance number or ask somebody to do it.',
'Tell the ambulance: what happened, where, rough age of injured person, gender. Answer to all operator’s questions. Operator should hang up first.',
'Make sure there is somebody to meet an ambulance crew.'
]
};
var injuries = {
ru: [
{
title: 'Сильное кровотечение',
response: [
'Попросите пострадавшего плотно прижать рану рукой. Это должно замедлить кровотечение',
]
},
{
title: 'Сбила машина',
response: [
'Оградите место ДТП любым удобным вам способом: аварийный треугольник из багажника, аварийные сигнализации других машин, конусами, жилетами и т.д.',
'Выясните нужна ли участникам ДТП медицинская помощь обратившись к ним. Если они получили травмы или просят вызывать скорую. ВЫЗОВИТЕ СКОРУЮ.',
'Постарайтесь определить человека, который получил наиболее серьезные травмы. Например, пешеход, которого сбила машина.',
'Обратитесь к пострадавшему с просьбой не двигаться. Движения могут причинить вред.'
]
},
{
title: 'Получил ожог',
response: [
'Сначала, убедись, что одежда не горит и не тлеет, что причина ожога устранена',
'Охладите место ожога холодной водой из под крана',
'Пока ему не станет холодно',
'Но не дольше 20 минут',
'Когда станет холодно, прекратите поливать ожог водой.',
'Скорую вызывайте по своему усмотрению, обязательно вызывать если: ожог большой площади (больше 5 его ладоней), обожжены стопы, кисти, лицо или пах. Так же, если ожоги глубокие.'
]
},
{
title: 'Упал с высоты',
response: [
'Обратитесь к пострадавшему с просьбой не двигаться. Движения могут причинить вред.',
'Выясните нужна ли пострадавшему медицинская помощь обратившись к нему. Если он получил травмы или просит вызывать скорую – вызовите скорую.',
]
},
{
title: 'Сломал конечность',
response: [
'Попросите пострадавшего не двигаться. Это очень важно.',
'Подложите мягкую ткань под сломанную конечность, обеспечив этим комфорт пострадавшего.',
'Если пострадавший сломал руку и он в состоянии поддерживать ее здоровой рукой – не мешайте этому.',
'Не пытайтесь вправить перелом или наложить шину. Это может навредить.',
'Убедитесь, что скорая едет и ее есть кому встретить.'
]
},
{
title: 'Человек без сознания',
response: [
'Обратитесь к нему. Громко спросите: "Вы меня слышите? С вами все в порядке?".',
]
},
{
title: 'Подавился',
response: [
'Громко спросите "Вы подавились?"',
'Если <b>ответил голосом и кашляет</b> - не вмешивайтесь!',
'Не давайте воды и не стучите по спине.',
'Скажите, что бы продолжал кашлять и успокаивайте. Слега наклоните пострадавшего вперед.',
'Если <b>не может говорить и кашлять</b>',
'Счет может идти на минуты.',
'Пусть кто-то вызовет скорую и спросите, умеет ли кто-то делать прием Геймлиха.',
'Если нет, срочно действуйте сами: наклоните вперед, 5 скользящих ударов по спине, 5 раз сильно сдавите живот. Повторять, пока не откашляется.'
]
},
{
title: 'Болит сердце',
response: [
'Проверьте, есть ли следующие симптомы:',
'Затрудненное дыхание',
'Боль в груди, которая отражается в шею, руку, живот.',
'Холодный пот, чувство страха.',
'Если таких симптомов <b>нет</b>, то скорее всего это не сердечный приступ.',
'В противном случае или для страховки вызывайте скорую.',
]
},
{
title: 'Подозрение на инсульт',
response: [
'1. Есть ли критичные изменения в поведении пострадавшего? Например: внезапная слепота, дезориентация в пространстве, внезапное сильное головокружение, и тд.',
'2. Попросите пострадавшего улыбнуться. Улыбка симметрична? (должна быть симметричной)',
'3. Попросите пострадавшего одновременно поднять обе руки перед собой. Симметрично ли он поднял руки?',
'Если что-то из этого есть, вызывайте скорую помощь',
'ВАЖНО! Не давайте пострадавшему есть и пить до прибытия скорой.',
'Обеспечьте ему покой, разговаривайте с ним и дайте доступ воздуха, например, открыв окно.',
]
},
{
title: 'Судорожный припадок',
response: [
'Быстро положите его голову на свою ногу или подложите что-то мягкое (например, куртку или свитер).',
'Чтобы человек не повредил голову',
'ВАЖНО! Не пытайтесь открыть рот пострадавшего или вставить что-то ему в зубы - это неправильно и опасно. Не допускайте, чтобы это сделал кто-то другой.',
'Выполните следующие действия:',
'Если можете, поверните пострадавшего на бок.',
'Придерживайте его, чтобы он не травмировал себя.',
'Особенно голову.',
'Но не пытайтесь обездвижить человека и не давите сильно. Это может навредить.'
]
}
],
en: [
{
title: 'Heavy bleeding',
response: [
'Ask injured to press and hold his wound tightly.',
'It should slow down the bleeding.',
]
},
{
title: 'Hit by a car',
response: [
'Protect an accident area using any available method: an emergency sign, other cars alarms, cones, bright vests, etc.',
'Ask accident participants if they need any medical aid. If any of them are injured or they ask for a help - CALL AN AMBULANCE.',
'Try to define who\'s got the most heavy injures. For ex., a pedestrian who was hit by a car.',
'Ask injured not to move, as movement can harm even more.'
]
},
{
title: 'Burn',
response: [
'Make sure the clothes aren\'t on fire and do not smolder, the burn reason is eliminated.',
'Cool the burn with cold tap water, until he starts feeling cold.',
'Then stop watering a burn.',
'When he\'ll start feeling the burning cool it again.',
'Call an ambulance at your discretion.',
'In next cases calling an ambulance is essential: burn takes big area (more than 5 palms); feet, hands, face or groin are burned, burns are deep.'
]
},
{
title: 'Fell from a height',
response: [
'Ask injured not to move, as movement can harm even more.',
'Ask injured if he needs any medical aid. If he got injured or asks to call an ambulance - call it.',
]
},
{
title: 'Broke a limb',
response: [
'Ask injured not to move, this is very important.',
'Put some soft fabric under the broken limb, ensuring injured\'s comfort.',
'If injured broke his arm but is able to hold it with a healthy one - do not prevent it.',
'Don\'t try to repair a fracture or splint it. That might make things worse.',
'Make sure an ambulance is coming and there is somebody to meet it.'
]
},
{
title: 'Person is unconscious',
response: [
'Talk to him, ask loudly: \"Can you hear me? Are you okay?\"',
]
},
{
title: 'Choked',
response: [
'Ask loudly: "Have you choked?"',
'If <b>voiced a reply, coughing</b> - do not interfere!',
'Do not give him water and don\'t hit his back.',
'Tell to keep coughing and calm him down, slightly lean him forward.',
'If <b>cannot speak and cough</b>',
'Injured might have only couple of minutes left.',
'Ask somebody to call an ambulance and if anyone can do the Heimlich maneuver.',
'If no, you should do it yourself: lean injured forward, make 5 back slaps, then 5 quick and strong abdomen presses. Repeat until expectorates.'
]
},
{
title: 'Heart attack',
response: [
'Check for the next symptoms:',
'Labored breathing',
'A chest pain which is referred to the neck, arm or stomach.',
'Cold sweat, fear.',
'If there are <b>no</b>such symptoms, most likely it is not a heart attack.',
'Nevertheless, if you have some doubts, better call an ambulance to be safe.',
]
},
{
title: 'Suspected stroke',
response: [
'Do next steps:',
'1. Are there any critical changes in injured’s behavior? Like sudden blindness, disorientation, heavy dizziness, etc.',
'2. Ask an injured to smile. Does his smile look asymmetrical? (should be symmetrical)',
'3. Ask injured to raise both hands in front of him. Does he keep them asymmetrically? (should be symmetrically)',
'If an answer on any of these questions is YES, call an ambulance.',
'IMPORTANT! Do not let injured drink or eat until an ambulance comes.',
'Provide him comfort, talk to him and make sure he has fresh fresh air (open a window, for ex.)',
]
},
{
title: 'Convulsive seizures',
response: [
'Quickly move his head onto your leg or put something soft under it (like jacket or pullover).',
'To prevent injured from hurting his head.',
'IMPORTANT! Do not try to open an injured’s mouth and put something between his teeth. This is very dangerous, prevent others from doing it.',
'Follow next steps:',
'If you can roll injured to his side.',
'Hold him, so he couldn\'t hurt himself. Especially his head.',
'But don\'t try to immobilize him or push him too hard, that might harm.'
]
}
]
};
function getInjureResponses(lang, query) {
if (query.length) lang = /[а-яА-Я]/g.test(query) ? 'ru' : 'en';
// lang = lang.indexOf('ru') !== -1 ? 'ru' : 'en';
// lang = 'ru';
var injuriesFiltered = injuries[lang].filter(function (elem) {
return elem.title.toLowerCase().indexOf(query.toLowerCase()) !== -1;
});
var injuriesToShow = injuriesFiltered.length ? injuriesFiltered : injuries[lang];
var ambulanceText = ambulance[lang].map(function(a, i) {
return String(i + 1) + '. ' + a;
});
return injuriesToShow.map(function (elem, ind) {
var responses = elem.response.map(function(r, i){
return String(i + 1) + '. ' + r;
});
responses.unshift('<i>' + elem.title + '</i>\n');
responses.push('_______________________');
return {
type: 'article',
id: String(ind),
title: elem.title,
// thumb_url: elem.image,
// thumb_width: 20,
// thumb_height: 20,
input_message_content: {
message_text: responses.concat(ambulanceText).join('\n'),
parse_mode: 'HTML'
}
}
});
}
module.exports = {
getInjureResponses: getInjureResponses
};<file_sep>/telegram_bot/helpers/reminders.js
console.logger('Init: Reminders');
var DB = require('./db');
var Message = require('./messaging');
var sendMessage = require('./send-messages');
var str = require('./string-constants');
var utils = require('./utils');
(function () {
DB.client.connect(DB.url, function (err, db) {
DB.test.equal(null, err);
db.collection('users').find({'actions.replyAllowed': false}).toArray(function (err, docs) {
DB.test.equal(null, err);
if (docs.length > 0) {
docs.forEach(function (user) {
Message.dialogQueue(user);
});
}
console.logger('Bot was relaunched, users renewed dialogs - ' + docs.length);
db.close();
});
});
})();
var remindersInterval = 30 * 60 * 1000;
var reminderGaps = [
2 * 60 * 1000,
6 * 60 * 1000,
18 * 60 * 60 * 1000
];
var sendReminder = function (user, type) {
if (!user.reminders.active) user.reminders.active = 0;
if (!user.reminders.overall) user.reminders.overall = 0;
DB.dbUsers(function (db, collection) {
collection.updateOne({'_id': user['_id']},
{'$inc': {'reminders.overall': 1, 'reminders.active': 1}},
function () {
console.logger(user['_id'] + ' - reminder was sent ' + type + ' (' + (user.reminders.active + 1) + ')');
db.close();
}
);
});
if (user.progress.answer) {
sendMessage.send({
id: user['_id'],
chapter: user.progress.game,
answer: user.progress.answer,
text: utils.getRandomItem(str.reminders[user.progress.game], user.name.first),
speaker: user.speaker,
type: 'text',
lastLine: true
});
}
};
//
// setInterval(function () {
//
// DB.dbUsers(function (db, collection) {
// collection.find({
// 'actions.replyAllowed': true,
// 'lastSeen': {'$lt': utils.getNow() - reminderGaps[0]}
// }).toArray(function (err, docs) {
// DB.test.equal(null, err);
// if (docs.length > 0) {
// docs.forEach(function (user) {
// if (user.lastSeen < utils.getNow() - reminderGaps[2]) {
// if (user.lastSeen < utils.getNow() - (reminderGaps[2] * (user.reminders.active - 1))) {
// sendReminder(user, 'longest');
// }
// } else if (user.lastSeen < utils.getNow() - reminderGaps[1]) {
// if (user.reminders.active === 1) {
// sendReminder(user, 'middle');
// }
// } else {
// if (user.reminders.active === 0) {
// sendReminder(user, 'first');
// }
// }
// });
// console.logger(docs.length + ' users can potentially get the reminder depending on the absence time');
// } else {
// console.logger('All users are active no need for reminders');
// }
// db.close();
// });
// });
//
// }, remindersInterval);
module.exports = {
send: sendReminder
};<file_sep>/telegram_bot/helpers/file-caching.js
console.logger('Init: Files Caching');
var DB = require('./db');
var useDB = function(callback){
DB.client.connect(DB.url, function(err, db){
DB.test.equal(null, err);
var collection = db.collection('cached-files');
if (callback) callback(db, collection);
});
};
var cacheFile = function(name, path, id, callback){
var file = {
name: name,
path: path,
id: id
};
useDB(function(db, collection){
collection.updateOne({'name': name}, file, {'upsert': true, 'w': 1},
function(err, docs){
DB.test.equal(null, err);
if (docs.result.ok) {
console.logger(file['name'] + ' was added/updated');
if (callback) callback(file['id']);
}
}
);
});
};
var getFileId = function(name, callback){
useDB(function(db, collection){
var file;
collection.find({'name': name}).toArray(function(err, docs){
DB.test.equal(null, err);
file = docs.length > 0 ? docs[0]['id'] : null;
if (file) console.logger(name, ' cached file was found and used');
else console.logger(name, ' cached file wasn\'t found');
if (callback) callback(file);
db.close();
});
});
};
module.exports = {
getFileId: getFileId,
cacheFile: cacheFile
};<file_sep>/utils/Twinery2JSON/index.js
'use strict';
let fs = require('fs'),
parser = require('./parser'),
testMedia = require('./check-media'),
editsGrabber = require('./compare');
// Он обиделся на город?
const twine = '../Twines/Chapter 1.html';
const filesPath = '../Twines/Jsons/';
const jsonName = twine.substring(twine.lastIndexOf('/') + 1, twine.length - 5) + '.json';
let chapters = [];
parser.start(twine, filesPath, () => {
chapters.push(require(filesPath + jsonName));
if (chapters.length > 0) {
testMedia.start(chapters, () => {
});
}
});<file_sep>/telegram_bot/helpers/minigames.js
var Scheduler = require('./user-scheduler');
var messaging = require('./send-messages');
var DBUsers = require('./db').dbUsers;
var str = require('./string-constants');
var utils = require('./utils');
// ***********************************************************
// *** Music mini-game
// ***********************************************************
var musicBasePath = '../../_Media/audio/minigame-maniac/';
var songSets = [
[
{
name: '<NAME> – La Traviata',
path: musicBasePath + 'Classic Traviata.mp3',
alt: {
classic: ['<NAME> –Turandot', '<NAME> – <NAME>'],
rock: ['RHCP – Dani California', 'The Beatles – Yesterday', 'Radiohead – Creep'],
pop: ['Britney Spears – Toxic', 'Backstreet Boys – Everybody', 'Christina Aguilera – Candyman']
}
},
{
name: 'Моё сердце – Сплин',
path: musicBasePath + 'Rock Splin.mp3',
alt: {
classic: ['П.И.Чайковский – Щелкунчик', 'А.П.Бородин – Князь Игорь', 'С.В.Рахманинов – Алеко'],
rock: ['Ленинград – Лабутены', 'ДДТ – Осень'],
pop: ['Тимати – Лада–седан', 'Потап и Настя – Непара', 'На–на — Фаина']
}
},
{
name: '<NAME> – My heart will go on',
path: musicBasePath + 'Pop Dion.mp3',
alt: {
classic: ['Ludwig van Beethoven – Fidelio', 'Vincen<NAME>ini – Norma', 'Léo Delibes – Lakmé'],
rock: ['Led Zeppelin – Kashmir', 'Pink Floyd – Time', 'Scorpions – Wind of Change'],
pop: ['PSY – Gangem style', 'Rhianna – Umbrella']
}
}
],
[
{
name: '<NAME> – Rigoletto',
path: musicBasePath + 'Classic Rigoletto.mp3',
alt: {
classic: ['<NAME> – Faust', 'L’Orfeo – <NAME>'],
rock: ['U2 – Elevation', 'The Doors – Light my fire', 'Chumbawamba – Tubthumping'],
pop: ['Kat<NAME> – Roar', '<NAME> – Wrecking Ball', '<NAME> – Sorry']
}
},
{
name: 'Nirvana – Like a teen spirit',
path: musicBasePath + 'Rock Nirvana.mp3',
alt: {
classic: ['R.Wagner – Siegfried', 'R.Wagner – Das Rheingold', 'R.Wagner – Parsifal'],
rock: ['Nirvana – In bloom', 'Nirvana – Come as you are'],
pop: ['Michael Jackson – Thriller', '<NAME> – Billie Jean', '<NAME> – Black or White']
}
},
{
name: '<NAME> – <NAME>',
path: musicBasePath + 'Pop George Michael.mp3',
alt: {
classic: ['<NAME> – Rusalka', '<NAME> – Pagliacci', 'D.Donizetti - L\'elisir d\'amore'],
rock: ['Motörhead – Ace of Spades', 'Aerosmith – Crazy', 'Limp Bizkit – Break stuff'],
pop: ['Bing Crosby – White Christmas', 'Mariah Carey – Oh Santa']
}
}
],
[
{
name: 'Georges Bizet – Carmen',
path: musicBasePath + 'Classic Carmen.mp3',
alt: {
classic: ['Rich<NAME> – Salome', 'Jacopo Peri – Euridice'],
rock: ['Black Sabbath – Iron man', 'Iron Maiden – The Trooper', 'Slipknot – Snuff'],
pop: ['Roxette – The Look', 'ABBA – Mamma mia', 'Ace of Base – The Sign']
}
},
{
name: 'Show must go on, Queen',
path: musicBasePath + 'Rock Queen.mp3',
alt: {
classic: ['G.Rossini – La Cenerentola', 'G.Rossini – Guillaume Tell', 'G.Rossini – Mosè in Egitto'],
rock: ['Elvis – Jailhouse rock', 'Rolling Stones – Satisfaction'],
pop: ['Madonna – Like a virgin', 'Prince – Purple Rain', 'Sade – Smooth Operator']
}
},
{
name: 'Bad Romance, Lady Gaga',
path: musicBasePath + 'Pop Lady Gaga.mp3',
alt: {
classic: ['Alban Berg – Wozzeck', '<NAME> – Manon', '<NAME> – Cats'],
rock: ['AC/DC – TNT', 'System of a down – Toxicity', 'Metallica – Master of puppets'],
pop: ['Tailor Swift – Shake it off', 'Spice Girls – Wannabe']
}
}
]
];
var MAX_TRIES = songSets[0].length;
var songsPlain = [[], [], []];
var songsPlainAll = [];
songSets.forEach(function (set) {
set.forEach(function (song, index) {
songsPlain[index].push(song.name);
for (var alt in song.alt) {
if (song.alt.hasOwnProperty(alt)) {
songsPlain[index] = songsPlain[index].concat(song.alt[alt]);
}
}
});
});
songsPlainAll = songsPlainAll.concat(songsPlain[0]).concat(songsPlain[1]).concat(songsPlain[2]);
var genres = str.miniGames.guessMusic.genres;
var backToGenres = str.miniGames.guessMusic.backToGenres;
var startGame = str.miniGames.guessMusic.startGame;
var shuffle = function (a) {
var j, x, i;
for (i = a.length; i; i--) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
};
var getSong = function (set, index) {
return songSets[set][index];
};
var getSongsChoices = function (set, index, genre) {
switch (genre) {
case genres[0]:
genre = 'classic';
break;
case genres[1]:
genre = 'rock';
break;
case genres[2]:
genre = 'pop';
break;
}
var list = songSets[set][index].alt[genre].slice(0);
if (list.length < 3) list.push(songSets[set][index].name);
shuffle(list);
return list;
};
var checkGuesses = function (musicGuessSongs, musicGuessSet) {
var guessed = 0;
songSets[musicGuessSet].forEach(function (song) {
musicGuessSongs.forEach(function (name) {
if (name === song.name) guessed++;
});
});
return guessed >= MAX_TRIES - 0;
};
var musicGuessFn = function (user, input) {
var wrongInput = !genres.some(function (g) {
return g === input
})
&& !songsPlainAll.some(function (s) {
return s === input
})
&& input !== backToGenres
&& input !== startGame;
if (wrongInput) return null;
var musicGuessSet = user['progress']['miniGames']['musicGuess']['set'];
var musicGuessSongs = user['progress']['miniGames']['musicGuess']['songs'];
var songEntered = songsPlainAll.some(function (s) {
return s === input
});
var categoryEntered = genres.some(function (g) {
return g === input
});
var sendCategories = function(){
messaging.send({
id: user['_id'],
answer: {
type: 'guess-music',
choices: [
{message: genres[0]},
{message: genres[1]},
{message: genres[2]}
]
},
text: '<NAME>:',
speaker: 'eva',
type: 'text',
lastLine: true
});
};
if (input === startGame) {
// Resetting game parameters, when the game starts
musicGuessSet = null;
musicGuessSongs = [];
DBUsers(function (db, collection) {
collection.updateOne({'_id': user['_id']},
{'$set': {
'progress.miniGames.musicGuess.songs': [],
'progress.miniGames.musicGuess.set': null
}}
);
});
}
if (input === backToGenres) sendCategories();
if (songEntered) {
// ...
// Send intermediate message here
// ...
musicGuessSongs.push(input);
DBUsers(function (db, collection) {
collection.updateOne({'_id': user['_id']},
{'$set': {'progress.miniGames.musicGuess.songs': musicGuessSongs}}
);
});
}
if (!musicGuessSet) {
musicGuessSet = Math.floor(Math.random() * songSets.length);
DBUsers(function (db, collection) {
collection.updateOne({'_id': user['_id']},
{'$set': {'progress.miniGames.musicGuess.set': musicGuessSet}}
);
});
}
if (musicGuessSongs.length >= MAX_TRIES) {
return checkGuesses(musicGuessSongs, musicGuessSet)
? 'guess-music-block-win'
: 'guess-music-block-fail';
}
if (input === startGame || songEntered) {
// TODO: send next audio here
var song = getSong(musicGuessSet, musicGuessSongs.length);
messaging.send({
id: user['_id'],
answer: null,
speaker: 'eva',
type: 'audio',
audio: song.path
}, function(){
Scheduler.add({
delay: 3, uid: user['_id'], event: function () {
sendCategories();
}
});
});
}
if (categoryEntered) {
var songsList = getSongsChoices(musicGuessSet, musicGuessSongs.length, input);
messaging.send({
id: user['_id'],
answer: {
type: 'guess-music',
choices: [
{message: songsList[0]},
{message: songsList[1]},
{message: songsList[2]},
{message: backToGenres}
]
},
text: 'Выбери песню:',
speaker: 'eva',
type: 'text',
lastLine: true
});
}
return 'stop-main-dialogs';
};
// ***********************************************************
// *** End of music mini-game
// ***********************************************************
// ***********************************************************
// *** Maniac photos mini-game
// ***********************************************************
var maniacOptions = ['Виновен', 'Не виновен'];
var maniacBasePath = '../../_Media/images/chapter2/minigame-judgement/';
var maniacPhotos = [
{path: maniacBasePath + 'alonso_lopes.jpg', isManiac: true},
{path: maniacBasePath + 'einstain.jpg', isManiac: false},
{path: maniacBasePath + 'geibl.jpg', isManiac: false},
{path: maniacBasePath + 'edvard_gein.jpg', isManiac: true},
{path: maniacBasePath + 'ledygaga.jpg', isManiac: false},
{path: maniacBasePath + 'lenon.jpg', isManiac: false},
{path: maniacBasePath + 'chekatilo.jpg', isManiac: true},
{path: maniacBasePath + 'mark_twain.jpg', isManiac: false},
{path: maniacBasePath + 'theodor_bandi.jpg', isManiac: true},
{path: maniacBasePath + 'paul_koshka.jpg', isManiac: false}
];
var checkManiacGuesses = function (maniacGuess) {
var amountToWin = 6;
var guessed = 0;
for (var i = 0; i < maniacPhotos.length; i++) {
if (maniacPhotos[i].isManiac == maniacGuess[i]) guessed++;
}
return guessed >= amountToWin;
};
var maniacGusssFn = function (user, input) {
var startEntered = input === str.miniGames.guessManiac.startGame;
var choiceEntered = maniacOptions.some(function (c) {
return input === c
});
if (!startEntered && !choiceEntered) return null; // Wrong input
var maniacGuess = user['progress']['miniGames']['maniacGuess'];
if (startEntered) {
DBUsers(function (db, collection) {
collection.updateOne({'_id': user['_id']},
{'$set': {'progress.miniGames.maniacGuess': []}}
);
});
maniacGuess = [];
}
if (choiceEntered) {
input = input === maniacOptions[0] ? 1 : 0;
maniacGuess.push(input);
DBUsers(function (db, collection) {
collection.updateOne({'_id': user['_id']},
{'$set': {'progress.miniGames.maniacGuess': maniacGuess}}
);
});
}
if (maniacGuess.length >= maniacPhotos.length) {
return checkManiacGuesses(maniacGuess)
? 'guess-maniac-block-win'
: 'guess-maniac-block-fail';
}
messaging.send({
id: user['_id'],
speaker: 'eva',
type: 'image',
text: 'Photo sent',
image: maniacPhotos[maniacGuess.length].path,
lastLine: false
}, function () {
Scheduler.add({
delay: 3, uid: user['_id'], event: function () {
messaging.send({
id: user['_id'],
answer: {
type: 'guess-maniac',
choices: [
{message: maniacOptions[0]},
{message: maniacOptions[1]},
]
},
text: 'Виновен или нет?',
speaker: 'eva',
type: 'text',
lastLine: true
});
}
});
});
return 'stop-main-dialogs';
};
// ***********************************************************
// *** End of maniac photos mini-game
// ***********************************************************
// ***********************************************************
// *** Send message in 30-40 seconds range time
// ***********************************************************
var sendMessagesInRange = ['Ева, ты там как?', '30 секунд прошло', 'Привет от Евы!'];
var sendMessageInRangeFn = function (user, input) {
var startEntered = input === str.miniGames.sendInRange.startGame;
var time = user['progress']['miniGames']['sendInRange'];
if (!startEntered) {
var diff = (utils.getNow() - time) / 1000;
if (diff < 25 || diff > 40) {
return 'try-again';
} else {
return 'success-block';
}
}
messaging.send({
id: user['_id'],
answer: {
type: 'send-in-range',
choices: [
{message: sendMessagesInRange[0]},
{message: sendMessagesInRange[1]},
{message: sendMessagesInRange[2]}
]
},
text: 'Через 30 секунд напиши, не затягивай!!',
speaker: 'eva',
type: 'text',
lastLine: true
}, function () {
DBUsers(function (db, collection) {
collection.updateOne({'_id': user['_id']},
{'$set': {'progress.miniGames.sendInRange': utils.getNow()}}
);
});
});
return 'stop-main-dialogs';
};
// ***********************************************************
// *** End of send message in 30-40 seconds range time
// ***********************************************************
module.exports = {
guessMusic: musicGuessFn,
guessManiac: maniacGusssFn,
sendInRange: sendMessageInRangeFn
};<file_sep>/telegram_bot/helpers/story-helpers.js
console.logger('Init: Story Helpers');
var utils = require('./utils');
var messaging = require('./send-messages');
var DBUsers = require('./db').dbUsers;
var Scheduler = require('./user-scheduler');
var str = require('./string-constants');
var numpadStickers = {
terminal: 'BQADAgADaQADtO0FAAGtOPu70XoenwI',
0: 'BQADAgADSAADtO0FAAGjKAUaJHMqBwI',
1: 'BQADAgADSgADtO0FAAF6z<KEY>',
2: 'BQADAgADTAADtO0FAAFEblVhwp4EOgI',
3: 'BQADAgADTgADtO0FAAGhokCpq6ng3gI',
4: 'BQADAgADUAAD<KEY>',
5: 'BQADAgADUgADtO0FAAFSCL1bfIsiawI',
6: 'BQADAgADVAADt<KEY>',
7: 'BQADAgADWAAD<KEY>',
8: 'BQADAgADWgADtO0FAAEko2sKaHCj5AI',
9: 'BQADAgADXAADtO0FAAHxM-FlD0bgAgI',
first: 'BQADAgADYQAD<KEY>',
second: 'BQADAgADYwAD<KEY>',
third: 'BQADAgADZQADtO0FAAEVhtitHJ0ElgI',
fourthFail: 'BQADAgADZwADtO0FAAGlPJ_nb-ym6AI',
fourthSuccess: 'BQADAgADawADtO0FAAEIFgnHDjJHAQI'
};
function checkAllaNumberOnInput(curUser, input) {
if (isNaN(Number(input))) {
sendMessageWrongInput(utils.getRandomItem(str.numpadInputs.notIntegerInput, curUser.name.first), curUser);
return 'stop-main-dialogs';
}
curUser.progress.guideNumberTry += input;
var codeTry = curUser.progress.guideNumberTry;
if (codeTry.length < 4) {
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']},
{'$set': {'progress.guideNumberTry': codeTry}},
function (res) {
console.logger(curUser['_id'] + ' alla code update "' + codeTry + '"');
}
);
});
allaCodes(curUser);
return 'stop-main-dialogs';
} else {
// Cleaning number in user profile
DBUsers(function (db, collection) {
collection.updateOne({'_id': curUser['_id']},
{'$set': {'progress.guideNumberTry': ''}},
function (res) {
console.logger(curUser['_id'] + ' alla code reset');
}
);
});
if (codeTry.length > 4) {
sendMessageWrongInput(utils.getRandomItem(str.numpadInputs.longInput, curUser.name.first), curUser);
return 'stop-main-dialogs';
} else {
if (allaCodesCheck(curUser)) {
messaging.send({
id: curUser['_id'],
answer: {
type: 'numpad',
choices: null
},
sticker: numpadStickers.fourthSuccess,
speaker: 'alla',
type: 'sticker',
lastLine: true
});
return 'Алла код - правильный ответ';
} else {
return 'Алла код - неправильный ответ';
}
}
}
}
var allaCodes = function (user) {
var text;
switch (user.progress.guideNumberTry.length) {
case 1:
text = '<b>Код: ' + user.progress.guideNumberTry + ' _ _ _ </b>\nПервая есть, давай дальше';
break;
case 2:
text = '<b>Код: ' + user.progress.guideNumberTry + ' _ _ </b>\nХорошо, вторая на месте, что дальше?';
break;
case 3:
text = '<b>Код: ' + user.progress.guideNumberTry + ' _ </b>\nХехе, мы почти у цели, последняя?';
break;
}
sendMessageWrongInput(text, user);
};
var allaCodesCheck = function (user) {
return user.progress.guideNumberTry == user.progress.guideNumber;
};
var sendMessageWrongInput = function (text, user) {
Scheduler.add({
delay: 2, uid: user['_id'], event: function () {
messaging.send({
id: user['_id'],
answer: {
type: 'numpad',
choices: null
},
text: text,
speaker: 'alla',
type: 'text',
lastLine: true
});
}
});
};
var needToLeave = {
leave: function (user) {
Scheduler.add({
delay: 2, uid: user['_id'], event: function () {
messaging.send({
id: user['_id'],
answer: {
type: 'default',
choices: [
{
message: str.needToLeave.cameBack
}
]
},
text: utils.getRandomItem(str.needToLeave.leaveReplies),
speaker: 'eva',
type: 'text',
lastLine: true
});
}
});
return 'stop-main-dialogs';
},
cameBack: function (user) {
Scheduler.add({
delay: 2, uid: user['_id'], event: function () {
messaging.send({
id: user['_id'],
answer: user['progress']['answer'],
text: utils.getRandomItem(str.needToLeave.cameBackReplies),
speaker: 'eva',
type: 'text',
lastLine: true
});
}
});
return 'stop-main-dialogs';
}
};
module.exports = {
allaCodes: allaCodes,
allaCodesCheck: allaCodesCheck,
checkAllaNumberOnInput: checkAllaNumberOnInput,
needToLeave: needToLeave
};<file_sep>/telegram_bot/helpers/user-scheduler.js
if (console.logger) console.logger('Init: Scheduler');
module.exports = Scheduler = (function () {
var events = [], now;
var interval = 1000;
setInterval(function () {
now = (new Date).getTime();
var lastIndex = -1;
for (var i = 0; i < events.length; i++) {
if (events[i].timestamp > now) {
break;
}
events[i].event();
lastIndex = i;
}
events.splice(0, lastIndex + 1);
}, interval);
var addEvent = function (params) {
var ev = {timestamp: params.time || (new Date()).getTime() + params.delay * 1000, event: params.event, uid: params.uid || null};
var inserted = false;
if (events.length === 0) events.push(ev);
else {
var leftEnd = 0, rightEnd = events.length;
while (!inserted) {
var candidate = events[Math.floor((rightEnd + leftEnd) / 2)];
if (candidate && ev.timestamp === candidate.timestamp) {
leftEnd = 0;
rightEnd = events.length;
ev.timestamp++;
} else if (rightEnd === leftEnd) {
events.splice(leftEnd, 0, ev);
inserted = true;
} else {
if (candidate.timestamp < ev.timestamp) {
leftEnd = Math.floor((rightEnd + leftEnd) / 2) + 1;
} else if (candidate.timestamp > ev.timestamp) {
rightEnd = Math.floor((rightEnd + leftEnd) / 2);
}
}
}
}
};
return {
add: function (params) {
if (params.time !== null) addEvent(params);
else params.event();
},
removeByTimestamp: function (time) {
var index = -1;
for (var i = 0; i < events.length; i++) {
if (events[i].timestamp === time) {
index = i;
break;
}
}
if (index !== -1) events.splice(index, 1);
},
removeById: function(uid){
events = events.filter(function(ev){
return ev.uid !== uid;
});
}
}
})();<file_sep>/telegram_bot/helpers/ga.js
console.logger('Init: GA');
// https://www.npmjs.com/package/universal-analytics
var ua = require('universal-analytics'),
gaId = '';
module.exports = {
ua: ua,
gaId: gaId
};<file_sep>/telegram_bot/config.js
if (console.logger) console.logger('Init: Config');
var ENV = 'bottest'; // local, test, live, alpha, bottest
var PLATFORM = 'telegram';
var botToken, gaHostname, passcode;
var delayLimit;
var wrongAnswerLimit = 3;
var skipDelayThreshold = 120;
var gifService = 'https://lookright.net/g/';
gaHostname = 'http://' + PLATFORM + '.zhgut.' + ENV;
switch (ENV) {
case 'bottest':
botToken = 'token';
passcode = /.*/;
delayLimit = 0.1;
break;
}
module.exports = {
env: ENV,
platform: PLATFORM,
botToken: botToken,
hostname: gaHostname,
pass: <PASSWORD>,
delayLimit: delayLimit,
wrongAnswerLimit: wrongAnswerLimit,
skipDelayThreshold: skipDelayThreshold,
gifService: gifService
};<file_sep>/README.md
# Telegram Bot - FastAid
[Link to see it in work](https://t.me/FastAid_bot) -
you'll need to have [Telegram](https://telegram.org/) installed in order to use it.
The idea behind this project was to help people do instant actions in emergency situations.
<br>*The project was untouched for a long time, so prepare to support legacy non-optimized code*
## How it works
The `telegram_bot` and `utils` were built with LookRight in mind.
Which was initially done with these tools.
Requires `mongo-db` set up. Easily launched via `npm pm2` package.
1. `telegram_bot/config.js` - change all configurations needed.
2. `audio`, `images`, `scenarios` and `videos` folders contain assets
you can refer to from the twine nodes.
3. `telegram_bot/index.js` is a starting point for an app.
<br>3.1. In that file `lines 42 - 344` are for accepting all incoming messages,
decomposing them and reacting back.
<br>3.2. `Lines 346 - 360` replying to button clicks
4. `telegram_bot/helpers/messaging.js` - contains main messaging logic as the name states.
And here is the place where you specify jsons generated from twines
with `getStory -> case` stands for the `final` attribute in json.
5. The first file is selected in user object here: `telegram_bot/helpers/user.js`
`line 40` and `line 54` for selecting first block in the file.
## Utils
*Util commands are used from within the corresponding folders*
`utils/JSON2Twinery` - converts JSON file back to twine file to be used with twinery.
``` javascript
// Put a path to json file you want to convert
15: const json = require('../path/Chapter 2.json');
```
``` javascript
// Specify the name and path for twinery html file
16: const html = `./${fileNames.name}.html`;
```
Usage: `npm build`
---
`utils/Twinery2JSON` - is kinda a separate mini-app,
which requires it's own `npm isntall`, since it relies on `jsdom` package.
``` javascript
// Specify twine html
9: const twine = '../Twines/Chapter 1.html';
// and the output path for jsons
10: const filesPath = '../Twines/Jsons/';
```
Usage: `npm install` to add needed packages, then just `npm index`
### Note: try it, if all paths are sent through correctly
---
`utils/Twinery2JSON/check-block-existence.js` - that's just a simple helper.
It compares blocks English and Russian versions of JSONs, so they have the same blocks.
``` javascript
// Provide the corresponding path names
3: const fileRus = require(path + 'Chapter 0.json');
4: const fileEng = require(path + 'Chapter 0 eng.json');
```
Usage: `npm check-block-existence`
<file_sep>/utils/Twinery2JSON/check-block-existence.js
const path = '../Twines/Jsons/';
const fileRus = require(path + 'Chapter 0.json');
const fileEng = require(path + 'Chapter 0 eng.json');
console.log('****** Looping through russian ******');
for (let blockName in fileRus) {
if (fileRus.hasOwnProperty(blockName)) {
if (!fileEng[blockName]) {
console.log(blockName);
}
}
}
console.log('****** Looping through english ******');
for (let blockName in fileEng) {
if (fileEng.hasOwnProperty(blockName)) {
if (!fileRus[blockName]) {
console.log(blockName);
}
}
} | be33e3140e897d6310ba2bdede166839be19fea3 | [
"JavaScript",
"Markdown"
] | 21 | JavaScript | ppkinev/Fast-Aid-Bot-NodeJS | 0fd92d149ee4686ec45c41b244625765d9eacdc3 | 455e379f798d924f34700360374a07f1c5dbdc51 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_gps_cli
{
public delegate string Command();
public static class Commands
{
public static Command Empty = () => string.Empty;
public static Command Unknown = () => "Unknown command";
public static Command Concatenate(Command first, Command second)
{
return () => first() + Environment.NewLine + second();
}
}
interface ICommandMatcher
{
bool IsMatch(string commandName);
Command GetCommand(string arguments);
}
class CommandMatcherSimple : ICommandMatcher
{
public string Name { get; private set; }
private Command m_Command;
public CommandMatcherSimple(string name, Command command) { Name = name; m_Command = command; }
public bool IsMatch(string commandName) { return commandName.Equals(Name); }
public Command GetCommand(string arguments) { return m_Command; }
}
class CommandGarmin : ICommandMatcher
{
public string Name { get; private set; }
private List<ICommandMatcher> GarminCommands;
public CommandGarmin()
{
Name = "garmin";
GarminCommands = new List<ICommandMatcher>();
GarminCommands.Add(new CommandMatcherSimple("help", () => "Garmin commands: help, version"));
GarminCommands.Add(new CommandMatcherSimple("version", () => "Garmin utility v0.1"));
}
public bool IsMatch(string commandName) { return commandName.Equals("garmin"); }
public Command GetCommand(string arguments)
{
if (!string.IsNullOrEmpty(arguments))
{
string newName = arguments.Split(' ').First();
string newArgs = arguments.Substring(newName.Length).Trim();
ICommandMatcher match = GarminCommands.Find(m => m.IsMatch(newName));
if (match != null) return match.GetCommand(newArgs);
return Commands.Concatenate(
Commands.Unknown,
GarminCommands.Find(m => m.IsMatch("help")).GetCommand(string.Empty)
);
}
return Commands.Empty;
}
}
class Program
{
#region Command line arguments
static void Help()
{
}
static bool TryProcessingArguments(string[] args)
{
return true;
}
#endregion
static void Main(string[] args)
{
if (!TryProcessingArguments(args))
{
Help();
return;
}
Console.WriteLine("Living-gps");
Program p = new Program(Console.In, Console.Out);
p.REPL();
}
private TextReader Input;
private TextWriter Output;
private bool IsRunning;
private List<ICommandMatcher> CommandList;
class CommandExit : ICommandMatcher
{
private Program Repl;
public CommandExit(Program repl) { Repl = repl; }
public bool IsMatch(string commandName) { return commandName.Equals("exit"); }
public Command GetCommand(string arguments) { return () => { Repl.IsRunning = false; return "Exiting..."; }; }
}
Program(TextReader input, TextWriter output)
{
IsRunning = true;
Input = input;
Output = output;
CommandList = new List<ICommandMatcher>();
CommandList.Add(new CommandExit(this));
CommandList.Add(new CommandGarmin());
}
Command Read()
{
string commandLine = Input.ReadLine().Trim();
if (!string.IsNullOrEmpty(commandLine))
{
string commandName = commandLine.Split(' ').First();
string arguments = commandLine.Substring(commandName.Length).Trim();
ICommandMatcher match = CommandList.Find(m => m.IsMatch(commandName));
if (match != null)
{
return match.GetCommand(arguments);
}
return Commands.Unknown;
}
return Commands.Empty;
}
void REPL()
{
while (IsRunning)
{
Command eval = Read();
Output.Write(eval() + Environment.NewLine);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public static class EnumerableExt
{
public static IEnumerable<IList<TSource>> PartitionBlocks<TSource>(this IEnumerable<TSource> source, int blockSize)
{
if (source == null) throw new ArgumentNullException("source");
if (blockSize < 1) throw new ArgumentOutOfRangeException("blockSize");
var block = new List<TSource>();
foreach (var x in source)
{
block.Add(x);
if (block.Count == blockSize) {
yield return block;
block = new List<TSource>();
}
}
if (block.Count > 0) yield return block;
}
public static IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action f)
{
if (source == null) throw new ArgumentNullException("source");
if (f == null) throw new ArgumentNullException("f");
foreach (var x in source)
{
f();
yield return x;
}
}
public static bool IsEmpty<TSource>(this IEnumerable<TSource> source)
{
return !source.Any();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public static class Categories
{
public static bool IsSync(Category c)
{
return (c == LivingLog_Startup) || (c == LivingLog_Sync);
}
public static readonly Category LivingLog_Startup = new Category() { Id = 0, Name = "LivingLog_Startup" };
public static readonly Category LivingLog_Sync = new Category() { Id = 10, Name = "LivingLog_Sync" };
public static readonly Category LivingLog_Exit = new Category() { Id = 11, Name = "LivingLog_Exit" };
public static readonly Category Mouse_Move = new Category() { Id = 1, Name = "Mouse_Move" };
public static readonly Category Mouse_Down = new Category() { Id = 2, Name = "Mouse_Down" };
public static readonly Category Mouse_Up = new Category() { Id = 3, Name = "Mouse_Up" };
public static readonly Category Mouse_Click = new Category() { Id = 4, Name = "Mouse_Click" };
public static readonly Category Mouse_DoubleClick = new Category() { Id = 5, Name = "Mouse_DoubleClick" };
public static readonly Category Mouse_Wheel = new Category() { Id = 6, Name = "Mouse_Wheel" };
public static readonly Category Keyboard_KeyDown = new Category() { Id = 7, Name = "Keyboard_KeyDown" };
public static readonly Category Keyboard_KeyUp = new Category() { Id = 8, Name = "Keyboard_KeyUp" };
public static readonly Category Keyboard_KeyPress = new Category() { Id = 9, Name = "Keyboard_KeyPress" };
private static Dictionary<int, Category> categories;
static Categories()
{
categories = new Dictionary<int, Category>()
{
{ LivingLog_Startup.Id , LivingLog_Startup },
{ LivingLog_Sync.Id , LivingLog_Sync },
{ LivingLog_Exit.Id , LivingLog_Exit },
{ Mouse_Move.Id , Mouse_Move },
{ Mouse_Down.Id , Mouse_Down },
{ Mouse_Up.Id , Mouse_Up },
{ Mouse_Click.Id , Mouse_Click },
{ Mouse_DoubleClick.Id , Mouse_DoubleClick },
{ Mouse_Wheel.Id , Mouse_Wheel },
{ Keyboard_KeyDown.Id , Keyboard_KeyDown },
{ Keyboard_KeyUp.Id , Keyboard_KeyUp },
{ Keyboard_KeyPress.Id , Keyboard_KeyPress },
};
Activity.SetParser(LivingLog_Startup, LivingLogger.SyncData.TryParse);
Activity.SetParser(LivingLog_Sync, LivingLogger.SyncData.TryParse);
Activity.SetParser(LivingLog_Exit, LivingLogger.SyncData.TryParse);
Activity.SetParser(Mouse_Move, MouseLogger.MouseMoveData.TryParse);
Activity.SetParser(Mouse_Down, MouseLogger.MouseButtonData.TryParse);
Activity.SetParser(Mouse_Up, MouseLogger.MouseButtonData.TryParse);
Activity.SetParser(Mouse_Click, MouseLogger.MouseButtonData.TryParse);
Activity.SetParser(Mouse_DoubleClick, MouseLogger.MouseButtonData.TryParse);
Activity.SetParser(Mouse_Wheel, MouseLogger.MouseWheelData.TryParse);
Activity.SetParser(Keyboard_KeyDown, KeyboardLogger.KeyboardKeyData.TryParse);
Activity.SetParser(Keyboard_KeyUp, KeyboardLogger.KeyboardKeyData.TryParse);
Activity.SetParser(Keyboard_KeyPress, KeyboardLogger.KeyboardPressData.TryParse);
}
public static Category get(int id)
{
Category result;
if (!categories.TryGetValue(id, out result)) return null;
return result;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Collections.Generic;
using living_log_cli;
namespace living_test
{
[TestClass]
public class Activities_RemoveDuplicates
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Null()
{
ActivityTools.RemoveDuplicates(null);
}
[TestMethod]
public void Test_NoDuplicates()
{
var t0 = new DateTime(2000, 01, 01);
var a0 = new Activity()
{
Timestamp = new Timestamp(t0),
Type = Categories.LivingLog_Startup,
Info = LivingLogger.SyncData.At(t0)
};
var t1 = new DateTime(2015, 05, 06);
var a1 = new Activity()
{
Timestamp = new Timestamp(t1),
Type = Categories.LivingLog_Exit,
Info = LivingLogger.SyncData.At(t1)
};
var source = new List<Activity>() { a0, a1 };
var result = ActivityTools.RemoveDuplicates(source);
Assert.IsTrue(result.SequenceEqual(source));
}
[TestMethod]
public void Test_Duplicate_Reference()
{
var t0 = new DateTime(2000, 01, 01);
var a0 = new Activity()
{
Timestamp = new Timestamp(t0),
Type = Categories.LivingLog_Startup,
Info = LivingLogger.SyncData.At(t0)
};
var source = new List<Activity>() { a0, a0 };
var result = ActivityTools.RemoveDuplicates(source);
var expected = source.Take(1);
Assert.IsTrue(result.SequenceEqual(expected));
}
[TestMethod]
public void Test_Duplicate_Value()
{
var t0 = new DateTime(2000, 01, 01);
var a0 = new Activity()
{
Timestamp = new Timestamp(t0),
Type = Categories.LivingLog_Startup,
Info = LivingLogger.SyncData.At(t0)
};
var a1 = new Activity()
{
Timestamp = a0.Timestamp,
Type = a0.Type,
Info = a0.Info
};
var source = new List<Activity>() { a0, a1 };
var result = ActivityTools.RemoveDuplicates(source);
Assert.IsTrue(result.SequenceEqual(source.Take(1)));
Assert.IsTrue(result.SequenceEqual(source.Skip(1)));
}
[TestMethod]
public void Test_NoDuplicate_ByTimestamp()
{
var t0 = new DateTime(2000, 01, 01);
var a0 = new Activity()
{
Timestamp = new Timestamp(t0),
Type = Categories.LivingLog_Startup,
Info = LivingLogger.SyncData.At(t0)
};
var t1 = new DateTime(2015, 06, 05);
var a1 = new Activity()
{
Timestamp = new Timestamp(t1),
Type = a0.Type,
Info = a0.Info
};
var source = new List<Activity>() { a0, a1 };
var result = ActivityTools.RemoveDuplicates(source);
Assert.IsTrue(result.SequenceEqual(source));
}
[TestMethod]
public void Test_NoDuplicate_ByType()
{
var t0 = new DateTime(2000, 01, 01);
var a0 = new Activity()
{
Timestamp = new Timestamp(t0),
Type = Categories.LivingLog_Startup,
Info = LivingLogger.SyncData.At(t0)
};
var a1 = new Activity()
{
Timestamp = a0.Timestamp,
Type = Categories.LivingLog_Sync,
Info = a0.Info
};
var source = new List<Activity>() { a0, a1 };
var result = ActivityTools.RemoveDuplicates(source);
Assert.IsTrue(result.SequenceEqual(source));
}
[TestMethod]
public void Test_NoDuplicate_ByInfo()
{
var t0 = new DateTime(2000, 01, 01);
var a0 = new Activity()
{
Timestamp = new Timestamp(t0),
Type = Categories.LivingLog_Startup,
Info = LivingLogger.SyncData.At(t0)
};
var t1 = new DateTime(2015, 06, 05);
var a1 = new Activity()
{
Timestamp = a0.Timestamp,
Type = a0.Type,
Info = LivingLogger.SyncData.At(t1)
};
var source = new List<Activity>() { a0, a1 };
var result = ActivityTools.RemoveDuplicates(source);
Assert.IsTrue(result.SequenceEqual(source));
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using living_log_cli;
namespace living_test
{
[TestClass]
public class Activities_IsValid
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Null()
{
ActivityTools.IsValid(null);
}
[TestMethod]
public void Test_Empty()
{
var activities = new List<Activity>();
Assert.IsTrue(ActivityTools.IsValid(activities));
}
[TestMethod]
public void Test_FirstIsSync()
{
var activities = new List<Activity>();
activities.Add(new Activity() { Type = Categories.Keyboard_KeyDown });
Assert.IsFalse(ActivityTools.IsValid(activities));
}
[TestMethod]
public void Test_HasNull()
{
var activities = new List<Activity>();
activities.Add(LivingLogger.GetSync());
activities.Add(null);
Assert.IsFalse(ActivityTools.IsValid(activities));
}
[TestMethod]
public void Test_NonChronological()
{
var t0 = DateTime.UtcNow;
var t1 = t0 - TimeSpan.FromSeconds(1);
var activities = new List<Activity>();
activities.Add(LivingLogger.GetSync(new Timestamp(t0)));
activities.Add(LivingLogger.GetSync(new Timestamp(t1)));
Assert.IsFalse(ActivityTools.IsValid(activities));
}
[TestMethod]
public void Test_Unknown()
{
var t0 = DateTime.UtcNow;
var t1 = t0 + TimeSpan.FromSeconds(1);
var activities = new List<Activity>();
activities.Add(LivingLogger.GetSync(new Timestamp(t0)));
activities.Add(new Activity()
{
Timestamp = new Timestamp(t1),
Type = Category.Unknown,
});
Assert.IsFalse(ActivityTools.IsValid(activities));
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using living_log_cli;
using System.Collections.Generic;
using System.Linq;
namespace living_test
{
[TestClass]
public class Activities_Merge
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Null_Null()
{
ActivityTools.Merge(null, null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Null_1()
{
var source = Enumerable.Empty<Activity>();
ActivityTools.Merge(null, source);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Null_2()
{
var source = Enumerable.Empty<Activity>();
ActivityTools.Merge(source, null);
}
[TestMethod]
public void Test_Empty_Empty()
{
var source = Enumerable.Empty<Activity>();
var result = ActivityTools.Merge(source, source).ToList();
Assert.IsTrue(result.IsEmpty());
}
[TestMethod]
public void Test_Empty_1()
{
var sourceA = Enumerable.Empty<Activity>();
var sourceB = new List<Activity>() { LivingLogger.GetSync() };
var result = ActivityTools.Merge(sourceA, sourceB).ToList();
Assert.IsTrue(result.SequenceEqual(sourceB));
}
[TestMethod]
public void Test_Empty_2()
{
var sourceA = new List<Activity>() { LivingLogger.GetSync() };
var sourceB = Enumerable.Empty<Activity>();
var result = ActivityTools.Merge(sourceA, sourceB).ToList();
Assert.IsTrue(result.SequenceEqual(sourceA));
}
[TestMethod]
public void Test_First_1()
{
var t0 = DateTime.Now;
var t1 = t0 + TimeSpan.FromSeconds(1);
var sourceA = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t0)) };
var sourceB = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t1)) };
var result = ActivityTools.Merge(sourceA, sourceB).ToList();
Assert.IsTrue(result.SequenceEqual(sourceA.Concat(sourceB)));
}
[TestMethod]
public void Test_First_2()
{
var t0 = DateTime.Now;
var t1 = t0 + TimeSpan.FromSeconds(1);
var sourceA = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t1)) };
var sourceB = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t0)) };
var result = ActivityTools.Merge(sourceA, sourceB).ToList();
Assert.IsTrue(result.SequenceEqual(sourceB.Concat(sourceA)));
}
[TestMethod]
public void Test_Ordering()
{
var t0 = DateTime.Now;
var t1 = t0 + TimeSpan.FromSeconds(1);
var t2 = t1 + TimeSpan.FromSeconds(1);
var t3 = t2 + TimeSpan.FromSeconds(1);
var sourceA = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t0)) };
var sourceB = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t1)) };
var sourceC = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t2)) };
var sourceD = new List<Activity>() { LivingLogger.GetSync(new Timestamp(t3)) };
var result = ActivityTools.Merge(
sourceA.Concat(sourceC),
sourceB.Concat(sourceD)
).ToList();
Assert.IsTrue(result.SequenceEqual(
sourceA.Concat(sourceB).Concat(sourceC).Concat(sourceD)
));
}
[TestMethod]
public void Test_Uniqueness()
{
Assert.Fail();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public abstract class Logger
{
public delegate void ActivityLoggedHandler(object sender, Activity activity);
public event ActivityLoggedHandler ActivityLogged;
public abstract bool Enabled { get; set; }
protected void Invoke(Category category, IData data)
{
if (ActivityLogged != null) ActivityLogged(this, new Activity() { Timestamp = new Timestamp(DateTime.UtcNow), Type = category, Info = data });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public class Activity : IEquatable<Activity>
{
public Timestamp Timestamp;
public Category Type;
public IData Info;
public bool Equals(Activity other)
{
return (Timestamp == other.Timestamp)
&& (Type == other.Type)
&& (Info.CompareTo(other.Info) == 0);
}
static Dictionary<Category, IData.TryParser> parsers
= new Dictionary<Category, IData.TryParser>();
public static void SetParser(Category c, IData.TryParser p)
{
parsers[c] = p;
}
public static IData.TryParser GetParser(Category c)
{
IData.TryParser parser;
if (!parsers.TryGetValue(c, out parser)) parser = NullParser;
return parser;
}
static bool NullParser(string s, out IData result) { result = null; return false; }
public static bool TryParse(string s, out Activity result)
{
result = null;
if (string.IsNullOrWhiteSpace(s)) return false;
var items = s.Split(new char[] { ' ' }, 3);
if (items.Length != 3) return false;
var dT = new Timestamp();
if (!long.TryParse(items[0], out dT.Milliseconds)) return false;
int type;
if (!int.TryParse(items[1], out type)) return false;
Category cat = Categories.get(type);
if (cat == null) return false;
IData data;
if (!GetParser(cat)(items[2], out data)) return false;
result = new Activity() { Timestamp = dT, Type = cat, Info = data };
return true;
}
}
public abstract class IData : IComparable<IData>
{
public delegate bool TryParser(string s, out IData result);
public int CompareTo(IData other)
{
return ToString().CompareTo(other.ToString());
}
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString() { return Id.ToString() + " " + Name; }
public static readonly Category Unknown = new Category() { Id = -1, Name = "Unknown" };
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public class Constants
{
public static long TicksPerMs = TimeSpan.TicksPerMillisecond;
public static int Millisecond = 1;
public static int Second = 1000;
public static int Minute = 60000;
public static int Hour = 3600000;
public static int DumpDelayInMs = Minute;
public static int SyncDelayInMs = Hour;
public static string SyncFormat = "yyyy-MM-dd_HH:mm:ss.fff";
public static string LogFilename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\living-log.log";
public static int ReadingBlockSize = 1000000;
public static int WritingBlockSize = 1000;
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using living_log_cli;
using System.Linq;
using System.Collections.Generic;
namespace living_test
{
[TestClass]
public class Activities_Partition
{
class FuncComparer<T> : IEqualityComparer<T>
{
Func<T, T, bool> _c;
Func<T, int> _h;
public FuncComparer(Func<T, T, bool> comparer) : this(comparer, x => 0) { }
public FuncComparer(Func<T, T, bool> comparer, Func<T, int> hasher) { _c = comparer; _h = hasher; }
public bool Equals(T x, T y) { return _c(x, y); }
public int GetHashCode(T x) { return _h(x); }
}
bool PartitionEqual(IEnumerable<IEnumerable<Activity>> expected, IEnumerable<IEnumerable<Activity>> result)
{
return expected.SequenceEqual(result, new FuncComparer<IEnumerable<Activity>>((e, r) => e.SequenceEqual(r)));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Chronological_Null()
{
ActivityTools.PartitionChronological(null).ToList();
}
[TestMethod]
public void Test_Chronological_Empty()
{
var empty = Enumerable.Empty<Activity>();
var result = ActivityTools.PartitionChronological(empty);
Assert.IsTrue(result.IsEmpty());
}
[TestMethod]
public void Test_Chronological_Single()
{
var a = LivingLogger.GetSync();
var activities = Enumerable.Repeat(a, 1);
var result = ActivityTools.PartitionChronological(activities);
var expected = Enumerable.Repeat(activities, 1);
Assert.IsTrue(PartitionEqual(expected, result));
}
[TestMethod]
public void Test_Chronological_Dual()
{
var t0 = DateTime.UtcNow;
var t1 = t0 + TimeSpan.FromSeconds(1);
var t2 = t1 + TimeSpan.FromSeconds(1);
var t3 = t2 + TimeSpan.FromSeconds(1);
var a0 = LivingLogger.GetSync(new Timestamp(t0));
var a1 = LivingLogger.GetSync(new Timestamp(t1));
var a2 = LivingLogger.GetSync(new Timestamp(t2));
var a3 = LivingLogger.GetSync(new Timestamp(t3));
var actA = new List<Activity>() { a0, a2 };
var actB = new List<Activity>() { a1, a3 };
var activities = actA.Concat(actB);
var result = ActivityTools.PartitionChronological(activities);
var expected = new List<List<Activity>>() { actA, actB };
Assert.IsTrue(PartitionEqual(expected, result));
}
[TestMethod]
public void Test_Chronological_AntiChrono()
{
var t0 = DateTime.UtcNow;
var t1 = t0 + TimeSpan.FromSeconds(1);
var t2 = t1 + TimeSpan.FromSeconds(1);
var t3 = t2 + TimeSpan.FromSeconds(1);
var a0 = LivingLogger.GetSync(new Timestamp(t0));
var a1 = LivingLogger.GetSync(new Timestamp(t1));
var a2 = LivingLogger.GetSync(new Timestamp(t2));
var a3 = LivingLogger.GetSync(new Timestamp(t3));
var act0 = Enumerable.Repeat(a0, 1);
var act1 = Enumerable.Repeat(a1, 1);
var act2 = Enumerable.Repeat(a2, 1);
var act3 = Enumerable.Repeat(a3, 1);
var activities = act3.Concat(act2).Concat(act1).Concat(act0);
var result = ActivityTools.PartitionChronological(activities);
var expected = new List<IEnumerable<Activity>>() { act3, act2, act1, act0 };
Assert.IsTrue(PartitionEqual(expected, result));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MouseKeyboardActivityMonitor;
using MouseKeyboardActivityMonitor.WinApi;
using System.Windows.Forms;
namespace living_log_cli
{
public class KeyboardLogger : Logger
{
public class KeyboardKeyData : IData
{
public Keys Key;
public KeyboardKeyData(KeyEventArgsExt e) { Key = e.KeyCode; }
public override string ToString() { return Key.ToString(); }
protected KeyboardKeyData() { }
public static bool TryParse(string s, out IData result)
{
result = null;
if (string.IsNullOrEmpty(s)) return false;
Keys k;
if (!System.Enum.TryParse(s, out k)) return false;
result = new KeyboardKeyData() { Key = k };
return true;
}
}
public class KeyboardPressData : IData
{
public char Character;
public KeyboardPressData(KeyPressEventArgsExt e) { Character = e.KeyChar; }
public override string ToString() { return Character.ToString(); }
protected KeyboardPressData() { }
public static bool TryParse(string s, out IData result)
{
result = null;
if (string.IsNullOrEmpty(s)) return false;
char c;
if (!char.TryParse(s, out c)) return false;
result = new KeyboardPressData() { Character = c };
return true;
}
}
private KeyboardHookListener m_keyboard;
public KeyboardLogger()
{
m_keyboard = new KeyboardHookListener(new GlobalHooker());
m_keyboard.KeyUp += (s, e) => { if (Enabled) Invoke(Categories.Keyboard_KeyUp, new KeyboardKeyData(e as KeyEventArgsExt)); };
m_keyboard.KeyDown += (s, e) => { if (Enabled) Invoke(Categories.Keyboard_KeyDown, new KeyboardKeyData(e as KeyEventArgsExt)); };
m_keyboard.KeyPress += (s, e) => { if (Enabled) Invoke(Categories.Keyboard_KeyPress, new KeyboardPressData(e as KeyPressEventArgsExt)); };
m_keyboard.Enabled = true;
m_enabled = false;
}
protected bool m_enabled;
public override bool Enabled
{
get { return m_enabled; }
set { m_enabled = value; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MouseKeyboardActivityMonitor;
using MouseKeyboardActivityMonitor.WinApi;
using System.Windows.Forms;
namespace living_log_cli
{
public class MouseLogger : Logger
{
public class MouseButtonData : IData
{
public MouseButtons Button;
public MouseButtonData(MouseEventExtArgs e) { Button = e.Button; }
public override string ToString() { return Button.ToString(); }
protected MouseButtonData() { }
public static bool TryParse(string s, out IData result)
{
result = null;
if (string.IsNullOrEmpty(s)) return false;
MouseButtons b;
if (!System.Enum.TryParse(s, out b)) return false;
result = new MouseButtonData() { Button = b };
return true;
}
}
public class MouseWheelData : IData
{
public int Delta;
public MouseWheelData(MouseEventExtArgs e) { Delta = e.Delta; }
public override string ToString() { return Delta.ToString(); }
protected MouseWheelData() { }
public static bool TryParse(string s, out IData result)
{
result = null;
if (string.IsNullOrEmpty(s)) return false;
int d;
if (!int.TryParse(s, out d)) return false;
result = new MouseWheelData() { Delta = d };
return true;
}
}
public class MouseMoveData : IData
{
public int X;
public int Y;
public MouseMoveData(MouseEventExtArgs e) { X = e.X; Y = e.Y; }
public override string ToString() { return X.ToString() + " " + Y.ToString(); }
protected MouseMoveData() { }
public static bool TryParse(string s, out IData result)
{
result = null;
if (string.IsNullOrEmpty(s)) return false;
var items = s.Split(' ');
if (items.Length != 2) return false;
int x;
if (!int.TryParse(items[0], out x)) return false;
int y;
if (!int.TryParse(items[1], out y)) return false;
result = new MouseMoveData() { X = x, Y = y };
return true;
}
}
private MouseHookListener m_mouse;
public MouseLogger()
{
m_mouse = new MouseHookListener(new GlobalHooker());
m_mouse.MouseMoveExt += (s, e) => { if (Enabled) Invoke(Categories.Mouse_Move, new MouseMoveData(e)); };
m_mouse.MouseDownExt += (s, e) => { if (Enabled) Invoke(Categories.Mouse_Down, new MouseButtonData(e)); };
m_mouse.MouseUp += (s, e) => { if (Enabled) Invoke(Categories.Mouse_Up, new MouseButtonData(e as MouseEventExtArgs)); };
m_mouse.MouseClickExt += (s, e) => { if (Enabled) Invoke(Categories.Mouse_Click, new MouseButtonData(e)); };
m_mouse.MouseDoubleClick += (s, e) => { if (Enabled) Invoke(Categories.Mouse_DoubleClick, new MouseButtonData(e as MouseEventExtArgs)); };
m_mouse.MouseWheel += (s, e) => { if (Enabled) Invoke(Categories.Mouse_Wheel, new MouseWheelData(e as MouseEventExtArgs)); };
m_mouse.Enabled = true;
m_enabled = false;
}
protected bool m_enabled;
public override bool Enabled
{
get { return m_enabled; }
set { m_enabled = value; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public class LivingFile
{
public static bool Exists(string filename)
{
return File.Exists(filename);
}
public string Filename { get; set; }
public struct Stats
{
public long Length { get; internal set; }
public long Count { get; internal set; }
}
public static Stats GetStats(string filename)
{
return new Stats()
{
Length = new FileInfo(filename).Length,
Count = File.ReadLines(filename).LongCount()
};
}
public struct Info
{
public string Name { get; internal set; }
public string BaseName { get; internal set; }
public string Extension { get; internal set; }
public string Child(int year, int month)
{
return BaseName
+ "."
+ year.ToString().PadLeft(4, '0')
+ "-"
+ month.ToString().PadLeft(2, '0')
+ Extension;
}
}
public static Info GetInfo(string filename)
{
var i = filename.LastIndexOf('.');
return new Info()
{
Name = filename,
BaseName = (i >= 0) ? filename.Substring(0, i) : filename,
Extension = (i >= 0) ? filename.Substring(i) : String.Empty,
};
}
public static IEnumerable<Activity> ReadActivities(string filename)
{
var t = new Timestamp();
return File.ReadLines(filename)
.Select((s) =>
{
Activity act = null;
if (Activity.TryParse(s, out act))
{
if (Categories.IsSync(act.Type))
{
var t0 = (act.Info as LivingLogger.SyncData).Timestamp;
t = new Timestamp(t0);
act.Timestamp = t;
}
else
{
t = t + act.Timestamp;
act.Timestamp = t;
}
}
return act;
})
.WhereValid();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Globalization;
using System.Diagnostics;
namespace living_log_cli
{
public static class ActivityTools
{
public static IEnumerable<Activity> Process(IEnumerable<Activity> source)
{
//var w = new Stopwatch();
//w.Start();
//var t0 = w.Elapsed;
//var list = source.ToList();
//var tList = w.Elapsed;
//var valid = WhereValid(list).ToList();
//var tValid = w.Elapsed;
//var parts = PartitionChronological(valid).ToList();
//var tParts = w.Elapsed;
//var merge = Merge(parts).ToList();
//var tMerge = w.Elapsed;
//var dupe = RemoveDuplicates(merge).ToList();
//var tDupe = w.Elapsed;
//w.Stop();
//return dupe;
return RemoveDuplicates(
Merge(
PartitionChronological(
WhereValid(
source
))));
}
// A valid activity list
// - is non-null
// - has non-null items
// - starts with a sync information
public static bool IsValid(ICollection<Activity> source)
{
if (source == null) throw new ArgumentNullException("source");
if (source.Any())
{
var item = source.First();
if (item == null) return false;
if (!Categories.IsSync(item.Type)) return false;
var t0 = item.Timestamp;
foreach (var a in source.Skip(1))
{
if (a == null) return false;
}
}
return true;
}
public static bool IsChronological(ICollection<Activity> source)
{
if (source == null) throw new ArgumentNullException("source");
if (source.Any())
{
var t0 = source.First().Timestamp;
foreach (var a in source.Skip(1))
{
var t = t0;
t0 = a.Timestamp;
if (t0 < t) return false;
}
}
return true;
}
public static IEnumerable<Activity> WhereValid(this IEnumerable<Activity> source)
{
if (source == null) throw new ArgumentNullException("source");
return source
.Where(a => a != null)
.SkipWhile(a => !Categories.IsSync(a.Type));
}
public static IEnumerable<Activity> WhereChronological(this IEnumerable<Activity> source)
{
if (source == null) throw new ArgumentNullException("source");
if (source.IsEmpty()) return source;
var t0 = source.First().Timestamp;
return source
.Where(a => a != null)
.TakeWhile(a =>
{
var t = t0;
t0 = a.Timestamp;
return t <= t0;
});
}
public static IEnumerable<Activity> MakeValid(this IEnumerable<Activity> source)
{
if (source == null) throw new ArgumentNullException("source");
// Non-null
var activities = source.Where((a) => a != null);
// Synced
if (activities.Any())
{
var item = activities.First();
if (!Categories.IsSync(item.Type))
{
activities = new List<Activity>() { LivingLogger.GetSync(item.Timestamp) }.Concat(activities);
}
}
return activities.ToList();
}
static IEnumerable<Activity> MergeIterator(IEnumerator<Activity> a, IEnumerator<Activity> b)
{
bool hasA = a.MoveNext();
bool hasB = b.MoveNext();
while (hasB)
{
var t = b.Current.Timestamp;
while (hasA)
{
if (a.Current.Timestamp <= t)
{
yield return a.Current;
hasA = a.MoveNext();
}
else break;
}
Tools.Swap(ref a, ref b);
Tools.Swap(ref hasA, ref hasB);
}
while (hasA)
{
yield return a.Current;
hasA = a.MoveNext();
}
}
public static IEnumerable<Activity> Merge(IEnumerable<Activity> sourceA, IEnumerable<Activity> sourceB)
{
if (sourceA == null) throw new ArgumentNullException("sourceA");
if (sourceB == null) throw new ArgumentNullException("sourceB");
if (sourceA.IsEmpty()) return sourceB;
if (sourceB.IsEmpty()) return sourceA;
return MergeIterator(sourceA.GetEnumerator(), sourceB.GetEnumerator());
}
public static IEnumerable<Activity> Merge(IEnumerable<IEnumerable<Activity>> sources)
{
if (sources == null) throw new ArgumentNullException("sources");
if (sources.IsEmpty()) return Enumerable.Empty<Activity>();
var queue = new Queue<IEnumerable<Activity>>(sources);
while (queue.Count > 1)
{
var a = queue.Dequeue();
var b = queue.Dequeue();
queue.Enqueue(Merge(a, b));
}
return queue.Dequeue();
}
static IEnumerable<Activity> DuplicateIterator(this IEnumerable<Activity> source)
{
var items = new Queue<Activity>();
var t = source.First().Timestamp;
foreach (var a in source)
{
if (a.Timestamp != t)
{
while (items.Count > 0) yield return items.Dequeue();
t = a.Timestamp;
}
if (!items.Contains(a)) items.Enqueue(a);
}
while (items.Count > 0) yield return items.Dequeue();
}
public static IEnumerable<Activity> RemoveDuplicates(IEnumerable<Activity> source)
{
if (source == null) throw new ArgumentNullException("source");
if (source.IsEmpty()) return source;
return DuplicateIterator(source);
}
public static IEnumerable<IList<Activity>> PartitionChronological(IEnumerable<Activity> source)
{
if (source == null) throw new ArgumentNullException("source");
if (source.IsEmpty()) yield break;
var t = source.First().Timestamp;
var items = new List<Activity>();
foreach (var a in source)
{
if (a.Timestamp < t) { yield return items; items = new List<Activity>(); }
items.Add(a);
t = a.Timestamp;
}
if (items.Count > 0) yield return items;
}
}
class Program
{
#region Console exit handler
[System.Runtime.InteropServices.DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
private static HandlerRoutine exitHandler = null;
public static bool SetExitHandler(HandlerRoutine handler)
{
exitHandler = handler;
return SetConsoleCtrlHandler(exitHandler, true);
}
#endregion
#region Command line arguments handling
private static void Help()
{
Console.WriteLine(
@"
living-log-cli
Starts a keyboard and mouse activity logger
Command: living-log-cli [-log LOG -delay DELAY -sync DELAY]
Options: -log LOG Uses the file LOG as log for the activity
Default is ""My Documents""\living-log.log
-delay DELAY Delay in seconds between each dump to the log file
Default is each minute (60s)
-sync DELAY Delay in seconds between each sync message in the dump
Default is each hour (3600s)
"
);
}
private static bool TryProcessingArguments(string[] args)
{
int index = 0;
while (index < args.Length)
{
if (index + 2 <= args.Length)
{
switch (args[index])
{
case "-log":
Constants.LogFilename = args[index + 1];
break;
case "-delay":
Constants.DumpDelayInMs = 1000 * Convert.ToInt32(args[index + 1]);
break;
case "-sync":
Constants.SyncDelayInMs = 1000 * Convert.ToInt32(args[index + 1]);
break;
default:
return false;
}
index += 2;
}
else
{
return false;
}
}
return true;
}
#endregion
private static UI ui;
static void Main(string[] args)
{
if (!TryProcessingArguments(args))
{
Help();
return;
}
System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.BelowNormal;
Program p = new Program(Constants.LogFilename);
SetExitHandler((t) =>
{
ForceExit();
return true;
});
Console.SetCursorPosition(0, 4);
ui = new UI();
new Thread(() => { p.REPL(ui); }) { IsBackground = true }.Start();
System.Windows.Forms.Application.Run();
//new Thread(() => { System.Windows.Forms.Application.Run(); }) { IsBackground = true }.Start();
//p.REPL(Console.In, Console.Out);
p.Enabled = false;
p.Dump();
}
static void ForceExit()
{
System.Windows.Forms.Application.Exit();
}
void Pause()
{
if (Enabled)
{
Enabled = false;
Ui.WriteLine("Paused");
}
}
void Resume()
{
if (!Enabled)
{
Enabled = true;
Ui.WriteLine("Resumed");
}
}
void FileStats()
{
if (LivingFile.Exists(m_filename))
{
var stats = LivingFile.GetStats(m_filename);
Ui.WriteLine("File " + m_filename + " has " + Tools.ToHumanString(stats.Length) + " bytes");
Ui.WriteLine("File " + m_filename + " has " + Tools.ToHumanString(stats.Count) + " lines");
}
}
void FileSplit()
{
if (Enabled)
{
Ui.WriteLine("Cannot split while logging. Please pause.");
}
else
{
if (LivingFile.Exists(m_filename))
{
Dump();
var info = LivingFile.GetInfo(m_filename);
Ui.WriteLine("Files of names " + info.BaseName + ".YYYY-MM" + info.Extension + " will be generated");
System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch();
long counter = 0;
var logger = new System.Timers.Timer();
logger.AutoReset = true;
logger.Interval = Constants.Second;
logger.Elapsed += (s, e) => { Ui.SetStatus("activities: " + Tools.ToHumanString(counter).PadRight(8) + " elapsed: " + w.Elapsed.ToString()); };
logger.Start();
var backups = new Dictionary<string, string>();
try
{
w.Start();
var activities = LivingFile.ReadActivities(m_filename)
.Do(() => ++counter);
foreach (var activityBlock in activities.PartitionBlocks(Constants.ReadingBlockSize))
{
var groups = activityBlock
.GroupBy((a) =>
{
var at = a.Timestamp.ToDateTime();
return new { Year = at.Year, Month = at.Month };
});
foreach (var group in groups)
{
if (group.Any())
{
IEnumerable<Activity> groupActivities;
var item = group.First();
if (!Categories.IsSync(item.Type))
{
// When appending activities, always start with a sync activity
// This will help "resorting" activities if needed
groupActivities = Enumerable.Repeat(LivingLogger.GetSync(item.Timestamp), 1).Concat(group);
}
else
{
groupActivities = group;
}
lock (locker)
{
var filename = info.Child(group.Key.Year, group.Key.Month);
var backup = filename + ".bak";
if (!backups.ContainsKey(filename))
{
if (File.Exists(filename))
{
if (File.Exists(backup)) File.Delete(backup);
File.Copy(filename, backup);
}
backups.Add(filename, backup);
Ui.WriteLine("Writing to " + filename);
}
Timestamp previous = groupActivities.First().Timestamp;
using (var writer = new StreamWriter(File.Open(filename, FileMode.Append)))
{
foreach (var groupActivityBlock in groupActivities.PartitionBlocks(Constants.WritingBlockSize))
{
WriteText(groupActivityBlock, ref previous, writer);
}
}
}
}
}
}
Ui.SetStatus("Split task successful.");
foreach (var kvp in backups)
{
counter = 0;
w.Restart();
Ui.WriteLine("Processing " + kvp.Key);
if (File.Exists(kvp.Value)) File.Delete(kvp.Value);
if (File.Exists(kvp.Key)) File.Copy(kvp.Key, kvp.Value);
var processed =
ActivityTools.Process(
LivingFile
.ReadActivities(kvp.Value)
.Do(() => ++counter)
);
Timestamp previous = processed.First().Timestamp;
using (var writer = new StreamWriter(File.Create(kvp.Key)))
{
foreach (var pBlock in processed.PartitionBlocks(Constants.WritingBlockSize))
{
WriteText(pBlock, ref previous, writer);
}
}
}
foreach (var kvp in backups)
{
if (File.Exists(kvp.Value)) File.Delete(kvp.Value);
}
using (var file = File.Create(m_filename))
{
// "using" makes sura that the file is properly closed and not still in use
}
Ui.SetStatus("Processing task successful.");
}
catch (Exception e)
{
Ui.SetStatus("Error during split task. Removing temporary files...");
foreach (var kvp in backups)
{
if (File.Exists(kvp.Key)) File.Delete(kvp.Key);
if (File.Exists(kvp.Value)) File.Move(kvp.Value, kvp.Key);
}
}
finally
{
logger.Stop();
}
}
}
}
class UI
{
private string Status;
public long Count;
public long Total;
public UI()
{
Status = string.Empty;
Count = 0;
Total = 0;
Update();
}
private void Update()
{
var x = Console.CursorLeft;
var y = Console.CursorTop;
string blank = new string(' ', Console.WindowWidth - 1);
string separator = new string('_', Console.WindowWidth - 1);
string status = Status.PadRight(Console.WindowWidth - 1);
string info = (Constants.LogFilename + " " + Tools.ToHumanString(Count).PadLeft(6) + " | " + Tools.ToHumanString(Total).PadLeft(6)).PadRight(Console.WindowWidth - 1);
Console.SetCursorPosition(Console.WindowLeft, Console.WindowTop);
Console.WriteLine(info);
Console.WriteLine(status);
Console.WriteLine(separator);
Console.WriteLine(blank);
Console.SetCursorPosition(x, y);
}
public string ReadLine()
{
var s = Console.ReadLine();
Update();
return s;
}
public void Write(string s) { Console.Write(s); }
public void WriteLine(string s)
{
Console.WriteLine(s);
Update();
}
public void SetStatus(string s)
{
Status = s;
Update();
}
}
private UI Ui;
void REPL(UI ui)
{
Ui = ui;
string command = string.Empty;
do
{
ui.Write("ll > ");
command = (ui.ReadLine() ?? "exit").Trim();
if (command.Equals("pause") || command.Equals("p"))
{
Pause();
}
else if (command.Equals("resume") || command.Equals("r"))
{
Resume();
}
else if (command.Equals("stats"))
{
FileStats();
}
else if (command.Equals("split"))
{
FileSplit();
}
else if (command.Equals("test"))
{
var activities = LivingFile.ReadActivities("C:\\Users\\scorder\\Documents\\living-log.2015-04.log");
ActivityTools.Process(activities);
}
} while (!command.Equals("exit"));
Program.ForceExit();
}
Program(string filename)
{
m_filename = filename;
m_activityList = new List<Activity>();
m_previous = new Timestamp(DateTime.UtcNow);
m_living = new LivingLogger(Constants.SyncDelayInMs);
m_living.ActivityLogged += (s, a) => { lock (locker) { m_activityList.Add(a); } };
//m_mouse = new MouseLogger();
//m_mouse.ActivityLogged += (s, a) => { lock (locker) { m_activityList.Add(a); } };
//m_keyboard = new KeyboardLogger();
//m_keyboard.ActivityLogged += (s, a) => { lock (locker) { m_activityList.Add(a); } };
m_dumpTimer = new System.Timers.Timer()
{
Interval = Constants.DumpDelayInMs,
AutoReset = true,
};
m_dumpTimer.Elapsed += (s, e) => Dump();
Enabled = true;
}
bool Enabled
{
get
{
return m_dumpTimer.Enabled;
}
set
{
m_dumpTimer.Enabled = value;
m_living.Enabled = value;
//m_mouse.Enabled = value;
//m_keyboard.Enabled = value;
}
}
private void Dump()
{
Ui.SetStatus("Logging " + m_activityList.Count + " activities...");
lock (locker)
{
try
{
Timestamp previous = m_previous;
using (var writer = new StreamWriter(File.Open(m_filename, FileMode.Append)))
{
// Only change m_previous is writing is successful
WriteText(m_activityList, ref previous, writer);
}
m_previous = previous;
ui.Count = m_activityList.Count;
ui.Total += ui.Count;
m_activityList.Clear();
Ui.SetStatus("Logged " + m_activityList.Count + " activities");
}
catch (IOException e)
{
Ui.SetStatus("Could not write to living log");
// Most likely to be the output file already in use
// Just keep storing Activities until we can access the file
}
}
}
void WriteText(IList<Activity> activities, ref Timestamp previous, TextWriter writer)
{
using (var text = new StringWriter())
{
foreach (var a in activities)
{
text.Write(a.Timestamp - previous);
text.Write(" ");
text.Write(a.Type.Id);
text.Write(" ");
text.Write(a.Info.ToString());
text.WriteLine();
previous = a.Timestamp;
};
writer.Write(text.ToString());
}
}
private Timestamp m_previous;
System.Timers.Timer m_dumpTimer;
string m_filename;
MouseLogger m_mouse;
KeyboardLogger m_keyboard;
LivingLogger m_living;
List<Activity> m_activityList;
private object locker = new object();
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using living_log_cli;
using System.Linq;
namespace living_test
{
[TestClass]
public class Extensions
{
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_ReadBlocks_Null()
{
List<int> list = null;
list.PartitionBlocks(1).ToList();
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Test_ReadBlocks_EmptyBlocks()
{
List<int> list = new List<int>();
list.PartitionBlocks(0).ToList();
}
[TestMethod]
public void Test_ReadBlocks_Empty()
{
List<int> list = new List<int>();
var blocks = list.PartitionBlocks(1);
Assert.IsNotNull(blocks);
Assert.IsTrue(blocks.IsEmpty());
}
[TestMethod]
public void Test_ReadBlocks_SingleBlock_Small()
{
var items = Enumerable.Range(0, 5);
var blocks = items.PartitionBlocks(10);
Assert.IsNotNull(blocks);
Assert.AreEqual(1, blocks.Count());
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(0), items));
}
[TestMethod]
public void Test_ReadBlocks_SingleBlock_Full()
{
var items = Enumerable.Range(0, 10);
var blocks = items.PartitionBlocks(10);
Assert.IsNotNull(blocks);
Assert.AreEqual(1, blocks.Count());
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(0), items));
}
[TestMethod]
public void Test_ReadBlocks_TripleBlock_Small()
{
var items = Enumerable.Range(0, 25);
var blocks = items.PartitionBlocks(10);
Assert.IsNotNull(blocks);
Assert.AreEqual(3, blocks.Count());
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(0), Enumerable.Range( 0, 10)));
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(1), Enumerable.Range(10, 10)));
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(2), Enumerable.Range(20, 5)));
}
[TestMethod]
public void Test_ReadBlocks_TripleBlock_Full()
{
var items = Enumerable.Range(0, 30);
var blocks = items.PartitionBlocks(10);
Assert.IsNotNull(blocks);
Assert.AreEqual(3, blocks.Count());
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(0), Enumerable.Range( 0, 10)));
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(1), Enumerable.Range(10, 10)));
Assert.IsTrue(Enumerable.SequenceEqual(blocks.ElementAt(2), Enumerable.Range(20, 10)));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace living_log_cli
{
public class LivingLogger : Logger
{
public class SyncData : IData
{
public string Version;
public DateTime Timestamp;
public override string ToString() { return Timestamp.ToString(Constants.SyncFormat, CultureInfo.InvariantCulture) + " " + Version; }
public static bool TryParse(string s, out IData result)
{
result = null;
if (string.IsNullOrEmpty(s)) return false;
var items = s.Split(' ');
if (items.Length != 2) return false;
DateTime syncTime;
if (!DateTime.TryParseExact(items[0], Constants.SyncFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out syncTime)) return false;
result = new SyncData() { Timestamp = syncTime, Version = items[1] };
return true;
}
public static SyncData Now()
{
return At(DateTime.UtcNow);
}
public static SyncData At(DateTime t)
{
return new SyncData() { Timestamp = t, Version = "1" };
}
}
public static Activity GetSync(Timestamp t)
{
return new Activity()
{
Timestamp = t,
Type = Categories.LivingLog_Sync,
Info = SyncData.At(t.ToDateTime())
};
}
public static Activity GetSync()
{
return GetSync(new Timestamp(DateTime.UtcNow));
}
public LivingLogger(int syncDelay)
{
m_sync = new Timer();
m_sync.AutoReset = true;
m_sync.Interval = syncDelay;
m_sync.Elapsed += (s, e) => { Invoke(Categories.LivingLog_Sync, SyncData.Now()); };
m_sync.Enabled = false;
}
public override bool Enabled
{
get
{
return m_sync.Enabled;
}
set
{
var enable = value;
if (enable != m_sync.Enabled)
{
m_sync.Enabled = enable;
if (enable)
{
Invoke(Categories.LivingLog_Startup, SyncData.Now());
}
else
{
Invoke(Categories.LivingLog_Exit, SyncData.Now());
}
}
}
}
private Timer m_sync;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public static class Tools
{
public static void Swap<T>(ref T a, ref T b)
{
var t = a;
a = b;
b = t;
}
public static string ToHumanString(int value) { return ToHumanString((long)value); }
public static string ToHumanString(long value)
{
if (value < 1000) return value.ToString();
string[] units = { "", "K", "M", "G", "T", "P", "E", "Z", "Y" };
int i = 0;
while (value >= 1000000)
{
value = value / 1000;
++i;
}
double d = value;
if (d >= 1000)
{
d = d / 1000;
++i;
}
if (d >= 100) return d.ToString("F0") + units[i];
else if (d >= 10) return d.ToString("F0") + units[i];
return d.ToString("F1") + units[i];
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_log_cli
{
public struct Timestamp
{
public long Milliseconds;
public Timestamp(DateTime time) : this(time.Ticks / Constants.TicksPerMs) { }
public DateTime ToDateTime() { return new DateTime(Milliseconds * Constants.TicksPerMs); }
public override string ToString() { return Milliseconds.ToString(); }
public static Timestamp operator +(Timestamp a, Timestamp b) { return new Timestamp(a.Milliseconds + b.Milliseconds); }
public static Timestamp operator -(Timestamp a, Timestamp b) { return new Timestamp(a.Milliseconds - b.Milliseconds); }
public static bool operator <(Timestamp a, Timestamp b) { return a.Milliseconds < b.Milliseconds; }
public static bool operator >(Timestamp a, Timestamp b) { return a.Milliseconds > b.Milliseconds; }
public static bool operator <=(Timestamp a, Timestamp b) { return a.Milliseconds <= b.Milliseconds; }
public static bool operator >=(Timestamp a, Timestamp b) { return a.Milliseconds >= b.Milliseconds; }
public static bool operator ==(Timestamp a, Timestamp b) { return a.Milliseconds == b.Milliseconds; }
public static bool operator !=(Timestamp a, Timestamp b) { return a.Milliseconds != b.Milliseconds; }
private Timestamp(long milliseconds) { Milliseconds = milliseconds; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace living_gps_cli
{
public class ConfigFile
{
private Dictionary<string, Dictionary<string, string>> m_dictionary;
public ConfigFile()
{
m_dictionary = new Dictionary<string, Dictionary<string, string>>();
}
public ConfigFile(string path)
: this()
{
if (File.Exists(path))
{
using (StreamReader reader = new StreamReader(path))
{
string section = string.Empty;
while (!reader.EndOfStream)
{
string line = reader.ReadLine().Trim();
int comment = line.IndexOf('#');
if (comment >= 0)
{
line = line.Substring(0, comment - 1).Trim();
}
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
if (line.StartsWith("[") && line.EndsWith("]"))
{
section = line.Trim(new char[] { '[', ']' });
}
else
{
int split = line.IndexOf('=');
if (split >= 0)
{
string key = line.Substring(0, split - 1).Trim();
string value = line.Substring(split + 1).Trim();
Set(section, key, value);
}
}
}
}
}
}
public void Write(string path)
{
using (StreamWriter writer = new StreamWriter(path))
{
foreach (var section in m_dictionary)
{
writer.WriteLine("[" + section.Key + "]");
foreach (var value in section.Value)
{
writer.WriteLine(value.Key + " = " + value.Value);
}
writer.WriteLine();
}
}
}
public string Get(string name) { return Get(string.Empty, name); }
public string Get(string section, string name) { return m_dictionary[section.ToLower()][name.ToLower()]; }
public void Set(string name, string value) { Set(string.Empty, name, value); }
public void Set(string section, string name, string value)
{
string s = section.ToLower();
if (!m_dictionary.ContainsKey(s) || m_dictionary[s] == null)
{
m_dictionary[s] = new Dictionary<string, string>();
}
m_dictionary[s][name.ToLower()] = value;
}
}
}
| 37cee7257ae7d385670ab404cce7f08ea1d172f7 | [
"C#"
] | 19 | C# | svenzin/living-log | 1b6efed8b192e545a121e1bad3b89bf75a62f3e6 | d4a4d3fd013209a5927955b00183301f3301c7a7 |
refs/heads/master | <repo_name>jsBlackBelt/graphql-workshop<file_sep>/server/src/resources/post/queries.js
import { GraphQLInt, GraphQLList } from 'graphql';
import { PostType } from './types';
import postResolver from '../../resolvers/post/search';
export const PostQuery = {
post: {
type: new GraphQLList(PostType),
args: {
id: {
type: GraphQLInt,
},
authorId: {
type: GraphQLInt,
}
},
resolve: postResolver,
},
};
<file_sep>/apollo-server/resolvers/author/create.js
import Store from '../../store';
/**
* create new author
*/
export const authorCreateResolver = (_, author, ctx) => {
return Store.createAuthor(author);
};
export default authorCreateResolver;
<file_sep>/apollo-server/resolvers/index.js
import authorResolver from './author/search';
import authorCreateResolver from './author/create';
import postResolver from './post/search';
import postUpvoteResolver from './post/upvote';
import postCreateResolver from './post/create';
const resolvers = {
Subscription: {
postAdded: {
// Additional event labels can be passed to asyncIterator creation
subscribe: (_, __, context) => context.pubSub.asyncIterator([context.topics.POST_ADDED]),
},
},
Query: {
author: authorResolver,
post: postResolver,
},
Mutation: {
createAuthor: authorCreateResolver,
postUpvote: postUpvoteResolver,
createPost: postCreateResolver,
},
Post: {
author: post => authorResolver(global, {id: post.author}),
},
Author: {
post: author => postResolver(global, {authorId: author.id}),
}};
export default resolvers;
<file_sep>/apollo-server/resources/Author.js
const Author = `
type Author {
id: Int!
name: String!
company: String!
post: [Post!]!
}
`;
export default Author;
<file_sep>/server/src/resolvers/author/search.js
import Store from '../../store';
const authorResolver = (obj, args, req) => {
let authors;
if (args.id) {
authors = [Store.getAuthor(args.id)];
} else {
authors = Store.getAuthors();
}
return authors;
};
export default authorResolver;
<file_sep>/server/src/resolvers/author/create.js
import Store from '../../store';
export const authorCreateResolver = (obj, author, req) => {
return Store.createAuthor(author);
};
export default authorCreateResolver;
<file_sep>/server/src/resources/blog/queries.js
import { GraphQLList } from 'graphql';
import blogResolver from '../../resolvers/blog/search';
import { PostType } from '../post/types';
export const BlogQuery = {
blog: {
type: new GraphQLList(PostType),
resolve: blogResolver,
},
};
<file_sep>/client/src/hooks/useGetPostListQuery.js
import { gql } from 'apollo-boost';
import { useQuery } from '@apollo/react-hooks';
const GET_POST_LIST = gql`
query PostListQuery {
post {
id
title
votes
author {
id
name
}
}
}
`;
export default function useGetPostListQuery () {
return useQuery(GET_POST_LIST);
};<file_sep>/server/src/resolvers/index.js
import { PubSub } from 'graphql-subscriptions';
import authorResolver from './author/search';
import authorCreateResolver from './author/create';
import postResolver from './post/search';
const AUTHOR_ADDED_TOPIC = 'newAuthor';
const pubsub = new PubSub();
const resolvers = {
Query: {
authors: authorResolver,
posts: postResolver,
},
Mutation: {
createAuthor: (obj, author, req) => {
const created = authorCreateResolver(obj, author, req);
pubsub.publish(AUTHOR_ADDED_TOPIC, { authorAdded: created });
return created;
},
},
Post: {
author: post => authorResolver(global, {id: post.author}),
},
Subscription: {
authorAdded: {
subscribe: () => pubsub.asyncIterator(AUTHOR_ADDED_TOPIC),
}
}
};
export default resolvers;
<file_sep>/client/src/hooks/usePostAddedSubscription.js
import { gql } from 'apollo-boost';
import { useSubscription } from '@apollo/react-hooks';
const POST_ADDED_SUBSCRIPTION = gql`
subscription PostAddedSubscription {
postAdded {
id
title
}
}
`;
export default function usePostAddedSubscription (options) {
return useSubscription(POST_ADDED_SUBSCRIPTION, options);
};<file_sep>/server/src/resources/author/types.js
import {
GraphQLInt,
GraphQLObjectType,
GraphQLString,
GraphQLNonNull,
GraphQLInputObjectType,
GraphQLList,
} from 'graphql';
import { PostType } from '../post/types';
import postResolver from '../../resolvers/post/search';
export const AuthorType = new GraphQLObjectType({
name: "Author",
fields: () => ({
id: {
type: GraphQLInt,
},
name: {
type: GraphQLString,
},
company: {
type: GraphQLString,
},
post: {
type: new GraphQLList(PostType),
resolve: obj => postResolver(obj, {authorId: obj.id}),
},
}),
});
export const AuthorCreateType = new GraphQLInputObjectType({
name: 'AuthorCreateType',
description: 'author create',
fields: {
name: {
type: new GraphQLNonNull(GraphQLString),
},
company: {
type: new GraphQLNonNull(GraphQLString),
},
},
});
<file_sep>/apollo-server/resources/Queries.js
const Queries = `
# This type specifies the entry points into our API.
type Query {
author(id: Int): [Author]
post(id: Int, authorId: Int): [Post]
}
`;
export default Queries;
<file_sep>/server/src/resources/post/mutations.js
import { PostType, PostUpvoteType } from './types';
import PostUpvoteResolver from '../../resolvers/post/upvote';
export const PostUpvoteMutation = {
postUpvote: {
type: PostType,
description: 'Post Upvote',
args: {
input: {
type: PostUpvoteType,
},
},
resolve: PostUpvoteResolver,
},
};
<file_sep>/server/src/resolvers/post/search.js
import Store from '../../store';
const postResolver = (obj, args, req) => {
let posts;
if (args.id) {
posts = [Store.getPost(args.id)];
}
else if (args.authorId) {
posts = Store.getAuthorPosts(args.authorId);
}
else {
posts = Store.getPosts();
}
return posts;
};
export default postResolver;
<file_sep>/server/src/store/index.js
const posts = {
"234": {
id: 234,
author: 2,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:01",
summary: "...",
tags: ["GraphQl", "API"],
title: "Contemporary API Design",
votes: 0
},
"456": {
id: 456,
author: 4,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:02",
summary: "...",
tags: ["Redux", "React", "redux-little-router"],
title: "Let The URL Do The Talking",
votes: 0
},
"17": {
id: 17,
author: 7,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:03",
summary: "...",
tags: ["HTTP/2", "Interlock", "compilers"],
title: "HTTP/2 Server Push",
votes: 0
},
"872": {
id: 872,
author: 4,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:04",
summary: "...",
tags: ["React", "Freactal", "state management"],
title: "Don't Fear The Fractal: Infinite State Composition With Freactal",
votes: 0
},
"642": {
id: 642,
author: 8,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:05",
summary: "...",
tags: ["OSS", "documentation", "design"],
title: "Your Docs And You: A Guide For Your First OSS Portfolio",
votes: 0
},
"56": {
id: 56,
author: 7,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:06",
summary: "...",
tags: ["React", "Rapscallion", "server side rendering"],
title: "Faster React SSR With Rapscallion",
votes: 0
},
"21": {
id: 21,
author: 9,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:07",
summary: "...",
tags: ["OSS", "career"],
title: "On Releasing My First OSS Project At Thirty-Five",
votes: 0
},
"73": {
id: 73,
author: 9,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:08",
summary: "...",
tags: ["Node", "performance", "monitoring"],
title: "Introducing NodeJS-Dashboard",
votes: 0
},
"943": {
id: 943,
author: 4,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:09",
summary: "...",
tags: ["React", "redux-little-router", "routers"],
title: "Introducing Nested Routing In Redux Little Router",
votes: 0
},
"856": {
id: 856,
author: 4,
categories: ["Software Engineering"],
publishDate: "2016/03/27 14:10",
summary: "...",
tags: ["Browsers", "HTTP"],
title: "The Only Correct Script Loader Ever Made",
votes: 0
}
};
const authors = {
"2": {
id: 2,
name: "<NAME>",
company: "Formidable"
},
"4": {
id: 4,
name: "<NAME>",
company: "Formidable"
},
"7": {
id: 7,
name: "<NAME>",
company: "Formidable"
},
"8": {
id: 8,
name: "<NAME>",
company: "Formidable"
},
"9": {
id: 9,
name: "<NAME>",
company: "Formidable"
},
"10": {
id: 10,
name: "<NAME>",
company: "Formidable"
}
};
const getPosts = () => Object.keys(posts).map(key => posts[key]);
const getPost = (id) => posts[id];
const getAuthors = () => Object.keys(authors).map(key => authors[key]);
const getAuthor = (id) => authors[id];
const getAuthorPosts = (authorId) => {
const r = Object.values(posts)
.filter(post => post.author === authorId);
return r;
};
const createAuthor = (author) => {
const id = Object.values(authors)
.map(author => author.id)
.reduce((acc, id) => id > acc ? id : acc, 0);
const authorToCreate = Object.assign({}, author, {
id: id + 1,
});
authors[authorToCreate.id] = authorToCreate;
return authorToCreate;
};
const postUpvote = ({id}) => {
const post = getPost(id);
const postToUpvote = Object.assign({}, post, {
votes: post.votes + 1,
});
posts[id] = postToUpvote;
return postToUpvote;
}
export default {
getPost,
getPosts,
getAuthor,
getAuthorPosts,
getAuthors,
createAuthor,
postUpvote,
}
<file_sep>/server/src/resolvers/blog/search.js
import Store from '../../store';
const blogResolver = () => {
return Store.getPosts();
};
export default blogResolver;
<file_sep>/server/src/resources/mutations.js
import { GraphQLObjectType } from 'graphql';
import { AuthorCreateMutation } from './author/mutations';
import { PostUpvoteMutation } from './post/mutations';
const MutationType = new GraphQLObjectType({
name: 'MutationType',
description: 'Top-level content mutations',
fields: {
...AuthorCreateMutation,
...PostUpvoteMutation,
},
});
export default MutationType;
<file_sep>/apollo-server/resources/Post.js
const Post = `
type Post {
id: Int!
categories: [String]
publishDate: String
summary: String
tags: [String]
votes: Int!
title: String!
author: [Author!]!
}
`;
export default Post;
<file_sep>/apollo-server/resources/Subscriptions.js
const Subscriptions = `
type Subscription {
postAdded: Post
}
`
export default Subscriptions;
<file_sep>/server/src/resources/index.js
const typeDefs = `
type Author {
id: Int
name: String
company: String
}
type Post {
id: Int
categories: [String]
publishDate: String
summary: String
tags: [String]
title: String
author: [Author]
}
# This type specifies the entry points into our API.
type Query {
authors(id: Int): [Author]
posts(id: Int, authorId: Int): [Post]
}
# The mutation root type, used to define all mutations.
type Mutation {
createAuthor(name: String!, company: String!): Author
}
# The subscription root type, specifying what we can subscribe to
type Subscription {
authorAdded: Author
}
`;
export default typeDefs;
<file_sep>/client/src/components/index.js
import PostList from "./PostList/PostList";
export {
PostList,
};<file_sep>/client/src/hooks/usePostUpvoteMutation.js
import { gql } from 'apollo-boost';
import { useMutation } from '@apollo/react-hooks';
const POST_UPVOTE = gql`
mutation($id: Int!) {
postUpvote (id: $id) {
id
title
votes
}
}
`;
export default function usePostUpvoteMutation (options) {
return useMutation(POST_UPVOTE, options);
};<file_sep>/client/src/hooks/useCreatePostMutation.js
import { gql } from 'apollo-boost';
import { useMutation } from '@apollo/react-hooks';
const POST_CREATE = gql`
mutation ($title: String!, $votes: Int!, $authorName: String!) {
createPost(title: $title, votes: $votes, authorName: $authorName) {
id
categories
publishDate
votes
title
author {
name
company
}
}
}
`;
export default function useCreatePostMutation (options) {
return useMutation(POST_CREATE, options);
};<file_sep>/apollo-server/resolvers/post/search.js
import Store from '../../store';
/**
*
* if args.id - return post by id as list
* if args.authorId - return all posts by authorId
* else return all posts
*/
const postResolver = (_, args, ctx) => {
let posts;
if (args.id) {
posts = [Store.getPost(args.id)];
}
else if (args.authorId) {
posts = Store.getAuthorPosts(args.authorId);
}
else {
posts = Store.getPosts();
}
return posts;
};
export default postResolver;
<file_sep>/apollo-server/resolvers/author/search.js
import Store from '../../store';
/**
* if args.id - return author by id as list
* else - return sll authors as list
*/
const authorResolver = (_, args, ctx) => {
let authors;
if (args.id) {
authors = [Store.getAuthor(args.id)];
} else {
authors = Store.getAuthors();
}
return authors;
};
export default authorResolver;
<file_sep>/server/src/server.js
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import schema from './schema';
import depthLimit from 'graphql-depth-limit'
const PORT = 5000;
const server = express();
const subscriptionsEndpoint = `ws://localhost:${PORT}/subscriptions`;
server.use(cors());
server.use('/graphql', bodyParser.json(), graphqlExpress({
schema,
}));
const DepthLimitRule = depthLimit(
3,
{ ignore: [ 'whatever', 'trusted' ] },
depths => console.log(depths)
)
app.use(graphqlHttp({
schema,
// Pretty Print the JSON response
pretty: true,
// Enable GraphiQL dev tool
graphiql: true,
validationRules: [
DepthLimitRule,
],
}));
// Making plain HTTP server for Websocket usage
const ws = createServer(server);
ws.listen(PORT, () => {
console.log(`Go to http://localhost:${PORT}/graphiql to run queries`);
console.log(`Open 2 tabs to see subscription in action!`);
/** GraphQL Websocket definition **/
// Set up the WebSocket for handling GraphQL subscriptions.
new SubscriptionServer({
execute,
subscribe,
schema
}, {
server: ws,
path: '/subscriptions',
});
});
<file_sep>/client/src/components/PostList/styled-components.js
import styled from 'styled-components';
import IconButton from '@material-ui/core/IconButton';
const Container = styled.div`
display: flex;
flex-direction: column;
margin: 2rem;
`;
const Author = styled.div`
`;
const Post = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 60%;
padding: 0.5rem;
`;
const PostTitle = styled.span`
margin-right: 1rem;
flex: 1 0 70%;
text-align: left;
`;
const PostVotes = styled.div`
flex: 1 0 100px;
`;
const LikeButton = styled(IconButton)`
`;
const AuthorItem = styled.div`
text-align: left;
flex: 1 0 150px;
margin-right: 0.5rem;
width: 150px;
`;
export default {
Author,
AuthorItem,
Container,
LikeButton,
Post,
PostTitle,
PostVotes,
};<file_sep>/apollo-server/index.js
import { ApolloServer } from 'apollo-server';
import depthLimit from 'graphql-depth-limit'
import resolvers from './resolvers';
import typeDefs from './resources';
import { PubSub } from 'apollo-server';
const validationRules = [
depthLimit(3),
];
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules,
context: {
pubSub: new PubSub(),
topics: {
POST_ADDED: 'post_added'
}
}
});
server.listen().then(({ url, subscriptionsUrl }) => {
console.log(`🚀 Server ready at ${url}`);
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`);
});
<file_sep>/server/src/resources/author/mutations.js
import { AuthorType, AuthorCreateType } from './types';
import authorCreateResolver from '../../resolvers/author/create';
export const AuthorCreateMutation = {
createAuthor: {
type: AuthorType,
description: 'Create author',
args: {
input: {
type: AuthorCreateType,
},
},
resolve: authorCreateResolver,
},
};
<file_sep>/client/src/components/PostList/PostList.js
import React, {useCallback, useState} from 'react';
import ThumbUp from '@material-ui/icons/ThumbUp';
import useGetPostListQuery from '../../hooks/useGetPostListQuery';
import usePostUpvoteMutation from '../../hooks/usePostUpvoteMutation';
import useCreatePostMutation from '../../hooks/useCreatePostMutation';
import usePostAddedSubscription from '../../hooks/usePostAddedSubscription';
import Styled from './styled-components';
const PostList = () => {
const {
loading,
error,
data,
refetch: postListQueryRefetch,
} = useGetPostListQuery();
const {data: postAddedData, loading: postAddedLoading} = usePostAddedSubscription();
const newPostTitle = postAddedData?.postAdded?.title;
const listener = useCallback(() => {
if (!postAddedLoading && newPostTitle) {
window.alert(`New post added ${newPostTitle}`)
}
}, [newPostTitle, postAddedLoading])
listener()
const [postUpvote] = usePostUpvoteMutation(
{
onCompleted: () => {
postListQueryRefetch();
},
}
);
const [createPost] = useCreatePostMutation(
{
onCompleted: () => {
postListQueryRefetch();
},
}
);
const [title, setTitle] = useState('');
const [votes, setVotes] = useState('');
const [authorName, setAuthorName] = useState('');
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
const {post} = data;
const upVote = (postId) => {
postUpvote({variables: {id: postId}});
}
const handleSubmit = (formEvent) => {
formEvent.preventDefault();
createPost({variables: {title, votes: parseInt(votes), authorName}});
}
return (
<>
<Styled.Container>
{post.map(post => (
<Styled.Post key={post.id}>
<Styled.PostTitle>{post.title}</Styled.PostTitle>
<Styled.Author>
{post.author.map(author => (
<Styled.AuthorItem key={author.id}>{author.name}</Styled.AuthorItem>
))}
</Styled.Author>
<Styled.PostVotes>Votes: {post.votes}</Styled.PostVotes>
<Styled.LikeButton color="primary" onClick={() => upVote(post.id)}>
<ThumbUp/>
</Styled.LikeButton>
</Styled.Post>
))}
</Styled.Container>
<form onSubmit={handleSubmit}>
<label>
title:
<input
type="text"
value={title}
onChange={e => setTitle(e.target.value)}
/>
</label>
<label>
votes:
<input
type="text"
value={votes}
onChange={e => setVotes(e.target.value)}
/>
</label>
<label>
author:
<input
type="text"
value={authorName}
onChange={e => setAuthorName(e.target.value)}
/>
</label>
<input type="submit" value="Submit"/>
</form>
</>
);
};
export default PostList;
<file_sep>/server/src/resources/author/queries.js
import { GraphQLInt, GraphQLList } from 'graphql';
import { AuthorType } from './types';
import authorResolver from '../../resolvers/author/search';
export const AuthorQuery = {
author: {
resolve: authorResolver,
args: {
id: {
type: GraphQLInt,
},
},
type: new GraphQLList(AuthorType),
},
};
<file_sep>/apollo-server/resolvers/post/upvote.js
import Store from '../../store';
/**
* increase post votes by 1
*/
export const PostUpvoteResolver = (_, args, ctx) => {
return Store.postUpvote(args);
};
export default PostUpvoteResolver;
| f3aaa45d3b5733d7b696078964e699fa4144357c | [
"JavaScript"
] | 32 | JavaScript | jsBlackBelt/graphql-workshop | 950755968ed35e47fda62e1b2d0b945ad4af3b7e | 8bf156f02088f6fdbce287640b8e8a15f20b86af |
refs/heads/master | <file_sep>import React from 'react';
import { Text, View, Image, TouchableHighlight, StyleSheet } from 'react-native';
import styled from "styled-components/native";
import Colors from "../util/colors";
const RowContainer = styled.View`
align-self: stretch;
flex-direction: row;
align-items: center;
height: 100;
background-color: ${Colors.dark};
margin-horizontal: 5;
margin-top: 5;
margin-bottom: 0;
border-radius: 0;
`;
const Thumbnail = styled.Image`
flex: 1;
height: 100;
flex-direction: column;
justify-content: center;
`;
const Title = styled.Text`
font-size: 36;
font-weight: bold;
margin: 30;
background-color: purple;
color: white;
text-align: center;
padding: 5;
`;
export default class CategoryRow extends React.Component {
// = ({thumbnailURI, title, onPress}) =>
setNativeProps = (nativeProps) => {
this._root.setNativeProps(nativeProps);
};
render() {
return (
<RowContainer>
<TouchableHighlight onPress={this.props.onPress} style={styles.highlight}>
<Image
source={{ uri: "https://media.giphy.com/media/3o7TKQXXnn5fwgfHr2/source.gif" }}
ref={component => this._root = component}
style={styles.highlight}
>
{
this.props.title
? <Title numberOfLines={1}>{this.props.title}</Title>
: null
}
</Image>
</TouchableHighlight>
</RowContainer>
);
}
}
const styles = StyleSheet.create({
highlight: {
flex: 1,
height: 100,
flexDirection: "column",
justifyContent: "center",
}
});<file_sep>const data = [
{title: "Confused", thumbnailURI: "https://media.giphy.com/media/3oEjHFz13et9fQKFb2/giphy.gif"},
{title: "Pug Music", thumbnailURI: "https://media.giphy.com/media/hEwST9KM0UGti/giphy.gif"},
{title: "Dogs", thumbnailURI: "https://media.giphy.com/media/QGSEGsTr04bPW/giphy.gif"},
{title: "Harambe", thumbnailURI: "https://media.giphy.com/media/26ufp0aB26lWMXZss/giphy.gif"},
{title: "Spongebob", thumbnailURI: "https://media.giphy.com/media/3o6ZtbDxnBzSkucV8I/source.gif"},
{title: "Mic Drop", thumbnailURI: "https://media.giphy.com/media/mVJ5xyiYkC3Vm/giphy.gif"},
{title: "Cats", thumbnailURI: "https://media.giphy.com/media/6Jo7Q3flQ1qEg/giphy.gif"},
];
export default data;<file_sep>export default {
primary: "#fb6964", // red
secondary: "#1352a2", // blue
tertiary: "#ffd464", // yellow
dark: "#333332",
light: "#f0f1ee", // light gray
};<file_sep>import Store from 'react-native-store';
const DB = {
'categories': Store.model('categories'),
}
// DB.categories.add({
// title: "Cats",
// order: 0,
// displayColor: "#ccff00",
// thumbnailURI: "",
// });
/**
* gets all categories
* [ret] promise
getCategoriesData().then(
res => {
console.log("categories", res);
}
);
*/
export function getCategoriesData() {
return DB.categories.find();
}
/**
* adds a category to the list of categories
* [param] Object<category object>
* [ret] null
*/
export function addCategory(category) {
if(category && category.title && category.thumbnailURI)
DB.categories.add(category);
}
/**
* updates an existing category using filter
* [param] filter:Object
* [param] newCategory:Object
* [ret] promise
*/
export function updateCategories(filter, newCategory) {
DB.categories.update(
newCategory, filter
)
}<file_sep>import Store from 'react-native-store';
const DB = {
'images': Store.model('images'),
}
/**
* gets all images
* [ret] promise
getAllImages().then(
res => {
console.log(res);
}
);
*/
export function getAllImages() {
return DB.images.find();
}
/**
* gets all images in a category
* [ret] promise
getImagesWithCategory(1).then(
res => {
console.log("images", res);
}
);
*/
export function getImagesWithCategory(categoryId) {
return DB.images.find({
where: {
categoryId: categoryId,
},
});
}
/**
* adds a category to the list of categories
* [param] Object<category object>
* [ret] null
addImage(1, "https://media.giphy.com/media/l0HlEwbMREYkPyrRu/giphy.gif").then(
res => {
console.log(res);
}
);
*/
export function addImage(categoryId, imageUrl) {
if(categoryId && imageUrl)
return DB.images.add({
thumbnailUrl: imageUrl,
imageUrl: imageUrl,
categoryId: categoryId,
});
}
/**
* updates an existing category using filter
* [param] filter:Object
* [param] newCategory:Object
* [ret] promise
*/
// export function updateCategories(filter, newCategory) {
// DB.categories.update(
// newCategory, filter
// )
// }<file_sep>import React, { Component } from 'react';
import { View, ListView, Button } from 'react-native';
import styled from "styled-components/native";
import Colors from "../util/colors";
import CategoryRow from "../components/CategoryRow";
import NewCategory from "./NewCategory.ios";
import CategoryDetail from "./CategoryDetail.ios";
import { getCategoriesData } from "../util/categories";
import { addImage, getImagesWithCategory, getAllImages } from "../util/images";
const WrapperView = styled.View`
flex: 1;
background-color: ${Colors.dark};
`;
const ListOfCategories = styled.ListView`
flex: 1;
background-color: ${Colors.dark};
`;
export default class CategoryList extends Component {
ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
//need to set up a blank initial datasource so the listview won't error out
constructor(props){
super(props);
this.state = {
dataSource: this.ds.cloneWithRows([]),
};
}
//fetch the data that will be loaded into the ListView
componentWillMount(){
getCategoriesData().then(
res => {
this.setState({ dataSource: this.ds.cloneWithRows(res) });
}
);
}
componentWillUpdate(){
getCategoriesData().then(
res => {
this.setState({ dataSource: this.ds.cloneWithRows(res) });
}
);
}
//used by ListOfCategories
renderRow = (rowData) =>
<CategoryRow
title={rowData.title}
thumbnailURI={rowData.thumbnailURI}
onPress={() => this.navToCategoryDetail(rowData._id, rowData.title)}
/>;
navToNewCategory(){
this.props.navigator.push({
title: 'New Category',
component: NewCategory,
})
}
navToCategoryDetail(categoryId, category){
this.props.navigator.push({
title: category,
component: CategoryDetail,
passProps: {categoryId: categoryId},
})
}
render() {
return (
<WrapperView>
<ListOfCategories
enableEmptySections={true}
dataSource={this.state.dataSource}
renderRow={this.renderRow}
/>
</WrapperView>
);
}
}<file_sep>import React, { Component } from 'react';
import { AppRegistry, NavigatorIOS, StyleSheet } from 'react-native';
import styled from "styled-components/native";
import NewCategory from "./imports/pages/NewCategory.ios";
import CategoryList from "./imports/pages/CategoryList.ios";
// import NewCategory from "./imports/pages/NewCategory.ios";
import { getCategoriesData, updateCategories } from "./imports/util/categories";
const StyledNavigator = styled.NavigatorIOS`
flex: 1;
`;
export default class gif extends Component {
constructor() {
super();
this. _handleNavigationRequest = this. _handleNavigationRequest.bind(this);
}
_handleNavigationRequest() {
console.log(this._nav);
this._nav.push({
component: NewCategory,
title: 'New Category',
});
}
render() {
return (
<NavigatorIOS
ref={(ref) => {this._nav = ref}}
style={styles.nav}
initialRoute={{
title: 'Categories',
component: CategoryList,
rightButtonTitle: "Add",
onRightButtonPress: () => this._handleNavigationRequest(),
}}
/>
);
}
}
AppRegistry.registerComponent('gif', () => gif);
const styles = StyleSheet.create({
nav: {
flex: 1,
}
}); | 3b7acbbfa2794921261ce4973b9d07903234017b | [
"JavaScript"
] | 7 | JavaScript | JakeDawkins/Gif-Manager | 92f0a966cd78a1d5d09eb44519dc3ae3039eaedb | b9d8b1471b5ded9c468fe2e4b65c7e5468a0463d |
refs/heads/master | <repo_name>DouglasKosvoski/URI<file_sep>/1061 - 1070/1066.py
evens, odds, positives, negatives = 0,0,0,0
for i in range(5):
num = int(input())
if num > 0:
positives += 1
elif num < 0:
negatives += 1
if num % 2 == 0:
evens += 1
else:
odds += 1
print('{0} valor(es) par(es)'.format(evens))
print('{0} valor(es) impar(es)'.format(odds))
print('{0} valor(es) positivo(s)'.format(positives))
print('{0} valor(es) negativo(s)'.format(negatives))
<file_sep>/1041 - 1050/1050.py
DDD = int(input())
if DDD == 61: print('Brasilia')
elif DDD == 71: print('Salvador')
elif DDD == 11: print('Sao Paulo')
elif DDD == 21: print('Rio de Janeiro')
elif DDD == 32: print('Juiz de Fora')
elif DDD == 19: print('Campinas')
elif DDD == 27: print('Vitoria')
elif DDD == 31: print('Belo Horizonte')
else: print('DDD nao cadastrado')
<file_sep>/1031 - 1040/1036.py
A, B, C = map(float, input().split())
if A != 0:
delta = (B * B) - (4 * A * C)
if delta > 0:
x1 = (-B + (delta**0.5)) / (2 * A)
x2 = (-B - (delta**0.5)) / (2 * A)
print("R1 = %.5f" % (x1))
print("R2 = %.5f" % (x2))
elif (delta < 0):
print("Impossivel calcular")
else:
print("Impossivel calcular")
<file_sep>/1131 - 1140/1132.py
x = int(input())
y = int(input())
total = 0
for i in range(min(x,y), max(x,y)+1):
if i % 13 != 0:
total += i
else:
pass
print(total)
<file_sep>/1001 - 1020/1008.c
#include<stdio.h>
int main(){
int number;
int hours;
double per_hour;
double salary;
scanf("%d%d%le\n", &number,&hours,&per_hour);
salary = hours * per_hour;
printf("NUMBER = %d\n", number);
printf("SALARY = U$ %.2f\n", salary);
return 0;
}
<file_sep>/1141 - 1150/1150.py
x = int(input())
y, soma, nums = 0, x, 1
while True:
y = int(input())
if y > x :
break
else:
pass
while soma < y:
soma += x + nums
nums += 1
print(nums)
<file_sep>/1001 - 1020/1014.c
#include<stdio.h>
int main(){
int distance;
double fuel_spent;
scanf("%d %le", &distance, &fuel_spent);
printf("%.3f km/l\n", distance/fuel_spent);
return 0;
}
<file_sep>/1001 - 1020/1002.c
#include<stdio.h>
int main(){
double PI = 3.14159;
double rad;
double area;
scanf("%lf", &rad);
area = PI * (rad*rad);
printf("A=%.4f\n", area);
return 0;
}
<file_sep>/1041 - 1050/1046.py
a, b = map(int, input().split())
if a > b:
horas = (24 - a) + b
elif b > a:
horas = b - a
else:
horas = 24
print('O JOGO DUROU %d HORA(S)' % (horas))
<file_sep>/1091 - 1100/1098.py
i = 0
j = 1
c = 0
while i <= 2:
for x in range(3):
if i == 0 or i == 1:
print("I=%d J=%d" % (i, j+i))
elif c == 10:
i=2
print("I=%d J=%d" % (i, j+i))
else:
print("I=%.1f J=%.1f" % (i, j+i))
j += 1
i += 0.2
j = 1
c += 1
<file_sep>/1131 - 1140/1131.py
inter_goals, gremio_goals = map(int, input().split())
grenais = 1
inter_victories = 0
gremio_victories = 0
draws = 0
while True:
print('Novo grenal (1-sim 2-nao)')
answer = int(input())
# WHO WON?
if inter_goals > gremio_goals:
inter_victories += 1
elif gremio_goals > inter_goals:
gremio_victories += 1
else:
draws += 1
# CONTINUE THE PROGRAM?
if answer == 1:
inter_goals, gremio_goals = map(int, input().split())
grenais += 1
else:
break
print('%d grenais' % (grenais))
print('Inter:%d' % (inter_victories))
print('Gremio:%d' % (gremio_victories))
print('Empates:%d' % (draws))
if inter_victories > gremio_victories:
print('Inter venceu mais')
elif inter_victories < gremio_victories:
print('Gremio venceu mais')
<file_sep>/1001 - 1020/1017.c
#include<stdio.h>
int main(){
double consume;
int km_per_litter = 12;
int spent_time;
int avg_speed;
scanf("%d %d", &spent_time, &avg_speed);
consume = (double)(spent_time * avg_speed) / km_per_litter;
printf("%.3f\n", consume);
return 0;
}
<file_sep>/1041 - 1050/1048.py
# Accepted
salary = float(input())
if salary <= 400:
percentual = 15
elif 400 < salary <= 800:
percentual = 12
elif 800 < salary <= 1200:
percentual = 10
elif 1200 < salary <= 2000:
percentual = 7
elif salary > 2000:
percentual = 4
new_salary = salary + ((salary * percentual) / 100)
earned = new_salary - salary
print('Novo salario: %.2f' % (new_salary))
print('Reajuste ganho: %.2f' % (earned))
print('Em percentual: {0} %'.format(percentual))
<file_sep>/1031 - 1040/1038.py
cod, quant = map(int, input().split())
if cod == 1: total = 4.00 * quant
elif cod == 2: total = 4.50 * quant
elif cod == 3: total = 5.00 * quant
elif cod == 4: total = 2.00 * quant
elif cod == 5: total = 1.50 * quant
print('Total: R$ %.2f'%(total))
<file_sep>/1001 - 1020/1019.py
time = int(input())
hours = time // (60 ** 2)
minutes = time % (60 ** 2) // 60
seconds = time % 60
print('{0}:{1}:{2}'.format(hours, minutes, seconds))
<file_sep>/1031 - 1040/1036.c
#include<stdio.h>
#include<math.h>
int main(){
double a,b,c;
scanf("%le %le %le", &a, &b, &c);
if (a != 0){
double x1, x2;
double delta;
delta = pow(b, 2) - (4 * a * c);
if (delta > 0){
x1 = (-b + pow(delta, 0.5)) / (2 * a);
x2 = (-b - pow(delta, 0.5)) / (2 * a);
printf("R1 = %.5f\n", x1);
printf("R2 = %.5f\n", x2);
}
else if (delta < 0){
printf("Impossivel calcular\n");
}
}
else {
printf("Impossivel calcular\n");
}
return 0;
}
<file_sep>/1001 - 1020/1013.py
a, b, c = map(int, input().split())
lista = [a,b,c]
print('%d eh o maior'%(max(lista)))
<file_sep>/1001 - 1020/1002.py
π = 3.14159
R = float(input())
A = π * (R**2)
print('A=%.4f'%(A))
<file_sep>/1151 - 1160/1154.py
total = 0
nums = 0
while True:
x = int(input())
if x > -1:
total += x
nums += 1
else:
break
print('%.2f' % (total/nums))
<file_sep>/1151 - 1160/1160.py
tests = int(input())
for i in range(tests):
lista = list(map(float, input().split()))
pa = lista[0]
pb = lista[1]
ta = 1 + (lista[2] / 100)
tb = 1 + (lista[3] / 100)
years = 0
while pa <= pb:
pa = int(pa * ta)
pb = int(pb * tb)
years += 1
if years > 100:
break
if years <= 100:
print(years, 'anos.')
else:
print('Mais de 1 seculo.')
<file_sep>/1051 - 1060/1051.py
# Accepted
salary = float(input())
if 0 < salary and salary <= 2000:
print("Isento")
elif 2000 < salary and salary <= 3000:
salary -= 2000
result = salary * 0.08
print("R$ %.2f" % (result))
elif 3000 < salary and salary < 4500:
salary -= 3000
result = (salary * 0.18) + (1000 * 0.08)
print("R$ %.2f" % (result))
else:
salary -= 4500
result = (salary * 0.28) + (1500 * 0.18) + (1000 * 0.08)
print("R$ %.2f" % (result))
<file_sep>/1001 - 1020/1011.py
PI = 3.14159
radius = float(input())
volume = (4/3.0) * PI * (radius ** 3)
print('VOLUME = %.3f'%(volume))
<file_sep>/1071 - 1080/1080.py
highest = 0
lista = {}
for i in range(100):
valor = int(input())
if valor > highest:
highest = valor
lista[valor] = i
print(highest)
print(lista[highest]+1)
<file_sep>/1001 - 1020/1020.py
age_in_days = int(input())
years = age_in_days // 365
months = age_in_days % 365 // 30
days = age_in_days % 365 % 30
print('{0} ano(s)'.format(years))
print('{0} mes(es)'.format(months))
print('{0} dia(s)'.format(days))
<file_sep>/1001 - 1020/1009.c
#include<stdio.h>
int main(){
char name;
double salary;
double sales;
double total;
scanf("%s %le %le\n", &name,&salary,&sales);
total = (salary + (sales * 0.15));
printf("TOTAL = R$ %.2f\n", total);
return 0;
}
<file_sep>/1001 - 1020/1010.c
#include<stdio.h>
int main(){
int code;
int units;
double unit_price;
double total = 0;
int i=0;
while(i<2){
scanf("%d %d %le\n", &code, &units, &unit_price);
total += (units * unit_price);
i++;
}
printf("VALOR A PAGAR: R$ %.2f\n", total);
return 0;
}
<file_sep>/1001 - 1020/1016.py
dist = int(input())
time = 2 * dist
print('%d minutos'%(time))
<file_sep>/1001 - 1020/1018.py
value = int(input())
print(value)
if 0 < value < 1000000:
a = value // 100
print('{0} nota(s) de R$ 100,00'.format(a))
a = value % 100
b = a // 50
print('{0} nota(s) de R$ 50,00'.format(b))
b = a % 50
a = b // 20
print('{0} nota(s) de R$ 20,00'.format(a))
a = b % 20
b = a // 10
print('{0} nota(s) de R$ 10,00'.format(b))
b = a % 10
a = b // 5
print('{0} nota(s) de R$ 5,00'.format(a))
a = b % 5
b = a // 2
print('{0} nota(s) de R$ 2,00'.format(b))
b = a % 2
a = b // 1
print('{0} nota(s) de R$ 1,00'.format(a))
<file_sep>/1041 - 1050/1042.py
a, b, c = map(int, input().split())
lista_original = [a, b, c]
lista_sorted = [a, b, c]
lista_sorted.sort()
for i in lista_sorted:
print(i)
print()
for i in lista_original:
print(i)
<file_sep>/1151 - 1160/1153.py
n = int(input())
total = 1
for i in range(n, 0, -1):
total *= i
print(total)
<file_sep>/1101 - 1110/1101.py
while True:
m, n = map(int, input().split())
total = 0
lista = [m, n]
lista.sort()
if m <= 0 or n <= 0:
break
else:
for i in range(lista[0], lista[1]+1):
total += i
print(i, end=' ')
print('Sum=%d' % (total))
<file_sep>/1171 - 1180/1175.py
lista = []
for i in range(20):
n = int(input())
lista.append(n)
lista.reverse()
for i in range(len(lista)):
print('N[{0}] = {1}'.format(i, lista[i]))
<file_sep>/1001 - 1020/1020.c
#include<stdio.h>
int main(){
int years, months, days;
int age;
scanf("%d", &age);
years = age / 365;
months = age % 365 / 30;
days = age % 365 % 30;
printf("%d ano(s)\n", years);
printf("%d mes(es)\n", months);
printf("%d dia(s)\n", days);
return 0;
}
<file_sep>/1001 - 1020/1009.py
name = str(input())
salary = float(input())
sales = float(input())
total_salary = salary + ((15/100) * sales)
print('TOTAL = R$ %.2f'%(total_salary))
<file_sep>/1151 - 1160/1158.py
n = int(input())
for i in range(n):
x,y = map(int, input().split())
nums = 0
total = 0
m = x
while nums < y:
if m % 2 != 0:
total += m
nums += 1
m += 1
print(total)
<file_sep>/1171 - 1180/1172.py
lista = []
for i in range(10):
x = int(input())
if x <= 0:
lista.append(1)
else:
lista.append(x)
for j in range(len(lista)):
print('X[{0}] = {1}'.format(j, lista[j]))
<file_sep>/1001 - 1020/1007.c
#include<stdio.h>
int main(){
int a,b,c,d;
int result;
scanf("%d%d%d%d\n", &a,&b,&c,&d);
result = ((a*b) - (c*d));
printf("DIFERENCA = %d\n", result);
return 0;
}
<file_sep>/1001 - 1020/1011.c
#include<stdio.h>
#include<math.h>
int main(){
double volume;
int radius;
scanf("%i", &radius);
volume = (4.0/3) * 3.14159 * pow(radius, 3);
printf("VOLUME = %.3f\n", volume);
return 0;
}
<file_sep>/1141 - 1150/1143.py
n = int(input())
a, b, c = 1, 1, 1
for i in range(n):
print(a, b, c)
a = a + 1
b = a ** 2
c = a ** 3
<file_sep>/1071 - 1080/1078.py
n = int(input())
for i in range(1, 10+1):
print('{0} x {1} = {2}'.format(i, n, i*n))
<file_sep>/1151 - 1160/1151.py
n = int(input())
lista = []
x, y = 0,1
while len(lista) < n:
lista.append(x)
if len(lista) < n:
lista.append(y)
x += y
y += x
for i in lista:
if i == lista[-1]:
print(i)
else:
print(i, end=' ')
<file_sep>/1131 - 1140/1133.py
x = int(input())
y = int(input())
for i in range(min(x,y)+1, max(x,y)):
if i % 5 == 2 or i % 5 == 3 and x != y:
print(i)
<file_sep>/1071 - 1080/1072.py
n = int(input())
inn = 0
outt = 0
for i in range(n):
num = int(input())
if 10 <= num and num <= 20:
inn += 1
else:
outt += 1
print('%d in' % (inn))
print('%d out' % (outt))
<file_sep>/1151 - 1160/1156.py
total = 1
n = 3
m = 2
while n <= 39:
total += (n/m)
n += 2
m *= 2
print('%.2f' % (total))
<file_sep>/README.md
# URI
Solution for Uri Problems (https://www.urionlinejudge.com.br/judge/en).
My Profile: https://www.urionlinejudge.com.br/judge/en/profile/327612.
<file_sep>/1061 - 1070/1064.py
positives = 0
average = 0
for i in range(6):
num = float(input())
if num > 0:
positives += 1
average += num
print('{0} valores positivos'.format(positives))
print('%.1f' % (average / positives))
<file_sep>/1031 - 1040/1040.py
# accepted
n1, n2, n3, n4 = map(float, input().split())
media = ((n1 * 2) + (n2 * 3) + (n3 * 4) + (n4 * 1)) / 10
if media >= 7:
print("Media: %0.1f" % (media))
print("Aluno aprovado.")
elif media >= 5:
print("Media: %0.1f" % (media))
print("Aluno em exame.")
exame = input()
exame = float(exame)
media_final = (media + exame) / 2
if media_final >= 5:
print("Nota do exame: %0.1f" % (exame))
print("Aluno aprovado.")
print("Media final: %0.1f" % (media_final))
else:
print("Nota do exame: %0.1f" % (exame))
print("Aluno reprovado.")
print("Media final: %0.1f" % (media_final))
else:
print("Media: %0.1f" % (media))
print("Aluno reprovado.")
<file_sep>/1061 - 1070/1061.py
di = input().split()
day_x, hi = int(di[1]), input().split()
hour_x, min_x, sec_x = int(hi[0]), int(hi[2]), int(hi[4])
df = input().split()
day_y, hf = int(df[1]), input().split()
hour_y, min_y, sec_y = int(hf[0]), int(hf[2]), int(hf[4])
dia = day_y - day_x
hora = hour_y - hour_x
minuto = min_y - min_x
segundos = sec_y - sec_x
if hora < 0:
hora = 24 + hora
dia = dia - 1
if minuto < 0:
minuto = 60 + minuto
hora = hora - 1
if segundos < 0:
segundos = 60 + segundos
minuto = minuto - 1
if dia <= 0:
dia = 0
print("%d dia(s)" % (dia))
print("%d hora(s)" % (hora))
print("%d minuto(s)" % (minuto))
print("%d segundo(s)" % (segundos))
<file_sep>/1001 - 1020/1014.py
dist = int(input())
fuel = float(input())
avrg = dist / fuel
print('%.3f km/l'%(avrg))
<file_sep>/1041 - 1050/1044.py
num1, num2 = map(int, input().split())
if num1 % num2 == 0:
print('Sao Multiplos')
elif num2 % num1 == 0:
print('Sao Multiplos')
else:
print('Nao sao Multiplos')
<file_sep>/1141 - 1150/1142.py
n = int(input())
a, b, c = 1, 2, 3
for i in range(n):
print(a, b, c, 'PUM')
a += 4
b += 4
c += 4
<file_sep>/1041 - 1050/1043.py
a, b, c = map(float, input().split())
lista = [a, b, c]
lista.sort()
if lista[0] + lista[1] > lista[2]:
perimeter = sum(lista)
print('Perimetro = %.1f' % (perimeter))
else:
area = ((a + b) * c) / 2
print('Area = %.1f' % (area))
<file_sep>/1001 - 1020/1010.py
CODE1, UNITS1, PRICE_UNIT1 = map(float, input().split())
CODE2, UNITS2, PRICE_UNIT2 = map(float, input().split())
CODE1, UNITS1 = int(CODE1), int(UNITS1)
CODE2, UNITS2 = int(CODE2), int(UNITS2)
PAY = (UNITS1 * PRICE_UNIT1) + (UNITS2 * PRICE_UNIT2)
print('VALOR A PAGAR: R$ %.2f'%(PAY))
<file_sep>/1111 - 1120/1117.py
soma, nums = 0, 0
while nums < 2:
nota = float(input())
if nota >= 0 and nota <= 10:
soma += nota
nums += 1
else:
print("nota invalida")
print("media = %.2f" % (soma/nums))
<file_sep>/1001 - 1020/1015.c
#include<stdio.h>
#include<math.h>
int main(){
double x1,y1,x2,y2;
double distance;
scanf("%le %le\n %le %le", &x1,&y1,&x2,&y2);
distance = pow(pow(x2-x1, 2) + pow(y2-y1, 2), 0.5);
printf("%.4f\n", distance);
return 0;
}
<file_sep>/1031 - 1040/1037.py
# accepted
a = float(input())
if 0 <= a and a <= 25:
print('Intervalo [0,25]')
elif 25 < a and a <= 50:
print('Intervalo (25,50]')
elif 50 < a and a <= 75:
print('Intervalo (25,50]')
elif 75 < a and a <= 100:
print('Intervalo (75,100]')
elif a < 0 or 100 < a:
print('Fora de intervalo')
<file_sep>/1051 - 1060/1052.py
# Accepted
num = int(input())
if num == 1: print('January')
elif num == 2: print('February')
elif num == 3: print('March')
elif num == 4: print('April')
elif num == 5: print('May')
elif num == 6: print('June')
elif num == 7: print('July')
elif num == 8: print('August')
elif num == 9: print('September')
elif num == 10: print('October')
elif num == 11: print('November')
elif num == 12: print('December')
<file_sep>/1161 - 1170/1165.py
n = int(input())
for j in range(n):
x = int(input())
divs = 0
for i in range(2,x):
if x % i == 0:
divs += 1
break
if divs == 0: print(x, 'eh primo')
else: print(x, 'nao eh primo')
<file_sep>/1001 - 1020/1012.py
PI = 3.14159
A, B, C = map(float, input().split())
area_triang = (A * C) / 2
area_circle = PI * (C ** 2)
area_trapez = ((A + B) * C) / 2
area_square = B ** 2
area_rectan = A * B
print('TRIANGULO: %.3f'%(area_triang))
print('CIRCULO: %.3f'%(area_circle))
print('TRAPEZIO: %.3f'%(area_trapez))
print('QUADRADO: %.3f'%(area_square))
print('RETANGULO: %.3f'%(area_rectan))
<file_sep>/1131 - 1140/1134.py
alcohol = 0
gasoline = 0
diesel = 0
while True:
n = int(input())
if n in range(1, 4):
if n == 1:
alcohol += 1
elif n == 2:
gasoline += 1
elif n == 3:
diesel += 1
elif n == 4:
break
print('MUITO OBRIGADO')
print('Alcool: %d' % (alcohol))
print('Gasolina: %d' % (gasoline))
print('Diesel: %d' % (diesel))
<file_sep>/1151 - 1160/1155.py
total = 1
for i in range (2,101):
total += (1 / i)
print("%.2f" % (total))
<file_sep>/1151 - 1160/1159.py
while True:
x = int(input())
if x == 0:
break
else:
total = 0
num = x
q = 0
while q < 5:
if num % 2 == 0:
total += num
q += 1
else:
pass
num += 1
print(total)
<file_sep>/1001 - 1020/1017.py
car = 12 # km/l
hours = int(input())
avrg_speed = int(input())
litters = (hours * avrg_speed) / car
print('%.3f'%(litters))
<file_sep>/1141 - 1150/1145.py
x,y = map(int,input().split())
cont = 1
for i in range(1, int((y/x)+1)):
r = ""
for j in range(x):
r += str(cont) + " "
cont += 1
print(r[:-1])
<file_sep>/1061 - 1070/1070.py
x = int(input())
nums = 0
i = x+1
while nums < 6:
if i % 2 == 0:
pass
else:
nums += 1
print(i)
i += 1
<file_sep>/1171 - 1180/1174.py
lista = [0] * 100
for i in range(len(lista)):
x = float(input())
lista[i] = x
for j in range(len(lista)):
if lista[j] <= 10:
print('A[%d] = %.1f' % (j, lista[j]))
else:
pass
<file_sep>/1091 - 1100/1094.py
test_cases = int(input())
total_animals = 0
coelhos, ratos, sapos = 0, 0, 0
for i in range(test_cases):
num, typo = input().split()
num = int(num)
total_animals += num
if typo.upper() == 'C':
coelhos += num
elif typo.upper() == 'R':
ratos += num
elif typo.upper() == 'S':
sapos += num
percent_coelhos = (coelhos / total_animals) * 100
percent_ratos = (ratos / total_animals) * 100
percent_sapos = (sapos / total_animals) * 100
print('Total: %d cobaias' % (total_animals))
print('Total de coelhos: %d' % (coelhos))
print('Total de ratos: %d' % (ratos))
print('Total de sapos: %d' % (sapos))
print('Percentual de coelhos: %.2f %%' % (percent_coelhos))
print('Percentual de ratos: %.2f %%' % (percent_ratos))
print('Percentual de sapos: %.2f %%' % (percent_sapos))
<file_sep>/1071 - 1080/1079.py
n = int(input())
for i in range(n):
a, b, c = map(float, input().split())
a, b, c = (a * 2), (b * 3), (c * 5)
avrg = (a + b + c) / 10
print('%.1f' % (avrg))
<file_sep>/1001 - 1020/1016.c
#include<stdio.h>
int main(){
int speed_x = 60;
int speed_y = 90;
int distance = 0;
int minutes = 0;
int km;
scanf("%d", &km);
while(distance < km){
// increase 1KM each 2 minutes
distance += 1;
minutes += 2;
}
printf("%d minutos\n", minutes);
return 0;
}
<file_sep>/1001 - 1020/1005.c
#include<stdio.h>
int main(){
double a; double b;
double avrg;
scanf("%le\n%le", &a, &b);
avrg = ((a*3.5) + (b*7.5))/11;
printf("MEDIA = %.5f\n", avrg);
return 0;
}
<file_sep>/1111 - 1120/1118.py
while True:
total = 0
nums = 0
while nums < 2:
nota = float(input())
if nota >= 0 and nota <= 10:
total += nota
nums += 1
else:
print("nota invalida")
print("media = %.2f" % (total/2))
answer = 0
while True:
print("novo calculo (1-sim 2-nao)")
answer = int(input())
if answer == 1 or answer == 2:
break
if answer == 2:
break
<file_sep>/1171 - 1180/1173.py
lista = [0] * 10
n = int(input())
for i in range(1, 10+1):
lista[i-1] = n
n = lista[i-1] * 2
for j in range(len(lista)):
print('N[{0}] = {1}'.format(j, lista[j]))
<file_sep>/1001 - 1020/1008.py
NUMBER = int(input())
HOURS = int(input())
VALUE = float(input())
SALARY = HOURS * VALUE
print('NUMBER = %d'%(NUMBER))
print('SALARY = U$ %.2f'%(SALARY))
<file_sep>/1141 - 1150/1149.py
lista = list(map(int,input().split()))
n1 = lista[0]
n2 = lista[-1]
soma = 0
for i in range(0, n2):
soma += n1 + i
print(soma)
<file_sep>/1091 - 1100/1099.py
n = int(input())
for i in range(n):
x, y = map(int, input().split())
odds = 0
for j in range(min(x,y)+1, max(x,y)):
if j % 2 != 0:
odds += j
print(odds)
<file_sep>/1001 - 1020/1019.c
#include<stdio.h>
#include<math.h>
int main(){
int hours, minutes, seconds;
int time;
scanf("%i", &time);
hours = time / (int)pow(60,2);
minutes = time % (int)pow(60,2) / 60;
seconds = time % 60;
printf("%d:%d:%d\n", hours, minutes, seconds);
return 0;
}
<file_sep>/1041 - 1050/1045.py
A, B, C = map(float, input().split())
lados = [A, B, C]
lados.sort()
if lados[2] >= lados[0] + lados[1]:
print('NAO FORMA TRIANGULO')
else:
if lados[2]**2 == lados[0]**2 + (lados[1]**2):
print('TRIANGULO RETANGULO')
if lados[2]**2 > lados[0]**2 + (lados[1]**2):
print('TRIANGULO OBTUSANGULO')
if lados[2]**2 < lados[0]**2 + (lados[1]**2):
print('TRIANGULO ACUTANGULO')
if lados[0] == lados[1] and lados[0] == lados[2]:
print('TRIANGULO EQUILATERO')
elif lados[0] == lados[1] or lados[2] == lados[1] or lados[0] == lados[2]:
print('TRIANGULO ISOSCELES')
<file_sep>/1161 - 1170/1164.py
tests = int(input())
for i in range(tests):
x = int(input())
divisores = []
j = x-1
while j > 0:
if x % j == 0:
divisores.append(j)
else:
pass
j -= 1
if int(sum(divisores)) == x:
print('{0} eh perfeito'.format(x))
else:
print('{0} nao eh perfeito'.format(x))
| 0c4c6b9d7a1c0570998cde53801101ba5656cade | [
"Markdown",
"C",
"Python"
] | 78 | Python | DouglasKosvoski/URI | 2be34e2e07c3816799e1e61f1f9076f0e8258ba6 | 72d85fb7f8c8d7bd2701dc65ef011d9eef778c81 |
refs/heads/master | <file_sep># analyzer.rb -- Text Analyzer
# read the contents of a text file into an array
lines = File.readlines(ARGV[0])
# count the number of lines
line_count = lines.size
# join all the lines into one big string
text = lines.join
# determine the number of characters in the text
total_characters = text.length
# determine total number of characters without spaces
total_characters_nospaces = text.gsub(/\s+/, '').length
# determine word count
word_count = text.split.length
# determine number of sentences
sentence_count = text.split(/\.|\?|\!/).length
# determine number of paragraphs
paragraph_count = text.split(/\n\n/).length
# summarize text
sentences = text.gsub(/\s+/, ' ').strip.split(/\.|\?|\!/)
sentences_sorted = sentences.sort_by { |sentence| sentence.length }
one_third = sentences_sorted.length / 3
ideal_sentences = sentences_sorted.slice(one_third, one_third + 1)
ideal_sentences = ideal_sentences.select { |sentence| sentence =~ /is|are/ }
puts "#{line_count} lines"
puts "#{total_characters} characters"
puts "#{total_characters_nospaces} characters excluding spaces"
puts "#{word_count} words"
puts "#{sentence_count} sentences"
puts "#{paragraph_count} paragraphs"
puts "#{sentence_count / paragraph_count} sentences per paragraph (average)"
puts "#{word_count / sentence_count} words per sentence (average)"
# build array of stop words
stopwords = %w{the a by on for of are with just but and to the my I has some in}
words = text.scan(/\w+/)
keywords = words.select { |word| !stopwords.include?(word) }
keywords2 = keywords.join(' ')
word_count_nostopwords = keywords2.split.length
puts "#{word_count_nostopwords} words (no stop words)"
puts "#{((keywords.length.to_f / words.length.to_f) * 100).to_i} percent of non-stop words to all words"
puts "Summary:\n\n" + ideal_sentences.join('. ')
puts "-- End of analysis"
| 3305ed7ecfde2aecb3a980f50581a76606b8fcf1 | [
"Ruby"
] | 1 | Ruby | abeburnett/beginning_ruby | 25e160382cbda270ced4ce616512fe17e72fc37e | c679836a4043ad874e247abb658b99919f204fbc |
refs/heads/master | <file_sep>using System;
using System.Windows;
using System.Collections.Generic;
using System.Windows.Threading;
using Telerik.Windows.Data;
using Telerik.Windows.Controls.ChartView;
using Telerik.Windows.Controls.Gauge;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows.Media.Animation;
using System.Linq;
using System.Timers;
using System.Diagnostics;
using System.Windows.Documents;
using ProdlineTwo.Models;
using System.Windows.Controls;
using WinInterop = System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Windows.Media;
namespace ProdlineTwo
{
public partial class MainWindow3 : Window
{
//int thHitCount = 0; //BG: general counter for bug testing
#region " Window Variables "
//Things that can be set by ScheduleWindow
protected internal int curLotOne = 0;
protected internal int curWipOne = 0;
protected internal string curOneIsAlt = "";
protected internal int lotNumOne; //Actual lot number, not the idx of the db record
protected internal bool isClosable = false;
protected internal int maxDownT;
protected internal bool useShortTimeout = false;
protected internal bool useMachine5Emulation = false;
protected internal SchedDetailFLF sc;
protected internal string machineNaame;
int scIdx = 0;
int qtyGoal = 0; // TODO this has to be factored to the BagsPerCase
int qtyPerCase = 1;
Product pr = null;
Recipe rp = null;
private Timer tm = new Timer(1000d); // Basic timer to check status every second
private Timer tmCheckForChanges = new Timer(180000d); //Timer forchecking for qty updates
Stopwatch stpWatch = new Stopwatch(); // TimeKeeper for run. Only starts once and only stops on Dispose()
Stopwatch stpWtDownTime = new Stopwatch(); // Starts whenever a Downtime event begins, gets reset every time a drop occurs
// Should only be touched by tm.Elapsed and Reset() every time lastWghtRcvdTime is newer
//TimeSpan totDownTime = new TimeSpan(); //TODO PUSHED BACK
private DateTime packDate; // Date of production day (needed if after midnight)
private DateTime lastWghtRcvdTime;
bool firstDrop = false;
bool inDownTime = false;
int downTimeID = 0;
int winCount = 0;
DateTime dayZero = new DateTime(1, 1, 1);
// Form-level data on the run0-
int ItemNo;
string paddedItemNo;
int ItemIdx;
int curRunId = 0;
int curWo = 0;
int curMachKepId = 0;
string jdeMachName = "";
DispatcherTimer dtTimer = new DispatcherTimer();
DispatcherTimer dtTimerUpdRunId = new DispatcherTimer();
DateTime launchTime;
double stDev1 = 0d;
bool useTightGraphing; // Set to true for Ishida machines as their variance is tiny
// Listing of all data regarding our run's ingredients
string ing1 = "";
string ing1Code;
string ing1AltCode; //TODO these only apply if not "NoAltPSItm" which is only two products
int targ1 = 0;
decimal weightDivisor = 1m;
bool weCanConnectToJDE; // TODO future use to hold a variable as regarding the ability to connect to JDE
int targDropSpd = 0;
public List<RunLotNumModel> runLots = new List<RunLotNumModel>();
BackgroundWorker bwCheck;
#endregion
public MainWindow3()
{
InitializeComponent();
win.SourceInitialized += new EventHandler(win_SourceInitialized);
dtTimer.Interval = TimeSpan.FromSeconds(1);
dtTimer.Tick += Timer_Tick;
dtTimerUpdRunId.Interval = TimeSpan.FromSeconds(10);
dtTimerUpdRunId.Tick += dtTimerUpdRunId_Tick;
}
private void dtTimerUpdRunId_Tick(object sender, EventArgs e)
{
using (ProdlineEntities db = new ProdlineEntities())
{
try
{
var thWghts = db.KepwareWeights
.OrderByDescending(p => p.idx)
.Where(p => p.KepNumericId == curMachKepId && p.RunId == 0 && p.dropTime > launchTime) //TODO && p.Weight > targ1
.Select(p => p).ToList();
if (thWghts.Count == 0)
{
return;
}
else
{
foreach (KepwareWeight k in thWghts)
{
k.RunId = curRunId;
k.LotNo = curLotOne > 0 ? curLotOne : k.LotNo;
}
}
db.SaveChanges();
}
catch { }
}
}
private void Timer_Tick(object sender, EventArgs e)
{
txCurrentTime.Text = DateTime.Now.ToString("hh:mm:ss tt");
TimeSpan tsNow = DateTime.Now - launchTime;
txElapsTime.Text = tsNow.Hours.ToString("00") + ":"
+ tsNow.Minutes.ToString("00") + ":"
+ tsNow.Seconds.ToString("00");
List<ChartDataObject> dataSource = new List<ChartDataObject>();
using (ProdlineEntities db = new ProdlineEntities())
{
var thWghts = db.KepwareWeights
.OrderByDescending(p => p.idx)
.Where(p => p.KepNumericId == curMachKepId && p.Weight > 0 && p.dropTime > launchTime) //TODO && p.Weight > targ1
.Select(p => new
{
drpTm = p.dropTime,
drpWght = p.Weight
}).ToList();
if (thWghts.Count == 0) return;
if (!firstDrop) // setting boolean HasZeroDrops to false so run will not be ignored
{
firstDrop = true;
stpWtDownTime.Start();
IshiRun ir = db.IshiRuns.SingleOrDefault(p => p.idx == curRunId);
if (ir != null)
{
ir.HasZeroDrops = false;
db.SaveChanges();
}
}
foreach (var x in thWghts)
{
ChartDataObject obj = new ChartDataObject { Date = x.drpTm, Value = (double)x.drpWght };
dataSource.Add(obj);
}
bool havePrevTime = lastWghtRcvdTime > dayZero;
DateTime lastWghtInFetch = dataSource.Select(p => p.Date).Max();
if (lastWghtRcvdTime < lastWghtInFetch)
{
stpWtDownTime.Reset();
stpWtDownTime.Start();
if (inDownTime) RestartRuntime(lastWghtInFetch);
}
if (havePrevTime)
{
TimeSpan timeDiff = lastWghtInFetch - lastWghtRcvdTime;
if (timeDiff.TotalSeconds > maxDownT)
{
inDownTime = true;
}
}
//finally after all status handling, put
lastWghtRcvdTime = lastWghtInFetch;
CalcDisplayVals(dataSource);
int qtyDone = thWghts.Count;
numIndGoalToGo.Value = qtyGoal - qtyDone;
numIndDropCount.Value = qtyDone;
double minutesUsed = tsNow.TotalMinutes;
double linSpeed = qtyDone / minutesUsed;
UpdateGaugeNeedle(ndlDrops, linSpeed);
UpdateNumericGauge(numericIndicatorSpd, linSpeed);
double effic = (linSpeed / targDropSpd) * 100;
UpdateGaugeNeedle(ndlEffic, effic);
UpdateNumericGauge(numIndicEff, effic);
AreaSeries seri = (AreaSeries)chart1.Series[0];
seri.CategoryBinding = new PropertyNameDataPointBinding() { PropertyName = "Date" };
seri.ValueBinding = new PropertyNameDataPointBinding() { PropertyName = "Value" };
seri.ItemsSource = dataSource;
//txDsrcCount.Text = dataSource.Count.ToString();
}
}
private void RestartRuntime(DateTime lastWghtInFetch)
{
if (downTimeID < 1) return; // TODO generate message that there was not a downtime log to close
using (ProdlineEntities db = new ProdlineEntities())
{
DowntimeLog dl = db.DowntimeLogs.FirstOrDefault(p => p.idx == downTimeID);
dl.EndTime = lastWghtInFetch;
db.SaveChanges();
inDownTime = false;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (machineNaame.Contains("A1") || machineNaame.Contains("B1") || machineNaame.Contains("B2")) useTightGraphing = true;
bool goodToGo = GetBaseData();
//weCanConnectToJDE = App.canConnectToJDE;
if (useShortTimeout) maxDownT = 20;
// NOTE GetBaseData creates a run with "HasZeroDrops" true. It must be changed to False at first drop
// TODO decide what to do if anything goes wrong with lot numbers or work order
if (goodToGo == false)
{
// Any error messages already shown in GetBaseData
Close();
}
dtTimer.Start();
dtTimerUpdRunId.Start();
launchTime = DateTime.Now;
txWorkOrd.Text = sc.WoNum.ToString();
txOperator.Text = App.machPoliteUsrName; //TODO get name from user logon
txItemCode.Text = sc.ItemCd;
txItemDescr.Text = sc.ItemDesc;
bwCheck = new BackgroundWorker();
bwCheck.DoWork += BwCheck_DoWork;
//bwCheck.RunWorkerCompleted += BwCheck_RunWorkerCompleted; //TODO re-enable
if (curRunId > 0)
{
stpWatch.Start();
tm.Elapsed += Tm_Elapsed;
tm.Start();
txStartTime.Text = launchTime.ToString("hh:mm:ss tt");
}
else
{
MessageBox.Show("An unexpected error with starting a new run has occurred. Please contact IT");
Close();
}
}
private bool GetBaseData()
{
paddedItemNo = sc.ItemCd;
ItemNo = int.Parse(sc.ItemCd); //TODO be sure this isn't substituting test value "00417"; //
ItemIdx = ItemNo;
txItemCode.Text = ItemNo.ToString().PadLeft(5, '0');
txItemDescr.Text = sc.ItemDesc;
txWorkOrd.Text = sc.WoNum.ToString();
curWo = sc.WoNum;
scIdx = sc.id;
int machID = 0;
string bPlant = App.locationMCU;
using (PaccumDBEntities dbp = new PaccumDBEntities())
{
packDate = dbp.RateSchedsUploadeds.Where(r => r.id == sc.RateSched).Select(r => r.DateProc).FirstOrDefault();
}
using (ProdlineEntities pe = new ProdlineEntities())
{
pr = pe.Products.FirstOrDefault(p => p.ItemCodeHP == paddedItemNo);
bool succeeded = false;
if (pr != null)
{
rp = pe.Recipes.FirstOrDefault(p => p.RecipeID == pr.RecipeID);
if (rp != null)
{
targDropSpd = rp.TargetSpeed;
txTargetVal.Text = targDropSpd.ToString("N0");
pthTargSpd.SetValue(ScaleObject.ValueProperty, (double)targDropSpd);
elpTargSpd.SetValue(ScaleObject.ValueProperty, (double)targDropSpd);
txTargetVal.SetValue(ScaleObject.ValueProperty, (double)targDropSpd);
ing1 = rp.S1_Product.Trim();
txIngred1.Content = ing1;
targ1 = rp.S1TargetWeight;
if (useTightGraphing)
{
verticalAxis1.Minimum = rp.S1TargetWeight * 0.99;
verticalAxis1.Maximum = rp.S1TargetWeight * 1.05;
}
else
{
verticalAxis1.Minimum = rp.S1TargetWeight * 0.8;
verticalAxis1.Maximum = rp.S1TargetWeight * 2.5;
}
customNote1.VerticalValue = rp.S1TargetWeight;
glAnnot1.Value = rp.S1TargetWeight;
txCh1Series1.Text = "Target for " + rp.S1_Product;
ing1Code = rp.S1_Product;
qtyPerCase = (int)pr.BagsPerCase;
qtyGoal = sc.Qty * qtyPerCase; // qtyGoal is BAGS
// Packages or bags
numIndGoal.Value = qtyGoal;
numIndGoalToGo.Value = qtyGoal;
// Cartons
numIndGoalCart.Value = sc.Qty;
numIndGoalToGoCart.Value = sc.Qty;
if (!pr.NoAltPSItm) //TODO note, this is just for two Organic items that can't be substituted
{
ing1AltCode = rp.S1_Product; // Either PSItm will be true for a Lot number
}
//cmNewLOne.Content = ing1;
//MessageBox.Show(machineNaame); // DEBUG purposes
FLF_Machines fm = (from c in pe.FLF_Machines where c.AttachedPCname == machineNaame select c).FirstOrDefault();
if (fm == null)
{
MessageBox.Show("Error Determining which machine you are operating at. Unable to continue.");
Close();
}
else
{
machID = fm.idx;
curMachKepId = fm.KepNumericID;
jdeMachName = fm.JDEName;
//MessageBox.Show(fm.JDEName); // DEBUG purposes
if (useMachine5Emulation) curMachKepId = 5;
weightDivisor = fm.UOM == "g" ? 453.59237m : 16m;
}
if (weightDivisor == 0m)
{
MessageBox.Show("Error getting Machine Unit of Measure, cannot proceed", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Close();
}
else
{
txTarg1.Content = rp.S1TargetWeight;
succeeded = true;
}
}
else
{
MessageBox.Show("Error getting Recipe information, cannot proceed", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Error getting Product association, cannot proceed", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
if (succeeded)
{
try
{
IshiRun rOld = pe.IshiRuns
.OrderByDescending(p => p.idx)
.Where(p => p.MachineID == machID && p.EndTime == null)
.Select(p => p).FirstOrDefault();
if (rOld != null)
{
rOld.EndTime = DateTime.Now.AddMinutes(-1);
rOld.IsEndTimeUncertain = true;
pe.SaveChanges();
}
FLF_Machines fm = (from c in pe.FLF_Machines where c.AttachedPCname == machineNaame select c).FirstOrDefault();
if (machineNaame == "PC1104-LINE-H1")
{
txMachStatus.Text = "PC1104-LINE-H" + " - " + fm.MachineName;
}
else if (machineNaame == "PC1105-LINE-H2")
{
txMachStatus.Text = "PC1105-W&T" + " - " + fm.MachineName;
}
else
{
txMachStatus.Text = machineNaame + " - " + fm.MachineName;
}
IshiRun r = new IshiRun() //TODO make sure we close any previous runs on same machine in case of crash or other
{
RunDate = DateTime.Today,
EmployeeID = App.EmployeeID,
ItemCode = ItemNo,
MachineID = fm.idx,
ShiftID = App.shiftNum,
StartTime = DateTime.Now,
RunMinutes = 0,
WO = sc.WoNum.ToString(),
BranchPlant = bPlant //TODO add automation for Yuma vs Chualar
// TODO RunDate should be yesterday if < 6 AM
};
pe.IshiRuns.Add(r); //TODO make sure this is never done elsewhere
pe.SaveChanges(); // This creates a record with HasZeroDrops = true, subject to ignoring
curRunId = r.idx;
txRunId.Text = curRunId.ToString();
return true; //all other routes need to stop MainWindow3!!!;
}
catch (Exception ex)
{
MessageBox.Show("Error creating new Run: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
else
{
return false;
}
}
}
private void BwCheck_DoWork(object sender, DoWorkEventArgs e)
{
int i = (int)e.Argument;
using (PaccumDBEntities pe = new PaccumDBEntities())
{
SchedDetailFLF scNow = pe.SchedDetailFLFs.SingleOrDefault(p => p.id == i);
int curQty = scNow.Qty;
if (curQty != qtyGoal)
{
e.Result = curQty;
}
else
{
e.Result = 0;
}
}
}
private void BwCheck_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) //TODO CALLED???
{
if (e.Result == null) return; //something went wrong
int i = (int) e.Result;
if (i != 0)
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
AttnNotification m = new AttnNotification();
m.txNotice.Text = $"Qty to make has changed from {qtyGoal} to {i * qtyPerCase}";
m.Topmost = true;
m.WindowStartupLocation = WindowStartupLocation.CenterOwner;
var myAdornerLayer = AdornerLayer.GetAdornerLayer(mainGrid);
myAdornerLayer.Add(new DimNotRedAdorner(mainGrid));
winCount++;
m.ShowDialog();
winCount--;
m = null;
try { myAdornerLayer.Remove((myAdornerLayer.GetAdorners(mainGrid))[0]); } catch { }
//qtyGoal = i * qtyPerCase; //TODO CAREFUL this is different than originally intended
numIndGoal.Value = qtyGoal;
}));
}
}
private void UpdateNumericGauge(object target, double spd)
{
try
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
((NumericIndicator) target).Value = spd;
}));
}
catch { }
}
private void UpdateNumericScale(double qty)
{
try
{
double pctDone = qty / qtyGoal;
double crtsCompl = Math.Floor(sc.Qty * pctDone);
double crtsToGo = sc.Qty - crtsCompl;
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
numIndDropCount.SetValue(GraphicIndicator.ValueProperty, qty);
numIndGoalToGo.SetValue(GraphicIndicator.ValueProperty, qtyGoal - qty); // Bags to go
numIndGoalToGoCart.SetValue(GraphicIndicator.ValueProperty, crtsToGo); // Cartons to go
}));
}
catch { }
}
private void UpdateGaugeNeedle(object target, double spd)
{
try
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
((Needle) target).Value = spd;
}));
}
catch { }
}
private void CalcDisplayVals(List<ChartDataObject> dSource)
{
int num = dSource.Count;
if (num > 0) UpdateNumericScale(num);
double totWghtUnits = dSource.Sum(p => p.Value);
double avgLbs = dSource.Average(p => p.Value) / (double)weightDivisor;
decimal trgtLbs1 = (targ1 * num) / weightDivisor;
LabelTextInvoker(txTargLbs1, trgtLbs1.ToString("N0") + " lbs");
double lbs1 = totWghtUnits / (double)weightDivisor;
LabelTextInvoker(txActLbs1, lbs1.ToString("N0") + " lbs");
LabelTextInvoker(txAvg1, avgLbs.ToString("N2") + " lbs");
double mean = dSource.Select(p => p.Value).Average();
double variance1 = dSource.Select(p => (p.Value - mean) * (p.Value - mean)).Sum();
stDev1 = Math.Sqrt(variance1 / num);
LabelTextInvoker(txStdDev1, stDev1.ToString("N2"));
//if (num > 100)
//{
// LabelTextInvoker(txL100Avg1, totL1.Average().ToString("N0") + " g");
//}
LabelTextInvoker(txGivAwy1, (lbs1 - (double) trgtLbs1).ToString("N0") + " lbs");
}
private void LabelTextInvoker(object sender, string str)
{
try
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
((Label) sender).Content = str;
}));
}
catch { }
}
private void TextboxTextInvoker(object sender, string str)
{
try
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
((TextBox) sender).Text = str;
}));
}
catch { }
}
private void Tm_Elapsed(object sender, ElapsedEventArgs e)
{
if (inDownTime) return;
if (firstDrop && stpWtDownTime.Elapsed.TotalSeconds > maxDownT)
{
inDownTime = true;
tm.Stop();
DateTime goneDown = DateTime.Now.AddSeconds(-stpWtDownTime.Elapsed.TotalSeconds);
stpWtDownTime.Reset();
using (ProdlineEntities dbCntxt = new ProdlineEntities())
{
DowntimeLog dl = new DowntimeLog()
{
StartTime = goneDown,
RunID = curRunId
}; // see dbCntxt.DowntimeLogs.Add(dl); below
try
{
dbCntxt.DowntimeLogs.Add(dl); // Don't add downtime logs anywhere but here and EndRun
dbCntxt.SaveChanges();
downTimeID = dl.idx;
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
DTCause m = new DTCause()
{
DT_Id = downTimeID,
runId = curRunId,
myDad = this,
Topmost = true,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
whenWentDown = DateTime.Now.AddSeconds(-(stpWtDownTime.Elapsed.TotalSeconds))
};
var myAdornerLayer = AdornerLayer.GetAdornerLayer(mainGrid);
myAdornerLayer.Add(new DimNotRedAdorner(mainGrid));
winCount++;
m.ShowDialog();
winCount--;
m = null;
try { myAdornerLayer.Remove((myAdornerLayer.GetAdorners(mainGrid))[0]); } catch { }
}));
}
catch (Exception ex)
{
MessageBox.Show("Error recording Downtime: " + ex.InnerException.InnerException.Message);
}
}
}
}
private void TmCheckForChanges_Elapsed(object sender, ElapsedEventArgs e) //TODO CALLED???
{
//TODO is this duplication???
//bwCheck.RunWorkerAsync(scIdx);
}
private void ChartTrackBallBehavior_TrackInfoUpdated(object sender, TrackBallInfoEventArgs e)
{
if (e.Context.DataPointInfos.Count < 1) return;
try
{
e.Context.DataPointInfos[0].DisplayContent = "Weight: " + ((ChartDataObject)e.Context.DataPointInfos[0].DataPoint.DataItem).Value.ToString()
+ Environment.NewLine + "Time: " + ((ChartDataObject)e.Context.DataPointInfos[0].DataPoint.DataItem).Date.ToString("hh:mm:ss");
}
catch { }
}
private void MainWindow3_Closing(object sender, CancelEventArgs e)
{
//if (n != null)
//{
// Application.Current.Dispatcher.BeginInvoke(
// DispatcherPriority.Background,
// new Action(() =>
// {
// n.Close();
// }));
// tmWarningWindow.Elapsed -= TmWarningWindow_Elapsed;
// tmWarningWindow.Stop();
//}
Closing -= MainWindow3_Closing;
Cursor = Cursors.Wait;
e.Cancel = true;
var anim = new DoubleAnimation(0, TimeSpan.FromMilliseconds(400));
anim.Completed += (s, _) => Close(); // (s, _) is shorthand for "object sender, EventArgs e"
BeginAnimation(OpacityProperty, anim);
}
private bool VerifyLotNumbers() //TODO not ref'd
{
if (curLotOne == 0)
{
MessageBox.Show("No Lot number entered for " + ing1 + ". Please enter before ending run.");
return false;
}
return true;
}
private string SaveJDEData(DateTime endTimeClicked)
{
//if (runLots.Count == 0) return "Success";
bool procsdFirstLine = false;
bool haveSomeWeight = false;
string loc = App.locationMCU;
using (ProdlineEntities dbLoc = new ProdlineEntities())
{
foreach (RunLotNumModel rl in runLots)
{
//variable for lot beginning
DateTime begTime = procsdFirstLine == true ? rl.TimeStarted : launchTime;
//variable for lot end time
DateTime endingTime = rl.TimeEnded.Year == 9999 ? endTimeClicked : rl.TimeEnded;
try
{
rl.TotWght = (double)Math.Round(dbLoc.KepwareWeights
.Where(p => (p.dropTime > begTime && p.dropTime <= endingTime) && p.KepNumericId == curMachKepId)
.Select(p => p.Weight).Sum() / weightDivisor, 5);
procsdFirstLine = true;
if (rl.TotWght > 0) haveSomeWeight = true;
}
catch
{
// haveSomeWeight = false;
return "Error";
}
}
}
if (!haveSomeWeight)
{
return "No weights";
}
else
{
using (JDE_PRODUCTIONEntities db = new JDE_PRODUCTIONEntities())
{
F57PRDH F57 = new F57PRDH()
{
QH_RUNID = curRunId,
QH_ITEMCD = ItemIdx,
QH_DATEPK = packDate.ToString("yyyy-MM-dd"),
QH_WO = curWo.ToString(),
QHEDSP = "",
QHMCU = loc
};
db.F57PRDH.Add(F57);
try
{
db.SaveChanges(); // TODO Error, we only save if there are lot numbers AND at least one "drop"
foreach (RunLotNumModel rln in runLots)
{
try
{
F57PRDD FDet = new F57PRDD()
{
QD_RUNID = rln.RunID,
QDLITM = rln.WipCode.ToString(),
QDLOTN = rln.LotNumb.ToString(),
QDZ57IN = rln.IngredOrd * 10,
QDUKID = db.F57PRDD.Where(p => p.QD_RUNID == rln.RunID).Select(p => p).Count() > 0 ?
db.F57PRDD.Where(p => p.QD_RUNID == rln.RunID).Select(p => p.QDUKID).Max() + 1 : 1,
QD_ITMWG1 = rln.TotWght,
QDEDSP = rln.IsForcedSave ? "e" : ""
};
db.F57PRDD.Add(FDet);
db.SaveChanges();
}
catch (Exception exDetail)
{
MessageBox.Show("Error saving JDE detail row: " + exDetail.Message);
}
}
return "Success";
}
catch (Exception ex) //TODO check for connection issues
{
MessageBox.Show("Error saving JDE header value: " + ex.Message); //TODO amplify
return "Error";
}
}
}
}
private void cmClose_Click(object sender, RoutedEventArgs e)
{
bool lotsOK = VerifyLotNumbers(); //TODO re-enable to force lot numbers
if (!lotsOK) return;
tm.Stop();
tm.Dispose();
stpWatch.Stop();
stpWtDownTime.Stop();
DateTime endOfRun = DateTime.Now;
try
{
// string savedDataJde = useMachine5Emulation ? "Success" : SaveJDEData(endOfRun);
string savedDataJde = "Ready";
if (useMachine5Emulation == true)
{
savedDataJde = "Success";
}
else
{
savedDataJde = SaveJDEData(endOfRun); //= "Success";
}
if (savedDataJde == "Error")
{
MessageBox.Show(string.Format("Data not saved to JDE, perhaps a connection issue prevented saving, please notify your manager that run number {0} has no data saved in JDE", curRunId.ToString()));
Close();
}
else if (savedDataJde == "No weights")
{
return;
}
else
{
// TODO what???
if (curRunId > 0)
{
dtTimer.Stop();
dtTimerUpdRunId.Stop();
using (ProdlineEntities dbCntxt = new ProdlineEntities())
{
dbCntxt.Database.Log = Console.Write;
DowntimeLog dl = new DowntimeLog()
{
RunID = curRunId
}; // only exception to tm_Elapsed event for new DownTimeLog
try
{
try
{
var thWghts = dbCntxt.KepwareWeights
.OrderByDescending(p => p.idx)
.Where(p => p.KepNumericId == curMachKepId && p.RunId == 0 && (p.dropTime > launchTime && p.dropTime <= endOfRun)) //TODO && p.Weight > targ1
.Select(p => p).ToList();
if (thWghts.Count > 0)
{
foreach (KepwareWeight k in thWghts)
{
k.RunId = curRunId;
k.LotNo = curLotOne;
}
}
dbCntxt.SaveChanges();
}
catch (Exception exSaveFinalRunid)
{
MessageBox.Show("Error saving final run id to weights in database. Please notify IT, error description: " + exSaveFinalRunid.Message);
}
dbCntxt.DowntimeLogs.Add(dl); // Don't add downtime logs anywhere but here and EndRun
dbCntxt.SaveChanges();
downTimeID = dl.idx;
DTCause m = new DTCause()
{
WindowStartupLocation = WindowStartupLocation.CenterOwner,
runId = curRunId,
whenWentDown = DateTime.Now,
sentByClose = true,
myDad = this,
DT_Id = downTimeID
};
var myAdornerLayer = AdornerLayer.GetAdornerLayer(mainGrid);
myAdornerLayer.Add(new DimOrngAdorner(mainGrid));
m.runId = curRunId;
winCount++;
m.ShowDialog();
winCount--;
m = null;
try { myAdornerLayer.Remove((myAdornerLayer.GetAdorners(mainGrid))[0]); } catch { }
if (isClosable)
{
tm.Elapsed -= Tm_Elapsed;
IshiRun ir = dbCntxt.IshiRuns.SingleOrDefault(p => p.idx == curRunId);
if (ir != null)
{
ir.EndTime = endOfRun;
TimeSpan ts = endOfRun - ir.StartTime;
ir.RunMinutes = (int)ts.TotalMinutes;
ir.updatedInJDE = savedDataJde == "Success" ? true : false;
dbCntxt.SaveChanges();
}
Close();
}
else
{
DowntimeLog dlNot = dbCntxt.DowntimeLogs.SingleOrDefault(p => p.idx == downTimeID);
if (dlNot != null)
{
dlNot.IsDeadRecord = true;
dbCntxt.SaveChanges();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error creating end-of-run downtime log: " + ex.ToString());
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void cmViewLots_Click(object sender, RoutedEventArgs e)
{
IshiRun ishi = null;
using (ProdlineEntities dbCntxt = new ProdlineEntities())
{
ishi = dbCntxt.IshiRuns.FirstOrDefault(p => p.idx == curRunId);
}
if (ishi != null)
{
ViewLots w = new ViewLots(this);
w.lbWo.Content = txWorkOrd.Text;
w.runID = curRunId;
w.ingOne = ing1;
var myAdornerLayer = AdornerLayer.GetAdornerLayer(mainGrid);
myAdornerLayer.Add(new DimAdorner(mainGrid));
winCount++;
w.ShowDialog();
winCount--;
try { myAdornerLayer.Remove((myAdornerLayer.GetAdorners(mainGrid))[0]); } catch { }
}
else
{
MessageBox.Show("Error getting Run data!");
}
}
private void cmFirstCase_Click(object sender, RoutedEventArgs e)
{
FirstCaseCheck w = new FirstCaseCheck
{
runId = curRunId
};
var myAdornerLayer = AdornerLayer.GetAdornerLayer(mainGrid);
myAdornerLayer.Add(new DimAdorner(mainGrid));
winCount++;
w.ShowDialog();
winCount--;
w = null;
try { myAdornerLayer.Remove((myAdornerLayer.GetAdorners(mainGrid))[0]); } catch { }
}
private void AnimateGridCell(Label tb)
{
ColorAnimation animation;
animation = new ColorAnimation
{
From = Colors.Transparent,
To = Color.FromRgb(255, 209, 123),
AutoReverse = true,
Duration = new Duration(TimeSpan.FromSeconds(3))
};
tb.Background = new SolidColorBrush(Colors.Transparent);
tb.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);
}
private void cmNewLot_Click(object sender, RoutedEventArgs e)
{
DateTime timStamp = DateTime.Now;
string nm = (sender as Telerik.Windows.Controls.RadButton).Name;
string ingred = "";
string ingE_Code;
string ingE_AltCode;
byte ingredNum = 0;
int curLotForThisIngred = 0;
bool alterAllDrops = false;
int curLotNumIng = 0;
ingred = ing1;
ingE_Code = ing1Code;
ingE_AltCode = ing1AltCode;
ingredNum = 1;
curLotForThisIngred = curLotOne;
curLotNumIng = lotNumOne;
AddLot w = new AddLot
{
Owner = this,
runId = curRunId,
ingName = ingred,
woNum = curWo,
ingEL1Code = ingE_Code,
ingEL1AltCode = ingE_AltCode,
itemNo = paddedItemNo,
ingredOrdinal = ingredNum,
lotStartTime = runLots.Count > 0 ? timStamp : launchTime,
curLotIdxForIngred = curLotForThisIngred, // the idx field of the lot
curLotNumForIngredient = curLotNumIng, // the actual lot number
myDad = this
};
var myAdornerLayer = AdornerLayer.GetAdornerLayer(mainGrid);
myAdornerLayer.Add(new DimAdorner(mainGrid));
if (curLotForThisIngred == 0) alterAllDrops = true;
winCount++;
w.ShowDialog();
winCount--;
w = null;
try { myAdornerLayer.Remove((myAdornerLayer.GetAdorners(mainGrid))[0]); } catch { }
if (lotNumOne > 0)
{
txLotInf1.Content = lotNumOne.ToString() + "-" + curWipOne.ToString() + curOneIsAlt;
AnimateGridCell(txLotInf1);
}
if (alterAllDrops)
{
// update all drops as there is not previous lot
using (ProdlineEntities db = new ProdlineEntities())
{
var drops = db.KepwareWeights.Where(p => p.KepNumericId == curMachKepId && p.dropTime >= launchTime).Select(p => p);
foreach (var d in drops) { d.LotNo = curLotOne; }
try
{
db.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
else
{
// update drops since "timStamp" to new lot if not first lot
using (ProdlineEntities db = new ProdlineEntities())
{
RunLotNumModel rln = runLots.LastOrDefault();
var drops = db.KepwareWeights.Where(p => p.KepNumericId == curMachKepId && p.dropTime >= timStamp).Select(p => p);
foreach (var d in drops) { d.LotNo = curLotOne; }
try
{
db.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void ShowDownTm_CLick(object sender, RoutedEventArgs e)
{
var myAdornerLayer = AdornerLayer.GetAdornerLayer(mainGrid);
myAdornerLayer.Add(new DimAdorner(mainGrid));
DowntimeHist d = new DowntimeHist()
{
Topmost = true,
Left = this.Left + 100,
Top = this.Top + 100,
runID = curRunId
};
d.ShowDialog();
try { myAdornerLayer.Remove((myAdornerLayer.GetAdorners(mainGrid))[0]); } catch { }
}
#region " Window Controls "
private void Min_MouseDown(object sender, MouseButtonEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void Maxmz_MouseDown(object sender, MouseButtonEventArgs e)
{
if (this.WindowState == WindowState.Maximized)
{
this.WindowState = WindowState.Normal;
this.restoreRect.Visibility = Visibility.Hidden;
this.restoreRect2.Visibility = Visibility.Hidden;
this.maxmzRect.Visibility = Visibility.Visible;
}
else
{
this.WindowState = WindowState.Maximized;
this.restoreRect.Visibility = Visibility.Visible;
this.restoreRect2.Visibility = Visibility.Visible;
this.maxmzRect.Visibility = Visibility.Hidden;
}
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.Source.GetType().Name == "RadCartesianChart") return;
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
#endregion
#region " Maximization kludge "
// BG: This is necessary because when in border type = none, maximization wants to go full-screen, on-top all
void win_SourceInitialized(object sender, EventArgs e)
{
System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));
}
private static System.IntPtr WindowProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)
{
switch (msg)
{
case 0x0024:
WmGetMinMaxInfo(hwnd, lParam);
handled = true;
break;
}
return (System.IntPtr)0;
}
private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
{
MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
// Adjust the maximized size and position to fit the work area of the correct monitor
int MONITOR_DEFAULTTONEAREST = 0x00000002;
System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
if (monitor != System.IntPtr.Zero)
{
MONITORINFO monitorInfo = new MONITORINFO();
GetMonitorInfo(monitor, monitorInfo);
RECT rcWorkArea = monitorInfo.rcWork;
RECT rcMonitorArea = monitorInfo.rcMonitor;
mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
}
Marshal.StructureToPtr(mmi, lParam, true);
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int x, int y)
{
this.x = x;
this.y = y;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MONITORINFO
{
public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
public RECT rcMonitor = new RECT();
public RECT rcWork = new RECT();
public int dwFlags = 0;
}
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public static readonly RECT Empty = new RECT();
public int Width
{
get { return Math.Abs(right - left); } // Abs needed for BIDI OS
}
public int Height
{
get { return bottom - top; }
}
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public RECT(RECT rcSrc)
{
this.left = rcSrc.left;
this.top = rcSrc.top;
this.right = rcSrc.right;
this.bottom = rcSrc.bottom;
}
public bool IsEmpty
{
get
{
// BUGBUG : On Bidi OS (hebrew arabic) left > right
return left >= right || top >= bottom;
}
}
public override string ToString()
{
if (this == RECT.Empty) { return "RECT {Empty}"; }
return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }";
}
/// <summary> Determine if 2 RECT are equal (deep compare) </summary>
public override bool Equals(object obj)
{
if (!(obj is Rect)) { return false; }
return (this == (RECT)obj);
}
/// <summary>Return the HashCode for this struct (not garanteed to be unique)</summary>
public override int GetHashCode()
{
return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode();
}
/// <summary> Determine if 2 RECT are equal (deep compare)</summary>
public static bool operator ==(RECT rect1, RECT rect2)
{
return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
}
/// <summary> Determine if 2 RECT are different(deep compare)</summary>
public static bool operator !=(RECT rect1, RECT rect2)
{
return !(rect1 == rect2);
}
}
[DllImport("user32")]
internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);
[DllImport("User32")]
internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.ComponentModel;
using Telerik.Windows.Controls;
using System.Diagnostics;
using ProdlineTwo.Models;
namespace ProdlineTwo
{
public partial class DTCause : Window
{
protected internal int runId;
protected internal int DT_Id;
DateTime whenResponded = new DateTime();
protected internal DateTime whenWentDown;
protected internal bool sentByClose = false;
protected internal MainWindow3 myDad = null;
public DTCause()
{
InitializeComponent();
}
#region " Window Controls "
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
//if (e.Source.GetType().Name == "RadCartesianChart") return;
if (e.ChangedButton == MouseButton.Left) DragMove();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
using (ProdlineEntities db = new ProdlineEntities())
{
var causeClasses = db.DownTPrimaries.OrderBy(p => p.PrimaryLabel).Select(p => p).ToList();
cbCauseMain.ItemsSource = causeClasses;
cbCauseMain.DisplayMemberPath = "PrimaryLabel";
cbCauseMain.SelectedValue = "PrimaryId";
cbCauseMain.IsDropDownOpen = true;
}
cbCauseSecond.IsEnabled = false;
}
#endregion
private void cmPostPone_Click(object sender, RoutedEventArgs e)
{
myDad.isClosable = false;
Close();
}
private void cbCauseMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RadComboBox rc = sender as RadComboBox;
DownTPrimary dt = rc.SelectedItem as DownTPrimary;
int i = dt.PrimaryId;
whenResponded = DateTime.Now;
using (ProdlineEntities db = new ProdlineEntities())
{
cbCauseSecond.ItemsSource = null;
var x = db.DownTSecondaries.OrderBy(p=>p.SecondaryCause)
.Where(p => p.PrimaryId == i)
.Select(p => new DTSecondCauseModel
{
PrimaryId = i,
SecondaryId = p.SecondaryId,
SecondaryCause = p.SecondaryCause
}).ToList();
cbCauseSecond.ItemsSource = x;
cbCauseSecond.DisplayMemberPath = "SecondaryCause";
cbCauseSecond.IsEnabled = true;
cbCauseSecond.IsDropDownOpen = true;
}
}
private void cmSave_Click(object sender, RoutedEventArgs e)
{
if (cbCauseSecond.SelectedItem == null)
{
MessageBox.Show("Main and Second cause must both be valid before save");
return;
}
using (ProdlineEntities db = new ProdlineEntities())
{
DowntimeLog dl = db.DowntimeLogs.SingleOrDefault(p => p.RunID == runId && p.idx == DT_Id);
if (dl != null)
{
dl.Comment = txComment.Text;
dl.SecondaryId = ((DTSecondCauseModel)cbCauseSecond.SelectedItem).SecondaryId;
dl.StartTime = whenWentDown;
dl.TimeResponded = whenResponded;
if (sentByClose) dl.EndTime = whenWentDown;
try
{
db.SaveChanges();
myDad.isClosable = true;
Close();
}
catch (Exception ex)
{
MessageBox.Show("Error saving downtime cause: " + ex.Message);
}
}
else
{
MessageBox.Show("Missing Downtime Log ID to save to");
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Media.Animation;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for TestingLineSelector.xaml
/// </summary>
public partial class TestingLineSelector : Window
{
protected internal string usr;
public TestingLineSelector()
{
InitializeComponent();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void Close_MouseDown(object sender, MouseButtonEventArgs e)
{
Close();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
List<RadioButton> buttons = grdRadios.Children.OfType<RadioButton>().ToList();
RadioButton rbTarget = buttons
.Where(r => r.GroupName == "MachineSel" && r.IsChecked == true)
.SingleOrDefault();
if (rbTarget == null)
{
MessageBox.Show("Please select a line above first...");
}
else
{
string mchName = rbTarget.Tag.ToString();
App.dontSaveIt = true;
using (ProdlineEntities dbCntxt = new ProdlineEntities())
{
Employee ee = dbCntxt.Employees.FirstOrDefault(p => p.Logon == usr);
if (ee != null)
{
App.machPoliteUsrName = ee.FirstName + " " + ee.LastName;
}
FLF_Machines fLF = dbCntxt.FLF_Machines.Where(p => p.AttachedPCname == mchName).Select(p => p).FirstOrDefault();
if (fLF == null)
{
MessageBox.Show("Sorry, there has been some data issue, please try another machine or call Bob");
}
else
{
ScheduleWindow m = new ScheduleWindow()
{
maxDown = fLF.DowntimeTrigger,
machNaame = mchName
};
m.Show();
Close();
}
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProdlineTwo.Models
{
public class RunLotNumModel
{
public int LotIdx { get; set; }
public int RunID { get; set; }
public int LotNumb { get; set; }
public DateTime TimeStarted { get; set; }
public DateTime TimeEnded { get; set; }
public int WipCode { get; set; }
public int IngredOrd { get; set; }
public double TotWght { get; set; }
public bool IsForcedSave { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ProdlineTwo.Models;
using System.Data.Entity;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for DowntimeHist.xaml
/// </summary>
public partial class DowntimeHist : Window
{
protected internal int runID;
public DowntimeHist()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
using (ProdlineEntities db = new ProdlineEntities())
{
List<DowntimeLog> thems = db.DowntimeLogs
.Where(p => p.RunID == runID) //TODO check for test values (digits instead of "runID")
.Select(p => p).ToList();
var themsMassaged = thems
.OrderBy(p => p.idx)
.Select(p => new DownTimeHistModel
{
Cause = p.DownTSecondary.DownTPrimary.PrimaryLabel + ", " + p.DownTSecondary.SecondaryCause,
Comment = p.Comment,
DowntimeLogID = p.idx,
DownTimeSpan = p.EndTime.HasValue ? (((DateTime) p.EndTime - (DateTime) p.StartTime).Minutes > 0
? ((DateTime) p.EndTime - (DateTime) p.StartTime).Minutes + "m, "
+ ((DateTime) p.EndTime - (DateTime) p.StartTime).Seconds + "s"
: ((DateTime) p.EndTime - (DateTime) p.StartTime).Seconds + "s")
: " - ",
EndTime = p.EndTime.HasValue ? ((DateTime) p.EndTime).ToString("hh:mm tt") : " - ",
RunID = p.RunID,
StartTime = ((DateTime) p.StartTime).ToString("hh:mm tt"),
TimeResponded = p.TimeResponded.HasValue ? (((DateTime) p.TimeResponded - (DateTime) p.StartTime).Minutes > 0
? ((DateTime) p.TimeResponded - (DateTime) p.StartTime).Minutes + "m, "
+ ((DateTime) p.TimeResponded - (DateTime) p.StartTime).Seconds + "s"
: ((DateTime) p.TimeResponded - (DateTime) p.StartTime).Seconds + "s")
: " - "
}).ToList();
gridDtList.ItemsSource = themsMassaged;
gridDtList.SelectedItems.Clear();
}
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.Source.GetType().Name == "RadGridView") return;
if (e.ChangedButton == MouseButton.Left) DragMove();
}
private void cmClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProdlineTwo.Models
{
class F57MatlModel
{
public int QH_RUNID { get; set; }
public int QH_ITEMCD { get; set; }
public string QH_DATEPK { get; set; }
public string QH_WO { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ProdlineTwo.Models;
using System.Threading;
using System.Windows.Threading;
using System.ComponentModel;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for AddLot.xaml
/// </summary>
public partial class AddLot : Window
{
#region " Window variables "
protected internal string ingName;
protected internal int runId;
protected internal int woNum;
protected internal string ingEL1Code;
protected internal string ingEL1AltCode;
protected internal string itemNo;
protected internal byte ingredOrdinal;
protected internal DateTime lotStartTime;
protected internal MainWindow3 myDad = null;
protected internal int curLotIdxForIngred = 0;
protected internal int curLotNumForIngredient;
//bool weCanConnectToJDE;
BackgroundWorker bw;
#endregion
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataObject.AddPastingHandler(txLotNum, OnPaste);
lbWoTitle.Content = string.Format("Add Lot # for {0}", ingName);
txLotNum.Text = "";
txLotNum.Focus();
bw = new BackgroundWorker();
bw.DoWork += Bw_DoWork;
bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
//weCanConnectToJDE = App.canConnectToJDE;
}
private void txLotNum_KeyDown(object sender, KeyEventArgs e)
{
// INFO Ignore if the key isn't either Enter or Esc
if (e.Key == Key.Enter)
{
mySpinner.IsBusy = true;
bw.RunWorkerAsync(txLotNum.Text);
}
else if (e.Key == Key.Escape)
{
Close();
}
}
private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
if ((e.Result.ToString() == "Same Number"))
{
MessageBox.Show("This is the same as the current lot number, please try again.");
mySpinner.IsBusy = false;
txLotNum.Focus();
txLotNum.SelectAll();
return;
}
else if (e.Result.ToString().StartsWith("Error"))
{
MessageBox.Show(e.Result.ToString());
mySpinner.IsBusy = false;
txLotNum.Focus();
txLotNum.SelectAll();
return;
}
}
Close();
}
private void Bw_DoWork(object sender, DoWorkEventArgs e)
{
string lotNumToSave = e.Argument.ToString().Trim();
if (lotNumToSave == "") return;
if (lotNumToSave == "9999")
{
int wipNumFromLot = int.Parse(ingEL1Code);
bool isSavedAs9999 = SaveLotToIshiLotNumbers(e, lotNumToSave, false, wipNumFromLot, true);
return;
}
bool isAlt = false;
if (curLotNumForIngredient > 0 && curLotNumForIngredient.ToString() == lotNumToSave)
{
e.Result = "Same Number";
return;
}
else
{
List<string> ErrorList = new List<string>();
int wipNumFromLot = 0;
bool lot_OK = false;
string loc = App.locationMCU;
using (JDE_PRODUCTIONEntities db = new JDE_PRODUCTIONEntities())
{
// Revalidate WO in JDE
var f481Rec = db.F4801.FirstOrDefault(
p => p.WADOCO == woNum
&& p.WALITM == itemNo);
if (f481Rec != null)
{
// Then validate the lot # in JDE
db.Database.Log = Console.Write;
if (ingName != "")
{
List<string> wipNums1 = new List<string> { ingEL1Code, ingEL1AltCode };
var lotExistsJDE = db.F4108.FirstOrDefault(p => p.IOLOTN == lotNumToSave
&& p.IOMCU.Contains(loc)
&& wipNums1.Contains(p.IOLITM.Trim())
);
if (lotExistsJDE != null && lotExistsJDE.IOLITM != "0")
{
lot_OK = true;
wipNumFromLot = int.Parse(lotExistsJDE.IOLITM.Trim());
// NOTE: Updated this to distinguish items where both codes are the same, it's only "ALT"
// if it ONLY matches the ALT code
if (lotExistsJDE.IOLITM.Trim() != ingEL1Code.ToString()
&& lotExistsJDE.IOLITM.Trim() == ingEL1AltCode.ToString()) isAlt = true;
}
else
{
// TODO Sylvia wants this functionality to be able to save incorrect lot numbers
// with an "e" code to JDE F57PRDD so that the operator's code can still be viewed
// up until the correct lot number is determined
MessageBoxResult dlResult =
MessageBox.Show("This is not a valid lot number, Press 'Yes' to force save or 'No' to try again.",
"Bad number, Save anyway?",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (dlResult == MessageBoxResult.Yes)
{
bool itSavedOk = SaveLotToIshiLotNumbers(e, lotNumToSave, isAlt, wipNumFromLot, true);
}
else
{
mySpinner.IsBusy = false;
txLotNum.Focus();
txLotNum.SelectAll();
}
return;
}
}
if (lot_OK)
{
//Finally add new lot number, and alter end time of previous if it wasn't "0"
bool itSavedOk = SaveLotToIshiLotNumbers(e, lotNumToSave, isAlt, wipNumFromLot, false);
return;
}
}
else
{
e.Result = "Error: There has been a corruption of the Work Order number, Please contact IT and move on to the next Work Order for now.";
return;
}
}
}
}
private bool SaveLotToIshiLotNumbers(DoWorkEventArgs e, string lotNumToSave, bool isAlt, int wipNumFromLot, bool isForced)
{
using (ProdlineEntities dbProd = new ProdlineEntities())
{
try
{
if (curLotIdxForIngred > 0)
{
IshiLotNumber ishOldLot = dbProd.IshiLotNumbers.SingleOrDefault(p => p.idx == curLotIdxForIngred);
if (ishOldLot != null)
{
ishOldLot.EndTimeStamp = lotStartTime.AddMilliseconds(-5);
dbProd.SaveChanges();
}
}
IshiLotNumber ishLot = new IshiLotNumber
{
RunId = runId,
LotNum = int.Parse(lotNumToSave),
TimeStamped = lotStartTime,
EndTimeStamp = new DateTime(9999, 1, 1),
IngredOrdinal = ingredOrdinal,
WipCode = wipNumFromLot,
IsAltIngred = isAlt,
saveStatus = isForced ? "e" : ""
};
dbProd.IshiLotNumbers.Add(ishLot);
dbProd.SaveChanges();
if (myDad.runLots.Count > 0) myDad.runLots[myDad.runLots.Count - 1].TimeEnded = lotStartTime.AddMilliseconds(-5);
myDad.curLotOne = ishLot.idx;
myDad.lotNumOne = ishLot.LotNum;
myDad.curWipOne = ishLot.WipCode;
myDad.curOneIsAlt = isAlt ? "a" : "";
myDad.runLots.Add(new RunLotNumModel
{
IngredOrd = ishLot.IngredOrdinal,
LotIdx = ishLot.idx,
LotNumb = ishLot.LotNum,
RunID = ishLot.RunId,
TimeEnded = new DateTime(9999, 1, 1),
TimeStarted = ishLot.TimeStamped,
WipCode = ishLot.WipCode,
IsForcedSave = isForced
});
return true;
}
catch (Exception ex)
{
e.Result = "Error saving lot number: " + ex.Message + " Please note the error down and contact IT (ext 2628).";
return false;
}
}
}
#region " Text handling "
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9]+"); //regex that matches allowed text
return regex.IsMatch(text);
}
private void txLotNum_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = IsTextAllowed(e.Text);
}
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
if (!isText) return;
var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
Regex regex = new Regex("[^0-9]+"); //regex that matches disallowed text
if (regex.IsMatch(text))
{
e.CancelCommand();
Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("Please only paste numeric values", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation)));
}
}
#endregion
#region " Boilerplate "
public AddLot()
{
InitializeComponent();
}
private void AddLot_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Closing -= AddLot_Closing;
e.Cancel = true;
var anim = new DoubleAnimation(0, TimeSpan.FromSeconds(.4));
anim.Completed += (s, _) => Close();
BeginAnimation(OpacityProperty, anim);
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
DragMove();
}
private void Close_MouseDown(object sender, MouseButtonEventArgs e)
{
Close();
}
#endregion
}
//bool lot_OK = false;
//string loc = App.locationMCU; // TODO App.machineNum < 100 ? "11P" : "15A"; //TODO hard-coded to differentiate here from NJ, abstract this into database as we add locations
//using (JDE_ProdEntModel db = new JDE_ProdEntModel())
//{
// // Revalidate WO in JDE
// var f481Rec = db.F4801.FirstOrDefault(
// p => p.WADOCO == woNum
// && p.WALITM == itemNo);
// if (f481Rec != null)
// {
// // Then validate the lot # in JDE
// db.Database.Log = Console.Write;
// if (ingName != "")
// {
// List<string> wipNums1 = new List<string> { ingEL1Code, ingEL1AltCode };
// var lotExistsJDE = db.F4108.FirstOrDefault(p => p.IOLOTN == lotNumToSave
// && p.IOMCU.Contains(loc)
// && wipNums1.Contains(p.IOLITM.Trim())
// );
// if (lotExistsJDE != null && lotExistsJDE.IOLITM != "0")
// {
// lot_OK = true;
// wipNumFromLot = int.Parse(lotExistsJDE.IOLITM.Trim());
// if (lotExistsJDE.IOLITM.Trim() == ingEL1AltCode.ToString()) isAlt = true;
// }
// else
// {
// e.Result = "Invalid Lot";
// return;
// }
// }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProdlineTwo.Models
{
public class DTSecondCauseModel
{
public int SecondaryId { get; set; }
public int PrimaryId { get; set; }
public string SecondaryCause { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProdlineTwo.Models
{
class DownTimeHistModel
{
public int RunID { get; set; }
public int DowntimeLogID { get; set; }
public string Cause { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public string TimeResponded { get; set; }
public string Comment { get; set; }
public string DownTimeSpan { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProdlineTwo
{
public class ChartDataObject
{
public DateTime Date
{
get;
set;
}
public double Value
{
get;
set;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Animation;
using Telerik.Windows.Controls;
using Telerik.Windows.Data;
using WinInterop = System.Windows.Interop;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for ScheduleWindow.xaml
/// </summary>
public partial class ScheduleWindow : Window
{
protected internal int maxDown;
protected internal int scaleProto = 0;
DateTime dt;
protected internal string machNaame;
private string machNaameFine; // TODO fine tuned due to discrepancies in final assignments vs hard-coded names in SQL
public ScheduleWindow()
{
InitializeComponent();
win.SourceInitialized += new EventHandler(win_SourceInitialized);
Process process = Process.GetCurrentProcess();
var dupl = (Process.GetProcessesByName("ProdlineTwo"));
MessageBoxResult dl;
if (dupl.Length > 0)
{
foreach (var p in dupl)
{
if (p.Id != process.Id)
{
dl = MessageBox.Show("This app is already running, Close existing instance?" + Environment.NewLine + "If you only see one Prodline \"M\" icon in taskbar click \"Yes\".", "Close previous???", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
if (dl == MessageBoxResult.Yes)
p.Kill();
else
Application.Current.Shutdown();
}
}
}
//using (ProdlineEntities db = new ProdlineEntities()) //TODO this code is if we choose to hide the short timeout option
//{
// List<string> actualPCs = db.FLF_Machines.Select(p => p.HolderForPCName).ToList();
// var curPc = machNaame;
// if (!(actualPCs.Contains(curPc)))
// {
// //ckUseEmulValu.Visibility = Visibility.Visible;
// ckUseShortTimeout.Visibility = Visibility.Visible;
// }
//}
}
#region " Window Controls "
private void Close_MouseDown(object sender, MouseButtonEventArgs e)
{
Application.Current.Shutdown();
}
private void Min_MouseDown(object sender, MouseButtonEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void Maxmz_MouseDown(object sender, MouseButtonEventArgs e)
{
if (this.WindowState == WindowState.Maximized)
{
this.WindowState = WindowState.Normal;
this.restoreRect.Visibility = Visibility.Hidden;
this.restoreRect2.Visibility = Visibility.Hidden;
this.maxmzRect.Visibility = Visibility.Visible;
}
else
{
this.WindowState = WindowState.Maximized;
this.restoreRect.Visibility = Visibility.Visible;
this.restoreRect2.Visibility = Visibility.Visible;
this.maxmzRect.Visibility = Visibility.Hidden;
}
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.Source.GetType().Name == "RadCartesianChart") return;
if (e.ChangedButton == MouseButton.Left) this.DragMove();
}
#endregion
#region " Maximization kludge "
// BG: From http: www.codeproject.com/Articles/107994/Taskbar-with-Window-Maximized-and-WindowState-to-N
// Allows for maximize window-style.None without becoming "Full Screen" on top of task bar
void win_SourceInitialized(object sender, EventArgs e)
{
System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));
}
private static System.IntPtr WindowProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)
{
switch (msg)
{
case 0x0024:
WmGetMinMaxInfo(hwnd, lParam);
handled = true;
break;
}
return (System.IntPtr) 0;
}
private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
{
MINMAXINFO mmi = (MINMAXINFO) Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
// Adjust the maximized size and position to fit the work area of the correct monitor
int MONITOR_DEFAULTTONEAREST = 0x00000002;
System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
if (monitor != System.IntPtr.Zero)
{
MONITORINFO monitorInfo = new MONITORINFO();
GetMonitorInfo(monitor, monitorInfo);
RECT rcWorkArea = monitorInfo.rcWork;
RECT rcMonitorArea = monitorInfo.rcMonitor;
mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
}
Marshal.StructureToPtr(mmi, lParam, true);
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int x, int y)
{
this.x = x;
this.y = y;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MONITORINFO
{
public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
public RECT rcMonitor = new RECT();
public RECT rcWork = new RECT();
public int dwFlags = 0;
}
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public static readonly RECT Empty = new RECT();
public int Width
{
get { return Math.Abs(right - left); } // Abs needed for BIDI OS
}
public int Height
{
get { return bottom - top; }
}
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public RECT(RECT rcSrc)
{
this.left = rcSrc.left;
this.top = rcSrc.top;
this.right = rcSrc.right;
this.bottom = rcSrc.bottom;
}
public bool IsEmpty
{
get
{
// BUGBUG : On Bidi OS (hebrew arabic) left > right
return left >= right || top >= bottom;
}
}
public override string ToString()
{
if (this == RECT.Empty) { return "RECT {Empty}"; }
return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }";
}
/// <summary> Determine if 2 RECT are equal (deep compare) </summary>
public override bool Equals(object obj)
{
if (!(obj is Rect)) { return false; }
return (this == (RECT) obj);
}
/// <summary>Return the HashCode for this struct (not garanteed to be unique)</summary>
public override int GetHashCode()
{
return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode();
}
/// <summary> Determine if 2 RECT are equal (deep compare)</summary>
public static bool operator ==(RECT rect1, RECT rect2)
{
return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
}
/// <summary> Determine if 2 RECT are different(deep compare)</summary>
public static bool operator !=(RECT rect1, RECT rect2)
{
return !(rect1 == rect2);
}
}
[DllImport("user32")]
internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);
[DllImport("User32")]
internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);
#endregion
private void Window_Closing(object sender, CancelEventArgs e)
{
Closing -= Window_Closing;
e.Cancel = true;
var anim = new DoubleAnimation(0, TimeSpan.FromSeconds(.6d));
anim.Completed += (s, _) => Close();
BeginAnimation(OpacityProperty, anim);
}
public void FillGrid()
{
// TODO the schedule data below is aggregated by machine types with hard-coded ID's:
int locshn = App.locationID;
List<int> machinesToAggregate = new List<int>();
int thisMachId = App.machineID;
using (ProdlineEntities dbProdCn = new ProdlineEntities())
{
machinesToAggregate = dbProdCn.MachineToPaccumIDs.Where(p => p.MachineID == thisMachId)
.Select(p => p.PaccumID).ToList();
}
List<SchedDetailFLF> scheds = new List<SchedDetailFLF>(); // 1) Arcadian (Ishida) (3 mach NO's 29, 30, 32) NOTE these numbers are Yuma-specific
//TODO alter machNaame for testing only in logon.xaml.cs // 2) Retail (2 mach NO's 21 and 22)
using (PaccumDBEntities dbPcntxt = new PaccumDBEntities()) // 3) Whole Leaf (3 mach NO's 20, 23, 33)
{ // 4) Wash & Trim (1 mach NO 31)
RateSchedsUploaded r = dbPcntxt.RateSchedsUploadeds.SingleOrDefault(p => p.ShiftOrLoc == locshn
&& p.DateProc == dt); //TODO 5 is hardcoded to single 16 hour day shift
if (r != null)
{
scheds = dbPcntxt.SchedDetailFLFs.Where(p => p.RateSched == r.id && machinesToAggregate.Contains(p.LineOrMch)).ToList();
//switch (machNaame.ToUpper())
//{
// // Retail lines
// case "PC1132-YUMAPROD":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 21, 22 }).Contains(p.LineOrMch)).ToList();
// break;
// case "PC1133-YUMAPROD":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 21, 22 }).Contains(p.LineOrMch)).ToList();
// break;
// // Arcadian lines
// case "PC1106-LINE-A1Y":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 29, 30, 32 }).Contains(p.LineOrMch)).ToList();
// break;
// case "PC1107-LINE-B1Y":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 29, 30, 32 }).Contains(p.LineOrMch)).ToList();
// break;
// case "PC1108-LINE-B2Y":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 29, 30, 32 }).Contains(p.LineOrMch)).ToList();
// break;
// // Whole Leaf lines
// case "PC1102-LINE-G1Y":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 20, 23, 24, 33 }).Contains(p.LineOrMch)).ToList();
// break;
// case "PC1095":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 20, 23, 24, 33 }).Contains(p.LineOrMch)).ToList();
// break;
// case "PC1104-LINE-H1Y":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 20, 23, 24, 33 }).Contains(p.LineOrMch)).ToList();
// break;
// case "PC1105-LINE-H2Y":
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id && (new List<int> { 20, 23, 24, 33 }).Contains(p.LineOrMch)).ToList();
// break;
// default:
// scheds = dbPcntxt.SchedDetailFLFs.OrderBy(p => p.OrdinalInLine).Where(p => p.RateSched == r.id).ToList();
// break;
//}
}
else
{
MessageBox.Show("No Schedule exists for this shift.");
}
}
gridJobList.ItemsSource = scheds;
gridJobList.SelectedItems.Clear();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (App.machineNum == 1) cmFlip.Visibility = Visibility.Visible;
string macUserNam = Environment.UserName;
App.machUserName = macUserNam;
byte shifft = App.shiftNum;
dt = DateTime.Today; //new DateTime(2017, 9, 8);
//if (DateTime.Now.Hour < 6) dt = dt.AddDays(-1); //see if it's yesterday's shift still (up til 6:00 AM)
cmFlip.IsChecked = false;
machNaameFine = machNaame;
//if (machNaameFine == "PC1104-LINE-H1Y") machNaameFine = "PC1104-LINE-HY";
//if (machNaameFine == "PC1105-LINE-H2Y") machNaameFine = "PC1105-W&TY";
txMchUser.Text = machNaameFine + " - " + macUserNam;
FillGrid();
}
private void RadButton_Click(object sender, RoutedEventArgs e)
{
int id = 0;
if (((RadButton)e.Source).CommandParameter is SchedDetailFLF theSender)
{
id = theSender.id;
MainWindow3 m3 = new MainWindow3()
{
Height = 764,
Width = 1147,
sc = theSender,
maxDownT = maxDown,
machineNaame = machNaame
};
if (ckUseShortTimeout.IsChecked == true) m3.useShortTimeout = true;
if (ckUseEmulValu.IsChecked == true) m3.useMachine5Emulation = true;
m3.ShowDialog();
m3 = null;
cmFlip.IsChecked = false;
FillGrid();
}
else
{
MessageBox.Show("Error getting the item data from the row clicked, contact IT");
}
}
private void ExitButton_Click(object sender, RoutedEventArgs e)
{
//MainWindow3 m = new MainWindow3();
//m.ShowDialog();
Application.Current.Shutdown();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProdlineTwo.Models
{
public class DropsModel
{
public int idx { get; set; }
public int RunID { get; set; }
public int wght1 { get; set; }
public int wght2 { get; set; }
public int wght3 { get; set; }
public DateTime drTime { get; set; }
public string EData { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProdlineTwo.Models
{
class ShortDropModel
{
public int ingred { get; set; }
public DateTime whenShort { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ProdlineTwo;
using System.Threading;
using System.Diagnostics;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for logon.xaml
/// </summary>
public partial class logon : Window
{
protected internal int maxDown;
int scaleProto = 0;
string machNaame;
public logon()
{
InitializeComponent();
txUser.Focus();
}
private void Close_MouseDown(object sender, MouseButtonEventArgs e)
{
Close();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.Source.GetType().Name == "RadCartesianChart") return;
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void radButton_Click(object sender, RoutedEventArgs e)
{
string usr = txUser.Text;
string pswrd = <PASSWORD>;
bool wereGood = false;
if (rbDay.IsChecked == false && rbNight.IsChecked == false)
{
lbError1.Visibility = Visibility.Visible;
lbWait.Visibility = Visibility.Hidden;
return; //todo this is a change
}
else
{
using (ProdlineEntities dbCntxt = new ProdlineEntities())
{
Employee ee = dbCntxt.Employees.FirstOrDefault(p => p.Logon == usr && p.Password == pswrd);
if (ee != null)
{
wereGood = true;
App.machPoliteUsrName = ee.FirstName + " " + ee.LastName;
App.EmployeeID = ee.idx;
App.userForJDE = ee.FirstName.ToUpper().Substring(0, 1) + (ee.LastName.Length > 9 ? ee.LastName.ToUpper().Substring(0, 9) : ee.LastName.ToUpper());
}
try
{
FLF_Machines mc = dbCntxt.FLF_Machines.SingleOrDefault(p => p.AttachedPCname.ToUpper() == machNaame.ToUpper());
if (mc != null)
{
switch (mc.BranchPlant)
{
case "34P":
App.locationID = 7;
break;
case "31P":
App.locationID = 5;
break;
default:
break;
}
App.locationMCU = mc.BranchPlant;
App.machineID = mc.idx;
bool canConnect = dbCntxt.JDE_ConnectionStatus.SingleOrDefault(p => p.BranchPlant == mc.BranchPlant).ConnectIsGood;
//App.canConnectToJDE = canConnect;
}
maxDown = mc.DowntimeTrigger;
}
catch (Exception ex)
{
MessageBox.Show("Error getting data on which machine you're on: " + ex.Message);
return;
}
}
if (wereGood)
{
App.isLoggedIn = true;
App.shiftNum = rbDay.IsChecked == true ? (byte)1 : (byte)2;
ScheduleWindow m = new ScheduleWindow()
{
maxDown = maxDown,
scaleProto = scaleProto,
machNaame = machNaame
};
m.Show();
Close();
}
else
{
lbError.Visibility = Visibility.Visible;
lbWait.Visibility = Visibility.Hidden;
passwordBox.Clear();
txUser.Focus();
txUser.SelectAll();
}
}
}
private void rb_Click(object sender, RoutedEventArgs e)
{
lbError1.Visibility = Visibility.Hidden;
lbWait.Visibility = Visibility.Hidden;
}
private void txBox_KeyDown(object sender, KeyEventArgs e)
{
lbError.Visibility = Visibility.Hidden;
lbWait.Visibility = Visibility.Hidden;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
machNaame = Environment.MachineName;
#if DEBUG
if (machNaame == "US-MN-SCH-W7048" || machNaame == "LT954")
{
txUser.Text = "william.wolff";
passwordBox.Password = "<PASSWORD>";
rbDay.IsChecked = true;
machNaame = "US-MN-FLF-LINEG";
}
#endif
Process process = Process.GetCurrentProcess();
var dupl = (Process.GetProcessesByName("ProdlineTwo"));
App.machineName = machNaame;
MessageBoxResult dl;
if (dupl.Length > 0)
{
foreach (var p in dupl)
{
if (p.Id != process.Id)
{
dl = MessageBox.Show("This app is already running, if you can't see any running instance use Task Manager to close the existing instance. Ask for help if you don't understand this. This new instance will close now.");
Application.Current.Shutdown();
}
}
}
List<string> testUsers = new List<string>() { "robert.graham", "william.wolff", "kevin.gillis", "sylvia.le", "tamra.steele", "chris.peixoto", "mark.raynes" };//"robert.graham",
string usr = Environment.UserName;
//if (testUsers.Contains(usr))
//{
// TestingLineSelector tm = new TestingLineSelector();
// tm.usr = usr;
// tm.Show();
// Close();
//}
//TODO ONLY PLACE!!!! to play with fake machine name
//machNaame = "PC1100-PROSEAL";
//machNaame = "PC1101-ORICS";
//machNaame = "PC1102-LINE-G1";
//machNaame = "PC1103-LINE-G2";
//machNaame = "PC1104-LINE-H1Y";
//machNaame = "PC1105-LINE-H2Y";
//machNaame = "PC1106-LINE-A1";
//machNaame = "PC1107-LINE-B1";
//machNaame = "PC1108-LINE-B2";
}
}
}
<file_sep>using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace ProdlineTwo
{
// Adorners must subclass the abstract base class Adorner.
public class DimAdorner : Adorner
{
// Be sure to call the base class constructor.
public DimAdorner(UIElement adornedElement)
: base(adornedElement)
{
}
// A common way to implement an adorner's rendering behavior is to override the OnRender
// method, which is called by the layout system as part of a rendering pass.
protected override void OnRender(DrawingContext drawingContext)
{
Rect adornedElementRect = new Rect(this.AdornedElement.RenderSize);
SolidColorBrush renderBrush = new SolidColorBrush(Colors.Gray);
renderBrush.Opacity = 0.65;
Pen renderPen = new Pen(new SolidColorBrush(Colors.Transparent), 0.1);
drawingContext.DrawRectangle(renderBrush, renderPen, adornedElementRect);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProdlineTwo.Models
{
class F57LotNumModel
{
public int QD_RUNID { get; set; }
public int QDUKID { get; set; }
public int QDZ57IN { get; set; } //BG: the ingredient ordinal
public string QDLITM { get; set; }
public string QDLOTN { get; set; }
public int QDITWT { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProdlineTwo.Models
{
class SchDetailsModel
{
public int id { get; set; }
public int RateSched { get; set; }
public string ItemCd { get; set; }
public string ItemDesc { get; set; }
public int WoNum { get; set; }
public int Qty { get; set; }
public int LineOrMch { get; set; }
public int OrigLineOrMch { get; set; }
public int LineNumericalPart { get; set; }
public int OrdinalInLine { get; set; }
public int InitialQtyDone { get; set; }
public int QtyDoneUpdated { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
//TODO reset any test values present
public static bool isLoggedIn;
public static string machineName;
public static string machUserName;
public static int EmployeeID;
public static string machPoliteUsrName;
public static string userForJDE;
public static int scalProtcl;
public static int machineNum;
public static byte shiftNum;
public static bool dontSaveIt;
public static int locationID;
public static string locationMCU;
public static int machineID; // the ID in the FLF_Machines table
public static bool canConnectToJDE;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProdlineTwo.Models
{
class ErrorsModel
{
public int errNum { get; set; }
public DateTime errTime { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.Diagnostics;
using ProdlineTwo.Models;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for EnterLots.xaml
/// </summary>
public partial class ViewLots : Window
{
protected internal int runID;
protected internal string ingOne;
protected internal string ingTwo;
protected internal string ingThr;
public ViewLots()
{
InitializeComponent();
}
public ViewLots(MainWindow3 mnWin)
{
InitializeComponent();
}
#region " Window Controls "
private void Close_MouseDown(object sender, MouseButtonEventArgs e)
{
this.Close();
}
void EnterLots_Closing(object sender, CancelEventArgs e)
{
Closing -= EnterLots_Closing;
e.Cancel = true;
var anim = new DoubleAnimation(0, (Duration) TimeSpan.FromSeconds(.4));
anim.Completed += (s, _) => this.Close(); // (s, _) is shorthand for "object sender, EventArgs e"
this.BeginAnimation(UIElement.OpacityProperty, anim);
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
//if (e.Source.GetType().Name == "RadCartesianChart") return;
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
#endregion
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lbProd1.Text = ingOne;
lbProd2.Text = ingTwo;
lbProd3.Text = ingThr;
using (ProdlineEntities db = new ProdlineEntities())
{
List<string> lotOnes = db.IshiLotNumbers
.Where(p => p.RunId == runID && p.IngredOrdinal == 1)
.Select(p => p.LotNum.ToString() + " - "
+ p.WipCode.ToString()
+ (p.IsAltIngred ? " a" : "")).ToList();
List<string> lotTwos = db.IshiLotNumbers
.Where(p => p.RunId == runID && p.IngredOrdinal == 2)
.Select(p => p.LotNum.ToString() + " - "
+ p.WipCode.ToString()
+ (p.IsAltIngred ? " a" : "")).ToList();
List<string> lotThrs = db.IshiLotNumbers
.Where(p => p.RunId == runID && p.IngredOrdinal == 3)
.Select(p => p.LotNum.ToString() + " - "
+ p.WipCode.ToString()
+ (p.IsAltIngred ? " a" : "")).ToList();
radLb1.ItemsSource = lotOnes;
radLb2.ItemsSource = lotTwos;
radLb3.ItemsSource = lotThrs;
}
}
private void cmClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
<file_sep>using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace ProdlineTwo
{
public class DimOrngAdorner : Adorner
{
// Be sure to call the base class constructor.
public DimOrngAdorner(UIElement adornedElement)
: base(adornedElement)
{
}
// A common way to implement an adorner's rendering behavior is to override the OnRender
// method, which is called by the layout system as part of a rendering pass.
protected override void OnRender(DrawingContext drawingContext)
{
Rect adornedElementRect = new Rect(this.AdornedElement.RenderSize);
SolidColorBrush renderBrush = new SolidColorBrush(Colors.Orange);
renderBrush.Opacity = 0.65;
Pen renderPen = new Pen(new SolidColorBrush(Colors.Transparent), 0.1);
drawingContext.DrawRectangle(renderBrush, renderPen, adornedElementRect);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;
namespace ProdlineTwo
{
/// <summary>
/// Interaction logic for FirstCaseCheck.xaml
/// </summary>
public partial class FirstCaseCheck : Window
{
protected internal int runId;
int firstCaseCkId;
public FirstCaseCheck()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
using (ProdlineEntities db = new ProdlineEntities())
{
var cntries = db.MPC_CountryOfOrigin.Select(p => p).ToList();
cbCountries.DisplayMemberPath = "COO_Name";
cbCountries.ItemsSource = cntries;
try
{
firstCaseCkId = db.MPC_FirstCase.SingleOrDefault(p => p.RUNID == runId).FirstCaseID;
}
catch { }
// TODO test value only...
//firstCaseCkId = 3;
MPC_FirstCase mpcee = db.MPC_FirstCase.SingleOrDefault(p => p.FirstCaseID == firstCaseCkId);
if (mpcee != null)
{
this.txBagCode.Text = mpcee.BagCodeDate;
this.rb25FYes.IsChecked = mpcee.MetalDetect25F == true;
this.rb30NFYes.IsChecked = mpcee.MetalDetect3NF == true;
this.rbSSYes.IsChecked = mpcee.MetalDetect4SS == true;
this.rbCartChYes.IsChecked = mpcee.CartonInfoCheck == true;
this.rbFilmChYes.IsChecked = mpcee.FilmDateCheck == true;
this.rbLeakYes.IsChecked = mpcee.LeakChecked == true;
this.txPker1.Text = mpcee.Packer.ToString();
this.txPker2.Text = mpcee.Packer2.ToString();
this.txPker3.Text = mpcee.Packer3.ToString();
this.txWght1.Text = mpcee.Weight1.ToString();
this.txWght2.Text = mpcee.Weight2.ToString();
this.txWght3.Text = mpcee.Weight3.ToString();
this.txWght4.Text = mpcee.Weight4.ToString();
this.txWght5.Text = mpcee.Weight5.ToString();
this.txHoleCount.Text = mpcee.Num_Holes.ToString();
this.cbCountries.Text = cntries.Single(p => p.idx == mpcee.CooId).COO_Name;
}
}
DataObject.AddPastingHandler(txPker1, OnPaste);
DataObject.AddPastingHandler(txPker2, OnPaste);
DataObject.AddPastingHandler(txPker3, OnPaste);
DataObject.AddPastingHandler(txWght1, OnPaste);
DataObject.AddPastingHandler(txWght2, OnPaste);
DataObject.AddPastingHandler(txWght3, OnPaste);
DataObject.AddPastingHandler(txWght4, OnPaste);
DataObject.AddPastingHandler(txWght5, OnPaste);
DataObject.AddPastingHandler(txHoleCount, OnPaste);
}
private void Close_MouseDown(object sender, MouseButtonEventArgs e)
{
this.Close();
}
void FirstCase_Closing(object sender, CancelEventArgs e)
{
Closing -= FirstCase_Closing;
e.Cancel = true;
var anim = new DoubleAnimation(0, (Duration) TimeSpan.FromSeconds(.4));
anim.Completed += (s, _) => this.Close(); // (s, _) is shorthand for "object sender, EventArgs e"
this.BeginAnimation(UIElement.OpacityProperty, anim);
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void cmCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void cmSave_Click(object sender, RoutedEventArgs e)
{
bool adding = false;
using (ProdlineEntities db = new ProdlineEntities())
{
try
{
MPC_FirstCase mpc = null;
if (firstCaseCkId == 0)
{
mpc = new MPC_FirstCase();
adding = true;
}
else
{
mpc = db.MPC_FirstCase.Single(p => p.FirstCaseID == firstCaseCkId);
}
var that = cbCountries.SelectedItem;
mpc.RUNID = runId;
mpc.Packer = txPker1.Text != "" ? int.Parse(txPker1.Text) : 0;
mpc.Packer2 = txPker2.Text != "" ? int.Parse(txPker2.Text) : 0;
mpc.Packer3 = txPker3.Text != "" ? int.Parse(txPker3.Text) : 0;
mpc.Weight1 = txWght1.Text != "" ? int.Parse(txWght1.Text) : 0;
mpc.Weight2 = txWght2.Text != "" ? int.Parse(txWght2.Text) : 0;
mpc.Weight3 = txWght3.Text != "" ? int.Parse(txWght3.Text) : 0;
mpc.Weight4 = txWght4.Text != "" ? int.Parse(txWght4.Text) : 0;
mpc.Weight5 = txWght5.Text != "" ? int.Parse(txWght5.Text) : 0;
mpc.CartonInfoCheck = rbCartChYes.IsChecked == true;
mpc.CooId = (cbCountries.SelectedValue as MPC_CountryOfOrigin).idx;
mpc.FilmDateCheck = false; // rbFilmChYes.IsChecked == true;
mpc.LeakChecked = false; // rbLeakYes.IsChecked == true;
mpc.MetalDetect25F = false; // rb25FYes.IsChecked == true;
mpc.MetalDetect3NF = false; // rb30NFYes.IsChecked == true;
mpc.MetalDetect4SS = false; // rbSSYes.IsChecked == true;
mpc.Num_Holes = 0; // txHoleCount.Text != "" ? int.Parse(txHoleCount.Text) : 0;
mpc.TimeStamp = DateTime.Now;
mpc.BagCodeDate = txBagCode.Text;
if (adding) db.MPC_FirstCase.Add(mpc);
db.SaveChanges();
this.Close();
}
catch (Exception ex)
{
MessageBoxResult mbr = MessageBox.Show(ex.Message + Environment.NewLine + "Try to correct?", "Error", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
if (mbr == MessageBoxResult.Yes)
return;
else
this.Close();
}
}
}
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9]+"); //regex that matches disallowed text
return !regex.IsMatch(text);
}
private void txBoxNumer_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
if (!isText) return;
var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
Regex regex = new Regex("[^0-9]+"); //regex that matches disallowed text
if (regex.IsMatch(text))
{
e.CancelCommand();
Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("Please only paste numeric values", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation)));
}
}
}
}
| de0baa0f129ee810641a39982dfcc17b233c20ba | [
"C#"
] | 22 | C# | wdwolff/ProdlineTwo-CurrentProd | 6796715deb41fda5b4c9be546aaf0cb9caefd5e2 | 98df8127cb02ff928a9641b4e14dd83edc65840b |
refs/heads/master | <file_sep># msfsLegacyImporter
FSX into MSFS aircraft importing tool
[SECURITY_NOTICE]
EXE file of this application is unsigned, so Windows Defender/some other antivirus software may be triggered. Sometimes it even blocking EXE file as malware (before or after archive extraction), it happen because of signatures comparison technology that does not analyze real program functionality but searching matches in binary data.
Each update build was submit into Microsoft Security Intelligence service to make sure it will be not blocked by Windows Defender, but it take days until cloud database, and then your client, will be updated. If you experience such issue - you may try to apply security intelligence manual update following this instruction [https://www.microsoft.com/en-us/wdsi/defenderupdates] and then try to run application again.
If you are using some different antivirus software - you can send file for detailed analysis manually, such service available for most services. Usually it takes 2-4 hours to complete, as result EXE file will be whitelisted after next signatures update.
If it still does not work and you do not trust program developer - don't use it for now and wait for the release version.
[DESCRIPTION]
This is complex tool for importing Microsoft Flight Simulator X (FSX, 2006) aircraft into Microsoft Flight Simulator (MSFS, 2020). It does apply all required actions for successful import (like files copying, JSON files generation, critical issues fixing, 2D gauges conversion and other useful stuff). Two levels of import available - Basic and Full. First one providing list of fixes for various critical issues, lights and textures conversion, 2D gauges import. Second also have tools for CFG files manipulations and AIR data migration.
Program still in development stage, but you can participate in testing and report about any issues you have. MSFS engine has its own limitations and issues of Legacy aircraft support, be sure you are importing native FSX aircraft (not FS2004, FS9 or P3D-only) before reporting issues.
[PROVIDED_FEATURES]
- copy files from FSX to MSFS Community folder with proper structure
- generate layout.json file with list of files
- generate manifest.json file based on loaded from aircraft package data (manual edit possible)
- load existing legacy or native MSFS aircraft
- split AIRCRAFT.CFG on relative CFG files
- insert missing values into imported CFG file(s)
- insert missing CFG file sections on user choice
- populate missing performance values from description
- fix ui_typerole invalid value
- insert external view gauges
- set speed indicator limits from cruise_speed value
- detect buggy engine values (engine_type and afterburner_available)
- adjust engines output power
- apply afterburner thrust
- display afterburner flame animation
- fix runway issues (gears raised, fuel pump disabled, parking brakes disabled)
- fix contact points duplicates (stuck landing gear issue)
- notify about contact point formatting issues
- convert exterior/interior lights
- insert taxi lights
- bulk convert of BMP textures to DDS
- import AIR values into CFG files
- import 2D gauges (WIP)
- toggle aircraft sounds
- insert/remove variometer tone
- backup and restore editable files
- inform about available program update, perform self update if triggered by user
[POSSIBLE_ISSUES]
- game crashing to desktop (ensure aircraft contain both exterior and interiors files inside of MODEL folder)
- cockpit instruments do not work (not displayed or inoperate, conversion script status is WIP)
- aircraft appear in the list, but model is invisible because of unsupported model format
- engines switched off when player taking control of some aircraft on the runway (try Ctrl+E)
- turbine engines under powered at thrust level more than 40%
- inaccurate flight model
- window glass texture without opacity (you can try to adjust glass material properties in ModelConverterX)
[INSTALLATION]
- download the latest version archive from https://www.nexusmods.com/microsoftflightsimulator/mods/117
- unpack files into some folder, launch "msfsLegacyImporter.exe"
[UNINSTALL]
- delete folder
[REQUIREMENTS]
- Windows 7/8/10
- .NET 4.5
[VIDEO_TUTORIALS]
https://www.youtube.com/watch?v=Tt_6Vsp9xZY
https://www.youtube.com/watch?v=wNFbwr3KstE
https://www.youtube.com/watch?v=O80P73twn5E
https://www.youtube.com/watch?v=L77aG5UABS4
https://www.youtube.com/watch?v=g00a3mDRZIA
[CFG_PARSER]
Application loading all required CFG and FLT filed into the memory once aircraft loaded or imported, and updating local files values after each user action.
If some files was edited manually while aircraft data loaded into the memory, notification appear that files should be reloaded.
To avoid parsing issues, keep files formatting properly (comment symbol is ";", no spaces inside of [SECTION_NAME], inactive (disabled) parameters has ";-" at the beginning of line)
0. Main Screen
0.1 Left side - new import from FSX. On press, import form will appear. Original FSX aircraft folder should be selected first (usually inside of [FSX]\SimObjects\Airplanes\ but may be unpacked aircraft directory). Perfectly, it could be stock airplane with analogue 2D or 3D gauges. After Community folder is selected and fields populated, import can be performed. After successful import tabs with available instruments will appear.
0.2 Right side - load MSFS aircraft. Button Browse will appear, after pressing it you'll need to find legacy or native aircraft folder inside of MSFS Community directory. After folder is selected, available CFG files and textures will be scanned, related tabs will show up. If you have not converted any aircraft yet (with Importer or any other method), use section 0.1 first.
0.3 Languages dropdown rely on CSV files inside of "lngFls" folder of the program. Detailed instructions about how to update translation files manually or add new language are here https://docs.google.com/document/d/1TRCWeobJksmINLaV6u7aRGjeSFQSA2fUx-Mlua6z4IM/edit?usp=sharing
1. Init page
1.1 Current aircraft information
1.2 Update LAYOUT.JSON section can be triggered manually if you are moving/renaming files inside of aircraft. When you're using Importer features that affects files and folders (like CFG split of textures conversion), this option being triggered automatically, no need to press it after each operation.
1.3 Current import mode information. If current mode is Basic, Full import mode button will be at the bottom. Before proceed, important to check that all sections in AIRCRAFT.CFG labeled properly - in format like '[SECTION_NAME]' (not ';[SECTION_NAME]' or '[ SECTION NAME ]' ). When pressed, script will compare template CFGs (taken from MSFS generic plane) with aircraft.cfg and move presented sections in relative files. Original aircraft.cfg file will be renamed to ".aircraft.cfg" and ignored by JSON generator. You can remove it if you want but it does not affect the game anyway. After processing, layout.json will be regenerated automatically
1.4 If current mode is Full import, list of CFG files inside of aircraft folder. If all of them presented - no actions required. If some/all except aircraft.cfg are missing - Process button available.
1.5 If "unknown.cfg" file appear after processing - some of the sections was not found in templates, first thing to do is check that unrecognized sections labels written correctly. If you sure, that that section was not moved to proper CFG file by mistake - please report.
2. Aircraft
2.1 Missing or invalid aircraft parameters list. You can check all/some options and press the button below, script will try to search for selected values in aircraft description, but they may be not presented. If some of the notifies left unresolved, you can add missing values in aircraft.cfg file manually. Red values are usually critical, without fixing them you may experience dramatic issues in the game.
2.2 Sections list of this file. In green - presented sections (but it still may have some missing/disabled values), in orange - missing but not required sections, in red - highly likely missing required section for this aircraft.
2.3 Once some sections selected and Insert button pressed, you will be asked about new variables - if you press YES, all default values will be inserted into file as active parameters, if NO - inactive. It is recommended to choose YES for sections colored in RED.
2.4 If DLL files exists in aircraft folder, message appear about partially working avionics
2.5 Backup button available on all editable sections, once created - it can be clicked to restore original file. Backup file can be removed only manually.
3. Engines
3.1 Script checking values of critical parameters
3.2 If checkbox checked near some of the wrong parameter, they will be set to "0" after button pressed
3.3 For jets afterburner adjustment available. You can use this tool to apply afterburner boost to engines parameters. Thrust will be increased for throttle positions greater than threshold value, same value will be set as a start point for flame animation (script should be inserted from Panels tab, and also variables replaced from Models tab). Table below represents thrust modifier (Y axis, from 0 to 300%) and throttle position (from 0 to 100%). Two lines are subsonic (black) and supersonic (red) speed. Be sure Black line stays between 100% and 200%, otherwise you will get too much power.
3.4 Engines power rough adjustments buttons change value of "static_thrust" for turbine engine and "power_scalar" for piston engine
3.5 AIR data import available if TXT dump of AIR file exists in aircraft folder
3.6 To create AIR dump, get AirUpdate program ( http://www.mudpond.org/ ) and unpack it into Importer directory, launch it, select AIR file inside of aircraft folder, check "Full dump" and press "Dump" button. TXT file should be saved in aircraft directory with same name as AIR file (with .txt extension)
3.7 All available values will appear in comparison table "AIR value" - "current or default" (if current is missing) value, it is recommended to validate all lines visually
3.8 You can import all available values, or ignore zero/flat tables
3.9 After import, you'll need to fix all untouched modern values manually
3.10 List of sections at the bottom (same as 2.7-2.8)
4. FlightModel
4.1 List of gears contact points that attached to same landing wheel (usually cause "stuck landing gear" bug).
4.2 When both points of same pair selected, they will be moved in their middle position.
4.3 If some points will be not properly formatted (like missing comma delimeter), they will be listed in red color. Manual fixing is required.
4.4 Missing critical flight model values list, some of them required only after AIR file import
4.4 AIR data import table same as in 3.4-3.8
4.5 To import all flight model values, you'll need to add AERODYNAMICS section. You may choose either option - insert default values or leave them disabled, but in second case you'll need to fix and enable them manually otherwise game will crash (all values inside of this section except "_table" are critical).
4.6 After both engines and flight model data imported, AIR file can be disabled so game will no longer read it. If some critical CFG values are not set, game may crash on loading process.
4.7 List of sections at the bottom (same as 2.7-2.8)
5. Cockpit (Full import mode)
5.1 Script is checking for instruments and gauges presence (but not their statuses, so if some gauge marked in green it still can be disabled or not configured)
5.2 In red marked missing instruments, that appear on external view. So it is recommended to enable them.
5.3 After button pressed, template values for each selected gauge will be inserted into the cockpit.cfg file.
5.4 AIRSPEED indicator values will be updated automatically (if cruise_speed value set in AIRCRAFT.CFG/FLIGHT_MODEL.CFG) but that method is inaccurate. After adding instruments you have to apply manual corrections to their values manually in COCKPIT.CFG file.
6. Systems
6.1 List of lights listed here. If some of them in FSX format, you can select checkboxes and press convert button. FSX has much shorter list of light effects compare to MSFS so possibly you will see not exactly the same effect in the game. You may need to adjust direction coordinates after conversion (by default set to 0,0,0)
6.2 If aircraft does not have taxi or landing lights, you will see list of landing gear points, to which taxi lights can be attached (raised 3ft). No animation, so lights always stay in same position. You can always adjust their position manually (format: type, left/right, forward/backward, down/up). In panel tab you can find option to include automatic switch for taxi lights.
6.3 List of sections (same as 2.7-2.8)
7. Runway (Full import mode only)
7.1 Configs section for Runway state (affect aircraft avionics state once you get controls on the ground).
7.2 May fix issues like raised landing gears, parking brakes disabled, fuel pumps/valves disabled
8. Textures
8.1 List of BMP textures inside of Textures (Textures.*) folder that should be converted
8.2 Two conversion tools available, you can try both if conversion failed with first one
8.3 On convert button press, BMPs converted into DX5 flipped DDS
8.4 Original BMPs will be stored as back up by adding dot to their names, but they can be removed anytime if DDS textures looks fine in the game
9. Models
9.1 Program read model.cfg file(s) and get name of "exterior" model. To make possible for custom script (that can be injected on Panels tab) to control afterburner animation, broken variables should be replaced in exterior models content.
9.2 This process can take up to several minutes, so be patient. If models disappear from the list after processing, replacement was successful.
9.3 Program read model.cfg file(s) and get name of "interior" model, if it exists. Clickable elements in that model can be disabled to avoid game crash since MSFS ver1.8.3.0, or for any other reason
9.4 After Remove button pressed, backup of MDL file will be created (only if it does not exists) and _CVC_ folder (cache) of this aircraft cleared
9.5 Original MDL can be restored by clicking button in right top corner of Models tab
9.6 If no interior file found - you will see notification about that, such arcraft will cause CTD
9.7 If MDL file has wrong format key (should be MDLX) - you will see notification about that, usually such arcraft cause CTD
10 Sounds
10.1 List of sound samples, used by aircraft. Each sound can be enabled or disabled anytime.
10.2 If sound.xml file does not exist yet, variometer tone button will be available with volume adjustment slider.
10.3 If sound.xml exists, removal button will be there.
11. Panel
11.1 Experimental feature for 2D gauges conversion
11.2 If you have FSX installed, you need to extract default instruments sources first by using top button, they will be stored in "\Community\legacy-vcockpits-instruments\.FSX" directory. Without default instruments sources some/all gauges of current aircraft may not work. However, DLL sources are not supported yet, so some gauges just can't be converted automaically.
11.3 If aircraft panel folder(s) contain CAB files, you need to use second button to extract these sources. If instruments already unpacked into panel folder by releaser, no actions required. You can edit these sources (both images and XML files) as they will be not changed by Importer anymore.
11.4 To convert available panels, check some/all of them of them and press Import button.
11.5 To adjust moving elements and individual gauges backgrounds brightness, use slider. Lower value makes image brighter, higher - darker.
11.6 If you see needles in the cockpit, but no gauges backgrounds appear - check "Force gauge background" option
11.7 If you see black squares in front of gauge elements, check "Force mask background transparency" option
11.8 If gauge size is smaller that spot that exists for it in the mode, check "Leave panel sizeas it in XML" option
11.9 If gauge size does not look right (smaller or larger), check "Scale gauge to fit image" option
11.10 If you want taxi lights to be disabled and enabled automatically (depending on landing gears lever position), check "Insert taxi lights switch" option
11.11 If aircraft model contain fixed afterburner variables, you can insert script that will set this variable depending on engine RPM value, so afterburner animation will be triggered.
11.12 If you are not willing to debug conversion process, check "Hide conversion errors popup" checkbox (detailed log still will be stored in the ".Panel.log.txt" file
11.13 If you experience any problems with imported gauges, you can try again with next update - each fixed issue may affect any FSX aircraft.
11.14 Possible results:
11.14.1 Gauges may get same view as originally in FSX and work as expected, i.e. conversion succeed
11.14.2 Gauges may get texture background and wireframe removed from it, even if it will not functioning properly; wait for updates or check generated JS files
11.14.3 Game crashes or no gauges appear (try to check "Force gauge background") or you see total mess in the cockpit (you can try to copy required files that mentioned in warning messages)
11.14.4 App crashes when you press one of the import buttons, usually because of XML file format issues (feel free to report)
11.15 To remove generated panels: Press "Restore Backup" button on Panel tab, delete /Community/legacy-vcockpits-instruments folder
12. About
12.1 Update availability. If update available, tab label will be colored in red
12.2 Manual update will open zip link in the browser
12.3 Self update will pull update archive from the server, unpack it, replace EXEs and restart process
[CREDITS]
Inspired by <NAME>'s "planeconverter"
Developed with assistance of MFS SDK Discord channel and MS Flight Simulator Gliders FB group members
For AIR data import conversion table was used made by OzWookiee
Many thanks to <NAME> and FlyFS YouTube channels for promotion
Thanks everyone for bug reports! It really save my time on testing.
Translation credits are inside of About tab of the program
<file_sep>using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
namespace msfsLegacyImporter
{
class csvHelper
{
private List<languageFile> langugeFiles;
private languageFile defaultLanguage;
private languageFile userLanguage;
private bool DEBUG = false;
public List<string[]> processAirTable(string path, string[] header)
{
if (File.Exists(path))
{
try
{
List<string[]> result = new List<string[]>();
using (var reader = new StreamReader(path))
{
string prev_id = "";
int sub_counter = 0;
var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.IgnoreQuotes = true;
csv.Configuration.Delimiter = ",";
while (csv.Read())
{
if (csv.Context.Row == 1)
{
csv.ReadHeader();
continue;
}
csv.TryGetField(header[0], out string field1);
csv.TryGetField(header[1], out string field2);
if (!String.IsNullOrEmpty(field1))
field1 = field1.Trim().TrimStart('0');
if (!String.IsNullOrEmpty(field2))
field2 = field2.Trim();
if (!String.IsNullOrEmpty(field1) && field1 != prev_id)
{
sub_counter = 0;
prev_id = field1;
result.Add(new string[] { prev_id + "-" + sub_counter, field2 });
sub_counter++;
}
else //if (!String.IsNullOrEmpty(field2))
{
result.Add(new string[] { prev_id + "-" + sub_counter, field2 });
sub_counter++;
}
//Console.WriteLine("AIR TABLE " + result.Last()[0] + " / " + result.Last()[1]);
}
}
return result;
} catch {
MessageBox.Show("File " + path + " is locked");
}
}
return null;
}
public List<string[]> processAirFile(string path)
{
if (File.Exists(path))
{
List<string[]> result = new List<string[]>();
using (var reader = new StreamReader(path))
{
var bad = new List<string>();
//var isRecordBad = false;
string prev_id = "";
int sub_counter = 0;
var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
csv.Configuration.HasHeaderRecord = false;
csv.Configuration.IgnoreQuotes = true;
csv.Configuration.Delimiter = ",";
while (csv.Read())
{
csv.TryGetField(0, out string field1);
csv.TryGetField(1, out string field2);
csv.TryGetField(2, out string field3);
if (!String.IsNullOrEmpty(field1))
{
field1 = field1.Trim();
field1 = Regex.Replace(field1, @".*([0-9]{4})$", "$1", RegexOptions.Singleline);
//field1.Substring(Math.Max(0, field1.Length - 4), field1.Length);
}
if (!String.IsNullOrEmpty(field2))
field2 = field2.Trim();
if (!String.IsNullOrEmpty(field3))
field3 = field3.Trim();
if (!String.IsNullOrEmpty(field1) && String.IsNullOrEmpty(field3)) {
// CHECK EXPORTED TABLE DATA FILE (-0.349066:1, -0.232711:1)
string tablePath = path.Replace("_air.txt", ".air_TAB" + field1 + ".txt");
if (File.Exists(tablePath))
{
Console.WriteLine("Reading " + tablePath);
string tableData = "";
string content = File.ReadAllText(tablePath);
int i = 0;
foreach (string line in Regex.Split(content, "\r\n|\r|\n"))
{
if (i > 0 && !String.IsNullOrEmpty(line) && line.Contains(","))
tableData += line.Replace(",", ":") + ",";
i++;
}
// USE TABLE DATA AS VALUE
if (!String.IsNullOrEmpty(tableData))
field3 = tableData.Trim(',');
}
sub_counter = 0;
result.Add(new string[] { field1.TrimStart('0') + (!String.IsNullOrEmpty(field3) ? "-" + sub_counter : ""), field2, field3 });
prev_id = field1.TrimStart('0');
}
else if (!String.IsNullOrEmpty(prev_id) && (String.IsNullOrEmpty(field2) || !field2.Contains("---") )/* && !String.IsNullOrEmpty(field3)*/) {
result.Add(new string[] { prev_id + "-" + sub_counter, field2, field3 });
sub_counter++;
}
if (DEBUG)
Console.WriteLine("AIR VALUES " + result.Last()[0] + " / " + result.Last()[1] + " / " + result.Last()[2]);
//isRecordBad = false;
}
foreach (string val in bad) {
Console.WriteLine("Bad value: " + val);
}
}
return result;
}
return null;
}
public List<string[]> processAirDump(string path)
{
string currentToken = "";
string tableData = "";
int sub_counter = 0;
if (File.Exists(path))
{
List<string[]> result = new List<string[]>();
string content = File.ReadAllText(path);
foreach (string line in Regex.Split(content, "\r\n|\r|\n"))
{
Regex regex = new Regex(@"Record:(\s+)(\d*)");
Match match = regex.Match(line);
if (String.IsNullOrEmpty(line.Trim())) // STORE COLLECTED DATA
{
if (currentToken != "" && tableData != "")
{
result.Add(new string[] { currentToken + "-" + sub_counter, "", tableData.TrimEnd(',') });
if (DEBUG)
Console.WriteLine("AIR VALUES " + result.Last()[0] + " / " + result.Last()[1] + " / " + result.Last()[2]);
}
currentToken = "";
tableData = "";
sub_counter = 0;
}
else if (match.Success && match.Groups.Count >= 3) // CAPTURE TOKEN NUMBER
{
currentToken = match.Groups[2].Value.Trim().TrimStart('0');
}
else // COLLECT TABLE DATA
{
if (line.StartsWith("FIELD"))
{
string[] arr = line.Replace("FIELD ", "").Split('\t');
if (arr.Length >= 4 && !String.IsNullOrEmpty(arr[3].Trim()))
{
string val = arr[3].Trim();
if (currentToken == "1101") // INT -> DBL CONVERSION
{
double dbl;
if (Double.TryParse(val, out dbl))
{
val = (dbl / 2048).ToString("0.0#####");
}
}
result.Add(new string[] { currentToken + "-" + sub_counter, "", val });
tableData = "";
if (DEBUG)
Console.WriteLine("AIR VALUES " + result.Last()[0] + " / " + result.Last()[1] + " / " + result.Last()[2].ToString());
}
sub_counter++;
}
else if (!line.StartsWith("Points:") && !line.StartsWith("Found") && !line.StartsWith("columns:"))
{
tableData += line.Replace("\t", ":").TrimEnd(':') + ",";
}
}
}
return result;
}
return null;
}
public void languageUpdate(string language)
{
string userLanguagefile = AppDomain.CurrentDomain.BaseDirectory + "\\lngFls\\userLanguage";
foreach (languageFile langugeFile in langugeFiles)
{
if (langugeFile.Name == language)
{
Console.WriteLine("Language changed to " + language);
userLanguage = langugeFile;
try { File.WriteAllText(userLanguagefile, language); }
catch (Exception ex) { MessageBox.Show("Can't save userLanguage file" + Environment.NewLine + "Error: " + ex.Message); }
break;
}
}
}
public void initializeLanguages(ComboBox LangSelector)
{
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\lngFls\\"))
{
try { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\lngFls\\"); } catch { MessageBox.Show("Failed to create languages folder"); }
}
string userLanguagefile = AppDomain.CurrentDomain.BaseDirectory + "\\lngFls\\userLanguage";
string language = "English - Default";
if (File.Exists(userLanguagefile))
{
try { language = File.ReadAllText(userLanguagefile); } catch { }
}
langugeFiles = new List<languageFile>();
defaultLanguage = null;
userLanguage = null;
foreach (string filepath in Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory + "\\lngFls\\", "*.csv", SearchOption.TopDirectoryOnly))
{
string filename = Path.GetFileNameWithoutExtension(filepath);
languageFile currentLanguage = new languageFile(filename, new List<string[]>());
try
{
using (var reader = new StreamReader(filepath))
{
var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
string[] header = new string[] { "slug", "translation", "original" };
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.IgnoreQuotes = false;
csv.Configuration.Delimiter = ",";
var bad = new List<string>();
csv.Configuration.BadDataFound = context =>
{
bad.Add(context.RawRecord);
};
while (csv.Read())
{
if (csv.Context.Row == 1)
{
csv.ReadHeader();
continue;
}
csv.TryGetField(header[0], out string field1);
string field2;
if (filename == "English - Default")
csv.TryGetField(header[2], out field2);
else
csv.TryGetField(header[1], out field2);
if (!string.IsNullOrEmpty(field1) && !string.IsNullOrEmpty(field2))
currentLanguage.Rows.Add(new string[] { field1, field2 });
}
Console.WriteLine("Bad records: " + string.Join(",", bad));
}
ComboBoxItem item = new ComboBoxItem();
item.Content = filename;
item.Tag = filename;
LangSelector.Items.Add(item);
langugeFiles.Add(currentLanguage);
if (currentLanguage.Rows.Count > 0 && filename == language)
{
userLanguage = currentLanguage;
LangSelector.Text = filename;
}
if (currentLanguage.Rows.Count > 0 && filename == "English - Default")
{
defaultLanguage = currentLanguage;
if (string.IsNullOrEmpty(language))
LangSelector.Text = filename;
}
Console.WriteLine("Language file " + filename + " loaded, " + currentLanguage.Rows.Count + " records added");
}
catch (Exception e)
{
MessageBox.Show("Error to parse \"\\lngFls\\" + language + ".csv\": " + e.Message);
}
}
if (userLanguage == null)
MessageBox.Show("Language file " + language + ".csv is empty or does not exists.");
}
public string trans(string slug)
{
if (userLanguage != null)
{
string[] trans = userLanguage.Rows.Find(x => x[0] == slug);
if (trans != null && !String.IsNullOrEmpty(trans[1]))
return trans[1].Replace("\\n", Environment.NewLine);
}
if (defaultLanguage != null)
{
string[] trans = defaultLanguage.Rows.Find(x => x[0] == slug);
if (trans != null && !String.IsNullOrEmpty(trans[1]))
return trans[1].Replace("\\n", Environment.NewLine);
}
return slug;
}
public class languageFile
{
public string Name { get; set; }
public List<string[]> Rows { get; set; }
public languageFile(string name, List<string[]> rows)
{
Name = name;
Rows = rows;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
namespace msfsLegacyImporter
{
public class cfgHelper
{
// cfg file
// ---- filename
// ---- sections
// --------- sectionname
// --------- lines
// ------------- active
// ------------- parameter
// ------------- value
// ------------- comment
private List<CfgFile> cfgTemplates;
private List<CfgFile> cfgAircraft;
public long lastChangeTimestamp;
private bool DEBUG = false;
public bool processCfgfiles(string sourcesPath, bool isAircraft = false)
{
List<CfgFile> cfgFiles = new List<CfgFile>();
List<CfgLine> cfgLines;
foreach (var file in new[] { "aircraft.cfg", "cameras.cfg", "cockpit.cfg", "engines.cfg", "flight_model.cfg", "gameplay.cfg", "systems.cfg", "runway.flt" })
{
string path = sourcesPath + file;
if (isAircraft)
Console.WriteLine(file + " file " + (File.Exists(path) ? "exists" : "not exists;") + " cfgFile " + (cfgFileExists(file) ? "exists" : "not exists"));
if (File.Exists(path))
{
string content = File.ReadAllText(path);
cfgLines = readCSV(content + "\r\n[]");
//Console.WriteLine(cfgLines.First().Name);
cfgFiles.Add(parseCfg(file, cfgLines));
} else if (isAircraft && file.Contains(".flt")) {
cfgFiles.Add(new CfgFile(true, file, new List<CfgSection>()));
}
else if (!isAircraft)
{
MessageBox.Show("File does not exists: " + path);
return false;
}
}
if (isAircraft)
cfgAircraft = cfgFiles;
else
cfgTemplates = cfgFiles;
return true;
//Console.WriteLine(cfgTemplates.Last().Sections.Last().Lines.First().Name + " " + cfgTemplates.Last().Sections.Last().Lines.First().Value + " " + cfgTemplates.Last().Sections.Last().Lines.First().Comment);
}
public void resetCfgfiles()
{
cfgAircraft = null;
}
public List<CfgLine> readCSV(string content)
{
content = content.Replace("//", ";");
List<CfgLine> list = new List<CfgLine>();
foreach (string line in Regex.Split(content, "\r\n|\r|\n"))// Split(new string[] { System.Environment.NewLine },StringSplitOptions.None))
{
bool active = true;
string fixedLine = line.Trim();
string comment = "";
// STORE ACTIVE FLAG
if (/*(fixedLine.Contains("=") || fixedLine.Contains("[") && fixedLine.Contains("]")) && fixedLine[0] == ';' ||*/
fixedLine.Length >= 2 && fixedLine.Substring(0,2) == ";-")
{
active = false;
fixedLine = fixedLine.Substring(2).Trim();
}
// STORE COMMENTS
int pos = fixedLine.IndexOf(";");
if (pos >= 0)
{
comment = fixedLine.Substring(pos + 1).Trim();
fixedLine = fixedLine.Substring(0, pos).Trim();
}
if (String.IsNullOrEmpty(fixedLine) || !fixedLine.Contains("="))
{
list.Add(new CfgLine(active, fixedLine, "", comment));
} else
{
list.Add(new CfgLine(active, fixedLine.Split('=')[0].Trim().ToLower(), fixedLine.Split('=')[1].Trim(), comment));
}
}
//foreach (var test in list)
//Console.WriteLine("<" + test.Active + "> <" + test.Name + "> <" + test.Value + "> <" + test.Comment + ">");
return list;
}
public CfgFile parseCfg(string file, List<CfgLine> lines)
{
List<CfgSection> cfgSections = new List<CfgSection>();
List<CfgLine> cfgLines = new List<CfgLine>();
string currentSection = "";
bool lastStatus = true;
foreach (var line in lines)
{
// SECTION START CHECK
if (!String.IsNullOrEmpty(line.Name) || !String.IsNullOrEmpty(line.Comment))
{
if (!String.IsNullOrEmpty(line.Name) && line.Name[0] == '[')
{
// ADD FINISHED SECTION
if (currentSection != "")
cfgSections.Add(new CfgSection(lastStatus, currentSection, cfgLines));
// PREPARE FOR NEW SECTION
currentSection = line.Name.ToUpper();
lastStatus = line.Active;
cfgLines = new List<CfgLine>();
}
else if (currentSection != "")
cfgLines.Add(line);
}
}
return new CfgFile(true, file, cfgSections);
}
public void splitCfg(string aircraftDirectory, string singleFile = "", bool addMissing = false)
{
List<CfgFile> cfgFiles = new List<CfgFile>();
processCfgfiles(aircraftDirectory + "\\", true);
if (cfgTemplates.Count > 0 && cfgFileExists("aircraft.cfg"))
{
foreach (var aircraftSection in cfgAircraft[0].Sections)
{
CfgSection cfgTempSection = null;
string cfgTemplateFile = singleFile == "" ? ".unknown.cfg" : "aircraft.cfg";
// FIND SECTION MATCH IN TEMPLATES
foreach (CfgFile tplfiles in cfgTemplates)
{
if (singleFile != "" && tplfiles.Name != singleFile)
continue;
CfgSection cfgTemplateSection = tplfiles.Sections.Find(x => x.Name == aircraftSection.Name);
// NUMERUOUS SECTION FIX
if (cfgTemplateSection == null)
cfgTemplateSection = tplfiles.Sections.Find(x => x.Name.Contains(".") && aircraftSection.Name.Contains(".") && x.Name.Split('.')[0] == aircraftSection.Name.Split('.')[0]);
if (cfgTemplateSection != null)
{
cfgTemplateFile = tplfiles.Name;
// DEEP COPY FOR COMPARISON PURPOSE
cfgTempSection = new CfgSection(cfgTemplateSection.Active, cfgTemplateSection.Name, new List<CfgLine>());
foreach (var cfgTempLine in cfgTemplateSection.Lines)
cfgTempSection.Lines.Add(new CfgLine(cfgTempLine.Active, cfgTempLine.Name, cfgTempLine.Value, cfgTempLine.Comment));
break;
}
}
// BUILD MIXED SECTION
List<CfgLine> cfgLines = new List<CfgLine>();
// ADD LEGACY LINES
cfgLines.Add(new CfgLine(true, "", "", ""));
foreach (CfgLine aircraftLine in aircraftSection.Lines)
{
CfgLine cfgTemplateLine = null;
if (cfgTempSection != null)
{
cfgTemplateLine = cfgTempSection.Lines.Find(x => x.Name == aircraftLine.Name ||
x.Name.Contains(".") && aircraftLine.Name.Contains(".") && x.Name.Split('.')[0] == aircraftLine.Name.Split('.')[0]);
if (cfgTemplateLine != null) // ATTRIBUTE FOUND IN TEMPLATE
{
cfgTempSection.Lines.Remove(cfgTemplateLine);
if (String.IsNullOrEmpty(aircraftLine.Comment))
aircraftLine.Comment = cfgTemplateLine.Comment;
}
// NOT FOUND
else if (!String.IsNullOrEmpty(aircraftLine.Name) && !String.IsNullOrEmpty(aircraftLine.Value) && !aircraftLine.Name.Contains("."))
{
//aircraftLine.Active = false;
aircraftLine.Comment += " ### ";
}
}
// SECTION NOT FOUND
else if (singleFile == "")
{
aircraftLine.Active = false;
}
cfgLines.Add(aircraftLine);
}
// ADD MODERN LINES
if (addMissing && cfgTempSection != null && cfgTempSection.Lines.Count > 0) {
cfgLines[0].Comment = "LEGACY";
cfgLines.Add(new CfgLine(true, "", "", "MODERN"));
foreach (CfgLine cfgTemplateLine in cfgTempSection.Lines)
{
cfgTemplateLine.Active = false;
cfgLines.Add(cfgTemplateLine);
}
}
CfgSection cfgSection = new CfgSection(true, aircraftSection.Name, cfgLines);
// ADD SECTION TO FILES LIST
if (cfgFiles != null && cfgFiles.Find(x => x.Name == cfgTemplateFile) != null)
{
cfgFiles.Find(x => x.Name == cfgTemplateFile).Sections.Add(cfgSection);
}
else
{
List<CfgSection> cfgSections = new List<CfgSection>();
cfgSections.Add(new CfgSection(true, "[VERSION]", new List<CfgLine>()));
cfgSections[0].Lines.Add(new CfgLine(true, "major", "1", ""));
cfgSections[0].Lines.Add(new CfgLine(true, "minor", "0", ""));
cfgSections.Add(cfgSection);
cfgFiles.Add(new CfgFile(true, cfgTemplateFile, cfgSections));
}
}
// RENAME ORIGINAL AIRCRAFT.CFG
File.Move(aircraftDirectory + "\\aircraft.cfg", aircraftDirectory + "\\.aircraft.cfg");
// SAVE FILES
foreach (CfgFile cfgFile in cfgFiles)
{
saveCfgFile(aircraftDirectory, cfgFile);
}
//cfgAircraft = cfgFiles;
processCfgfiles(aircraftDirectory + "\\", true);
}
}
public bool cfgFileExists(string filename)
{
return cfgAircraft != null && cfgAircraft.Count > 0 && cfgAircraft.Find(x => x.Name == filename) != null;
}
public void saveCfgFiles(string aircraftDirectory, string[] files)
{
bool aircraftCfgSaved = false;
foreach (string file in files)
{
string filename = file;
if (!cfgFileExists(filename)) { filename = "aircraft.cfg"; }
if (filename == "aircraft.cfg" && aircraftCfgSaved) // SKIP AIRCRAFT.CFG
continue;
else if (filename == "aircraft.cfg") // SKIP NEXT TIME
aircraftCfgSaved = true;
saveCfgFile(aircraftDirectory, cfgAircraft.Find(x => x.Name == filename));
}
}
public void saveCfgFile(string aircraftDirectory, CfgFile cfgFile)
{
string path = aircraftDirectory + "\\" + cfgFile.Name;
Console.WriteLine("Saving config file " + cfgFile.Name + " into " + path);
lastChangeTimestamp = DateTime.UtcNow.Ticks;
if (File.Exists(path))
{
try { File.Delete(path); }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Can't update file " + path);
return;
}
}
if (!File.Exists(path))
{
using (FileStream fs = File.Create(path))
{
byte[] text = new UTF8Encoding(true).GetBytes("");// new UTF8Encoding(true).GetBytes("[VERSION]" + System.Environment.NewLine + "major = 1" + System.Environment.NewLine + "minor = 0" + System.Environment.NewLine);
fs.Write(text, 0, text.Length);
}
}
using (FileStream fs = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Write))
{
foreach (CfgSection cfgSection in cfgFile.Sections)
{
byte[] text = new UTF8Encoding(true).GetBytes(System.Environment.NewLine + (!cfgSection.Active ? ";-" : "") + cfgSection.Name + System.Environment.NewLine + System.Environment.NewLine);
fs.Write(text, 0, text.Length);
foreach (CfgLine cfgLine in cfgSection.Lines)
{
if (!String.IsNullOrEmpty(cfgLine.Name) || !String.IsNullOrEmpty(cfgLine.Value) || !String.IsNullOrEmpty(cfgLine.Comment))
{
if (String.IsNullOrEmpty(cfgLine.Name) && String.IsNullOrEmpty(cfgLine.Value))
text = new UTF8Encoding(true).GetBytes("; " + cfgLine.Comment + System.Environment.NewLine);
else
text = new UTF8Encoding(true).GetBytes((!cfgLine.Active ? ";-" : "") + cfgLine.Name + " = " + cfgLine.Value + " ; " + cfgLine.Comment + System.Environment.NewLine);
fs.Write(text, 0, text.Length);
}
}
}
}
}
public string[] getSectionsList(string aircraftDirectory, string filename)
{
CfgFile availableSections = cfgTemplates.Find(x => x.Name == filename);
CfgFile installedSections = cfgFileExists(filename) ? cfgAircraft.Find(x => x.Name == filename) : cfgAircraft.Find(x => x.Name == "aircraft.cfg");
string[] sections = new string[100];
if (availableSections != null)
{
int i = 0;
foreach (var cockpitSection in availableSections.Sections)
{
if (installedSections != null && installedSections.Sections.Find(x => x.Name == cockpitSection.Name) != null )
sections[i] = cockpitSection.Name + Environment.NewLine;
else
sections[i] = "-" + cockpitSection.Name.ToUpper() + Environment.NewLine;
i++;
}
}
return sections;
}
public void insertSections(string aircraftDirectory, string sourceFilename, string targetFilename, string[] sections, bool active)
{
if (cfgFileExists(targetFilename) && sections.Length > 0)
{
string message = "";
CfgFile availableSections = cfgTemplates.Find(x => x.Name == sourceFilename);
CfgFile cfgFile = cfgAircraft.Find(x => x.Name == targetFilename);
if (availableSections != null)
{
foreach (var section in sections)
{
if (String.IsNullOrEmpty(section))
break;
foreach (var sect in availableSections.Sections)
{
var pattern = @"\[(.*?)\]";
if (Regex.Matches(sect.Name, pattern)[0].Groups[1].ToString().Trim() == Regex.Matches(section, pattern)[0].Groups[1].ToString().Trim())
{
//Console.WriteLine("availableGaugeLines found in section " + sect.Name + " lines " + sect.Lines.Count);
List <CfgLine> newLines = new List<CfgLine>();
foreach (var cfgLine in sect.Lines)
{
// AIRSPEED INDICATOR ADJUSTMENTS
if (sect.Name.ToString() == "[AIRSPEED]") {
string value = getCfgValue("cruise_speed", "flight_model.cfg");
if (value != "" && int.TryParse(value.Contains('.') ? value.Trim('"').Trim().Split('.')[0] : value.Trim('"').Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out int cruiseSpeed) && cruiseSpeed > 0)
{
switch (cfgLine.Name.ToString())
{
case "white_start":
cfgLine.Value = Math.Max(20, cruiseSpeed / 3).ToString();
break;
case "white_end":
case "green_start":
cfgLine.Value = Math.Max(30, cruiseSpeed / 2).ToString(); ;
break;
case "green_end":
case "highlimit":
cfgLine.Value = (cruiseSpeed).ToString();
break;
case "max":
cfgLine.Value = (1.1 * cruiseSpeed).ToString();
break;
}
}
}
newLines.Add(new CfgLine(active, cfgLine.Name, cfgLine.Value, cfgLine.Comment));
}
//if (sect.Name.ToString() == "[AIRSPEED]")
//message += "AIRSPEED section values was calculated from cruise_speed, you'll need to adjust them manually";
CfgSection newSection = new CfgSection(true, sect.Name, newLines);
cfgFile.Sections.Add(newSection);
break;
}
}
}
saveCfgFile(aircraftDirectory, cfgFile);
if (message != "")
MessageBox.Show(message);
}
else
{
Console.WriteLine("availableSections is null: cockpit");
}
}
}
public string[] getLights(string aircraftDirectory)
{
string[] lightsList = new string[100];
int i = 0;
CfgSection section = cfgFileExists("systems.cfg") ? cfgAircraft.Find(x => x.Name == "systems.cfg").Sections.Find(x => x.Name == "[LIGHTS]") :
cfgAircraft.Find(x => x.Name == "aircraft.cfg").Sections.Find(x => x.Name == "[LIGHTS]");
if (section != null)
foreach (CfgLine line in section.Lines)
if (line.Active && line.Name.StartsWith("light."))
{
lightsList[i] = line.Name + " = " + line.Value;
i++;
}
return lightsList;
}
public int getTaxiLights(string aircraftDirectory)
{
int i = 0;
CfgSection section = cfgFileExists("systems.cfg") ? cfgAircraft.Find(x => x.Name == "systems.cfg").Sections.Find(x => x.Name == "[LIGHTS]") :
cfgAircraft.Find(x => x.Name == "aircraft.cfg").Sections.Find(x => x.Name == "[LIGHTS]");
if (section != null)
foreach (CfgLine line in section.Lines)
if (line.Active && line.Name.StartsWith("lightdef.") && (line.Value.ToLower().Contains("type:6") || line.Value.ToLower().Contains("type:6")) )
i++;
return i;
}
public List<string> getContactPoints(string aircraftDirectory, string type = "")
{
List<string> contactPointsList = new List<string>();
CfgSection section = cfgFileExists("flight_model.cfg") ? cfgAircraft.Find(x => x.Name == "flight_model.cfg").Sections.Find(x => x.Name == "[CONTACT_POINTS]") :
cfgAircraft.Find(x => x.Name == "aircraft.cfg").Sections.Find(x => x.Name == "[CONTACT_POINTS]");
if (section != null)
foreach (CfgLine line in section.Lines)
if (line.Active && line.Name.StartsWith("point.") && ( type == "" || line.Value.Contains(',') &&
(line.Value.Split(',')[0].Trim() == type || line.Value.Split(',')[0].Trim().Contains('.') && line.Value.Split(',')[0].Trim().Split('.')[0] == type) ))
contactPointsList.Add(line.Name + " = " + line.Value);
return contactPointsList;
}
public void adjustEnginesPower(string aircraftDirectory, double multiplier)
{
CfgFile cfgFile = cfgFileExists("engines.cfg") ? cfgAircraft.Find(x => x.Name == "engines.cfg") :
cfgAircraft.Find(x => x.Name == "aircraft.cfg");
if (cfgFile != null)
{
string attr = "";
string sect = "";
string engine_type = getCfgValue("engine_type", "engines.cfg", "[GENERALENGINEDATA]");
if (engine_type.Contains('.'))
engine_type = engine_type.Split('.')[0];
if (engine_type == "1" || engine_type == "5") // JET
{
attr = "static_thrust";
sect = "[TURBINEENGINEDATA]";
}
else if (engine_type == "0") // PISTON
{
attr = "power_scalar";
sect = "[PISTON_ENGINE]";
} else if (engine_type == "5") // TURBOPROP
{
attr = "power_scalar";
sect = "[TURBOPROP_ENGINE]";
}
if (attr != "" && sect != "") {
string thrust = getCfgValue(attr, "engines.cfg", sect);
if (thrust != "")
{
double.TryParse(thrust.Replace(",", ".").Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out double num);
if (num > 0)
{
double newThrust = Math.Max((num * multiplier), 0.001);
if (attr == "power_scalar")
newThrust = Math.Min((num * multiplier), 1.9);
string newThrustString = newThrust.ToString("0.###");
MessageBoxResult messageBoxResult = MessageBox.Show("Old value: " + num + Environment.NewLine + "New value: " + newThrustString, "Engines power adjustment", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
setCfgValue(aircraftDirectory, attr, newThrustString, "engines.cfg", sect);
saveCfgFiles(aircraftDirectory, new string[] {"engines.cfg"});
}
}
}
}
}
}
// MISC STUFF
// IF NO ACTIVE FLAG PROVIDED - ATTRIBUTE WILL BE SET TO 'ACTIVE'
// SECTION CAN BE EMPTY BUT NEW VALUE WILL BE NOT CREATED IF NOT FOUND
// FILE NAME OCNVERTED TO LOWERCASE
// SECTION NAME CONVERTED TO UPPERCASE
// ATTRIBUTE NAME CONVERTED TO LOWERCASE
// VALUE AND COMMENT - WHITESPACES TRIM ONLY
public bool setCfgValue(string aircraftDirectory, string attrname, string value, string filename, string sectionname = "", bool active = true, string comment = "")
{
if (!cfgFileExists(filename))
filename = "aircraft.cfg";
// TODO: ADD MISSING SECTION
if (cfgAircraft.Count >= 1)
{
foreach (CfgFile cfgFile in cfgAircraft)
{
if (!String.IsNullOrEmpty(filename) && cfgFile.Name != filename.Trim().ToLower())
continue;
foreach (CfgSection cfgSection in cfgFile.Sections)
{
if (!String.IsNullOrEmpty(sectionname) && cfgSection.Name != sectionname.Trim().ToUpper())
continue;
foreach (CfgLine cfgLine in cfgSection.Lines)
{
// UPDATE EXISTING ATTR
if (cfgLine.Name == attrname.Trim().ToLower())
{
cfgLine.Active = active;
cfgLine.Value = value.Trim();
if (!String.IsNullOrEmpty(comment))
cfgLine.Comment = comment.Trim();
Console.WriteLine("setCfgExisting: " + cfgFile.Name + "/" + cfgSection.Name + "/" + cfgLine.Name + " = " + cfgLine.Value);
//saveCfgFile(aircraftDirectory, cfgFile);
return true;
}
}
// CREATE NEW ATTR
if (!String.IsNullOrEmpty(filename) && !String.IsNullOrEmpty(sectionname))
{
CfgLine cfgLine = new CfgLine(active, attrname.Trim().ToLower(), value, comment);
cfgSection.Lines.Add(cfgLine);
Console.WriteLine("setCfgNew: " + cfgFile.Name + "/" + cfgSection.Name + "/" + cfgLine.Name + " = " + cfgLine.Value);
//saveCfgFile(aircraftDirectory, cfgFile);
return true;
}
}
}
}
return false;
}
// RETURN EMPTY IF NOT FOUND
public string getCfgValue(string attrname, string filename, string sectionname = "", bool ignoreInactive = false)
{
if (!cfgFileExists(filename))
filename = "aircraft.cfg";
if (cfgAircraft.Count >= 1)
{
foreach (CfgFile cfgFile in cfgAircraft)
{
if (!String.IsNullOrEmpty(filename) && cfgFile.Name != filename.Trim().ToLower())
continue;
foreach (CfgSection section in cfgFile.Sections)
{
if (!String.IsNullOrEmpty(sectionname) && section.Name != sectionname.Trim().ToUpper())
continue;
CfgLine line = section.Lines.Find(x => x.Name == attrname);
if (line != null && (line.Active || ignoreInactive))
{
if (DEBUG)
Console.WriteLine("getCfgValue: " + filename + " / " + (sectionname != "" ? sectionname : "ANY") + " / " + attrname + " = " + line.Value);
return line.Value;
}
}
}
}
if (DEBUG)
Console.WriteLine("getCfgValue: " + filename + " / " + (sectionname != "" ? sectionname : "ANY") + " / " + attrname + " NOT FOUND");
return "";
}
public bool setCfgValueStatus(string aircraftDirectory, string attrname, string filename, string sectionname = "", bool active = true)
{
if (!cfgFileExists(filename))
filename = "aircraft.cfg";
CfgFile cfgFile = cfgAircraft.Find(x => x.Name == filename);
if (cfgFile != null)
{
CfgSection ligtsList = cfgFile.Sections.Find(x => x.Name == sectionname);
if (ligtsList != null)
{
CfgLine line = ligtsList.Lines.Find(x => x.Name == attrname);
if (line != null) {
line.Active = active;
if (DEBUG)
Console.WriteLine("setCfgValueStatus: " + filename + " / " + (sectionname != "" ? sectionname : "ANY") + " / " + attrname + " set to " + active);
return true;
}
}
}
if (DEBUG)
Console.WriteLine("setCfgValueStatus: " + filename + " / " + (sectionname != "" ? sectionname : "ANY") + " / " + attrname + " NOT FOUND");
return false;
}
public CfgFile setCfgSectionStatus(CfgFile cfgFile, string sectionname, bool active = true)
{
if (cfgFile != null)
{
CfgSection ligtsList = cfgFile.Sections.Find(x => x.Name == sectionname);
if (ligtsList != null)
{
if (DEBUG)
Console.WriteLine("setCfgValueStatus: " + cfgFile.Name + " / " + sectionname + " set to " + active);
ligtsList.Active = active;
foreach (CfgLine line in ligtsList.Lines)
line.Active = active;
return cfgFile;
}
}
if (DEBUG)
Console.WriteLine("setCfgValueStatus: " + cfgFile.Name + " / " + sectionname + " NOT FOUND");
return cfgFile;
}
public List<string> getInteriorModels(string aircraftDirectory)
{
List<string> models = new List<string>();
var cfgFiles = Directory.EnumerateFiles(aircraftDirectory, "model.cfg", SearchOption.AllDirectories);
foreach (string currentFile in cfgFiles)
{
if (Path.GetFileName(currentFile)[0] != '.')
{
foreach (var modelString in readCSV(File.ReadAllText(currentFile)))
{
if (modelString.Name == "interior")
models.Add(Path.GetDirectoryName(currentFile) + "\\" + modelString.Value + (modelString.Value.ToLower().EndsWith(".mdl") ? "" : ".mdl"));
}
}
}
return models;
}
public List<string> getExteriorModels(string aircraftDirectory)
{
List<string> models = new List<string>();
var cfgFiles = Directory.EnumerateFiles(aircraftDirectory, "model.cfg", SearchOption.AllDirectories);
foreach (string currentFile in cfgFiles)
{
if (Path.GetFileName(currentFile)[0] != '.')
{
foreach (var modelString in readCSV(File.ReadAllText(currentFile)))
{
if (modelString.Name == "normal")
models.Add(Path.GetDirectoryName(currentFile) + "\\" + modelString.Value + ".mdl");
}
}
}
return models;
}
public List<string> getSounds(string aircraftDirectory)
{
List<string> sounds = new List<string>();
var cfgFiles = Directory.EnumerateFiles(aircraftDirectory, "sound.cfg", SearchOption.AllDirectories);
foreach (string currentFile in cfgFiles)
{
if (Path.GetFileName(currentFile)[0] != '.')
{
List<CfgLine> cfgLines = readCSV(File.ReadAllText(currentFile) + "\r\n[]");
//Console.WriteLine(cfgLines.First().Name);
CfgFile tempFile = parseCfg(currentFile.Replace(aircraftDirectory, "").TrimStart('\\'), cfgLines);
foreach (CfgSection section in tempFile.Sections) {
if (section.Name.Length > 0)
sounds.Add((!section.Active ? "-" : "") + currentFile.Replace(aircraftDirectory, "") + "\\" + section.Name);
}
}
}
return sounds;
}
public void updateSounds(string aircraftDirectory, List<string> checkboxes)
{
string currentFile = "";
CfgFile tempFile = null;
foreach (string checkbox in checkboxes)
{
if (checkbox.Contains('['))
{
string filename = checkbox.Split('[')[0].TrimEnd('\\');
string filepath = aircraftDirectory + filename;
if (currentFile != filename && File.Exists(filepath))
{
if (tempFile != null) // SAVE PREVIOUS FILE
saveCfgFile(aircraftDirectory, tempFile);
currentFile = filename;
List<CfgLine> cfgLines = readCSV(File.ReadAllText(filepath) + "\r\n[]");
tempFile = parseCfg(filename.TrimStart('\\'), cfgLines);
foreach (CfgSection section in tempFile.Sections)
setCfgSectionStatus(tempFile, section.Name, false);
}
string sectionname = '[' + checkbox.Split('[')[1];
setCfgSectionStatus(tempFile, sectionname, true);
}
}
if (tempFile != null) // SAVE PREVIOUS FILE
saveCfgFile(aircraftDirectory, tempFile);
}
public bool cfgSectionExists(string filename, string sectionName)
{
if (!cfgFileExists(filename))
filename = "aircraft.cfg";
return cfgAircraft.Find(x => x.Name == filename).Sections.Find(x => x.Name == sectionName) != null;
}
public List<string> getMissingLiveryModels(string aircraftDirectory)
{
List<string> missingLiveryModels = new List<string>();
if (cfgFileExists("aircraft.cfg"))
{
for (int k = 0; k <= 99; k++)
{
if (cfgSectionExists("aircraft.cfg", "[FLTSIM." + k + "]"))
{
string texture = getCfgValue("texture", "aircraft.cfg", "[FLTSIM." + k + "]").ToLower().Trim('"').Trim();
string model = getCfgValue("model", "aircraft.cfg", "[FLTSIM." + k + "]").ToLower().Trim('"').Trim();
if (!String.IsNullOrEmpty(texture) && (String.IsNullOrEmpty(model) || model != texture))
missingLiveryModels.Add("[FLTSIM." + k + "] (texture:"+texture+" model:"+ (String.IsNullOrEmpty(model) ? "empty" : model) + ")");
}
}
}
return missingLiveryModels;
}
public class CfgFile
{
public bool Active { get; set; }
public string Name { get; set; }
public List<CfgSection> Sections { get; set; }
public CfgFile(bool active, string name, List<CfgSection> sections)
{
Active = active;
Name = name;
Sections = sections;
}
}
public class CfgSection
{
public bool Active { get; set; }
public string Name { get; set; }
public List<CfgLine> Lines { get; set; }
public CfgSection(bool active, string name, List<CfgLine> lines)
{
Active = active;
Name = name;
Lines = lines;
}
}
public class CfgLine
{
public bool Active { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public string Comment { get; set; }
public object Sections { get; internal set; }
public CfgLine(bool active, string name, string value, string comment)
{
Active = active;
Name = name;
Value = value;
Comment = comment;
}
}
public List<double[]>[] parseCfgDoubleTable(string table)
{
List<double[]>[] data = new List<double[]>[] { new List<double[]>(), new List<double[]>() };
List<double[]> table1 = new List<double[]>();
List<double[]> table2 = new List<double[]>();
foreach (string value in table.Split(','))
{
string[] values = value.Trim().Split(':');
if (values.Length == 3)
{
Double.TryParse(values[0], out double res0);
Double.TryParse(values[1], out double res1);
Double.TryParse(values[2], out double res2);
table1.Add(new double[] { res0, res1 });
table2.Add(new double[] { res0, res2 });
}
}
data[0] = table1;
data[1] = table2;
return data;
}
}
}
<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
namespace msfsLegacyImporter
{
class jsonHelper
{
public Dictionary<string, string> importerSettings;
public void createManifest(MainWindow parent, string SourceFolder, string TargetFolder, string[] data)
{
try
{
if (!Directory.Exists(TargetFolder + "SimObjects\\AIRPLANES\\")) { Directory.CreateDirectory(TargetFolder + "SimObjects\\AIRPLANES\\"); }
}
catch (Exception ex)
{
MessageBox.Show("Unable to create target folder." + Environment.NewLine + "Error message: " + Environment.NewLine + ex.Message);
return;
}
// COPY FSX FILES TO MSFS
string json;
try
{
string sourceChild = new DirectoryInfo(SourceFolder).Name;
Console.WriteLine(SourceFolder + " - " + TargetFolder + "SimObjects\\AIRPLANES\\" + sourceChild + "\\");
CloneDirectory(SourceFolder, TargetFolder + "SimObjects\\AIRPLANES\\" + sourceChild + "\\");
Manifest manifest = new Manifest(new Dependencies[] { }, data[1], data[2], data[3], data[4], data[5], data[6], new ReleaseNotes(new Neutral("", "")));
// READ ALIASES
var cfgFiles = Directory.EnumerateFiles(TargetFolder + "SimObjects\\AIRPLANES\\" + sourceChild + "\\", "*.cfg", SearchOption.AllDirectories);
foreach (var file in cfgFiles)
{
cfgHelper.CfgFile cfgFile;
List<cfgHelper.CfgLine> cfgLines;
if (File.Exists(file))
{
string content = File.ReadAllText(file);
cfgLines = parent.CfgHelper.readCSV(content + "\r\n[]");
cfgFile = parent.CfgHelper.parseCfg(file, cfgLines);
foreach (var cfgSection in cfgFile.Sections)
{
if (cfgSection.Name == "[FLTSIM]")
{
foreach (var alias in cfgSection.Lines)
{
if (alias.Name == "alias") // copy alias files
{
Console.WriteLine("Processing alias from " + SourceFolder + "\\.." + alias.Value + " to " + System.IO.Path.GetDirectoryName(file));
try {
CloneDirectory(SourceFolder + "\\..\\" + alias.Value, System.IO.Path.GetDirectoryName(file));
}
catch (Exception ex)
{
MessageBox.Show("Unable to process alias files from " + SourceFolder + "\\..\\" + alias.Value +Environment.NewLine + "Error message: " + Environment.NewLine + ex.Message);
}
}
}
}
}
}
}
json = JsonConvert.SerializeObject(manifest, Newtonsoft.Json.Formatting.Indented);
}
catch (Exception ex)
{
MessageBox.Show("Unable to copy FSX files." + Environment.NewLine + "Error message: " + Environment.NewLine + ex.Message);
return;
}
try { File.WriteAllText(TargetFolder + "manifest.json", json); }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Can't write into file " + TargetFolder + "\\manifest.json");
return;
}
// GENERATE LAYOUT FILE
scanTargetFolder(TargetFolder);
// SET CURRENT AIRCRAFT
parent.setAircraftDirectory(TargetFolder.Remove(TargetFolder.Length - 1));
}
public void createInstrumentManifest(string TargetFolder, string[] data)
{
Manifest manifest = new Manifest(new Dependencies[] { new Dependencies("fs-base-ui", "0.1.10") } , data[1], data[2], data[3], data[4], data[5], data[6], new ReleaseNotes(new Neutral("", "")));
string json = JsonConvert.SerializeObject(manifest, Newtonsoft.Json.Formatting.Indented);
try { File.WriteAllText(TargetFolder + "manifest.json", json); }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Can't write into file " + TargetFolder + "\\manifest.json");
return;
}
}
public int scanTargetFolder(string TargetFolder)
{
int i = 0;
if (TargetFolder != "")
{
Content[] array = new Content[10000000];
// ADD MANIFEST AT THE TOP
string[] parentDirectory = new string[] { TargetFolder };
string[] subDirectories = Directory.GetDirectories(TargetFolder, "*", SearchOption.AllDirectories).Where(x => !x.Contains("\\.")).ToArray();
subDirectories = parentDirectory.Concat(subDirectories).ToArray();
foreach (var subdir in subDirectories)
{
string folderName = subdir.Split('\\').Last().ToLower().Trim();
if (folderName.Length > 0 && folderName[0] != '.')
{
var txtFiles = Directory.EnumerateFiles(subdir, "*.*", SearchOption.TopDirectoryOnly);
foreach (string currentFile in txtFiles)
{
if (System.IO.Path.GetFileName(currentFile)[0] != '.' && System.IO.Path.GetExtension(currentFile).ToLower() != "json" && System.IO.Path.GetExtension(currentFile).ToLower() != "exe"
&& System.IO.Path.GetExtension(currentFile).ToLower() != "zip" && System.IO.Path.GetExtension(currentFile).ToLower() != "rar" && System.IO.Path.GetExtension(currentFile).ToLower() != "7z"
&& System.IO.Path.GetExtension(currentFile).ToLower() != "dll" && System.IO.Path.GetExtension(currentFile).ToLower() != "gau")
{
FileInfo info = new System.IO.FileInfo(currentFile);
array[i] = new Content(currentFile.Replace(TargetFolder, "").Replace("\\", "/").Trim('/'), info.Length, info.LastWriteTimeUtc.ToFileTimeUtc());
i++;
}
}
}
}
// CLEAR UNUSED ARRAY ITEMS
Content[] truncArray = new Content[i];
Array.Copy(array, truncArray, truncArray.Length);
// ENCODE AND SAVE JSON
ParentContent obj = new ParentContent(truncArray);
string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
try { File.WriteAllText(TargetFolder + "\\layout.json", json); }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Can't write into file " + TargetFolder + "\\layout.json");
return 0;
}
}
return i;
}
private static void CloneDirectory(string root, string dest)
{
foreach (var directory in Directory.GetDirectories(root))
{
string dirName = System.IO.Path.GetFileName(directory);
if (!Directory.Exists(System.IO.Path.Combine(dest, dirName)))
{
Directory.CreateDirectory(System.IO.Path.Combine(dest, dirName));
}
CloneDirectory(directory, System.IO.Path.Combine(dest, dirName));
}
foreach (var file in Directory.GetFiles(root))
{
File.Copy(file, System.IO.Path.Combine(dest, System.IO.Path.GetFileName(file)), true);
}
}
public void loadSettings()
{
importerSettings = new Dictionary<string, string>();
if (File.Exists("msfsLegacyImporter.json"))
{
try
{
JsonConvert.PopulateObject(File.ReadAllText("msfsLegacyImporter.json"), importerSettings);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public void saveSettings()
{
try
{
File.WriteAllText("msfsLegacyImporter.json", JsonConvert.SerializeObject(importerSettings));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public class Dependencies
{
public string name { get; set; }
public string package_version { get; set; }
public Dependencies(string Name, string Package_version)
{
name = Name;
package_version = Package_version;
}
}
public class Manifest
{
public Dependencies[] dependencies { get; set; }
public string content_type { get; set; }
public string title { get; set; }
public string manufacturer { get; set; }
public string creator { get; set; }
public string package_version { get; set; }
public string minimum_game_version { get; set; }
public ReleaseNotes release_notes { get; set; }
public Manifest(Dependencies[] Dependencies, string Content_type, string Title, string Manufacturer, string Creator,
string Package_version, string Minimum_game_version, ReleaseNotes Release_notes)
{
dependencies = Dependencies;
content_type = Content_type;
title = Title;
manufacturer = Manufacturer;
creator = Creator;
package_version = Package_version;
minimum_game_version = Minimum_game_version;
release_notes = Release_notes;
}
}
public class ReleaseNotes
{
public Neutral neutral { get; set; }
public ReleaseNotes(Neutral Neutral)
{
neutral = Neutral;
}
}
public class Neutral
{
public string LastUpdate { get; set; }
public string OlderHistory { get; set; }
public Neutral(string lastUpdate, string olderHistory )
{
LastUpdate = lastUpdate;
OlderHistory = olderHistory;
}
}
public class ParentContent
{
public Content[] content { get; set; }
public ParentContent(Content[] Content)
{
content = Content;
}
}
public class Content
{
public string path { get; set; }
public long size { get; set; }
public long date { get; set; }
public Content(string Path, long Size, long Date)
{
path = Path;
size = Size;
date = Date;
}
}
}
<file_sep>namespace fs2020LegacyImporter.Properties
{
internal class Resources
{
}
}<file_sep>using System.Windows.Forms;
namespace msfsLegacyImporter
{
class fileDialogHelper
{
public string getFolderPath(string defaultPath)
{
FolderBrowserDialog diag = new FolderBrowserDialog();
diag.Description = "Select folder";
diag.SelectedPath = defaultPath;
if (System.Windows.Forms.DialogResult.OK == diag.ShowDialog())
return diag.SelectedPath;
else
return "";
}
}
}
<file_sep>using ICSharpCode.SharpZipLib.Zip;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
namespace msfsLegacyImporter
{
class Extract
{
public Extract()
{
}
public void Run(string TEMP_FILE, string EXE_PATH, string targetDir)
{
BackgroundWorker bgw = new BackgroundWorker
{
WorkerReportsProgress = true
};
bgw.DoWork += new DoWorkEventHandler(
delegate (object o, DoWorkEventArgs args) {
BackgroundWorker bw = o as BackgroundWorker;
FastZip fastZip = new FastZip();
Console.WriteLine("Unzipping");
fastZip.ExtractZip(TEMP_FILE, targetDir, FastZip.Overwrite.Always, null, @"-(ICSharpCode.SharpZipLib.dll)", null, false);
});
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
delegate (object o, RunWorkerCompletedEventArgs args) {
//((MainWindow)System.Windows.Application.Current.MainWindow).setUpdateReady();
if (!String.IsNullOrEmpty(EXE_PATH))
{
if (File.Exists(EXE_PATH))
{
Process.Start(EXE_PATH);
Environment.Exit(0);
}
else
{
MessageBox.Show("Update failed, but you can extract temp.zip manually");
File.Move(EXE_PATH + ".BAK", EXE_PATH);
}
}
});
bgw.RunWorkerAsync();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace msfsLegacyImporter
{
class fsxVarHelper
{
public string fsx2msfsSimVar(string fsxSimVar, xmlHelper XmlHelper, bool returnVariable, string globalVars)
{
Console.WriteLine("globalVars: " + globalVars);
fsxSimVar = Regex.Replace(fsxSimVar, "\r\n|\r|\n", " ");
fsxSimVar = Regex.Replace(fsxSimVar, @"\s\s+", " ");
fsxSimVar = fsxSimVar.Replace(")!", ") !").Replace(">", ">").Replace("<", "<").Replace("&", "&");
string fsxVariable = fsxSimVar;
List<string[]> variables = new List<string[]>();
// REPLACE VARIABLES
Random r = new Random();
var regex = new Regex(@"\((.*?)\)");
foreach (var match in regex.Matches(fsxVariable))
{
if (match.ToString().Trim().StartsWith("(>") || match.ToString().Trim().StartsWith("( >")) // SET VARIABLE GAP
{
//variables.Add(new string[] { match.ToString(), "SETVARPLACEHOLDER" });
fsxVariable = fsxVariable.Replace(match.ToString(), "SETVARPLACEHOLDER");
}
else
{
string placeholder = r.Next(1000000, 9000000).ToString();
variables.Add(new string[] { match.ToString(), placeholder });
fsxVariable = fsxVariable.Replace(match.ToString(), placeholder);
}
}
// PARSE FSX FORMULA
string infix = PostfixToInfix(fsxVariable, XmlHelper);
// INSERT VARIABLES
if (!String.IsNullOrEmpty(infix))
{
infix = infix.Replace("SETVARPLACEHOLDER", "1");
// VALIDATE
string JSResult = "";
if (globalVars != "False") {
JSResult = "0";
try
{
var engine = new Jint.Engine();
JSResult = engine.Execute(globalVars + infix).GetCompletionValue().ToString();
XmlHelper.writeLog("JS validatio result: " + JSResult);
}
catch (Exception ex)
{
XmlHelper.writeLog("JS validation exception: " + ex.Message);
}
}
foreach (string[] variable in variables)
{
string msfsVariable = getMsfsVariable(variable[0], XmlHelper);
infix = infix.Replace(variable[1], msfsVariable);
}
// REMOVE TRALING SYMBOLS
infix = infix.Trim();
if (infix[infix.Length - 1] == '+' || infix[infix.Length - 1] == '*' || infix[infix.Length - 1] == '/' || infix[infix.Length - 1] == '-')
infix = infix.Substring(infix.Length - 1).Trim();
XmlHelper.writeLog("Expression: " + fsxSimVar);
XmlHelper.writeLog("Parsing result: " + infix + Environment.NewLine);
if (!String.IsNullOrEmpty(infix))
{
if (JSResult == "0" || JSResult == "False")
return "var ExpressionResult = 0; /* POSSIBLE JS ERROR \"" + fsxSimVar + "\" */";
if (returnVariable)
return "var ExpressionResult = " + infix + "; /* PARSED FROM \"" + fsxSimVar + "\" */";
else
return infix;
}
}
XmlHelper.writeLog("NOT PARSED " + fsxSimVar + Environment.NewLine);
if (returnVariable)
return "var ExpressionResult = 0; /* SIM VAR \"" + fsxSimVar + "\" NOT PARSED! */";
else
return "0";
}
public string fsx2msfsGaugeString(string gaugeTextString, xmlHelper XmlHelper, string globalVars)
{
string gaugeString = Regex.Replace(gaugeTextString, "\r\n|\r|\n", " ");
gaugeString = gaugeString./*Replace(") %", ")%").Replace("% (", "%(").*/Replace(")%(", ")%%(").Trim();
XmlHelper.writeLog("### Gauge String: " + gaugeString);
List<string[]> gaugeScripts = new List<string[]>();
// EXTRACT SCRIPTS
int counter = 0;
Random r = new Random();
var regex = new Regex(@"((\%\s*\(.+?\)\s*\%)(![0-9a-z\.\-\+ ]+?!)?[\%]{0,1}.*?)?");
foreach (Match script in regex.Matches(gaugeString))
{
if (string.IsNullOrEmpty(script.Value))
continue;
XmlHelper.writeLog("Group: " + script.Value);
string[] gaugeData = new string[4];
foreach (var group in script.Groups) {
int num = counter % 4;
XmlHelper.writeLog("Script part #" + num + ": " + group.ToString());
gaugeData[num] = group.ToString();
if (num == 1)
{
if (!string.IsNullOrEmpty(group.ToString()))
{
string placeholder = "scriptPlaceholder" + r.Next(100000, 900000).ToString();
gaugeString = gaugeString.Replace(group.ToString(), placeholder);
gaugeData[0] = placeholder;
} else
{
gaugeData[0] = "";
}
}
else if (num == 3 && !string.IsNullOrEmpty(gaugeData[0]))
{
gaugeScripts.Add(gaugeData);
}
counter++;
}
}
// ECAPE PLAIN TEXT
string newGaugeString = "";
if (gaugeString.Contains("scriptPlaceholder"))
{
var regex1 = new Regex(@"scriptPlaceholder[0-9]{6}");
var placeholdersList = regex1.Matches(gaugeString);
int i = 0;
foreach (string line in Regex.Split(gaugeString, @"scriptPlaceholder[0-9]{6}"))
{
if (!String.IsNullOrEmpty(line))
{
XmlHelper.writeLog("Line: " + line + "; Current: " + newGaugeString);
//gaugeString = gaugeString.Replace(line, "\"" + line + "\" + ");
newGaugeString += "\"" + line + "\" + ";
}
if (i < placeholdersList.Count)
newGaugeString += placeholdersList[i].ToString();
i++;
}
}
if (newGaugeString == "")
newGaugeString = "\"" + gaugeString + "\"";
// REPLACE WEIRD VALUES LIKE %R%
newGaugeString = Regex.Replace(newGaugeString, @"\%([A-Za-z])\%", "$1");
// INSERT EXPRESSIONS
foreach (string[] gaugeScript in gaugeScripts)
{
string placeholder = gaugeScript[0];
string msfsVariable = gaugeScript[2];
string formattingValue = gaugeScript[3].Trim('!').Trim();
XmlHelper.writeLog("placeholder: " + placeholder + "; msfsVariable: " + msfsVariable + "; formattingValue: " + formattingValue);
if (!string.IsNullOrEmpty(msfsVariable))
{
string textvar = Regex.Replace(msfsVariable, @"\%\s?\(?(.*)\)\s?\%", "$1").Trim();
msfsVariable = "( " + fsx2msfsSimVar(textvar, XmlHelper, false, globalVars) + " )";
XmlHelper.writeLog("Processing SimVar: " + textvar);
XmlHelper.writeLog("SimVar result: " + msfsVariable);
if (!String.IsNullOrEmpty(formattingValue))
{
if (formattingValue.Contains("s")) // STRING
{
}
else if (formattingValue.Contains("d"))
{ // DIGIT
if (formattingValue.Contains("-"))
msfsVariable = "Math.min(0, Math.round" + msfsVariable + ")";
else if (formattingValue.Contains("+"))
msfsVariable = "Math.max(0, Math.round" + msfsVariable + ")";
else
msfsVariable = "Math.round" + msfsVariable + "";
}
else if (formattingValue.Contains("f")) // FLOAT
{
formattingValue = formattingValue.Replace("f", "");
if (formattingValue.Contains("."))
msfsVariable = msfsVariable + ".toFixed(" + (formattingValue.Split('.')[1]) + ")";
}
}
//Console.WriteLine("Replacing " + gaugeScript[0] + " in " + newGaugeString);
newGaugeString = newGaugeString.Replace(gaugeScript[0], msfsVariable + ".toString() + ");
}
else if (!string.IsNullOrEmpty(placeholder))
{
newGaugeString = newGaugeString.Replace(placeholder, "");
}
}
newGaugeString = newGaugeString.Trim().Trim('+');
/*// REPLACE STRING LOGIC ON CODE
newGaugeString = Regex.Replace(newGaugeString, @"({\s*if\s*})", "{if}");
newGaugeString = Regex.Replace(newGaugeString, @"({\s*else\s*})", "{else}");
newGaugeString = Regex.Replace(newGaugeString, @"({\s*end\s*})", "{end}");
// {if} {else} {end}
// if{ }els{ }
string[] delim = {@"\{if\}", @"\{else\}", @"\{end\}"};
string final = "";
var results = Regex.Split(newGaugeString, "({if}|{else}|{end})");
foreach (var result in results)
{
XmlHelper.writeLog("Final split part: " + result + Environment.NewLine);
int ifs = 0;
int elses = 0;
if (result == "{if}")
{
ifs++;
final = Regex.Replace(final, "(\" \\+ )|(\\+ \")", "");
final = "( " + final + " ) ? ( ";
}
else if (result == "{else}")
{
elses++;
final = Regex.Replace(final, "(\" \\+ )|(\\+ \")", "");
final = final + ") : (";
}
else if (result == "{end}") {
final = Regex.Replace(final, "(\" \\+ )|(\\+ \")", "");
if (ifs == elses)
{
final = final + " )";
ifs--;
elses--;
} else
{
final = final + ") : \"\" ";
ifs--;
}
}
else
final += result;
}
XmlHelper.writeLog("Final split result: " + final + Environment.NewLine);
*/
// {if}GPS%{else}DME%{end}
// (P:Units of measure, enum) 2 == if{ (A:Indicated Altitude:1, meters) } els{ (A:Indicated Altitude:1, feet) } 10000 % 1000 / int
// DME % ((A: NAV1 DME, nmiles) 999 min 0 max s1 0 >=)% if{ % (l1 100 >=)% if{ % (l1) % !d! % } els{ % (l1) % !0.1f! % } % } els{ ----% }
XmlHelper.writeLog("### Result: " + newGaugeString + Environment.NewLine);
// %((A:Kohlsman setting hg,millibars))%!6.2f! mb
// %\((.*?)\)%\!.*\!|%\((.*?)\)%
return newGaugeString;
}
private string getMsfsVariable(string fsxVariable, xmlHelper XmlHelper)
{
string fsxVar = fsxVariable.Trim().Replace("( ", "(").Replace(" )", ")").Replace(" ,", ",").Replace(", ", ",").Replace("{ ", "{").
Replace(" {", "{").Replace("} ", "}").Replace(" }", "}").Replace(": ", ":").Replace(" :", ":").Replace(", ", ",").Replace(" ,", ",");
switch (fsxVar)
{
case string hk when hk.Equals("(P:Units of measure,enum)", StringComparison.InvariantCultureIgnoreCase):
return "1";
// 0 = ok, 1 = fail, 2 = blank.
case string ha when ha.Equals("(A:PARTIAL PANEL ADF,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hb when hb.Equals("(A:PARTIAL PANEL AIRSPEED,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hc when hc.Equals("(A:PARTIAL PANEL ALTIMETER,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hd when hd.Equals("(A:PARTIAL PANEL ATTITUDE,enum)", StringComparison.InvariantCultureIgnoreCase):
case string he when he.Equals("(A:PARTIAL PANEL COMM,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hf when hf.Equals("(A:PARTIAL PANEL COMPASS,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hg when hg.Equals("(A:PARTIAL PANEL ELECTRICAL,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hh when hh.Equals("(A:PARTIAL PANEL AVIONICS,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hi when hi.Equals("(A:PARTIAL PANEL ENGINE,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hj when hj.Equals("(A:PARTIAL PANEL FUEL INDICATOR,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:PARTIAL PANEL HEADING,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:PARTIAL PANEL VERTICAL VELOCITY,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hm when hm.Equals("(A:PARTIAL PANEL TRANSPONDER,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hn when hn.Equals("(A:PARTIAL PANEL NAV,enum)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:PARTIAL PANEL PITOT,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:PARTIAL PANEL TURN COORDINATOR,enum)", StringComparison.InvariantCultureIgnoreCase):
case string hq when hq.Equals("(A:PARTIAL PANEL VACUUM,enum)", StringComparison.InvariantCultureIgnoreCase):
case string fj when fj.Equals("(L:HUD Power,bool)", StringComparison.InvariantCultureIgnoreCase):
case string fk when fk.Equals("(L:VectorOnGlass,enum)", StringComparison.InvariantCultureIgnoreCase):
return "0";
case string fi when fi.Equals("(A:Avionics master switch,bool)", StringComparison.InvariantCultureIgnoreCase):
case string hn when hn.Equals("(A:CIRCUIT AVIONICS ON,bool)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:PARTIAL PANEL AVIONICS,bool)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:PARTIAL PANEL COMPASS,bool)", StringComparison.InvariantCultureIgnoreCase):
case string hq when hq.Equals("(A:PARTIAL PANEL ELECTRICAL,bool)", StringComparison.InvariantCultureIgnoreCase):
case string hr when hr.Equals("(A:PARTIAL PANEL HEADING,bool)", StringComparison.InvariantCultureIgnoreCase):
case string hs when hs.Equals("(A:PARTIAL PANEL NAV:1,bool)", StringComparison.InvariantCultureIgnoreCase):
case string ht when ht.Equals("(A:PARTIAL PANEL NAV:2,bool)", StringComparison.InvariantCultureIgnoreCase):
case string hu when hu.Equals("(A:Circuit general panel on,bool)", StringComparison.InvariantCultureIgnoreCase):
return "1";
// HORIZONTAL
case string hn when hn.Equals("(A:Airspeed select indicated or true,knots)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Airspeed select indicated or true:1,knots)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Airspeed select indicated or true:2,knots)", StringComparison.InvariantCultureIgnoreCase):
case string hq when hq.Equals("(A:Airspeed true,knots)", StringComparison.InvariantCultureIgnoreCase):
case string hr when hr.Equals("(A:AIRSPEED BARBER POLE,knots)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AIRSPEED TRUE\", \"knots\")";
case string hp when hp.Equals("(A:Airspeed select indicated or true,k/h)", StringComparison.InvariantCultureIgnoreCase):
case string hq when hq.Equals("(A:Airspeed select indicated or true,kilometers per hour)", StringComparison.InvariantCultureIgnoreCase):
case string hr when hr.Equals("(A:Airspeed true,k/h)", StringComparison.InvariantCultureIgnoreCase):
case string hs when hs.Equals("(A:Airspeed true,kilometers per hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AIRSPEED TRUE\", \"mph\")";
case string hp when hp.Equals("(A:Airspeed select indicated or true,mph)", StringComparison.InvariantCultureIgnoreCase):
case string hq when hq.Equals("(A:Airspeed select indicated or true,miles per hour)", StringComparison.InvariantCultureIgnoreCase):
case string hr when hr.Equals("(A:Airspeed true,mph)", StringComparison.InvariantCultureIgnoreCase):
case string hs when hs.Equals("(A:Airspeed true,miles per hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AIRSPEED TRUE\", \"mph\")";
case string hp when hp.Equals("(A:Airspeed indicated,knots)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AIRSPEED INDICATED\", \"knots\")";
case string hn when hn.Equals("(A:AIRSPEED INDICATED,mph)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AIRSPEED INDICATED\", \"mph\")";
case string hn when hn.Equals("(A:AIRSPEED INDICATED,k/h)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:AIRSPEED INDICATED,kilometers per hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AIRSPEED INDICATED\", \"kilometers per hour\")";
case string hn when hn.Equals("(A:Airspeed mach,machs)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Airspeed mach,mach)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AIRSPEED TRUE\", \"mach\")";
case string hn when hn.Equals("(A:ACCELERATION BODY X,feet per second squared)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ACCELERATION WORLD X\", \"feet per second squared\")";
case string hn when hn.Equals("(A:ACCELERATION BODY Y,feet per second squared)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ACCELERATION WORLD Y\", \"feet per second squared\")";
case string hn when hn.Equals("(A:ACCELERATION BODY Z,feet per second squared)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ACCELERATION WORLD Z\", \"feet per second squared\")";
case string hn when hn.Equals("(A:ACCELERATION BODY X,feet per minute squared)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ACCELERATION WORLD X\", \"feet per minute squared\")";
case string hn when hn.Equals("(A:ACCELERATION BODY Y,feet per minute squared)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ACCELERATION WORLD Y\", \"feet per minute squared\")";
case string hn when hn.Equals("(A:ACCELERATION BODY Z,feet per minute squared)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ACCELERATION WORLD Z\", \"feet per minute squared\")";
case string hn when hn.Equals("(A:VELOCITY WORLD X,m/s)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VELOCITY WORLD X\", \"meter per second\")";
case string hn when hn.Equals("(A:VELOCITY WORLD X,knots)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VELOCITY WORLD X\", \"knots\")";
case string hn when hn.Equals("(A:VELOCITY WORLD Y,m/s)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VELOCITY WORLD Y\", \"meter per second\")";
case string hn when hn.Equals("(A:VELOCITY WORLD Y,knots)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VELOCITY WORLD Y\", \"knots\")";
case string hn when hn.Equals("(A:VELOCITY WORLD Z,m/s)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:VELOCITY WORLD Z,meters per second)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VELOCITY WORLD Z\", \"meter per second\")";
case string hn when hn.Equals("(A:VELOCITY WORLD Z,knots)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VELOCITY WORLD Z\", \"knots\")";
case string hn when hn.Equals("(A:GROUND VELOCITY,m/s)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:GROUND VELOCITY,meters per second)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:GPS Ground Speed,meters per second)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GPS GROUND SPEED\", \"meter per second\")";
case string hn when hn.Equals("(A:GROUND VELOCITY,knots)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:GPS Ground Speed,knots)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GPS GROUND SPEED\", \"knots\")";
// VERTICAL
case string hn when hn.Equals("(A:Vertical speed,feet per minute)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VERTICAL SPEED\", \"feet per minute\")";
case string hn when hn.Equals("(A:Vertical speed,meters per minute)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VERTICAL SPEED\", \"meters per minute\")";
case string hn when hn.Equals("(A:Vertical speed,meters per second)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"VERTICAL SPEED\", \"meters per second\")";
case string hn when hn.Equals("(A:Indicated Altitude,meters)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Indicated Altitude:1,meters)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Indicated Altitude:2,meters)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"INDICATED ALTITUDE\", \"meters\")";
case string hp when hp.Equals("(A:PLANE ALTITUDE,nmiles)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"INDICATED ALTITUDE\", \"nautical miles\")";
case string hn when hn.Equals("(A:Indicated Altitude,feet)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Indicated Altitude:1,feet)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Indicated Altitude:2,feet)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"INDICATED ALTITUDE\", \"feet\")";
case string hn when hn.Equals("(A:Variometer rate,knots)", StringComparison.InvariantCultureIgnoreCase):
//return "SimVar.GetSimVarValue(\"AIRCRAFT WIND Y\", \"knots\")"; // TODO: fix rate
//return "SimVar.GetSimVarValue(\"ACCELERATION BODY Y\", \"feet per second squared\");";
return "SimVar.GetSimVarValue(\"VERTICAL SPEED\", \"feet per minute\") / 101 + SimVar.GetSimVarValue(\"ACCELERATION WORLD Z\", \"feet per minute squared\")";
case string hn when hn.Equals("(A:RADIO HEIGHT,meters)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"RADIO HEIGHT\", \"meters\")";
case string hn when hn.Equals("(A:RADIO HEIGHT,feet)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"RADIO HEIGHT\", \"feet\")";
case string hn when hn.Equals("(A:DECISION HEIGHT,feet)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"DECISION HEIGHT\", \"feet\")";
case string hn when hn.Equals("(A:DECISION HEIGHT,meters)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"DECISION HEIGHT\", \"meters\")";
case string hn when hn.Equals("(A:G force,G force)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:G force,Gforce)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"G FORCE\", \"GForce\")";
case string hn when hn.Equals("(A:Min G force,Gforce)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Min G force,G force)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"MIN G FORCE\", \"GForce\")";
case string hn when hn.Equals("(A:MaxG force,Gforce)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:MaxG force,G force)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"MAX G FORCE\", \"GForce\")";
// ATTITUDE
case string hn when hn.Equals("(A:TURN COORDINATOR BALL,percent)", StringComparison.InvariantCultureIgnoreCase):
return "Math.min(30, Math.max(-30 , -SimVar.GetSimVarValue(\"PLANE BANK DEGREES\", \"degree\"))) / 30 * 100";
case string hn when hn.Equals("(A:Delta Heading Rate,rpm)", StringComparison.InvariantCultureIgnoreCase):
return "-SimVar.GetSimVarValue(\"TURN INDICATOR RATE\", \"degree per second\") * 60 / 360";
case string hn when hn.Equals("(A:Wiskey compass indication degrees,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Magnetic compass,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:PLANE HEADING DEGREES MAGNETIC,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE HEADING DEGREES MAGNETIC\", \"degrees\")";
case string hm when hm.Equals("(A:Wiskey compass indication degrees,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hn when hn.Equals("(A:Magnetic compass,radians)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:PLANE HEADING DEGREES MAGNETIC,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE HEADING DEGREES MAGNETIC\", \"radians\")";
case string hn when hn.Equals("(A:Plane heading degrees gyro,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:heading indicator,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hm when hm.Equals("(A:heading indicator:1,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:heading indicator:2,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE HEADING DEGREES TRUE\", \"degrees\")";
case string hn when hn.Equals("(A:PLANE HEADING DEGREES GYRO,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:heading indicator,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hm when hm.Equals("(A:heading indicator:1,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:heading indicator:2,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE HEADING DEGREES TRUE\", \"radians\")";
case string hn when hn.Equals("(A:Autopilot heading lock dir,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT HEADING LOCK DIR\", \"degrees\")";
case string hn when hn.Equals("(A:RUDDER TRIM PCT,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"RUDDER TRIM PCT\", \"percent\")";
case string hn when hn.Equals("(A:ELEVATOR TRIM POSITION,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ELEVATOR TRIM PCT\", \"percent\")";
case string hn when hn.Equals("(A:Attitude indicator bank degrees,radians)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:PLANE BANK DEGREES,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE BANK DEGREES\", \"radians\")";
case string ho when ho.Equals("(A:PLANE BANK DEGREES,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE BANK DEGREES\", \"degree\")";
case string hn when hn.Equals("(A:Attitude indicator bank degrees,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE BANK DEGREES\", \"degree\")";
case string hn when hn.Equals("(A:Attitude indicator bank degrees:1,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE BANK DEGREES\", \"degree\")";
case string hn when hn.Equals("(A:Attitude indicator bank degrees,radians)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Attitude indicator bank degrees:1,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Attitude indicator bank degrees:2,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE BANK DEGREES\", \"radians\")";
case string hn when hn.Equals("(A:Attitude indicator pitch degrees,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Attitude indicator pitch degrees:1,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Attitude indicator pitch degrees:2,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hq when hq.Equals("(A:PLANE PITCH DEGREES,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE PITCH DEGREES\", \"degree\")";
case string hn when hn.Equals("(A:PLANE HEADING DEGREES GYRO,radians)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Plane heading degrees true,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE HEADING DEGREES TRUE\", \"radians\")";
// AMBIENT
case string hn when hn.Equals("(A:AMBIENT TEMPERATURE,Celsius)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Total air temperature,Celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AMBIENT TEMPERATURE\", \"celsius\")";
case string hn when hn.Equals("(A:Ambient Wind Direction,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AMBIENT WIND DIRECTION\", \"degree\")";
case string hn when hn.Equals("(A:Ambient Wind VELOCITY,knots)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AMBIENT WIND VELOCITY\", \"knots\")";
case string hn when hn.Equals("(A:Ambient Wind VELOCITY,kilometers per hour)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Ambient Wind VELOCITY,kilometer/hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AMBIENT WIND VELOCITY\", \"kilometers per hour\")";
case string hn when hn.Equals("(A:Ambient Wind VELOCITY,mph)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AMBIENT WIND VELOCITY\", \"mph\")";
case string hn when hn.Equals("(A:AMBIENT VISIBILITY,nmiles)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AMBIENT VISIBILITY\", \"nautical mile\")";
case string hn when hn.Equals("(A:Kohlsman setting hg,inHg)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"KOHLSMAN SETTING HG\", \"inches of mercury\")";
case string ho when ho.Equals("(A:Kohlsman setting hg:1,inHg)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"KOHLSMAN SETTING HG:1\", \"inches of mercury\")";
case string ho when ho.Equals("(A:Kohlsman setting hg:2,inHg)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"KOHLSMAN SETTING HG:2\", \"inches of mercury\")";
case string hn when hn.Equals("(A:Kohlsman setting hg,mbar)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"KOHLSMAN SETTING HG\", \"Millibars\")";
case string ho when ho.Equals("(A:Kohlsman setting hg:1,mbar)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"KOHLSMAN SETTING HG:1\", \"Millibars\")";
case string ho when ho.Equals("(A:Kohlsman setting hg:2,mbar)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"KOHLSMAN SETTING HG:2\", \"Millibars\")";
case string hn when hn.Equals("(P:Local time,seconds)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetGlobalVarValue(\"LOCAL TIME\", \"seconds\")";
case string hn when hn.Equals("(P:Local time,minutes)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetGlobalVarValue(\"LOCAL TIME\", \"minutes\")";
case string hn when hn.Equals("(P:Local time,hours)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetGlobalVarValue(\"LOCAL TIME\", \"hours\")";
case string hn when hn.Equals("(L:Zulu,bool)", StringComparison.InvariantCultureIgnoreCase):
return "0";
case string hn when hn.Equals("(P:ZULU TIME,hours)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetGlobalVarValue(\"ZULU TIME\", \"hours\")";
case string hn when hn.Equals("(P:ZULU TIME,minutes)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetGlobalVarValue(\"ZULU TIME\", \"minutes\")";
case string hn when hn.Equals("(P:Absolute time,seconds)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"E: ABSOLUTE TIME\", \"seconds\")";
// FUEL
case string hl when hl.Equals("(A:Fuel weight per gallon,pounds)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL WEIGHT PER GALLON\", \"lbs\")";
case string hk when hk.Equals("(A:fuel tank left quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank left quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank right quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank right quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank left aux quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left aux quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT AUX QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank left aux quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left aux quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT AUX QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank right aux quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right aux quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT AUX QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank right aux quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right aux quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT AUX QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank left MAIN quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left MAIN quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT MAIN QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank left MAIN quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left MAIN quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT MAIN QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank right MAIN quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right MAIN quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT MAIN QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank right MAIN quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right MAIN quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT MAIN QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank left tip quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left tip quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT TIP QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank left tip quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel left tip quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK LEFT TIP QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank right tip quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right tip quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT TIP QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank right tip quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel right tip quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK RIGHT TIP QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:fuel tank center quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel center quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK CENTER QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:fuel tank center quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:fuel center quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK CENTER QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:Fuel tank center level,position)", StringComparison.InvariantCultureIgnoreCase):
case string hl when hl.Equals("(A:Fuel center level,position)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TANK CENTER QUANTITY\", \"gallons\") / SimVar.GetSimVarValue(\"FUEL TANK CENTER CAPACITY\", \"gallons\")";
case string hk when hk.Equals("(A:Fuel total quantity,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TOTAL QUANTITY\", \"gallons\")";
case string hk when hk.Equals("(A:Fuel total quantity,liter)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TOTAL QUANTITY\", \"liters\")";
case string hk when hk.Equals("(A:FUEL TOTAL CAPACITY,gallons)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TOTAL CAPACITY\", \"gallons\")";
case string hk when hk.Equals("(A:FUEL TOTAL CAPACITY,liters)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TOTAL CAPACITY\", \"liters\")";
case string hn when hn.Equals("(A:Fuel tank total level,position)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"FUEL TOTAL QUANTITY\", \"gallons\") / SimVar.GetSimVarValue(\"FUEL TOTAL CAPACITY\", \"gallons\")";
// ENGINES
case string hn when hn.Equals("(A:SUCTION PRESSURE,inHg)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"SUCTION PRESSURE\", \"inch of mercury\")";
case string hn when hn.Equals("(A:GENERAL ENG1 OIL PRESSURE,PSI)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng1 Oil Pressure,PSI)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:1\", \"psi\")";
case string hn when hn.Equals("(A:GENERAL ENG2 OIL PRESSURE,PSI)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng2 Oil Pressure,PSI)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:2\", \"psi\")";
case string hn when hn.Equals("(A:GENERAL ENG3 OIL PRESSURE,PSI)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng3 Oil Pressure,PSI)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:3\", \"psi\")";
case string hn when hn.Equals("(A:GENERAL ENG4 OIL PRESSURE,PSI)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng4 Oil Pressure,PSI)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:4\", \"psi\")";
case string hn when hn.Equals("(A:GENERAL ENG1 OIL PRESSURE,PSF)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng1 Oil Pressure,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:1\", \"psf\")";
case string hn when hn.Equals("(A:GENERAL ENG2 OIL PRESSURE,PSF)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng2 Oil Pressure,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:2\", \"psf\")";
case string hn when hn.Equals("(A:GENERAL ENG3 OIL PRESSURE,PSF)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng3 Oil Pressure,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:3\", \"psf\")";
case string hn when hn.Equals("(A:GENERAL ENG4 OIL PRESSURE,PSF)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng4 Oil Pressure,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL PRESSURE:4\", \"psf\")";
case string hj when hj.Equals("(A:ENG1 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:GENERAL ENG1 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL TEMPERATURE:1\", \"celsius\")";
case string hj when hj.Equals("(A:ENG2 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:GENERAL ENG2 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL TEMPERATURE:2\", \"celsius\")";
case string hj when hj.Equals("(A:ENG3 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:GENERAL ENG3 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL TEMPERATURE:3\", \"celsius\")";
case string hj when hj.Equals("(A:ENG4 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:GENERAL ENG4 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL TEMPERATURE:4\", \"celsius\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:1,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:1\", \"psi\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:2,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:2\", \"psi\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:3,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:3\", \"psi\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:4,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:4\", \"psi\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:1,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:1\", \"PSF\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:2,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:2\", \"PSF\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:3,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:3\", \"PSF\")";
case string hn when hn.Equals("(A:General Eng Fuel Pressure:4,PSF)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG FUEL PRESSURE:4\", \"PSF\")";
case string hn when hn.Equals("(A:GENERAL ENG1 RPM,rpm)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG RPM:2\", \"Rpm\")";
case string hn when hn.Equals("(A:GENERAL ENG2 RPM,rpm)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG RPM:1\", \"Rpm\")";
case string hn when hn.Equals("(A:ENG1 MANIFOLD PRESSURE,inHg)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG MANIFOLD PRESSURE:1\", \"inHG\")";
case string hn when hn.Equals("(A:ENG2 MANIFOLD PRESSURE,inHg)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG MANIFOLD PRESSURE:2\", \"inHG\")";
case string hn when hn.Equals("(A:RECIP CARBURETOR TEMPERATURE:1,celsius)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:GENERAL ENG1 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG OIL TEMPERATURE:1\", \"celsius\") * 0.5";//??
case string hn when hn.Equals("(A:RECIP CARBURETOR TEMPERATURE:2,celsius)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:GENERAL ENG2 OIL TEMPERATURE,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG OIL TEMPERATURE:2\", \"celsius\") * 0.5";//??
case string hn when hn.Equals("(A:RECIP ENG CYLINDER HEAD TEMPERATURE:1,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG CYLINDER HEAD TEMPERATURE:1\", \"celsius\")";
case string hn when hn.Equals("(A:RECIP ENG CYLINDER HEAD TEMPERATURE:2,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG CYLINDER HEAD TEMPERATURE:2\", \"celsius\")";
case string hn when hn.Equals("(A:Eng1 oil quantity,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL QUANTITY:1\", \"percent\")";
case string hn when hn.Equals("(A:Eng2 oil quantity,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG OIL QUANTITY:2\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng1 N1,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng1 N1 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N1 RPM:1\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng2 N1,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng2 N1 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N1 RPM:2\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng3 N1,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng3 N1 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N1 RPM:3\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng4 N1,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng4 N1 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N1 RPM:4\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng1 N2,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng1 N2 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM:1\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng2 N2,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng2 N2 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM:2\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng3 N2,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng3 N2 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM:3\", \"percent\")";
case string hn when hn.Equals("(A:Turb eng4 N2,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng4 N2 RPM,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM:4\", \"percent\")";
case string hn when hn.Equals("(A:TURB ENG1 N1,part)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TURB ENG N1:1\", \"part\")";
case string hn when hn.Equals("(A:TURB ENG2 N1,part)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TURB ENG N1:2\", \"part\")";
case string hn when hn.Equals("(A:TURB ENG3 N1,part)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TURB ENG N1:3\", \"part\")";
case string hn when hn.Equals("(A:TURB ENG4 N1,part)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TURB ENG N1:4\", \"part\")";
case string hn when hn.Equals("(A:general eng1 throttle lever position,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG THROTTLE LEVER POSITION:1\", \"percent\")";
case string hn when hn.Equals("(A:general eng2 throttle lever position,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG THROTTLE LEVER POSITION:2\", \"percent\")";
case string hn when hn.Equals("(A:general eng3 throttle lever position,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG THROTTLE LEVER POSITION:3\", \"percent\")";
case string hn when hn.Equals("(A:general eng4 throttle lever position,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG THROTTLE LEVER POSITION:4\", \"percent\")";
case string hn when hn.Equals("(A:TURB ENG1 corrected N2,Percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM: 1\", \"percent\")";
case string hn when hn.Equals("(A:TURB ENG2 corrected N2,Percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM: 2\", \"percent\")";
case string hn when hn.Equals("(A:TURB ENG3 corrected N2,Percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM: 3\", \"percent\")";
case string hn when hn.Equals("(A:TURB ENG4 corrected N2,Percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG N2 RPM: 4\", \"percent\")";
case string hn when hn.Equals("(A:Turb Eng1 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng1 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG FUEL FLOW PPH:1\", \"Pounds per hour\")";
case string hn when hn.Equals("(A:Turb Eng2 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng2 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG FUEL FLOW PPH:2\", \"Pounds per hour\")";
case string hn when hn.Equals("(A:Turb Eng3 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng3 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG FUEL FLOW PPH:3\", \"Pounds per hour\")";
case string hn when hn.Equals("(A:Turb Eng4 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng4 Fuel Flow PPH,pounds per hour)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG FUEL FLOW PPH:4\", \"Pounds per hour\")";
case string hn when hn.Equals("(A:Hydraulic1 Pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng1 hydraulic pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Eng hydraulic pressure:1,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG HYDRAULIC PRESSURE: 1\", \"psi\")";
case string hn when hn.Equals("(A:Hydraulic2 Pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng2 hydraulic pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Eng hydraulic pressure:2,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG HYDRAULIC PRESSURE: 2\", \"psi\")";
case string hn when hn.Equals("(A:Hydraulic3 Pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng3 hydraulic pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Eng hydraulic pressure:3,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG HYDRAULIC PRESSURE: 3\", \"psi\")";
case string hn when hn.Equals("(A:Hydraulic4 Pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Eng4 hydraulic pressure,psi)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:Eng hydraulic pressure:4,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG HYDRAULIC PRESSURE: 4\", \"psi\")";
case string hn when hn.Equals("(A:General eng1 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG EXHAUST GAS TEMPERATURE: 1\", \"celsius\")";
case string hn when hn.Equals("(A:eng1 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG EXHAUST GAS TEMPERATURE:1\", \"celsius\")";
case string hn when hn.Equals("(A:General eng2 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG EXHAUST GAS TEMPERATURE: 2\", \"celsius\")";
case string hn when hn.Equals("(A:eng2 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG EXHAUST GAS TEMPERATURE:2\", \"celsius\")";
case string hn when hn.Equals("(A:General eng3 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG EXHAUST GAS TEMPERATURE: 3\", \"celsius\")";
case string hn when hn.Equals("(A:eng3 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG EXHAUST GAS TEMPERATURE:3\", \"celsius\")";
case string hn when hn.Equals("(A:General eng4 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG EXHAUST GAS TEMPERATURE: 4\", \"celsius\")";
case string hn when hn.Equals("(A:eng4 exhaust gas temperature,celsius)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG EXHAUST GAS TEMPERATURE:4\", \"celsius\")";
case string hn when hn.Equals("(A:Turb eng1 vibration,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Turb vibration:1,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG VIBRATION:1\", \"Number\") / 0.05";
case string hn when hn.Equals("(A:Turb eng2 vibration,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Turb vibration:2,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG VIBRATION:2\", \"Number\") / 0.05";
case string ho when ho.Equals("(A:Turb eng1 pressure ratio,ratio)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG PRESSURE RATIO:1\", \"ratio\")";
case string ho when ho.Equals("(A:Turb eng2 pressure ratio,ratio)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG PRESSURE RATIO:2\", \"ratio\")";
case string ho when ho.Equals("(A:Turb eng3 pressure ratio,ratio)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG PRESSURE RATIO:3\", \"ratio\")";
case string ho when ho.Equals("(A:Turb eng4 pressure ratio,ratio)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG PRESSURE RATIO:4\", \"ratio\")";
case string ho when ho.Equals("(A: Turb Eng1 Afterburner,bool)", StringComparison.InvariantCultureIgnoreCase):
return "(SimVar.GetSimVarValue(\"ENG N1 RPM:1\", \"percent\") >= 90)";
case string ho when ho.Equals("(A: Turb Eng2 Afterburner,bool)", StringComparison.InvariantCultureIgnoreCase):
return "(SimVar.GetSimVarValue(\"ENG N1 RPM:2\", \"percent\") >= 90)";
case string ho when ho.Equals("(A: Turb Eng3 Afterburner,bool)", StringComparison.InvariantCultureIgnoreCase):
return "(SimVar.GetSimVarValue(\"ENG N1 RPM:3\", \"percent\") >= 90)";
case string ho when ho.Equals("(A: Turb Eng4 Afterburner,bool)", StringComparison.InvariantCultureIgnoreCase):
return "(SimVar.GetSimVarValue(\"ENG N1 RPM:4\", \"percent\") >= 90)";
// NAV
case string hn when hn.Equals("(A:NAV GSI:1,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:NAV1 GSI,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV GSI:1\", \"percent\")";
case string hn when hn.Equals("(A:NAV GSI:2,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:NAV2 GSI,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV GSI:2\", \"percent\")";
case string hn when hn.Equals("(A:NAV GSI:1,number)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:NAV1 GSI,number)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV GSI:1\", \"number\")";
case string hn when hn.Equals("(A:NAV GSI:2,number)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:NAV2 GSI,number)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV GSI:2\", \"number\")";
case string hn when hn.Equals("(A:NAV CDI:1,number)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:NAV1 CDI,number)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV CDI:1\", \"number\")";
case string hn when hn.Equals("(A:NAV CDI:2,number)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:NAV2 CDI,number)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV CDI:2\", \"number\")";
case string hn when hn.Equals("(A:NAV ident:1,string)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav1 ident,string)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV IDENT:1\", \"string\")";
case string hn when hn.Equals("(A:NAV ident:2,string)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav2 ident,string)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV IDENT:2\", \"string\")";
case string hn when hn.Equals("(A:NAV HAS NAV:1,bool)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav1 HAS NAV,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV HAS NAV:1\", \"boolean\")";
case string hn when hn.Equals("(A:NAV HAS NAV:2,bool)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav2 HAS NAV,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV HAS NAV:2\", \"boolean\")";
case string hn when hn.Equals("(A:NAV HAS DME:1,bool)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav1 HAS DME,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV HAS DME:1\", \"boolean\")";
case string hn when hn.Equals("(A:NAV HAS DME:2,bool)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav2 HAS DME,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV HAS DME:2\", \"boolean\")";
case string hn when hn.Equals("(A:NAV DME:1,kilometers)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav1 DME,kilometers)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV DME:1\", \"kilometers\")";
case string hn when hn.Equals("(A:NAV DME:2,kilometers)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav2 DME,kilometers)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV DME:2\", \"kilometers\")";
case string hn when hn.Equals("(A:NAV DME:1,nmiles)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav1 DME,nmiles)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV DME:1\", \"nautical mile\")";
case string hn when hn.Equals("(A:NAV DME:2,nmiles)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Nav2 DME,nmiles)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV DME:2\", \"nautical mile\")";
case string hn when hn.Equals("(A:NAV1 OBS,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:NAV1 radial,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV OBS:1\", \"degrees\")";
case string hn when hn.Equals("(A:NAV2 OBS,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:NAV2 radial,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV OBS:2\", \"degrees\")";
case string hn when hn.Equals("(A:NAV1 OBS,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:NAV1 radial,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV OBS:1\", \"radians\")";
case string hn when hn.Equals("(A:NAV2 OBS,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:NAV2 radial,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV OBS:2\", \"radians\")";
case string hn when hn.Equals("(A:GPS WP TRUE BEARING,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GPS WP BEARING\", \"degree\")";
case string hn when hn.Equals("(A:GPS MAGVAR,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"MAGVAR\", \"degrees\")";
case string hn when hn.Equals("(A:NAV1 DME,nmiles)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV DME\", \"nautical miles\")";
case string hn when hn.Equals("(A:GPS WP DISTANCE,nmiles)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:GPS WP DISTANCE)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GPS WP DISTANCE\", \"nautical mile\")";
case string hn when hn.Equals("(A:PLANE LONGITUDE,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE LONGITUDE\", \"radians\")";
case string hn when hn.Equals("(A:PLANE LATITUDE,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE LATITUDE\", \"radians\")";
case string hn when hn.Equals("(A:PLANE LONGITUDE,degree)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:PLANE LONGITUDE,degree longitude)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE LONGITUDE\", \"degree longitude\")";
case string hn when hn.Equals("(A:PLANE LATITUDE,degree)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:PLANE LATITUDE,degree latitude)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PLANE LATITUDE\", \"degree latitude\")";
case string hn when hn.Equals("(A:GPS GROUND MAGNETIC TRACK,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GPS GROUND MAGNETIC TRACK\", \"degree\")";
case string ho when ho.Equals("(A:GPS WP BEARING,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GPS WP BEARING\", \"degree\")";
case string ho when ho.Equals("(A:GPS drives nav1,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GPS DRIVES NAV1\", \"boolean\")";
case string ho when ho.Equals("(A:Nav1 Active Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV ACTIVE FREQUENCY:1\", \"MHz\")";
case string ho when ho.Equals("(A:Nav1 Active Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV ACTIVE FREQUENCY:1\", \"KHz\")";
case string ho when ho.Equals("(A:Nav2 Active Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV ACTIVE FREQUENCY:2\", \"MHz\")";
case string ho when ho.Equals("(A:Nav2 Active Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV ACTIVE FREQUENCY:2\", \"KHz\")";
case string ho when ho.Equals("(A:Nav1 Standby Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV STANDBY FREQUENCY:1\", \"MHz\")";
case string ho when ho.Equals("(A:Nav1 Standby Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV STANDBY FREQUENCY:1\", \"KHz\")";
case string ho when ho.Equals("(A:Nav2 Standby Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV STANDBY FREQUENCY:2\", \"MHz\")";
case string ho when ho.Equals("(A:Nav2 Standby Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"NAV STANDBY FREQUENCY:2\", \"KHz\")";
// RADIO
case string ho when ho.Equals("(A:Com1 Active Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM ACTIVE FREQUENCY:1\", \"MHz\")";
case string ho when ho.Equals("(A:Com1 Active Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM ACTIVE FREQUENCY:1\", \"KHz\")";
case string ho when ho.Equals("(A:Com2 Active Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM ACTIVE FREQUENCY:2\", \"MHz\")";
case string ho when ho.Equals("(A:Com2 Active Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM ACTIVE FREQUENCY:2\", \"KHz\")";
case string ho when ho.Equals("(A:Com1 Standby Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM STANDBY FREQUENCY:1\", \"MHz\")";
case string ho when ho.Equals("(A:Com1 Standby Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM STANDBY FREQUENCY:1\", \"KHz\")";
case string ho when ho.Equals("(A:Com2 Standby Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM STANDBY FREQUENCY:2\", \"MHz\")";
case string ho when ho.Equals("(A:Com2 Standby Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"COM STANDBY FREQUENCY:2\", \"KHz\")";
case string hn when hn.Equals("(A:ADF radial:1,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:ADF1 radial,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF RADIAL:1\", \"radians\")";
case string hn when hn.Equals("(A:ADF radial:2,radians)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:ADF2 radial,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF RADIAL:2\", \"radians\")";
case string hn when hn.Equals("(A:ADF radial:1,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:ADF1 radial,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF RADIAL:1\", \"degrees\")";
case string hn when hn.Equals("(A:ADF radial:2,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string hk when hk.Equals("(A:ADF2 radial,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF RADIAL:2\", \"degrees\")";
case string ho when ho.Equals("(A:Adf1 Active Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:ADF active frequency:1,megahertz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF ACTIVE FREQUENCY:1\", \"MHz\")";
case string ho when ho.Equals("(A:Adf1 Active Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:ADF active frequency:1,kilohertz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF ACTIVE FREQUENCY:1\", \"KHz\")";
case string ho when ho.Equals("(A:Adf2 Active Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:ADF active frequency:2,megahertz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF ACTIVE FREQUENCY:2\", \"MHz\")";
case string ho when ho.Equals("(A:Adf2 Active Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
case string hp when hp.Equals("(A:ADF active frequency:2,kilohertz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF ACTIVE FREQUENCY:2\", \"KHz\")";
case string ho when ho.Equals("(A:Adf1 Standby Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF STANDBY FREQUENCY:1\", \"MHz\")";
case string ho when ho.Equals("(A:Adf1 Standby Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF STANDBY FREQUENCY:1\", \"KHz\")";
case string ho when ho.Equals("(A:Adf2 Standby Frequency,MHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF STANDBY FREQUENCY:2\", \"MHz\")";
case string ho when ho.Equals("(A:Adf2 Standby Frequency,KHz)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF STANDBY FREQUENCY:2\", \"KHz\")";
case string ho when ho.Equals("(A:Adf signal:1,number)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF SIGNAL:1\", \"number\")";
case string hp when hp.Equals("(A:Adf signal:2,number)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ADF SIGNAL:2\", \"number\")";
case string hp when hp.Equals("(A:ATC ID,string)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ATC ID\", \"string\")";
// CONTROLS
case string ho when ho.Equals("(A:GEAR HANDLE POSITION,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GEAR HANDLE POSITION\", \"percent\")";
case string hn when hn.Equals("(A:INCIDENCE ALPHA,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"INCIDENCE ALPHA\", \"degrees\")";
case string hn when hn.Equals("(A:Autopilot heading lock dir,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT HEADING LOCK DIR\", \"radians\")";
case string hn when hn.Equals("(A:Autopilot heading lock dir,degree)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT HEADING LOCK DIR\", \"degree\")";
case string hn when hn.Equals("(A:AUTOPILOT FLIGHT DIRECTOR ACTIVE,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT FLIGHT DIRECTOR ACTIVE\", \"boolean\")";
case string hn when hn.Equals("(A:Autopilot flight director bank,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT FLIGHT DIRECTOR BANK\", \"degree\")";
case string hn when hn.Equals("(A:Autopilot flight director bank,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT FLIGHT DIRECTOR BANK\", \"radians\")";
case string hn when hn.Equals("(A:Autopilot flight director pitch,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT FLIGHT DIRECTOR BANK\", \"degree\")";
case string hn when hn.Equals("(A:Autopilot flight director pitch,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AUTOPILOT FLIGHT DIRECTOR BANK\", \"radians\")";
case string hn when hn.Equals("(A:CG Percent,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"CG PERCENT\", \"percent\")";
case string hn when hn.Equals("(A:Pressurization Pressure Differential,psi)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PRESSURIZATION PRESSURE DIFFERENTIAL\", \"psi\")";
case string hn when hn.Equals("(A:Pressurization Cabin Altitude,feet)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PRESSURIZATION CABIN ALTITUDE\", \"feet\")";
case string hn when hn.Equals("(A:Pressurization Cabin Altitude,meters)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PRESSURIZATION CABIN ALTITUDE\", \"meters\")";
case string hn when hn.Equals("(A:Pressurization Cabin Altitude Rate,feet per minute)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PRESSURIZATION CABIN ALTITUDE RATE\", \"feet per minute\")";
case string hn when hn.Equals("(A:Pressurization Cabin Altitude Rate,meters per second)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"PRESSURIZATION CABIN ALTITUDE RATE\", \"meters per second\")";
case string hn when hn.Equals("(A:Aileron trim pct,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"AILERON TRIM PCT\", \"percent\")";
case string hn when hn.Equals("(A:MAGVAR,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"MAGVAR\", \"degree\")";
case string hn when hn.Equals("(A:Trailing edge flaps0 left angle,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Trailing edge flaps1 left angle,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TRAILING EDGE FLAPS LEFT ANGLE\", \"degrees\")";
case string hn when hn.Equals("(A:Trailing edge flaps0 left angle,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Trailing edge flaps1 left angle,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TRAILING EDGE FLAPS LEFT ANGLE\", \"percent\")";
case string hn when hn.Equals("(A:TRAILING EDGE FLAPS LEFT ANGLE,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TRAILING EDGE FLAPS LEFT ANGLE\", \"radians\")";
case string hn when hn.Equals("(A:Trailing edge flaps0 right angle,degrees)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Trailing edge flaps1 right angle,degrees)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TRAILING EDGE FLAPS RIGHT ANGLE\", \"degrees\")";
case string hn when hn.Equals("(A:Trailing edge flaps0 right angle,percent)", StringComparison.InvariantCultureIgnoreCase):
case string ho when ho.Equals("(A:Trailing edge flaps1 right angle,percent)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TRAILING EDGE FLAPS RIGHT ANGLE\", \"percent\")";
case string hn when hn.Equals("(A:TRAILING EDGE FLAPS RIGHT ANGLE,radians)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"TRAILING EDGE FLAPS RIGHT ANGLE\", \"radians\")";
// ELECTRICS
case string hn when hn.Equals("(L:Show Volts 1,bool)", StringComparison.InvariantCultureIgnoreCase):
return "1";//"SimVar.GetSimVarValue(\"ELECTRICAL MAIN BUS VOLTAGE:1\", \"volts\")";
case string hn when hn.Equals("(L:Show Volts 2,bool)", StringComparison.InvariantCultureIgnoreCase):
return "1";//SimVar.GetSimVarValue(\"ELECTRICAL MAIN BUS VOLTAGE:2\", \"volts\")";
case string hn when hn.Equals("(A:ELECTRICAL GENALT BUS VOLTAGE:1,volts)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ELECTRICAL GENALT BUS VOLTAGE:1\", \"volts\")";
case string hn when hn.Equals("(A:ELECTRICAL GENALT BUS VOLTAGE:2,volts)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ELECTRICAL GENALT BUS VOLTAGE:2\", \"volts\")";
case string hn when hn.Equals("(A:ELECTRICAL GENALT BUS AMPS:1,amps)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ELECTRICAL GENALT BUS AMPS:1\", \"amperes\")";
case string hn when hn.Equals("(A:ELECTRICAL GENALT BUS AMPS:2,amps)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ELECTRICAL GENALT BUS AMPS:2\", \"amperes\")";
case string hn when hn.Equals("(A:ELECTRICAL BATTERY BUS AMPS,amps)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ELECTRICAL BATTERY BUS AMPS\", \"amperes\")";
case string hn when hn.Equals("(A:ELECTRICAL BATTERY BUS VOLTAGE,volts)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ELECTRICAL BATTERY BUS VOLTAGE\", \"volts\")";
case string hn when hn.Equals("(A:General Eng Generator Active:1,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG GENERATOR SWITCH:1\", \"boolean\")";
case string hn when hn.Equals("(A:General Eng Generator Active:2,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG GENERATOR SWITCH:2\", \"boolean\")";
case string hn when hn.Equals("(A:General Eng Generator Active:3,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG GENERATOR SWITCH:3\", \"boolean\")";
case string hn when hn.Equals("(A:General Eng Generator Active:4,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"GENERAL ENG GENERATOR SWITCH:4\", \"boolean\")";
case string hn when hn.Equals("(A:General eng1 anti ice position,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG ANTI ICE:1\", \"boolean\")";
case string hn when hn.Equals("(A:General eng2 anti ice position,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG ANTI ICE:2\", \"boolean\")";
case string hn when hn.Equals("(A:General eng3 anti ice position,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG ANTI ICE:3\", \"boolean\")";
case string hn when hn.Equals("(A:General eng4 anti ice position,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"ENG ANTI ICE:4\", \"boolean\")";
case string hn when hn.Equals("(A:Sim On Ground,bool)", StringComparison.InvariantCultureIgnoreCase):
return "SimVar.GetSimVarValue(\"SIM ON GROUND\", \"boolean\")";
/*
-(A:Aileron Position,degrees)
-(A:Airspeed Barber Pole,knots)
+(A:AMBIENT AMBIENT VELOCITY,kilometer/hour)
-(A:Apu On Fire Detected,bool)
-(A:APU PCT RPM,part)
-(A:APU PCT RPM,percent over 100)
-(A:APU Volts,volts)
-(A:Attitude bars position,position)
-(A:Auto brake switch cb,enum)
(A:Autopilot airspeed hold var,knots)
(A:Autopilot airspeed hold,bool)
(A:AUTOPILOT ALTITUDE LOCK VAR,FEET)
(A:Autopilot altitude lock var,feet)
(A:AUTOPILOT ALTITUDE LOCK VAR,METERS)
(A:Autopilot altitude lock var,meters)
(A:AUTOPILOT ALTITUDE LOCK,bool)
(A:Autopilot altitude lock,bool)
(A:AUTOPILOT APPROACH HOLD,bool)
(A:AUTOPILOT BACKCOURSE HOLD,bool)
(A:Autopilot Glideslope Hold,bool)
(A:AUTOPILOT HEADING LOCK,bool)
(A:Autopilot heading lock,bool)
(A:Autopilot mach hold var,mach)
(A:Autopilot mach hold,bool)
(A:AUTOPILOT MASTER,bool)
(A:Autopilot master,bool)
(A:Autopilot nav1 lock,bool)
(A:Autopilot takeoff power active,bool)
(A:AUTOPILOT THROTTLE ARM,bool)
(A:AUTOPILOT VERTICAL HOLD VAR,feet per minute)
(A:Autopilot vertical hold var,feet per minute)
(A:Autopilot vertical hold var,ft/min)
(A:AUTOPILOT VERTICAL HOLD VAR,meters per minute)
-(A:AUTOTHROTTLE ACTIVE,bool)
-(A:BARBER POLE MACH,mach)
-(A:Brake Dependent Hydraulic Pressure,PSF)
-(A:BRAKE INDICATOR,enum)
(A:BRAKE LEFT POSITION,percent)
(A:BRAKE RIGHT POSITION,percent)
-(A:Electrical avionics bus voltage,volts)
(A:Electrical genalt1 bus amps,amps)
(A:ELECTRICAL GENALT1 BUS AMPS,amps)
(A:Electrical genalt2 bus amps,amps)
(A:ELECTRICAL GENALT2 BUS AMPS,amps)
(A:Electrical main bus voltage,volts)
(A:Electrical total load amps,amps)
(A:Elevator position,degrees)
(A:ELEVATOR POSITION,degrees)
(A:Eng1 fuel flow PPH:@ENGINE_NUMBER,pounds per hour)
(A:Eng1 hydraulic pressure:1,psi)
(A:Eng1 On Fire,bool)
(A:Eng2 fuel flow PPH:@ENGINE_NUMBER,pounds per hour)
(A:Eng2 hydraulic pressure:1,psi)
(A:Eng2 On Fire,bool)
(A:Eng3 On Fire,bool)
(A:Eng4 On Fire,bool)
(A:FLAPS HANDLE PERCENT,percent)
(A:fly by wire alpha protection,bool)
(A:Gear left position,percent)
(A:Gear Warning,bool)
(A:HSI CDI needle valid,bool)
(A:HSI CDI NEEDLE VALID:1,bool)
(A:HSI CDI needle,number)
(A:HSI distance,nmiles)
(A:HSI GSI needle valid,bool)
(A:HSI GSI needle,number)
(A:HSI has localizer,bool)
(A:HSI TF FLAGS,enum)
(A:INCIDENCE ALPHA,number)
(A:Inner Marker,bool)
(A:Launchbar Position,percent)
(A:Light Panel,bool)
(A:Middle Marker,bool)
(A:NAV GS FLAG:2,bool)
(A:NAV HAS GLIDE SLOPE,bool)
(A:NAV TOFROM:2,enum)
(A:Outer Marker,bool)
(A:Rudder Position,degrees)
(A:STALL ALPHA,number)
(A:Trailing Edge Flaps0 Left percent,percent)
(A:Trailing edge flaps0 left percent,percent)
(A:Turb Eng Max Torque Percent:1,part)
(A:Turb Eng Max Torque Percent:2,part)
(A:Turn coordinator ball,position)
(P:Zulu time,seconds)
*/
// TRY TO COPY 1IN1
default:
XmlHelper.writeLog("FSX variable not found: " + fsxVar);
if (fsxVar.StartsWith("(L:"))
return "1";
fsxVar = Regex.Replace(fsxVar, @"(\([A-Za-z]:)|\(|\)", "");
if (fsxVar.Contains(",") && fsxVar.Split(',').Length == 2)
{
string varname = fsxVar.Split(',')[0].Trim();
string unit = fsxVar.Split(',')[1].Trim().ToLower();
if (unit == "m/s")
unit = "meter per second";
else if (unit == "nmiles")
unit = "nautical miles";
else if (unit == "bool")
unit = "boolean";
else if (unit == "kilohertz")
unit = "KHz";
else if (unit == "megahertz")
unit = "MHz";
else if (unit == "pounds" || unit == "pound")
unit = "lbs";
else if (unit == "mbars" || unit == "mbar")
unit = "Millibars";
string converted = "SimVar.GetSimVarValue(\"" + varname + "\", \"" + unit + "\")";
XmlHelper.writeLog("Conversion result: " + converted);
return converted;
}
return "0";
}
}
// POSTFIX CONVERTER BY <NAME> STARTS
public class Intermediate
{
public string expr; // subexpression string
public string oper; // the operator used to create this expression
public Intermediate(string expr, string oper)
{
this.expr = expr;
this.oper = oper;
}
}
public string PostfixToInfix(string postfix, xmlHelper XmlHelper)
{
try
{
Stack<int> elseCounter = new Stack<int>();
Stack<Intermediate> ifCond = new Stack<Intermediate>();
Intermediate[] stackRegister = new Intermediate[50];
postfix = postfix.Replace("if {", "if{").Replace("} els", "}els").Replace("els {", "els{").Trim();
// CHECK TRAILING BRACKET BUG
//if (postfix.Length > 0 && postfix[postfix.Length - 1] == '}' && postfix.Count(f => f == '{') < postfix.Count(f => f == '}'))
if (postfix.Length > 0 && postfix[postfix.Length - 1] == '}' && ((postfix.Split('{').Length - 1) < (postfix.Split('}').Length - 1)))
postfix = postfix.TrimEnd('}').Trim();
// PROCESS STACKS
var postfixTokens = postfix.Split(' ');
string lastToken = "";
var stack = new Stack<Intermediate>();
var backupStack = new Stack<Intermediate>();
foreach (string token in postfixTokens)
{
lastToken = token;
string newExpr;
XmlHelper.writeLog("Current token: " + token);
if (token == "SET<PASSWORD>") // SET VARIABLE GAP
{
stack.Pop();
stack.Push(new Intermediate(token, token));
}
// s0 - Stores the top value in an internal register, but does not pop it from the stack.
else if (Regex.IsMatch(token, @"^s[-0-9.]+$"))
{
if (int.TryParse(token.Replace("s", ""), out int num))
{
stackRegister[num] = stack.Peek();
}
else
{
XmlHelper.writeLog("Failed to save stack " + token);
return "";
}
}
// l0 - Loads a value from a register to the top of the stack
else if (Regex.IsMatch(token, @"^l[-0-9.]+$"))
{
if (int.TryParse(token.Replace("l", ""), out int num) && stackRegister[num] != null)
{
stack.Push(stackRegister[num]);
}
else
{
XmlHelper.writeLog("Failed to load stack " + token);
return "";
}
}
// sp0 - Loads a value from a register to the top of the stack
else if (Regex.IsMatch(token, @"^sp[-0-9.]+$"))
{
if (int.TryParse(token.Replace("sp", ""), out int num))
{
stackRegister[num] = stack.Pop();
}
else
{
XmlHelper.writeLog("Failed to popsave stack " + token);
return "";
}
}
// Pops and discards the top value on the stack
else if (token.ToLower() == "p")
if (stack.Count > 0)
{
stack.Pop();
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
// Backup the stack
else if (token.ToLower() == "b")
stack = backupStack;
// Clears the stack
else if (token.ToLower() == "c")
stack = new Stack<Intermediate>();
// Duplicates the value that is on the top of the stack
else if (token.ToLower() == "d")
if (stack.Count > 0)
{
stack.Push(stack.Peek());
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
// Reverses the top and second values on the stack
else if (token.ToLower() == "r")
{
if (stack.Count > 1)
{
Intermediate first = stack.Pop();
Intermediate second = stack.Pop();
stack.Push(first);
stack.Push(second);
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "==" || token == "!=" || token == ">" || token == "<" || token == ">=" || token == "<=")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "( " + leftIntermediate.expr + " " + token + " " + rightIntermediate.expr + " )";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "?")
{
if (stack.Count > 2)
{
var check = stack.Pop();
var opt2 = stack.Pop();
var opt1 = stack.Pop();
newExpr = " ( " + check.expr + " ? " + opt1.expr + " : " + opt2.expr + " ) ";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "if{")
{
elseCounter.Push(0);
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = "( " + rightIntermediate.expr + " ? ";
//stack.Push(new Intermediate(newExpr, token));
ifCond.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "}els{")
{
elseCounter.Push(elseCounter.Pop() + 1);
if (elseCounter.Peek() <= 1) // TO AVOID DUPLICATE ELSES
{
if (stack.Count > 0 && ifCond.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = ifCond.Pop().expr + " " + rightIntermediate.expr + " : ";
ifCond.Push(new Intermediate(newExpr, token));
}
else if (ifCond.Count > 0)
{
newExpr = ifCond.Pop().expr;
ifCond.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
} else
{
XmlHelper.writeLog("SKIPPED: " + token);
}
}
else if (token == "}")
{
if (elseCounter.Peek() >= 1 && ifCond.Count > 0)
{
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = ifCond.Pop().expr + " " + rightIntermediate.expr + " )";
stack.Push(new Intermediate(newExpr, token));
} else
{
newExpr = ifCond.Pop().expr + " )";
stack.Push(new Intermediate(newExpr, token));
}
}
else if (elseCounter.Peek() == 0 && ifCond.Count > 0)
{
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = ifCond.Pop().expr + " " + rightIntermediate.expr + " : 0 )";
stack.Push(new Intermediate(newExpr, token));
} else
{
newExpr = ifCond.Pop().expr + " : 0 )";
stack.Push(new Intermediate(newExpr, token));
}
}
else
{
XmlHelper.writeLog("Failed to apply " + token + " (elseCount: " + elseCounter.Peek() + ")");
return "";
}
elseCounter.Pop();
}
else if (token == "&&" || token.ToLower() == "and")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = leftIntermediate.expr + " && " + rightIntermediate.expr;
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "||" || token.ToLower() == "or")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "( " + leftIntermediate.expr + " || " + rightIntermediate.expr + " )";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "!" || token.ToLower() == "not")
{
var leftIntermediate = stack.Pop();
stack.Push(new Intermediate("!(" + leftIntermediate.expr + ")", token));
}
else if (token == "/-/" || token.ToLower() == "neg")
{
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = "(" + rightIntermediate.expr + ") * (-1)";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "++")
{
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = "(( " + rightIntermediate.expr + " ) + 1)";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "--")
{
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = "(( " + rightIntermediate.expr + " ) - 1)";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "+" || token == "-" || token == "scat")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = leftIntermediate.expr + " " + (token != "scat" ? token : "+") + " " + rightIntermediate.expr;
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token == "*" || token == "/" || token == "%" || token == "&" || token == "|" || token == "^" || token == ">>" || token == "<<")
{
string leftExpr, rightExpr;
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
if (rightIntermediate.oper == "+" || rightIntermediate.oper == "-")
{
rightExpr = "(" + rightIntermediate.expr + ")";
}
else
{
rightExpr = rightIntermediate.expr;
}
var leftIntermediate = stack.Pop();
if (leftIntermediate.oper == "+" || leftIntermediate.oper == "-")
{
leftExpr = "(" + leftIntermediate.expr + ")";
}
else
{
leftExpr = leftIntermediate.expr;
}
newExpr = leftExpr + " " + token + " " + rightExpr;
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "quit")
{
break;
}
else if (token.ToLower() == "div")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "Math.floor( parseInt(" + leftIntermediate.expr + ") / parseInt(" + rightIntermediate.expr + ") )";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "lg")
{
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = "Math.log(" + rightIntermediate.expr + ") / Math.log(10)";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "log")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "Math.log(" + leftIntermediate.expr + ") / Math.log(" + rightIntermediate.expr + ")";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "ctg")
{
if (stack.Count > 0)
{
var rightIntermediate = stack.Pop();
newExpr = "1 / Math.tan(" + rightIntermediate.expr + ")";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
// g0
// case
else if (token.ToLower() == "rng")
{
if (stack.Count > 2)
{
var compare = stack.Pop();
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "( " + leftIntermediate.expr + " <= " + compare.expr + " && " + compare.expr + " <= " + rightIntermediate.expr + " )";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "schr")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "(" + leftIntermediate.expr + ").indexOf(String.fromCharCode(" + rightIntermediate.expr + "))";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "sstr")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "(" + rightIntermediate.expr + ").indexOf(" + leftIntermediate.expr + ")";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "ssub")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "(" + rightIntermediate.expr + ").replace(" + leftIntermediate.expr + ", '')";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "symb")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "(" + leftIntermediate.expr + ")[" + rightIntermediate.expr + "]";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "scmp")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = leftIntermediate.expr + " !== " + rightIntermediate.expr;
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else if (token.ToLower() == "scmi")
{
if (stack.Count > 1)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = "(" + leftIntermediate.expr + ").toLowerCase() !== (" + rightIntermediate.expr + ").toLowerCase()";
stack.Push(new Intermediate(newExpr, token));
}
else
{
XmlHelper.writeLog("Failed to apply " + token);
return "";
}
}
else
{
if (token.Length >= 2 && token[0] == '@')
{
stack.Push(new Intermediate(token.Substring(1), "VAR"));
}
else if (Regex.IsMatch(token, @"^[-0-9.]+$"))
{
stack.Push(new Intermediate(token, "NUM"));
}
else if (Regex.IsMatch(token, @"0[xX][0-9A-Fa-f]+"))
{
stack.Push(new Intermediate(token, "HEX"));
}
else if (token.Length >= 2 && token[0] == '\'' && token[token.Length - 1] == '\'')
{
stack.Push(new Intermediate(token, "STR"));
}
else if (token.ToLower() == "true" || token.ToLower() == "false") {
stack.Push(new Intermediate(token.ToLower(), "SYS"));
}
else
{
// OPERATOR
switch (token.ToLower())
{
case "dnor":
case "d360":
case "rdeg":
case "rnor":
// JUST SKIP
break;
case "pi":
stack.Push(new Intermediate("Math.PI", ""));
break;
case "dgrd":
addExpression(stack, token, "* Math.PI/180", "after", 1, XmlHelper);
break;
case "rddg":
addExpression(stack, token, "* 180/Math.PI", "after", 1, XmlHelper);
break;
case "abs":
addExpression(stack, token, "Math.abs", "before", 1, XmlHelper);
break;
case "int":
case "flr":
addExpression(stack, token, "Math.floor", "before", 1, XmlHelper);
break;
case "cos":
addExpression(stack, token, "Math.cos", "before", 1, XmlHelper);
break;
case "sin":
addExpression(stack, token, "Math.sin", "before", 1, XmlHelper);
break;
case "acos":
addExpression(stack, token, "Math.acos", "before", 1, XmlHelper);
break;
//case "ctg":
// addExpression(stack, token, "Math.cot", "before", XmlHelper);
// break;
case "ln":
addExpression(stack, token, "Math.log", "before", 1, XmlHelper);
break;
case "sqr":
addExpression(stack, token, " ** 2", "after", 1, XmlHelper);
break;
case "asin":
addExpression(stack, token, "Math.asin", "before", 1, XmlHelper);
break;
case "sqrt":
addExpression(stack, token, "Math.sqrt", "before", 1, XmlHelper);
break;
case "exp":
addExpression(stack, token, "Math.exp", "before", 1, XmlHelper);
break;
case "tg":
addExpression(stack, token, "Math.tan", "before", 1, XmlHelper);
break;
case "atg":
addExpression(stack, token, "Math.atan", "before", 1, XmlHelper);
break;
case "ceil":
addExpression(stack, token, "Math.ceil", "before", 1, XmlHelper);
break;
case "near":
addExpression(stack, token, "Math.round", "before", 1, XmlHelper);
break;
case "min":
addExpression(stack, token, "Math.min", "before", 2, XmlHelper);
break;
case "max":
addExpression(stack, token, "Math.max", "before", 2, XmlHelper);
break;
case "pow":
addExpression(stack, token, "Math.pow", "before", 2, XmlHelper);
break;
case "~":
addExpression(stack, token, "~", "before", 1, XmlHelper);
break;
case "eps":
addExpression(stack, token, "Number.EPSILON * ", "before", 1, XmlHelper);
break;
case "atg2":
addExpression(stack, token, "Math.atan2", "before", 2, XmlHelper);
break;
case "lc":
addExpression(stack, token, ".toLowerCase()", "after", 1, XmlHelper);
break;
case "uc":
case "cap":
addExpression(stack, token, ".toUpperCase()", "after", 1, XmlHelper);
break;
case "chr":
addExpression(stack, token, "String.fromCharCode", "before", 1, XmlHelper);
break;
case "ord":
addExpression(stack, token, ".charCodeAt(0)", "after", 1, XmlHelper);
break;
default:
XmlHelper.writeLog("Unknown operator \"" + token + "\"");
return "";
}
}
}
backupStack = stack;
string stackLog = "";
foreach (var stackItem in stack)
stackLog = stackItem.expr + " | " + stackLog;
string condLog = "";
foreach (var condItem in ifCond)
condLog = condItem.expr + " | " + condLog;
XmlHelper.writeLog("Main stack: " + stackLog);
XmlHelper.writeLog("Condition stack: " + condLog);
XmlHelper.writeLog("");
}
int i = 0;
foreach (var obj in stack)
{
XmlHelper.writeLog("Final stack #"+i+": " + obj.expr);
i++;
}
if (stack.Count > 0)
return stack.Peek().expr;
else
return "";
}
catch (Exception ex)
{
XmlHelper.writeLog(ex.Message);
return "";
}
}
private void addExpression(Stack<Intermediate> stack, string token, string modifier, string position, int arguments, xmlHelper XmlHelper)
{
string newExpr = "";
if (arguments == 2 && stack.Count >= 2)
{
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
newExpr = (position == "before" ? modifier : "") + "( " + leftIntermediate.expr + ", " + rightIntermediate.expr + " )" + (position == "after" ? modifier : "");
}
else if (arguments == 1 && stack.Count >= 1)
{
var rightIntermediate = stack.Pop();
newExpr = (position == "before" ? modifier : "") + "(" + rightIntermediate.expr + ")" + (position == "after" ? modifier : "");
}
else if (arguments == 0)
{
newExpr = (position == "before" ? modifier + "()" : "") + (position == "after" ? "1" + modifier : "");
} else
XmlHelper.writeLog("Failed to apply " + token);
stack.Push(new Intermediate(newExpr, token));
}
// POSTFIX CONVERTER ENDS
}
}
<file_sep>class [MATERIALNAME] extends TemplateElement {
constructor() {
super();
this.location = "interior";
this.curTime = 0.0;
this.bNeedUpdate = false;
this._isConnected = false;
}
get templateID() { return "[MATERIALNAME]"; }
connectedCallback() {
super.connectedCallback();
let parsedUrl = new URL(this.getAttribute("Url").toLowerCase());
let updateLoop = () => {
if (!this._isConnected)
return;
this.Update();
requestAnimationFrame(updateLoop);
};
this._isConnected = true;
requestAnimationFrame(updateLoop);
}
disconnectedCallback() {
}
Update() {
this.updateInstruments();
}
/*playInstrumentSound(soundId) {
if (this.isElectricityAvailable()) {
Coherent.call("PLAY_INSTRUMENT_SOUND", soundId);
return true;
}
return false;
} */
updateInstruments() {
[INSTRUMENTS]
}
}
registerLivery("[MATERIALNAME]-element", [MATERIALNAME]);
<file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
namespace msfsLegacyImporter
{
class xmlHelper
{
private double[] prevPoint;
private double prevAngle;
private int rotationDirection;
string logfile = "";
string logcontent = "";
string[] imagesExceptions = new string[]
{
"hsi_hsi_reflection",
"compass_compass_highlight",
"AN_24_GROZA_BLIK",
//"HUD_pfd_background"
};
string[] imagesForceTransparancy = new string[]
{
"pfd_attitude_inner_att_mask",
"pfd_attitude_sky_ground_strip_mask",
"compass_strip_mask",
"HUD_pfd_attitude_sky_ground_strip_pfd_attitude_sky_ground_strip_mask"
};
string[][] positionExceptions = new string[][]
{
new string[] { "HUD_pfd_attitude_ladder", "-25", "-198" },
new string[] { "HUD_Heading_pointer", "95", "12" },
new string[] { "Attitude_Attitude_Map", "0", "-229" },
new string[] { "Stby_Attitude_Stby_Attitude_Map", "10", "-122" }
};
string[][] scaleExceptions = new string[][]
{
//new string[] { "RMI_RMI_BG", "0.464", "0.464" },
};
string[][] zIndexExceptions = new string[][]
{
new string[] { "Attitude_Attitude_Overlay", "2", "" },
};
private string gaugeGroup;
private string gaugeSanitizedGroup;
private string gaugeName;
private string gaugeSanitizedName;
private string acSlug;
private string xPos;
private string yPos;
private string gaugeWidth;
private string gaugeHeight;
private string scaleUp;
private string panelDir;
private int index;
private string html;
private string css;
private string js;
private string globalVars;
private string materialName;
private string InstrumentFolder;
private string errors;
public void insertFsxGauge(MainWindow parent, object sender, string aircraftDirectory, string projectDirectory, string chkContent, float[] atts, cfgHelper CfgHelper, fsxVarHelper FsxVarHelper, jsonHelper JSONHelper)
{
string mainFile = aircraftDirectory + "\\" + (string)chkContent;
string backupFile = Path.GetDirectoryName(mainFile) + "\\." + Path.GetFileName(mainFile);
if (!File.Exists(mainFile))
return;
// PREPARE LOG FILE
logfile = Path.GetDirectoryName(mainFile) + "\\." + Path.GetFileNameWithoutExtension(mainFile) + ".log.txt";
errors = "";
logcontent = "";
string htmlTpl = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "panelTpl\\panel.html");
string cssTpl = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "panelTpl\\panel.css");
string jsTpl = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "panelTpl\\panel.js");
if (!File.Exists(backupFile))
{
CfgHelper.lastChangeTimestamp = DateTime.UtcNow.Ticks;
File.Copy(mainFile, backupFile);
}
// LOAD PANEL CFG
string content = File.ReadAllText(backupFile);
List<msfsLegacyImporter.cfgHelper.CfgLine> panelLines = CfgHelper.readCSV(content + "\r\n[]");
msfsLegacyImporter.cfgHelper.CfgFile panelCfg = CfgHelper.parseCfg(backupFile.Replace(aircraftDirectory + "\\", ""), panelLines);
msfsLegacyImporter.cfgHelper.CfgFile newPanelFile = new msfsLegacyImporter.cfgHelper.CfgFile(true, mainFile.Replace(aircraftDirectory + "\\", ""), new List<msfsLegacyImporter.cfgHelper.CfgSection>());
// PROCESS PANEL CFG
foreach (var panelSection in panelCfg.Sections)
{
if (panelSection.Name.Contains("VCOCKPIT"))
{
List<String[]> gaugesList = new List<String[]>();
string pixel_size = panelSection.Lines.Find(x => x.Name == "pixel_size") != null ? panelSection.Lines.Find(x => x.Name == "pixel_size").Value : "";
string size_mm = panelSection.Lines.Find(x => x.Name == "size_mm") != null ? panelSection.Lines.Find(x => x.Name == "size_mm").Value : "";
if (String.IsNullOrEmpty(pixel_size) && !String.IsNullOrEmpty(size_mm))
pixel_size = size_mm;
else if (String.IsNullOrEmpty(size_mm) && !String.IsNullOrEmpty(pixel_size))
size_mm = pixel_size;
string file = panelSection.Lines.Find(x => x.Name == "file") != null ? panelSection.Lines.Find(x => x.Name == "file").Value.Trim() : "";
string texture = panelSection.Lines.Find(x => x.Name == "texture") != null ? panelSection.Lines.Find(x => x.Name == "texture").Value : "";
if (String.IsNullOrEmpty(pixel_size) || String.IsNullOrEmpty(texture))
{
string msg = "Panel " + panelSection.Name + " does not have enough parameters";
errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
continue;
}
acSlug = Regex.Replace(Path.GetFileName(aircraftDirectory).Replace("\\", "").Trim().ToLower() + "_" + Path.GetDirectoryName(chkContent), @"[^0-9A-Za-z ,.\-_]", "").Replace(" ", "_").Replace(".", "_");
materialName = "gauges_" + texture.Replace("$", "").ToLower();
int[] size = pixel_size != null && pixel_size.Contains(',') &&
int.TryParse(pixel_size.Split(',')[0].Trim(), out int num1) && int.TryParse(pixel_size.Split(',')[1].Trim(), out int num2) ?
new int[] { num1, num2 } : new int[] { 0, 0 };
int[] size2 = size_mm != null && pixel_size.Contains(',') &&
int.TryParse(size_mm.Split(',')[0].Trim(), out int num11) && int.TryParse(size_mm.Split(',')[1].Trim(), out int num22) ?
new int[] { num11, num22 } : new int[] { 0, 0 };
cfgHelper.CfgSection newPanelSection = new msfsLegacyImporter.cfgHelper.CfgSection(true, panelSection.Name.Replace("VCOCKPIT", "VPainting"), new List<msfsLegacyImporter.cfgHelper.CfgLine>());
// PROCESS GAUGES LIST
for (int i = 0; i < 1000; i++)
{
var gauge = panelSection.Lines.Find(x => x.Name == "gauge" + i.ToString("00"));
if (gauge != null && gauge.Value.Contains(',') && !gauge.Value.Contains("n_number_plaque"))
{
string[] gaugeData = gauge.Value.Split(',');
if (gaugeData.Length >= 4 && gaugeData[0].Contains('!'))
{
if (gaugeData.Length == 4) // ADD MISSING HEIGHT
gaugeData = gaugeData.Concat(new string[] { gaugeData[3] }).ToArray();
gaugesList.Add(gaugeData);
}
else
{
string msg = "Unrecognized gauge string: " + gauge.Value;
errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
}
}
}
/*if (Directory.Exists(InstrumentFolder))
{
MessageBoxResult messageBoxResult = MessageBox.Show("Existing files will be overwritten", "Legacy instruments folder \"" + gaugeGroup + "\" already exists", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult != MessageBoxResult.Yes)
{
continue;
}
}
else*/
// INSERT GAUGES
if (gaugesList.Count > 0)
{
html = "";
css = "";
js = Environment.NewLine;
globalVars = atts[8] == 1 ? "" : "False";
if (atts[4] == 1)
{
js += " // TAXI LIGHTS CONTROL" + Environment.NewLine;
js += " if (SimVar.GetSimVarValue(\"IS GEAR RETRACTABLE\", \"Boolean\")) {" + Environment.NewLine;
js += " var gears_extracted = SimVar.GetSimVarValue(\"GEAR HANDLE POSITION\", \"Boolean\");" + Environment.NewLine;
js += " if (SimVar.GetSimVarValue(\"LIGHT TAXI\", \"bool\") && !gears_extracted)" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"K:TOGGLE_TAXI_LIGHTS\", \"bool\", false)" + Environment.NewLine;
js += " else if (!SimVar.GetSimVarValue(\"LIGHT TAXI\", \"bool\") && gears_extracted)" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"K:TOGGLE_TAXI_LIGHTS\", \"bool\", true)" + Environment.NewLine;
js += " }" + Environment.NewLine + Environment.NewLine;
}
if (atts[7] == 1)
{
double[] ABdata = parent.getABdata();
js += " // AFTERBURNER CONTROL START" + Environment.NewLine;
js += " if (SimVar.GetSimVarValue(\"ENGINE TYPE\",\"Enum\") == 1) {" + Environment.NewLine;
js += " var stages = " + (ABdata[4] > 0 ? ABdata[4] : 1) + ";" + Environment.NewLine;
js += " var threshold = " + (100 * (ABdata[1] > 0 ? ABdata[1] : ABdata[1])) + ";" + Environment.NewLine;
js += " var eng;" + Environment.NewLine;
js += " var currABpct = Math.ceil(parseFloat(SimVar.GetSimVarValue(\"L:TURB ENG AFTERBURNER PCT ACTIVE\",\"percent\")) / (100 / stages));" + Environment.NewLine + Environment.NewLine; ;
js += " for (eng = 1; eng <= 4; eng++) {" + Environment.NewLine;
js += " var rpm = parseFloat(SimVar.GetSimVarValue(\"ENG N1 RPM:\"+eng,\"percent\"));" + Environment.NewLine;
js += " var i;" + Environment.NewLine + Environment.NewLine; ;
js += " var currABstage = SimVar.GetSimVarValue(\"L:TURB ENG AFTERBURNER STAGE ACTIVE:\"+eng,\"number\");" + Environment.NewLine;
js += " var currABbool = SimVar.GetSimVarValue(\"L:TURB ENG AFTERBURNER:\"+eng,\"boolean\");" + Environment.NewLine;
js += " var currABbool2 = SimVar.GetSimVarValue(\"L:TURB ENG\"+eng+\" AFTERBURNER\",\"boolean\");" + Environment.NewLine + Environment.NewLine; ;
js += " var afterburnedEnabled = false;" + Environment.NewLine + Environment.NewLine; ;
js += " var step = (100 - threshold) / stages;" + Environment.NewLine;
js += " for(i=1; i <= stages; i++) {" + Environment.NewLine;
js += " if (rpm >= threshold + step * (i - 1) && (i == stages || rpm < threshold + step * i)) {" + Environment.NewLine;
js += " afterburnedEnabled = true;" + Environment.NewLine;
js += " if (currABstage != i || eng == 1 && currABpct != i) {" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG AFTERBURNER STAGE ACTIVE:\"+eng,\"number\",i);" + Environment.NewLine + Environment.NewLine; ;
js += " if (eng == 1)" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG AFTERBURNER PCT ACTIVE\",\"percent\",100 / stages * i);" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " }" + Environment.NewLine + Environment.NewLine; ;
js += " if (!afterburnedEnabled && (currABstage != 0 || currABpct!= 0 || currABbool != false || currABbool2 != false)) {" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG AFTERBURNER STAGE ACTIVE:\"+eng,\"number\",0);" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG AFTERBURNER PCT ACTIVE\",\"percent\",0);" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG AFTERBURNER:\"+eng,\"boolean\",false);" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG\"+eng+\" AFTERBURNER\",\"boolean\",false);" + Environment.NewLine;
js += " } else if (afterburnedEnabled && (currABbool == false || currABbool2 == false)) {" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG AFTERBURNER:\"+eng,\"boolean\",true);" + Environment.NewLine;
js += " SimVar.SetSimVarValue(\"L:TURB ENG\"+eng+\" AFTERBURNER\",\"boolean\",true);" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " // AFTERBURNER CONTROL END" + Environment.NewLine;
}
string baseFolder = /*projectDirectory.TrimEnd('\\')*/ Path.GetDirectoryName(projectDirectory.TrimEnd('\\')) + "\\legacy-vcockpits-instruments\\";
InstrumentFolder = baseFolder + "html_ui\\Pages\\VLivery\\liveries\\Legacy\\" + acSlug + "\\";
if (!Directory.Exists(InstrumentFolder))
Directory.CreateDirectory(InstrumentFolder);
if (!String.IsNullOrEmpty(file) && !imagesExceptions.Contains(Path.GetFileNameWithoutExtension(file)))
{
if (File.Exists(Path.GetDirectoryName(mainFile) + "\\" + file))
{
Bitmap bmp = new Bitmap(Path.GetDirectoryName(mainFile) + "\\" + file);
bmp = setBitmapGamma(bmp, atts[0], false, file);
try { bmp.Save(InstrumentFolder + Path.GetFileNameWithoutExtension(file) + ".png", ImageFormat.Png); }
catch (Exception e) { MessageBox.Show("Can't save image " + Path.GetFileNameWithoutExtension(file) + ".png" + Environment.NewLine + "Error: " + e.Message); }
}
else
{
string msg = "Background image " + Path.GetDirectoryName(mainFile) + "\\" + file + " not found";
errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
}
}
string[] last = gaugesList.Last();
foreach (var gaugeData in gaugesList)
{
gaugeGroup = Path.GetFileName(gaugeData[0].Split('!')[0].Trim().ToLower());
gaugeSanitizedGroup = Regex.Replace(gaugeGroup, @"[^0-9A-Za-z ,.-_]", "").Replace(" ", "_");
gaugeName = gaugeData[0].Split('!')[1].Trim();
gaugeSanitizedName = sanitizeString(gaugeName);
if (!Char.IsLetter(gaugeSanitizedName, 0)) // FIX FIRST DIGIT
gaugeSanitizedName = "g" + gaugeSanitizedName;
xPos = gaugeData[1].Trim().Trim('"');
yPos = gaugeData[2].Trim().Trim('"');
gaugeWidth = gaugeData.Length >= 4 ? gaugeData[3].Trim().Trim('"') : "0";
gaugeHeight = gaugeData.Length >= 5 ? gaugeData[4].Trim().Trim('"') : gaugeWidth;
scaleUp = gaugeData.Length >= 7 ? gaugeData[6].Trim().Trim('"') : "1";
//SET BUTTON LABEL
Application.Current.Dispatcher.Invoke(() => {
if (sender.GetType() == typeof(Button))
((Button)sender).Content = gaugeName;
});
// AC CAB
panelDir = Path.GetDirectoryName(mainFile) + "\\." + gaugeGroup;
// AC SUBFOLDER
if (!Directory.Exists(panelDir) || !File.Exists(panelDir + "\\" + gaugeName + ".xml"))
panelDir = Path.GetDirectoryName(mainFile) + "\\" + gaugeGroup;
if (!Directory.Exists(panelDir) || !File.Exists(panelDir + "\\" + gaugeName + ".xml"))
panelDir = Path.GetDirectoryName(mainFile) + "\\." + gaugeGroup;
// FSX CABS
if (!Directory.Exists(panelDir) || !File.Exists(panelDir + "\\" + gaugeName + ".xml"))
panelDir = Path.GetDirectoryName(projectDirectory.TrimEnd('\\')) + "\\legacy-vcockpits-instruments\\.FSX\\" + gaugeGroup;
if (!Directory.Exists(panelDir) || !File.Exists(panelDir + "\\" + gaugeName + ".xml")) {
string msg = "Gauge file " + gaugeGroup + "\\" + gaugeName + ".xml not found";
errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
try { if (panelDir == Path.GetDirectoryName(mainFile) + "\\" + gaugeGroup)
Directory.Move(panelDir, Path.GetDirectoryName(mainFile) + "\\." + gaugeGroup); }
catch { }
// LAST CHANCE TO RENDER SPECIAL SCRIPT
if (!gaugeData.Equals(last) || atts[4] != 1 && atts[7] != 1)
continue;
else
html = " ";
}
// SET UP GAUGE
try
{
writeLog(Environment.NewLine + "### Processing " + gaugeGroup + "\\" + gaugeName + ".xml ###" + Environment.NewLine);
string[] GaugeSize = new string[] { gaugeWidth, gaugeHeight };
string[] imgSize = new string[] { "0", "0" };
XElement gaugeXml = XElement.Load(panelDir + "\\" + gaugeName + ".xml");
if (gaugeXml.Element("SimGauge.Gauge") != null)
gaugeXml = gaugeXml.Element("SimGauge.Gauge");
else if (gaugeXml.Element("Gauge") != null)
gaugeXml = gaugeXml.Element("Gauge");
html += " <div id=\"" + gaugeSanitizedName + "\">" + Environment.NewLine;
css += materialName + "-element #Mainframe #" + gaugeSanitizedName + " {" + Environment.NewLine + " position: absolute;" + Environment.NewLine + " overflow: hidden;" + Environment.NewLine + " left: " + xPos + "px;" + Environment.NewLine + " top: " + yPos + "px;" + Environment.NewLine;
// MACRO
foreach (var macro in gaugeXml.Elements("Macro"))
{
if (macro.Attribute("Name") != null && !string.IsNullOrEmpty(macro.Value))
{
string var = " var " + macro.Attribute("Name").Value + " = " + FsxVarHelper.fsx2msfsSimVar(macro.Value, this, false, globalVars) + ";" + Environment.NewLine;
js += var;
if (globalVars != "False")
globalVars += " var " + macro.Attribute("Name").Value + " = 0;" + Environment.NewLine;
}
else if (macro.Attribute("Name") != null)
{
string var = " var " + macro.Attribute("Name").Value + " = \"\";" + Environment.NewLine;
js += var;
if (globalVars != "False")
globalVars += " var " + macro.Attribute("Name").Value + " = 0;" + Environment.NewLine;
}
}
// SET BG IMAGE IF NECESSARY
XElement mainImage = gaugeXml.Element("Image");
if (String.IsNullOrEmpty(Path.GetFileNameWithoutExtension(file)) || atts[1] == 1)
{
if (mainImage != null && mainImage.Attribute("Name") != null)
{
string MainImageSource = probablyFixBmpName(mainImage.Attribute("Name").Value);
string MainImageFilename = gaugeSanitizedName + "_" + Path.GetFileNameWithoutExtension(MainImageSource).Trim();
if (mainImage.Attribute("ImageSizes") != null)
imgSize = getXYvalue(mainImage, false);
if (!String.IsNullOrEmpty(MainImageFilename) && !imagesExceptions.Contains(Path.GetFileNameWithoutExtension(MainImageFilename)))
{
string sourceFile = panelDir + "\\" + MainImageSource;
if (!File.Exists(sourceFile)) // TRY 1024 SUBFOLDER
sourceFile = panelDir + "\\1024\\" + MainImageSource;
if (File.Exists(sourceFile))
{
Bitmap bmp = new Bitmap(sourceFile);
bmp = setBitmapGamma(bmp, atts[0],
mainImage.Element("Transparent") != null && mainImage.Element("Transparent").Value == "True" ||
mainImage.Attribute("Alpha") != null && mainImage.Attribute("Alpha").Value == "Yes" ||
imagesForceTransparancy.Contains(Path.GetFileNameWithoutExtension(sourceFile)), sourceFile);
if (imgSize[0] == "0" && imgSize[1] == "0")
imgSize = new string[] { bmp.Width.ToString(), bmp.Height.ToString() };
try { bmp.Save(InstrumentFolder + MainImageFilename + ".png", ImageFormat.Png); }
catch (Exception e) { MessageBox.Show("Can't save image " + MainImageFilename + ".png" + Environment.NewLine + "Error: " + e.Message); }
css += " background-image: url(\"/Pages/VLivery/Liveries/legacy/" + acSlug + "/" + MainImageFilename + ".png\");" + Environment.NewLine + " background-position: 0px 0px;" + Environment.NewLine + " background-repeat: no-repeat;" + Environment.NewLine; ;
}
else
{
string msg = "Background image " + panelDir + "\\" + MainImageSource + " not found";
errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
}
}
}
}
var ParentSize = gaugeXml.Element("Size");
if (ParentSize != null)
GaugeSize = getXYvalue(ParentSize, false);
/*else if (mainImage != null)
GaugeSize = getXYvalue(mainImage, false);*/
if (GaugeSize[0] == "0" && GaugeSize[1] == "0")
writeLog("ERROR: " + "Gauge with zero size!");
if (atts[6] == 1 && GaugeSize[0] != "0" && GaugeSize[1] != "0" && imgSize[0] != "0" && imgSize[1] != "0") // SCALE GAUGE IF NECESSARY
{
css += " width: " + imgSize[0] + "px;" + Environment.NewLine + " height: " + imgSize[1] + "px;" + Environment.NewLine;
css += Environment.NewLine + " transform: scale(calc(" + scaleUp + " * " + GaugeSize[0] + " / " + imgSize[0] + "), calc(" + scaleUp + " * " + GaugeSize[1] + " / " + imgSize[1] + "));" + Environment.NewLine + " transform-origin: 0 0;" + Environment.NewLine;
} else
{
css += " width: " + GaugeSize[0] + "px;" + Environment.NewLine + " height: " + GaugeSize[1] + "px;" + Environment.NewLine;
if (scaleUp != "1")
css += Environment.NewLine + " transform: scale(" + scaleUp + ");" + Environment.NewLine + " transform-origin: 0 0;" + Environment.NewLine;
}
// SCALE UP/DOWN IF GAUGE SIZE NOT MATCH PANEL SIZE
if (atts[3] < 1 && (size2[0] != 0 && size2[0].ToString() != gaugeWidth || size2[1] != 0 && size2[1].ToString() != gaugeHeight))
{
writeLog("Scaling up panel from " + gaugeWidth + " " + gaugeHeight + " to " + size2[0] + " " + size2[1]);
css += " transform: scale(calc(" + scaleUp + " * " + size2[0].ToString() + " / " + gaugeWidth + "), calc(" + scaleUp + " * " + size2[1].ToString() + " / " + gaugeHeight + ")); transform-origin: 0 0;" + Environment.NewLine;
}
css += "}" + Environment.NewLine;
// SET UP GAUGE ELEMENTS
var gaugeElements = gaugeXml.Elements("Element");
if (gaugeElements.Count() < 0)
{
string msg = "No elements in " + gaugeGroup + "\\" + gaugeName + ".xml found!";
errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
}
else
{
index = -1;
foreach (XElement gaugeElement in gaugeElements)
{
processGaugeElement(gaugeElement, FsxVarHelper, atts, 0);
}
}
html += " </div>" + Environment.NewLine;
}
catch (Exception ex)
{
errors += "Failed to process " + gaugeGroup + "\\" + gaugeName + ".xml" + Environment.NewLine + Environment.NewLine;
writeLog(ex.Message);
}
try { if (panelDir == Path.GetDirectoryName(mainFile) + "\\" + gaugeGroup)
Directory.Move(panelDir, Path.GetDirectoryName(mainFile) + "\\." + gaugeGroup); }
catch { }
}
if (html != "")
{
html = htmlTpl.Replace("[INSTRUMENTS]", html);
html = html.Replace("[MATERIALNAME]", materialName);
html = html.Replace("[ACSLUG]", acSlug);
css = cssTpl.Replace("[INSTRUMENTS]", css);
css = css.Replace("[MATERIALNAME]", materialName);
css = css.Replace("[IMAGE]", !String.IsNullOrEmpty(Path.GetFileNameWithoutExtension(file)) ?
"/Pages/VLivery/Liveries/legacy/" + acSlug + "/" + Path.GetFileNameWithoutExtension(file) + ".png" : "");
css = css.Replace("[BACKGROUND-COLOR]", !String.IsNullOrEmpty(Path.GetFileNameWithoutExtension(file)) ?
"#111" : "transparent");
js = jsTpl.Replace("[INSTRUMENTS]", js);
js = js.Replace("[MATERIALNAME]", materialName);
/*
// BLUR FIX START
var skipFrames = 1;
this.querySelector("#Mainframe").style.opacity = "0.99";
this.curTime += 1;
if (this.curTime == skipFrames + 1) {
this.curTime = 0;
this.querySelector("#Mainframe").style.opacity = "1";
} else {
return;
}
// BLUR FIX END
*/
// SAVE FILES
try
{
File.WriteAllText(InstrumentFolder + materialName + ".html", html);
File.WriteAllText(InstrumentFolder + materialName + ".css", css);
File.WriteAllText(InstrumentFolder + materialName + ".js", js);
}
catch (Exception e) { MessageBox.Show("Can't save HTML files" + Environment.NewLine + "Error: " + e.Message); }
JSONHelper.scanTargetFolder(baseFolder);
string[] data = new string[] { "", "CORE", "MSFS Legacy Importer Instruments", "MSFS Legacy Importer", "<NAME>", "1.0.0", "1.0.0", "" };
JSONHelper.createInstrumentManifest(baseFolder, data);
// INSERT NEW PANEL.CFG DATA
newPanelSection.Lines.Add(new msfsLegacyImporter.cfgHelper.CfgLine(true, "size_mm", size_mm, ""));
newPanelSection.Lines.Add(new msfsLegacyImporter.cfgHelper.CfgLine(true, "pixel_size", pixel_size, ""));
newPanelSection.Lines.Add(new msfsLegacyImporter.cfgHelper.CfgLine(true, "texture", texture, ""));
newPanelSection.Lines.Add(new msfsLegacyImporter.cfgHelper.CfgLine(true, "location", "interior", ""));
newPanelSection.Lines.Add(new msfsLegacyImporter.cfgHelper.CfgLine(true, "painting00", "legacy/" + acSlug + "/" + materialName + ".html?font_color=white,0,0," + (size[0] - 1) + "," + (size[1] - 1), ""));
newPanelFile.Sections.Add(newPanelSection);
}
if (atts[2] != 1 && errors != "")
MessageBox.Show(errors + "You can try to unpack FSX gauges resources first or report it to program author (links in About tab)", materialName + " conversion errors");
}
}
}
saveLog();
CfgHelper.saveCfgFile(aircraftDirectory, newPanelFile);
}
private void processGaugeElement(XElement gaugeElement, fsxVarHelper FsxVarHelper, float[] atts, int depth)
{
index++;
XElement Image = gaugeElement.Element("Image");
XElement FloatPosition = gaugeElement.Element("FloatPosition");
if (FloatPosition == null)
FloatPosition = gaugeElement.Element("Position");
XElement Rotation = gaugeElement.Element("Rotation");
if (Rotation == null)
Rotation = gaugeElement.Element("Rotate");
XElement Shift = gaugeElement.Element("Shift");
XElement GaugeText = gaugeElement.Element("GaugeText");
XElement MaskImage = gaugeElement.Element("MaskImage");
XElement Axis = null;
XElement Transparent = null;
string visibilityCond = "";
XElement Visibility = gaugeElement.Element("Visibility");
if (Visibility == null)
Visibility = gaugeElement.Element("Visible");
if (Visibility != null)
visibilityCond = FsxVarHelper.fsx2msfsSimVar(Visibility.Value, this, false, globalVars);
string slug = gaugeElement.Attribute("id") != null ? gaugeSanitizedName + "_" + gaugeElement.Attribute("id").Value : "";
if (Image != null && Image.Attribute("Name") != null)
slug = gaugeSanitizedName + "_" + Path.GetFileNameWithoutExtension(Image.Attribute("Name").Value).Trim();
else if (GaugeText != null && GaugeText.Attribute("id") != null)
slug = gaugeSanitizedName + "_" + GaugeText.Attribute("id").Value.Trim();
if (String.IsNullOrEmpty(slug))
slug = gaugeSanitizedName + "_unknownGauge";
string sanitizedSlug = sanitizeString(slug) + "_" + index;
if (!Char.IsLetter(sanitizedSlug, 0)) // FIX FIRST DIGIT
sanitizedSlug = "g" + sanitizedSlug;
string[] FloatPositionValues = getXYvalue(FloatPosition);
// RENDER MASK FIRST
if (MaskImage != null && !String.IsNullOrEmpty(MaskImage.Attribute("Name").Value))
{
string maskSlug = slug + "_" + Path.GetFileNameWithoutExtension(MaskImage.Attribute("Name").Value).Trim();
string MainImageSource = probablyFixBmpName(MaskImage.Attribute("Name").Value);
string sourceFile1 = panelDir + "\\" + MainImageSource;
if (!File.Exists(sourceFile1)) // TRY 1024 SUBFOLDER
sourceFile1 = panelDir + "\\1024\\" + MainImageSource;
string targetFile1 = InstrumentFolder + maskSlug + ".png";
if (File.Exists(sourceFile1) && !imagesExceptions.Contains(Path.GetFileNameWithoutExtension(targetFile1)))
{
Bitmap bmp = new Bitmap(sourceFile1);
bmp = setBitmapGamma(bmp, atts[0], atts[5] == 1 ||
MaskImage.Element("Transparent") != null && MaskImage.Element("Transparent").Value == "True" ||
MaskImage.Attribute("Alpha") != null && MaskImage.Attribute("Alpha").Value == "Yes" ||
imagesForceTransparancy.Contains(Path.GetFileNameWithoutExtension(sourceFile1)), sourceFile1);
string[] maskSize = new string[] { bmp.Width.ToString(), bmp.Height.ToString() };
if (MaskImage.Attribute("ImageSizes") != null)
maskSize = getXYvalue(MaskImage, false);
try { bmp.Save(targetFile1, ImageFormat.Png); }
catch (Exception e) { MessageBox.Show("Can't save image " + maskSlug + ".png" + Environment.NewLine + "Error: " + e.Message); }
for (int i = 0; i < depth; i++) { html += " "; }
html += " <div id=\"" + sanitizedSlug + "_mask\">" + Environment.NewLine;
css += materialName + "-element #Mainframe #" + sanitizedSlug + "_mask {" + Environment.NewLine + " background: transparent;" +
Environment.NewLine + " position: absolute;" + Environment.NewLine + " overflow: hidden;" + Environment.NewLine +
Environment.NewLine + " width: " + maskSize[0] + "px;" + Environment.NewLine + " height: " + maskSize[1] + "px;" + Environment.NewLine;
//if (FloatPosition != null)
css += " left: " + FloatPositionValues[0] + "px;" + Environment.NewLine + " top: " + FloatPositionValues[1] + "px;" + Environment.NewLine + "}" + Environment.NewLine;
//else
//css += " left: 50%;" + Environment.NewLine + " top: 50%" + Environment.NewLine + "}" + Environment.NewLine;
css += materialName + "-element #Mainframe #" + sanitizedSlug + "_mask_image {" + Environment.NewLine + " background: transparent;" +
Environment.NewLine + " background-image: url(\"/Pages/VLivery/Liveries/legacy/" + acSlug + "/" + maskSlug + ".png\");" + Environment.NewLine + " background-position: 0px 0px;" + Environment.NewLine + " background-repeat: no-repeat;" +
Environment.NewLine + " position: absolute;" + Environment.NewLine + " overflow: hidden;" + Environment.NewLine +
Environment.NewLine + " width: 100%;" + Environment.NewLine + " height: 100%; " + Environment.NewLine + "}" + Environment.NewLine;
depth++;
}
else
{
string msg = "Mask image " + panelDir + "\\" + MainImageSource + " not found";
//errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
MaskImage = null;
}
}
// READ MACRO
js += Environment.NewLine + " /* " + sanitizedSlug.ToUpper() + " */" + Environment.NewLine;
foreach (var macro in gaugeElement.Elements("Macro"))
{
if (macro.Attribute("Name") != null && !string.IsNullOrEmpty(macro.Value))
{
string var = " var " + macro.Attribute("Name").Value + " = " + FsxVarHelper.fsx2msfsSimVar(macro.Value, this, false, globalVars) + ";" + Environment.NewLine;
js += var;
if (globalVars != "False")
globalVars += " var " + macro.Attribute("Name").Value + " = 0;" + Environment.NewLine;
}
else if (macro.Attribute("Name") != null)
{
string var = " var " + macro.Attribute("Name").Value + " = \"\";" + Environment.NewLine;
js += var;
if (globalVars != "False")
globalVars += " var " + macro.Attribute("Name").Value + " = 0;" + Environment.NewLine;
}
}
// START ELEMENT CONTAINER
for (int i = 0; i < depth; i++) { html += " "; }
html += " <div id=\"" + sanitizedSlug + "\">" + Environment.NewLine;
string[] imgSize = null;
string[] AxisPositionValues = new string[] { "0", "0" };
// IMAGE
if (Image != null)
{
if (Image.Attribute("ImageSizes") != null)
imgSize = getXYvalue(Image, true);
Axis = Image.Elements("Axis").FirstOrDefault();
Transparent = Image.Element("Transparent");
AxisPositionValues = getXYvalue(Axis);
// GENERATE IMAGE
if (Image.Attribute("Name") != null)
{
string ImageSource = probablyFixBmpName(Image.Attribute("Name").Value);
string sourceFile = panelDir + "\\" + ImageSource;
if (!File.Exists(sourceFile)) // TRY 1024 SUBFOLDER
sourceFile = panelDir + "\\1024\\" + ImageSource;
string targetFile = InstrumentFolder + slug + ".png";
if (!imagesExceptions.Contains(Path.GetFileNameWithoutExtension(targetFile)))
{
if (File.Exists(sourceFile))
{
Bitmap bmp = new Bitmap(sourceFile);
bmp = setBitmapGamma(bmp, atts[0],
(Transparent == null && MaskImage == null) ||
Transparent != null && Transparent.Value != "False" ||
MaskImage != null && (MaskImage.Attribute("Alpha") == null || MaskImage.Attribute("Alpha").Value != "No") ||
imagesForceTransparancy.Contains(Path.GetFileNameWithoutExtension(sourceFile)), sourceFile);
if (imgSize == null)
imgSize = new string[] { bmp.Width.ToString(), bmp.Height.ToString() };
try { bmp.Save(targetFile, ImageFormat.Png); }
catch (Exception e) { MessageBox.Show("Can't save image " + slug + ".png" + Environment.NewLine + "Error: " + e.Message); }
}
else
{
string msg = "Gauge image " + panelDir + "\\" + ImageSource + " not found";
//errors += msg + Environment.NewLine + Environment.NewLine;
writeLog("ERROR: " + msg);
Image = null;
}
}
}
}
// GENERATE CODE
css += materialName + "-element #Mainframe #" + sanitizedSlug + " {" + Environment.NewLine + " background: transparent;" + Environment.NewLine;
if (Image != null)
css += " background-image: url(\"/Pages/VLivery/Liveries/legacy/" + acSlug + "/" + slug + ".png\");" + Environment.NewLine + " background-position: 0px 0px;" + Environment.NewLine + " background-repeat: no-repeat;" + Environment.NewLine;
css += " position: absolute;" + Environment.NewLine + " overflow: hidden;" + Environment.NewLine;
if (imgSize != null)
css += Environment.NewLine + " width: " + imgSize[0] + "px;" + Environment.NewLine + " height: " + imgSize[1] + "px;" + Environment.NewLine;
else
css += Environment.NewLine + " width: 100%;" + Environment.NewLine + " height: 100%;" + Environment.NewLine;
if (getSizeException(slug, positionExceptions) != null)
css += " left: " + getSizeException(slug, positionExceptions)[0] + "px;" + Environment.NewLine + " top: " + getSizeException(slug, positionExceptions)[1] + "px; /* EXCEPTION */" + Environment.NewLine;
else if (MaskImage != null)
css += " left: -" + AxisPositionValues[0] + "px;" + Environment.NewLine + " top: -" + AxisPositionValues[1] + "px;" + Environment.NewLine;
else if (FloatPosition == null && AxisPositionValues[0] != "0" && AxisPositionValues[1] != "0")
css += " left: calc(50% - " + AxisPositionValues[0] + "px);" + Environment.NewLine + " top: calc(50% - " + AxisPositionValues[1] + "px);" + Environment.NewLine;
else
css += " left: calc(" + FloatPositionValues[0] + "px - " + AxisPositionValues[0] + "px);" + Environment.NewLine + " top: calc(" + FloatPositionValues[1] + "px - " + AxisPositionValues[1] + "px);" + Environment.NewLine;
css += " transform-origin: " + AxisPositionValues[0] + "px " + AxisPositionValues[1] + "px;" + Environment.NewLine;
if (getSizeException(slug, scaleExceptions) != null)
css += " transform: scale(" + getSizeException(slug, scaleExceptions)[0] + ", " + getSizeException(slug, scaleExceptions)[1] + "); /* EXCEPTION */" + Environment.NewLine;
if (getSizeException(slug, zIndexExceptions) != null)
css += " z-index: " + getSizeException(slug, zIndexExceptions)[0] + "; /* EXCEPTION */" + Environment.NewLine;
js += " var " + sanitizedSlug + " = this.querySelector(\"#" + sanitizedSlug + "\");" + Environment.NewLine;
js += " if (typeof " + sanitizedSlug + " !== \"undefined\") {" + Environment.NewLine;
js += " var transform = '';" + Environment.NewLine + Environment.NewLine;
if (!String.IsNullOrEmpty(visibilityCond)) { js += " " + sanitizedSlug + ".style.display = " + visibilityCond + " ? \"block\" : \"none\";" + Environment.NewLine + Environment.NewLine; }
// APPLY ANIM
XElement Expression = null;
// PERFORM ROTATION
if (Rotation != null)
{
Expression = Rotation.Elements("Expression").FirstOrDefault();
if (Expression == null)
Expression = Rotation.Elements("Value").FirstOrDefault();
if (Expression != null)
{
js += " {" + Environment.NewLine + Environment.NewLine;
expressionRoutin(Expression, FsxVarHelper, globalVars);
XElement PointsTo = Rotation.Elements("PointsTo").FirstOrDefault();
XAttribute ImagePointsTo = Image != null ? Image.Attribute("PointsTo") : null;
XElement DegreesPointsTo = Rotation.Elements("DegreesPointsTo").FirstOrDefault();
if (PointsTo != null || ImagePointsTo != null)
{
string pointValue = PointsTo != null ? PointsTo.Value : ImagePointsTo.Value;
switch (pointValue.ToUpper())
{
case "SOUTH":
js += " var PointsTo = 180;" + Environment.NewLine;
break;
case "WEST":
js += " var PointsTo = 90;" + Environment.NewLine;
break;
case "EAST":
js += " var PointsTo = (-90);" + Environment.NewLine;
break;
case "NORTH":
js += " var PointsTo = 0;" + Environment.NewLine;
break;
default:
js += " var PointsTo = 0;" + Environment.NewLine;
break;
}
}
else if (DegreesPointsTo != null && Double.TryParse(DegreesPointsTo.Value, out double num))
js += " var PointsTo = " + (num - 90.0) + "; " + Environment.NewLine;
else
js += " var PointsTo = 0;" + Environment.NewLine;
// NONLINEAR
if (Rotation.Elements("NonlinearityTable").FirstOrDefault() != null || Rotation.Elements("Nonlinearity").FirstOrDefault() != null)
{
js += getNonlinearityTable(Rotation, FloatPositionValues[0], FloatPositionValues[1], true);
js += " if (NonlinearityTable.length > 0) {" + Environment.NewLine;
js += " Minimum = NonlinearityTable[0][0];" + Environment.NewLine;
js += " ExpressionResult = Math.max(ExpressionResult, Minimum);" + Environment.NewLine;
js += " Maximum = NonlinearityTable[NonlinearityTable.length-1][0];" + Environment.NewLine;
js += " ExpressionResult = Math.min(ExpressionResult, Maximum);" + Environment.NewLine;
js += " var prevAngle = 0;" + Environment.NewLine;
js += " var result = 0;" + Environment.NewLine;
js += " var prevVal = Minimum;" + Environment.NewLine;
js += " for (var i = 0; i < NonlinearityTable.length; i++) {" + Environment.NewLine;
js += " var NonlinearityEntry = NonlinearityTable[i][0];" + Environment.NewLine;
js += " var NonlinearityAngle = NonlinearityTable[i][1];" + Environment.NewLine;
js += " if (NonlinearityAngle < 0) { NonlinearityAngle += 360 };" + Environment.NewLine;
js += " if (ExpressionResult == NonlinearityEntry || prevAngle == NonlinearityAngle && ExpressionResult > prevVal && ExpressionResult < NonlinearityEntry) {" + Environment.NewLine;
js += " result = NonlinearityAngle;" + Environment.NewLine;
js += " break;" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " else if (ExpressionResult > prevVal && ExpressionResult < NonlinearityEntry ) {" + Environment.NewLine;
js += " var coef = 1 - (NonlinearityEntry - ExpressionResult) / (NonlinearityEntry - prevVal);" + Environment.NewLine + Environment.NewLine;
js += " result = prevAngle + coef * (NonlinearityAngle - prevAngle);" + Environment.NewLine;
js += " break;" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " prevVal = NonlinearityEntry;" + Environment.NewLine;
js += " prevAngle = NonlinearityAngle;" + Environment.NewLine;
js += " }" + Environment.NewLine + Environment.NewLine;
js += " if (Minimum >= 0)" + Environment.NewLine;
js += " while (result < 0)" + Environment.NewLine;
js += " result += 360;" + Environment.NewLine + Environment.NewLine;
js += " transform += 'rotate(' + (result + PointsTo) + 'deg) ';" + Environment.NewLine;
js += " }" + Environment.NewLine + Environment.NewLine;
}
// LINEAR
else
{
js += " transform += 'rotate(' + (ExpressionResult * 180 / Math.PI + PointsTo) + 'deg) ';" + Environment.NewLine;
}
js += " }" + Environment.NewLine;
}
}
// PERFORM SHIFT
if (Shift != null)
{
Expression = Shift.Elements("Expression").FirstOrDefault();
if (Expression == null)
Expression = Shift.Elements("Value").FirstOrDefault();
if (Expression != null)
{
js += " {" + Environment.NewLine;
expressionRoutin(Expression, FsxVarHelper, globalVars);
// NONLINEAR
if (Shift.Elements("NonlinearityTable").FirstOrDefault() != null || Shift.Elements("Nonlinearity").FirstOrDefault() != null)
{
js += getNonlinearityTable(Shift, "0", "0", false);
js += " if (NonlinearityTable.length > 0) {" + Environment.NewLine;
js += " Minimum = NonlinearityTable[0][0];" + Environment.NewLine;
js += " ExpressionResult = Math.max(ExpressionResult, Minimum);" + Environment.NewLine;
js += " Maximum = NonlinearityTable[NonlinearityTable.length-1][0];" + Environment.NewLine;
js += " ExpressionResult = Math.min(ExpressionResult, Maximum);" + Environment.NewLine;
js += " var prevP2 = { x: 0, y: 0 };" + Environment.NewLine;
js += " var result = { x: 0, y: 0 };" + Environment.NewLine;
js += " var prevVal = Minimum;" + Environment.NewLine;
js += " for (var i = 0; i < NonlinearityTable.length; i++) {" + Environment.NewLine;
js += " var NonlinearityEntry = NonlinearityTable[i][0];" + Environment.NewLine;
js += " var p2 = { x: NonlinearityTable[i][1], y: NonlinearityTable[i][2] };" + Environment.NewLine;
js += " if (ExpressionResult == NonlinearityEntry) {" + Environment.NewLine;
js += " result = p2;" + Environment.NewLine;
js += " break;" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " else if (ExpressionResult > prevVal && ExpressionResult < NonlinearityEntry ) {" + Environment.NewLine;
js += " var coef = 1 - (NonlinearityEntry - ExpressionResult) / (NonlinearityEntry - prevVal);" + Environment.NewLine + Environment.NewLine;
js += " result = { y: prevP2.y + coef * (p2.y - prevP2.y), x: prevP2.x + coef * (p2.x - prevP2.x) };" + Environment.NewLine;
js += " break;" + Environment.NewLine;
js += " }" + Environment.NewLine;
js += " prevVal = NonlinearityEntry;" + Environment.NewLine;
js += " prevP2 = p2;" + Environment.NewLine;
js += " }" + Environment.NewLine + Environment.NewLine;
js += " " + sanitizedSlug + ".style.left = result.x + 'px';" + Environment.NewLine;
js += " " + sanitizedSlug + ".style.top = result.y +'px';" + Environment.NewLine;
js += " }" + Environment.NewLine + Environment.NewLine;
}
// LINEAR
else
{
// GET SCALE
double[] scale = new double[] { 1.0, 0.0 };
XElement Scale = Shift.Elements("Scale").FirstOrDefault();
string[] ScaleValues = getXYvalue(Scale);
if (Scale != null && Double.TryParse(ScaleValues[0], out double scaleX) && Double.TryParse(ScaleValues[1], out double scaleY))
scale = new double[] { scaleX, scaleY };
js += " transform += 'translate(' + (ExpressionResult * " + scale[0] + ") + 'px, ' + (ExpressionResult * " + scale[1] + ") + 'px) ';" + Environment.NewLine;
}
js += " }" + Environment.NewLine;
}
}
// TEXT
if (GaugeText != null)
{
XElement id = GaugeText.Element("id");
XElement Alpha = GaugeText.Element("Alpha");
XElement TextAxis = GaugeText.Element("Axis");
XElement BackgroundColor = GaugeText.Element("BackgroundColor");
XElement BackgroundColorScript = GaugeText.Element("BackgroundColorScript");
XElement BlinkCode = GaugeText.Element("BlinkCode");
XElement Bold = GaugeText.Element("Bold");
XElement Bright = GaugeText.Element("Bright");
XElement Caption = GaugeText.Element("Caption");
XElement Charset = GaugeText.Element("Charset");
XElement DegreesPointsTo = GaugeText.Element("DegreesPointsTo");
XElement Fixed = GaugeText.Element("Fixed");
XElement FontFace = GaugeText.Element("FontFace");
XElement FontFaceLocalize = GaugeText.Element("FontFaceLocalize");
XElement FontColor = GaugeText.Element("FontColor");
XElement FontColorScript = GaugeText.Element("FontColorScript");
XElement FontHeight = GaugeText.Element("FontHeight");
XElement FontHeightScript = GaugeText.Element("FontHeightScript");
XElement FontWeight = GaugeText.Element("FontWeight");
XElement GaugeString = GaugeText.Element("GaugeString");
XElement HilightColor = GaugeText.Element("HilightColor");
XElement HorizontalAlign = GaugeText.Element("HorizontalAlign");
XElement Italic = GaugeText.Element("Italic");
XElement Length = GaugeText.Element("Length");
XElement LineSpacing = GaugeText.Element("LineSpacing");
XElement Luminous = GaugeText.Element("Luminous");
XElement Multiline = GaugeText.Element("Multiline");
XElement PointsTo = GaugeText.Element("PointsTo");
XElement ScrollY = GaugeText.Element("ScrollY");
XElement Size = GaugeText.Element("Size");
XElement HeightScript = GaugeText.Element("HeightScript");
XElement WidthScript = GaugeText.Element("WidthScript");
XElement StrikeThrough = GaugeText.Element("StrikeThrough");
XElement Tabs = GaugeText.Element("Tabs");
XElement TextTransparent = GaugeText.Element("Transparent");
XElement Underline = GaugeText.Element("Underline");
XElement VerticalAlign = GaugeText.Element("VerticalAlign");
XElement WidthFit = GaugeText.Element("WidthFit");
string value = GaugeString != null ? FsxVarHelper.fsx2msfsGaugeString(GaugeString.Value.Trim(), this, globalVars) : "";
string[] GaugeSize = getXYvalue(Size, false);
//if (id != null) { css += " rule: " + id.Value + ";" + Environment.NewLine; }
//if (Alpha != null) { css += " rule: " + Alpha.Value + ";" + Environment.NewLine; }
//if (Axis != null) { css += " transform-origin: " + getXYvalue(Axis)[0] + "px " + getXYvalue(Axis)[1] + "px;" + Environment.NewLine; }
if (BackgroundColor != null) { css += " background-color: " + BackgroundColor.Value.Replace("0x", "#") + ";" + Environment.NewLine; }
if (Bold != null && Bold.Value == "True") { css += " font-weight: bold;" + Environment.NewLine; }
//if (Bright != null) { css += " rule: " + Bright.Value + ";" + Environment.NewLine; }
//if (Caption != null) { css += " rule: " + Caption.Value + ";" + Environment.NewLine; }
//if (Charset != null) { css += " rule: " + Charset.Value + ";" + Environment.NewLine; }
//if (DegreesPointsTo != null) { css += " rule: " + DegreesPointsTo.Value + ";" + Environment.NewLine; }
if (Fixed != null && Fixed.Value == "True" || Multiline == null || Multiline.Value == "False") { css += " white-space: nowrap; overflow: hidden;" + Environment.NewLine; }
if (FontFace != null) { css += " font-family: \"" + FontFace.Value + "\";" + Environment.NewLine; }
//if (FontFaceLocalize != null) { css += " rule: " + FontFaceLocalize.Value + ";" + Environment.NewLine; }
if (FontColor != null) { css += " color: " + FontColor.Value.Replace("0x", "#") + ";" + Environment.NewLine; }
if (FontHeight != null) { css += " font-size: " + FontHeight.Value + "px;" + Environment.NewLine; }
if (FontHeightScript != null) { css += " font-size: " + FontHeightScript.Value + "px;" + Environment.NewLine; }
if (FontWeight != null) { css += " font-weight: " + FontWeight.Value + ";" + Environment.NewLine; }
//if (HilightColor != null) { css += " rule: " + HilightColor.Value + ";" + Environment.NewLine; }
if (HorizontalAlign != null) { css += " text-align: " + HorizontalAlign.Value + ";" + Environment.NewLine; }
if (Italic != null && Italic.Value == "True") { css += " font-style: italic;" + Environment.NewLine; }
if (Length != null) { css += " overflow: hidden; max-width: " + Length.Value + "ch;" + Environment.NewLine; }
if (LineSpacing != null) { css += " line-height: " + LineSpacing.Value + "px;" + Environment.NewLine; }
//if (Luminous != null) { css += " rule: " + Luminous.Value + ";" + Environment.NewLine; }
//if (Multiline != null) { css += " rule: " + Multiline.Value + ";" + Environment.NewLine; }
//if (PointsTo != null) { css += " rule: " + PointsTo.Value + ";" + Environment.NewLine; }
//if (ScrollY != null) { css += " rule: " + ScrollY.Value + ";" + Environment.NewLine; }
if (GaugeSize[0] != "0" && GaugeSize[1] != "0")
css += " width: " + GaugeSize[0] + "px;" + Environment.NewLine + " height: " + GaugeSize[1] + "px;" + Environment.NewLine;
if (StrikeThrough != null && StrikeThrough.Value == "True") { css += " text-decoration: line-through;" + Environment.NewLine; }
//if (Tabs != null) { css += " rule: " + Tabs.Value + ";" + Environment.NewLine; }
if (TextTransparent != null && TextTransparent.Value == "True") { css += " background: transparent;" + Environment.NewLine; }
if (Underline != null && Underline.Value == "True") { css += " text-decoration: underline;" + Environment.NewLine; }
if (VerticalAlign != null) { css += " vertical-align: " + VerticalAlign.Value + ";" + Environment.NewLine; }
if (WidthFit != null && WidthFit.Value == "True") { css += " font-size: 4vw;;" + Environment.NewLine; }
//* if (BlinkCode != null) { css += " rule: " + BlinkCode.Value + ";" + Environment.NewLine; }
if (HeightScript != null) { js += " " + sanitizedSlug + ".style.height = " + FsxVarHelper.fsx2msfsGaugeString(HeightScript.Value.Trim(), this, globalVars) + " + \"px\";" + Environment.NewLine; }
if (WidthScript != null) { js += " " + sanitizedSlug + ".style.width = " + FsxVarHelper.fsx2msfsGaugeString(WidthScript.Value.Trim(), this, globalVars) + " + \"px\";" + Environment.NewLine; }
if (FontColorScript != null) { js += " " + sanitizedSlug + ".style.color = " + hexToString(FsxVarHelper.fsx2msfsGaugeString(FontColorScript.Value.Trim(), this, globalVars)) + ";" + Environment.NewLine; }
if (BackgroundColorScript != null) { js += " " + sanitizedSlug + ".style.backgroundColor = " + hexToString(FsxVarHelper.fsx2msfsGaugeString(BackgroundColorScript.Value.Trim(), this, globalVars)) + ";" + Environment.NewLine; }
if (GaugeString != null && !string.IsNullOrEmpty(value)) { js += " " + sanitizedSlug + ".innerHTML = " + value + ";" + Environment.NewLine + Environment.NewLine; }
}
js += " if (transform != '')" + Environment.NewLine;
js += " " + sanitizedSlug + ".style.transform = transform; " + Environment.NewLine + Environment.NewLine;
js += " }" + Environment.NewLine;
css += " }" + Environment.NewLine;
// PROCESS CHILDREN
var gaugeElements = gaugeElement.Elements("Element");
foreach (XElement childElement in gaugeElements)
{
processGaugeElement(childElement, FsxVarHelper, atts, depth + 1);
}
// END ELEMENT CONTAINER
for (int i = 0; i < depth; i++) { html += " "; }
html += " </div>" + Environment.NewLine;
// RENDER MASK LAST
if (MaskImage != null)
{
for (int i = 0; i < depth; i++) { html += " "; }
html += " <div id=\"" + sanitizedSlug + "_mask_image\"></div>" + Environment.NewLine;
depth--;
for (int i = 0; i < depth; i++) { html += " "; }
html += " </div>" + Environment.NewLine;
}
}
private string hexToString(string hex)
{
hex = hex.Replace("0x", "#").Trim();
if (hex[0] == '#' && hex.Length == 7)
hex = "\"" + hex + "\"";
//hex = Regex.Replace(hex.Replace("0x", "#"), @"(#[A-Fa-f0-9]{6})", "\"$1\"");
return hex;
}
private void expressionRoutin(XElement Expression, fsxVarHelper FsxVarHelper, string globalVars)
{
if (Expression.Elements("Script").FirstOrDefault() != null)
js += " " + FsxVarHelper.fsx2msfsSimVar(Expression.Elements("Script").FirstOrDefault().Value, this, true, globalVars) + Environment.NewLine;
else if (Expression.Value.Length > 0 && Expression.Value[0] != '<' && Expression.Value.Contains(')') && Expression.Value.Contains('('))
js += " " + FsxVarHelper.fsx2msfsSimVar(Expression.Value, this, true, globalVars) + Environment.NewLine;
else
js += " var ExpressionResult = 0; /* NO SCRIPT NODE FOUND!!! */" + Environment.NewLine;
if (Expression.Elements("Minimum").FirstOrDefault() != null)
{
js += " var Minimum = " + Expression.Elements("Minimum").FirstOrDefault().Value + ";" + Environment.NewLine;
js += " ExpressionResult = Math.max(ExpressionResult, Minimum);" + Environment.NewLine;
}
else if (Expression.Attribute("Minimum") != null)
{
js += " var Minimum = " + Expression.Attribute("Minimum").Value + ";" + Environment.NewLine;
js += " ExpressionResult = Math.max(ExpressionResult, Minimum);" + Environment.NewLine;
}
else
{
js += " var Minimum = 0;" + Environment.NewLine;
}
if (Expression.Elements("Maximum").FirstOrDefault() != null)
{
js += " var Maximum = " + Expression.Elements("Maximum").FirstOrDefault().Value + ";" + Environment.NewLine;
js += " ExpressionResult = Math.min(ExpressionResult, Maximum);" + Environment.NewLine;
}
else if (Expression.Attribute("Maximum") != null)
{
js += " var Maximum = " + Expression.Attribute("Maximum").Value + ";" + Environment.NewLine;
js += " ExpressionResult = Math.min(ExpressionResult, Maximum);" + Environment.NewLine;
}
else
{
js += " var Maximum = 999999999;" + Environment.NewLine;
}
}
public string getNonlinearityTable(XElement parent, string centerX, string centerY, bool isAngle)
{
string js = "";
prevPoint = new double[2];
prevAngle = -9999;
rotationDirection = 0;
js += " var NonlinearityTable = [" + Environment.NewLine;
if (parent.Elements("NonlinearityTable").FirstOrDefault() != null)
foreach (var NonlinearityEntry in parent.Elements("NonlinearityTable").FirstOrDefault().Elements("NonlinearityEntry"))
{
string NonlinearExpressionResult = NonlinearityEntry.Elements("ExpressionResult").FirstOrDefault().Value;
string[] NonlinearFloatPositionValues = getXYvalue(NonlinearityEntry.Elements("FloatPosition").FirstOrDefault());
if (isAngle)
{
if (double.TryParse(NonlinearFloatPositionValues[0], out double xVal) && double.TryParse(NonlinearFloatPositionValues[1], out double yVal) && double.TryParse(centerX, out double xCen) && double.TryParse(centerY, out double yCen))
{
js += getNonlinearityAngle(NonlinearExpressionResult, xVal, xCen, yVal, yCen);
}
}
else
js += " [" + NonlinearExpressionResult + "," + NonlinearFloatPositionValues[0] + "," + NonlinearFloatPositionValues[1] + "]," + Environment.NewLine;
}
else if (parent.Elements("Nonlinearity").FirstOrDefault() != null)
foreach (var NonlinearityEntry in parent.Elements("Nonlinearity").FirstOrDefault().Elements("Item"))
{
// XY
if (NonlinearityEntry.Attribute("Value") != null && NonlinearityEntry.Attribute("X") != null && NonlinearityEntry.Attribute("Y") != null)
{
string NonlinearExpressionResult = NonlinearityEntry.Attribute("Value").Value;
string X = NonlinearityEntry.Attribute("X").Value;
string Y = NonlinearityEntry.Attribute("Y").Value;
if (isAngle)
{
if (double.TryParse(X, out double xVal) && double.TryParse(Y, out double yVal) && double.TryParse(centerX, out double xCen) && double.TryParse(centerY, out double yCen))
js += getNonlinearityAngle(NonlinearExpressionResult, xVal, xCen, yVal, yCen);
} else
js += " [" + NonlinearExpressionResult + "," + NonlinearityEntry.Attribute("X").Value + "," + NonlinearityEntry.Attribute("Y").Value + "]," + Environment.NewLine;
}
// DEGREES
else if (NonlinearityEntry.Attribute("Value") != null && NonlinearityEntry.Attribute("Degrees") != null)
{
string NonlinearExpressionResult = NonlinearityEntry.Attribute("Value").Value;
string Degrees = NonlinearityEntry.Attribute("Degrees").Value;
if (isAngle)
{
js += " [" + NonlinearExpressionResult + ", " + Degrees + "]," + Environment.NewLine;
}
else
{
if (double.TryParse(Degrees, out double angle) && int.TryParse(centerX, out int intX) && int.TryParse(centerY, out int intY))
{
js += " [" + NonlinearExpressionResult + "," + (intX + 10 * Math.Sin(angle * Math.PI / 180)) + "," + (intY + 10 * Math.Cos(angle * Math.PI / 180)) + "]," + Environment.NewLine;
}
}
}
}
js += " ];" + Environment.NewLine + Environment.NewLine;
return js;
}
private string getNonlinearityAngle(string NonlinearExpressionResult, double xVal, double xCen, double yVal, double yCen) {
string js = "";
double currAngle = Math.Atan2(yVal - yCen, xVal - xCen) * 180 / Math.PI + 90;
currAngle += 360;
// FIND OUT DIRECTION
if (prevAngle != -9999 && prevAngle != currAngle && rotationDirection == 0)
{
double transformedX = (xVal - xCen) * Math.Cos(prevAngle / 180 * Math.PI) + (yVal - yCen) * Math.Sin(prevAngle / 180 * Math.PI);
double transformedY = (yVal - yCen) * Math.Cos(prevAngle / 180 * Math.PI) + (xVal - xCen) * Math.Sin(prevAngle / 180 * Math.PI);
rotationDirection = transformedX >= 0 ? 1 : -1;
}
if (rotationDirection != 0)
{
while (currAngle > prevAngle && rotationDirection == -1)
currAngle -= 360;
while (currAngle < prevAngle && rotationDirection == 1)
currAngle += 360;
}
js += " [" + NonlinearExpressionResult + ", " + currAngle + "]," + Environment.NewLine;
prevAngle = currAngle;
prevPoint = new double[] { xVal, yVal };
return js;
}
public string[] getXYvalue(XElement Size, bool returnEmpty = true)
{
if (Size != null)
{
if (Size.Attribute("X") != null && !String.IsNullOrEmpty(Size.Attribute("X").Value) || Size.Attribute("Y") != null && !String.IsNullOrEmpty(Size.Attribute("Y").Value))
{
return new string[] {
Size.Attribute("X") != null && !String.IsNullOrEmpty(Size.Attribute("X").Value) ? Size.Attribute("X").Value.Trim() : "0",
Size.Attribute("Y") != null && !String.IsNullOrEmpty(Size.Attribute("Y").Value) ? Size.Attribute("Y").Value.Trim() : "0"
};
}
else if (Size.Attribute("ImageSizes") != null && !String.IsNullOrEmpty(Size.Attribute("ImageSizes").Value) && Size.Attribute("ImageSizes").Value.Contains(','))
return new string[] { Size.Attribute("ImageSizes").Value.Split(',')[0].Trim(), Size.Attribute("ImageSizes").Value.Split(',')[1].Trim() };
else if (!String.IsNullOrEmpty(Size.Value) && Size.Value.Contains(','))
return new string[] { Size.Value.Split(',')[0].Trim(), Size.Value.Split(',')[1].Trim() };
}
//if (returnEmpty)
return new string[] { "0", "0" };
//else
//return new string[] { "500", "500" };
}
private Bitmap setBitmapGamma(Bitmap oldBmp, float gamma, bool transparent, string sourceFile)
{
// ARGB CONVERSION
Bitmap newBmp;
Bitmap bmp;
newBmp = new Bitmap(oldBmp);
bmp = newBmp.Clone(new Rectangle(0, 0, newBmp.Width, newBmp.Height), PixelFormat.Format32bppArgb);
// TRANSPARENCY CHECK
if (transparent)
bmp = MakeBitmapTransparent(bmp, sourceFile);
// SET GAMMA
if (gamma < 0.99f || gamma > 1.01f)
bmp = setBitmapGammaFunct(bmp, gamma);
return bmp;
}
private Bitmap setBitmapGammaFunct(Bitmap bmp, float gamma)
{
ImageAttributes attributes = new ImageAttributes();
attributes.SetGamma(gamma);
System.Drawing.Point[] points =
{
new System.Drawing.Point(0, 0),
new System.Drawing.Point(bmp.Width, 0),
new System.Drawing.Point(0, bmp.Height),
};
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
Bitmap newBmp = new Bitmap(bmp.Width, bmp.Height);
using (Graphics graphics = Graphics.FromImage(newBmp))
{
graphics.DrawImage(bmp, points, rect, GraphicsUnit.Pixel, attributes);
}
return newBmp;
}
private string probablyFixBmpName(string name)
{
if (Path.GetFileName(name) == Path.GetFileNameWithoutExtension(name))
return name + ".bmp";
return name;
}
public void writeLog(string lines)
{
logcontent += lines + Environment.NewLine;
}
public void saveLog()
{
Console.WriteLine("Saving log content into " + logfile);
if (!String.IsNullOrEmpty(logfile) && !String.IsNullOrEmpty(logcontent))
{
try { File.WriteAllText(logfile, logcontent); }
catch (Exception e) { MessageBox.Show("Can't save logfile" + Environment.NewLine + "Error: " + e.Message); }
}
else
{
Console.WriteLine(logcontent);
}
}
public string sanitizeString(string val)
{
return Regex.Replace(val, @"[^0-9A-Za-z ,_\-]", "").Replace(" ", "_").Replace("-", "_").Replace(",", "_");
}
private Bitmap MakeBitmapTransparent(Bitmap bmp, string sourceFile)
{
bool transpApplied = false;
// writeLog("Processing image: " + Path.GetFileNameWithoutExtension(sourceFile) + " (" + bmp.GetPixel(0, 0).ToString() + ")");
if (bmp.GetPixel(0, 0) == Color.FromArgb(255, 1, 1, 1) || bmp.GetPixel(bmp.Width / 2, bmp.Height / 2) == Color.FromArgb(255, 1, 1, 1))
{
bmp.MakeTransparent(Color.FromArgb(255, 1, 1, 1));
transpApplied = true;
}
if (!transpApplied || imagesForceTransparancy.Contains(Path.GetFileNameWithoutExtension(sourceFile)))
if (bmp.GetPixel(0, 0) == Color.FromArgb(255, 0, 0, 0) || bmp.GetPixel(bmp.Width / 2, bmp.Height / 2) == Color.FromArgb(255, 0, 0, 0))
{
bmp.MakeTransparent(Color.FromArgb(255, 0, 0, 0));
transpApplied = true;
}
if (!transpApplied || imagesForceTransparancy.Contains(Path.GetFileNameWithoutExtension(sourceFile)))
if (bmp.GetPixel(0, 0) == Color.FromArgb(255, 255, 255, 255) || bmp.GetPixel(bmp.Width / 2, bmp.Height / 2) == Color.FromArgb(255, 255, 255, 255))
{
bmp.MakeTransparent(Color.FromArgb(255, 255, 255, 255));
transpApplied = true;
}
return bmp;
}
private string[] getSizeException (string slug, string[][] exceptionsArray)
{
for (int x = 0; x < exceptionsArray.GetLength(0); x++)
{
if (Equals(exceptionsArray[x][0], slug))
{
return new string[] { exceptionsArray[x][1], exceptionsArray[x][2] };
}
}
return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace msfsLegacyImporter
{
class mdlHelper
{
//Mdl g = Mdl.FromFile("path/to/some.gif");
}
}
<file_sep>[SECURITY_NOTICE]
EXE file of this application is unsigned, so Windows Defender/some other antivirus software may be triggered. Sometimes it even blocking EXE file as malware (before or after archive extraction), it happen because of signatures comparison technology that does not analyze real program functionality but searching matches in binary data.
Each update build was submit into Microsoft Security Intelligence service to make sure it will be not blocked by Windows Defender, but it take days until cloud database, and then your client, will be updated. If you experience such issue - you may try to apply security intelligence manual update following this instruction [https://www.microsoft.com/en-us/wdsi/defenderupdates] and then try to run application again.
If you are using some different antivirus software - you can send file for detailed analysis manually, such service available for most services. Usually it takes 2-4 hours to complete, as result EXE file will be whitelisted after next signatures update.
If it still does not work and you do not trust program developer - don't use it for now and wait for the release version.
[DESCRIPTION]
This is complex tool for importing Microsoft Flight Simulator X (FSX, 2006) aircraft into Microsoft Flight Simulator (MSFS, 2020). It does apply all required actions for successful import (like files copying, JSON files generation, critical issues fixing, 2D gauges conversion and other useful stuff). Two levels of import available - Basic and Full. First one providing list of fixes for various critical issues, lights and textures conversion, 2D gauges import. Second also have tools for CFG files manipulations and AIR data migration.
Program still in development stage, but you can participate in testing and report about any issues you have. MSFS engine has its own limitations and issues of Legacy aircraft support, be sure you are importing native FSX aircraft (not FS2004, FS9 or P3D-only) before reporting issues.
[PROVIDED_FEATURES]
- copy files from FSX to MSFS Community folder with proper structure
- generate layout.json file with list of files
- generate manifest.json file based on loaded from aircraft package data (manual edit possible)
- load existing legacy or native MSFS aircraft
- split AIRCRAFT.CFG on relative CFG files
- insert missing values into imported CFG file(s)
- insert missing CFG file sections on user choice
- populate missing performance values from description
- fix ui_typerole invalid value
- insert external view gauges
- set speed indicator limits from cruise_speed value
- detect buggy engine values (engine_type and afterburner_available)
- adjust engines output power
- apply afterburner thrust
- display afterburner flame animation
- fix runway issues (gears raised, fuel pump disabled, parking brakes disabled)
- fix contact points duplicates (stuck landing gear issue)
- notify about contact point formatting issues
- convert exterior/interior lights
- insert taxi lights
- bulk convert of BMP textures to DDS
- import AIR values into CFG files
- import 2D gauges (WIP)
- toggle aircraft sounds
- insert/remove variometer tone
- backup and restore editable files
- inform about available program update, perform self update if triggered by user
[POSSIBLE_ISSUES]
- game crashing to desktop (ensure aircraft contain both exterior and interiors files inside of MODEL folder)
- cockpit instruments do not work (not displayed or inoperate, conversion script status is WIP)
- aircraft appear in the list, but model is invisible because of unsupported model format
- engines switched off when player taking control of some aircraft on the runway (try Ctrl+E)
- turbine engines under powered at thrust level more than 40%
- inaccurate flight model
- window glass texture without opacity (you can try to adjust glass material properties in ModelConverterX)
[INSTALLATION]
- download the latest version archive from https://www.nexusmods.com/microsoftflightsimulator/mods/117
- unpack files into some folder, launch "msfsLegacyImporter.exe"
[UNINSTALL]
- delete folder
[REQUIREMENTS]
- Windows 7/8/10
- .NET 4.5
[VIDEO_TUTORIALS]
https://www.youtube.com/watch?v=Tt_6Vsp9xZY
https://www.youtube.com/watch?v=wNFbwr3KstE
https://www.youtube.com/watch?v=O80P73twn5E
https://www.youtube.com/watch?v=L77aG5UABS4
https://www.youtube.com/watch?v=g00a3mDRZIA
[CFG_PARSER]
Application loading all required CFG and FLT filed into the memory once aircraft loaded or imported, and updating local files values after each user action.
If some files was edited manually while aircraft data loaded into the memory, notification appear that files should be reloaded.
To avoid parsing issues, keep files formatting properly (comment symbol is ";", no spaces inside of [SECTION_NAME], inactive (disabled) parameters has ";-" at the beginning of line)
0. Main Screen
0.1 Left side - new import from FSX. On press, import form will appear. Original FSX aircraft folder should be selected first (usually inside of [FSX]\SimObjects\Airplanes\ but may be unpacked aircraft directory). Perfectly, it could be stock airplane with analogue 2D or 3D gauges. After Community folder is selected and fields populated, import can be performed. After successful import tabs with available instruments will appear.
0.2 Right side - load MSFS aircraft. Button Browse will appear, after pressing it you'll need to find legacy or native aircraft folder inside of MSFS Community directory. After folder is selected, available CFG files and textures will be scanned, related tabs will show up. If you have not converted any aircraft yet (with Importer or any other method), use section 0.1 first.
0.3 Languages dropdown rely on CSV files inside of "lngFls" folder of the program. Detailed instructions about how to update translation files manually or add new language are here https://docs.google.com/document/d/1TRCWeobJksmINLaV6u7aRGjeSFQSA2fUx-Mlua6z4IM/edit?usp=sharing
1. Init page
1.1 Current aircraft information
1.2 Update LAYOUT.JSON section can be triggered manually if you are moving/renaming files inside of aircraft. When you're using Importer features that affects files and folders (like CFG split of textures conversion), this option being triggered automatically, no need to press it after each operation.
1.3 Current import mode information. If current mode is Basic, Full import mode button will be at the bottom. Before proceed, important to check that all sections in AIRCRAFT.CFG labeled properly - in format like '[SECTION_NAME]' (not ';[SECTION_NAME]' or '[ SECTION NAME ]' ). When pressed, script will compare template CFGs (taken from MSFS generic plane) with aircraft.cfg and move presented sections in relative files. Original aircraft.cfg file will be renamed to ".aircraft.cfg" and ignored by JSON generator. You can remove it if you want but it does not affect the game anyway. After processing, layout.json will be regenerated automatically
1.4 If current mode is Full import, list of CFG files inside of aircraft folder. If all of them presented - no actions required. If some/all except aircraft.cfg are missing - Process button available.
1.5 If "unknown.cfg" file appear after processing - some of the sections was not found in templates, first thing to do is check that unrecognized sections labels written correctly. If you sure, that that section was not moved to proper CFG file by mistake - please report.
2. Aircraft
2.1 Missing or invalid aircraft parameters list. You can check all/some options and press the button below, script will try to search for selected values in aircraft description, but they may be not presented. If some of the notifies left unresolved, you can add missing values in aircraft.cfg file manually. Red values are usually critical, without fixing them you may experience dramatic issues in the game.
2.2 Sections list of this file. In green - presented sections (but it still may have some missing/disabled values), in orange - missing but not required sections, in red - highly likely missing required section for this aircraft.
2.3 Once some sections selected and Insert button pressed, you will be asked about new variables - if you press YES, all default values will be inserted into file as active parameters, if NO - inactive. It is recommended to choose YES for sections colored in RED.
2.4 If DLL files exists in aircraft folder, message appear about partially working avionics
2.5 Backup button available on all editable sections, once created - it can be clicked to restore original file. Backup file can be removed only manually.
3. Engines
3.1 Script checking values of critical parameters
3.2 If checkbox checked near some of the wrong parameter, they will be set to "0" after button pressed
3.3 For jets afterburner adjustment available. You can use this tool to apply afterburner boost to engines parameters. Thrust will be increased for throttle positions greater than threshold value, same value will be set as a start point for flame animation (script should be inserted from Panels tab, and also variables replaced from Models tab). Table below represents thrust modifier (Y axis, from 0 to 300%) and throttle position (from 0 to 100%). Two lines are subsonic (black) and supersonic (red) speed. Be sure Black line stays between 100% and 200%, otherwise you will get too much power.
3.4 Engines power rough adjustments buttons change value of "static_thrust" for turbine engine and "power_scalar" for piston engine
3.5 AIR data import available if TXT dump of AIR file exists in aircraft folder
3.6 To create AIR dump, get AirUpdate program ( http://www.mudpond.org/ ) and unpack it into Importer directory, launch it, select AIR file inside of aircraft folder, check "Full dump" and press "Dump" button. TXT file should be saved in aircraft directory with same name as AIR file (with .txt extension)
3.7 All available values will appear in comparison table "AIR value" - "current or default" (if current is missing) value, it is recommended to validate all lines visually
3.8 You can import all available values, or ignore zero/flat tables
3.9 After import, you'll need to fix all untouched modern values manually
3.10 List of sections at the bottom (same as 2.7-2.8)
4. FlightModel
4.1 List of gears contact points that attached to same landing wheel (usually cause "stuck landing gear" bug).
4.2 When both points of same pair selected, they will be moved in their middle position.
4.3 If some points will be not properly formatted (like missing comma delimeter), they will be listed in red color. Manual fixing is required.
4.4 Missing critical flight model values list, some of them required only after AIR file import
4.4 AIR data import table same as in 3.4-3.8
4.5 To import all flight model values, you'll need to add AERODYNAMICS section. You may choose either option - insert default values or leave them disabled, but in second case you'll need to fix and enable them manually otherwise game will crash (all values inside of this section except "_table" are critical).
4.6 After both engines and flight model data imported, AIR file can be disabled so game will no longer read it. If some critical CFG values are not set, game may crash on loading process.
4.7 List of sections at the bottom (same as 2.7-2.8)
5. Cockpit (Full import mode)
5.1 Script is checking for instruments and gauges presence (but not their statuses, so if some gauge marked in green it still can be disabled or not configured)
5.2 In red marked missing instruments, that appear on external view. So it is recommended to enable them.
5.3 After button pressed, template values for each selected gauge will be inserted into the cockpit.cfg file.
5.4 AIRSPEED indicator values will be updated automatically (if cruise_speed value set in AIRCRAFT.CFG/FLIGHT_MODEL.CFG) but that method is inaccurate. After adding instruments you have to apply manual corrections to their values manually in COCKPIT.CFG file.
6. Systems
6.1 List of lights listed here. If some of them in FSX format, you can select checkboxes and press convert button. FSX has much shorter list of light effects compare to MSFS so possibly you will see not exactly the same effect in the game. You may need to adjust direction coordinates after conversion (by default set to 0,0,0)
6.2 If aircraft does not have taxi or landing lights, you will see list of landing gear points, to which taxi lights can be attached (raised 3ft). No animation, so lights always stay in same position. You can always adjust their position manually (format: type, left/right, forward/backward, down/up). In panel tab you can find option to include automatic switch for taxi lights.
6.3 List of sections (same as 2.7-2.8)
7. Runway (Full import mode only)
7.1 Configs section for Runway state (affect aircraft avionics state once you get controls on the ground).
7.2 May fix issues like raised landing gears, parking brakes disabled, fuel pumps/valves disabled
8. Textures
8.1 List of BMP textures inside of Textures (Textures.*) folder that should be converted
8.2 Two conversion tools available, you can try both if conversion failed with first one
8.3 On convert button press, BMPs converted into DX5 flipped DDS
8.4 Original BMPs will be stored as back up by adding dot to their names, but they can be removed anytime if DDS textures looks fine in the game
9. Models
9.1 Program read model.cfg file(s) and get name of "exterior" model. To make possible for custom script (that can be injected on Panels tab) to control afterburner animation, broken variables should be replaced in exterior models content.
9.2 This process can take up to several minutes, so be patient. If models disappear from the list after processing, replacement was successful.
9.3 Program read model.cfg file(s) and get name of "interior" model, if it exists. Clickable elements in that model can be disabled to avoid game crash since MSFS ver1.8.3.0, or for any other reason
9.4 After Remove button pressed, backup of MDL file will be created (only if it does not exists) and _CVC_ folder (cache) of this aircraft cleared
9.5 Original MDL can be restored by clicking button in right top corner of Models tab
9.6 If no interior file found - you will see notification about that, such arcraft will cause CTD
9.7 If MDL file has wrong format key (should be MDLX) - you will see notification about that, usually such arcraft cause CTD
10 Sounds
10.1 List of sound samples, used by aircraft. Each sound can be enabled or disabled anytime.
10.2 If sound.xml file does not exist yet, variometer tone button will be available with volume adjustment slider.
10.3 If sound.xml exists, removal button will be there.
11. Panel
11.1 Experimental feature for 2D gauges conversion
11.2 If you have FSX installed, you need to extract default instruments sources first by using top button, they will be stored in "\Community\legacy-vcockpits-instruments\.FSX" directory. Without default instruments sources some/all gauges of current aircraft may not work. However, DLL sources are not supported yet, so some gauges just can't be converted automaically.
11.3 If aircraft panel folder(s) contain CAB files, you need to use second button to extract these sources. If instruments already unpacked into panel folder by releaser, no actions required. You can edit these sources (both images and XML files) as they will be not changed by Importer anymore.
11.4 To convert available panels, check some/all of them of them and press Import button.
11.5 To adjust moving elements and individual gauges backgrounds brightness, use slider. Lower value makes image brighter, higher - darker.
11.6 If you see needles in the cockpit, but no gauges backgrounds appear - check "Force gauge background" option
11.7 If you see black squares in front of gauge elements, check "Force mask background transparency" option
11.8 If gauge size is smaller that spot that exists for it in the mode, check "Leave panel sizeas it in XML" option
11.9 If gauge size does not look right (smaller or larger), check "Scale gauge to fit image" option
11.10 If you want taxi lights to be disabled and enabled automatically (depending on landing gears lever position), check "Insert taxi lights switch" option
11.11 If aircraft model contain fixed afterburner variables, you can insert script that will set this variable depending on engine RPM value, so afterburner animation will be triggered.
11.12 If you are not willing to debug conversion process, check "Hide conversion errors popup" checkbox (detailed log still will be stored in the ".Panel.log.txt" file
11.13 If you experience any problems with imported gauges, you can try again with next update - each fixed issue may affect any FSX aircraft.
11.14 Possible results:
11.14.1 Gauges may get same view as originally in FSX and work as expected, i.e. conversion succeed
11.14.2 Gauges may get texture background and wireframe removed from it, even if it will not functioning properly; wait for updates or check generated JS files
11.14.3 Game crashes or no gauges appear (try to check "Force gauge background") or you see total mess in the cockpit (you can try to copy required files that mentioned in warning messages)
11.14.4 App crashes when you press one of the import buttons, usually because of XML file format issues (feel free to report)
11.15 To remove generated panels: Press "Restore Backup" button on Panel tab, delete /Community/legacy-vcockpits-instruments folder
12. About
12.1 Update availability. If update available, tab label will be colored in red
12.2 Manual update will open zip link in the browser
12.3 Self update will pull update archive from the server, unpack it, replace EXEs and restart process
[CREDITS]
Inspired by <NAME>'s "planeconverter"
Developed with assistance of MFS SDK Discord channel and MS Flight Simulator Gliders FB group members
For AIR data import conversion table was used made by OzWookiee
Many thanks to <NAME>s and FlyFS YouTube channels for promotion
Thanks everyone for bug reports! It really save my time on testing.
Translation credits are inside of About tab of the program<file_sep>using Microsoft.Win32;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Collections.Generic;
using System.Net.Http;
using System.Globalization;
using Microsoft.Deployment.Compression.Cab;
using System.Windows.Controls.Primitives;
using Microsoft.WindowsAPICodePack.Dialogs;
using System.Threading.Tasks;
using System.Windows.Shapes;
namespace msfsLegacyImporter
{
public partial class MainWindow : Window
{
public string EXE_PATH = "msfsLegacyImporter.exe";
public string TEMP_FILE = "temp.zip";
public string updatedirectory = "http://msfs.touching.cloud/legacyimporter/";
public string updateVersion = "";
public string updateURL = "";
public string projectDirectory = "";
public string aircraftDirectory = "";
public string airFilename = "";
public cfgHelper CfgHelper;
private jsonHelper JSONHelper;
private csvHelper CsvHelper;
private xmlHelper XmlHelper;
private fsxVarHelper FsxVarHelper;
private fileDialogHelper FileDialogHelper;
private float gammaSliderPos = 1;
private string communityPath = "";
//private bool extractingCabs = false;
string SourceFolder = "";
string TargetFolder = "";
string currentMode = "";
FileSystemWatcher fileTrackWatcher = null;
public MainWindow()
{
CultureInfo customCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
// REMOVE TEMP FILES
try
{
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\" + EXE_PATH + ".BAK");
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\" + TEMP_FILE);
}
catch { /*MessageBox.Show("Can't delete temporary files");*/ }
// GET COMMUNITY PATH
// MSFS 2020 Windows Store version: C: \Users\*USERNAME *\AppData\Local\Packages\Microsoft.FlightSimulator_8wekyb3d8bbwe\LocalCache\UserCfg.opt
// MSFS 2020 Steam version: C: \Users\*USERNAME *\AppData\Roaming\Microsoft Flight Simulator\UserCfg.opt
try
{
string optPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Packages\Microsoft.FlightSimulator_8wekyb3d8bbwe\LocalCache\UserCfg.opt";
if (!File.Exists(optPath))
optPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft Flight Simulator\UserCfg.opt";
if (File.Exists(optPath))
{
string content = File.ReadAllText(optPath);
Regex regex = new Regex("InstalledPackagesPath\\s+\"(.*)\"");
Match match = regex.Match(content);
if (match.Success && match.Groups.Count > 1 && Directory.Exists(match.Groups[1].Value + "\\Community\\"))
{
communityPath = match.Groups[1].Value + "\\Community\\";
Console.WriteLine("Community path found: " + communityPath);
}
}
if (String.IsNullOrEmpty(communityPath))
Console.WriteLine("Community path NOT found");
}
catch {
}
InitializeComponent();
JSONHelper = new jsonHelper();
CfgHelper = new cfgHelper();
CsvHelper = new csvHelper();
XmlHelper = new xmlHelper();
FsxVarHelper = new fsxVarHelper();
FileDialogHelper = new fileDialogHelper();
JSONHelper.loadSettings();
// INIT LANGUAGES
CsvHelper.initializeLanguages(LangSelector);
LangSelector.DropDownClosed += new EventHandler(languageUpdated);
// SETUP MAIN SCREEN
mainScreen.Visibility = Visibility.Visible;
fsTabControl.Visibility = Visibility.Collapsed;
// STYLE BUTTONS
setupStyles();
// HIDE TABS
int k = 0;
foreach (TabItem item in fsTabControl.Items)
{
if (k > 0 && k < fsTabControl.Items.Count - 1)
item.Visibility = Visibility.Collapsed;
k++;
}
// TRY TO LOAD CFGTPL FILES
if (!CfgHelper.processCfgfiles(AppDomain.CurrentDomain.BaseDirectory + "\\cfgTpl\\"))
{
MessageBox.Show(CsvHelper.trans("init_cfg_tpl_missing"));
Environment.Exit(1);
}
_ = CheckUpdateAsync();
}
private void setupStyles()
{
btnOpenFile = SetButtonAtts(btnOpenFile);
btnSourceFolder = SetButtonAtts(btnSourceFolder);
btnTargetFolder = SetButtonAtts(btnTargetFolder);
btnScan = SetButtonAtts(btnScan);
btnImportSubmit = SetButtonAtts(btnImportSubmit);
TextExpressionButton = SetButtonAtts(TextExpressionButton);
MainMenuButton = SetButtonAtts(MainMenuButton, false);
load_imported_header = SetHeaderAtts(load_imported_header);
load_imported_notice = SetHeaderAtts(load_imported_notice);
update_layout_header = SetHeaderAtts(update_layout_header);
new_import_header = SetHeaderAtts(new_import_header);
new_import_notice = SetHeaderAtts(new_import_notice);
engines_power = SetHeaderAtts(engines_power);
about_links_header = SetHeaderAtts(about_links_header);
about_colored_header = SetHeaderAtts(about_colored_header);
about_colored_green = SetHeaderAtts(about_colored_green);
about_colored_orange = SetHeaderAtts(about_colored_orange);
about_colored_red = SetHeaderAtts(about_colored_red);
about_translation_header = SetHeaderAtts(about_translation_header);
imageLeftTooltip = SetHeaderAtts(imageLeftTooltip);
imageRightTooltip = SetHeaderAtts(imageRightTooltip);
}
private void languageUpdated(object sender, System.EventArgs e)
{
CsvHelper.languageUpdate(((ComboBoxItem)(sender as ComboBox).SelectedItem).Content.ToString());
setupStyles();
SummaryUpdate(true);
}
// FSX IMPORT
private void mainImportClick(object sender, RoutedEventArgs e)
{
showInitPage("import");
}
// MSFS LOAD
private void mainLoadClick(object sender, RoutedEventArgs e)
{
showInitPage("load");
}
private void ShowMainMenu(object sender, RoutedEventArgs e)
{
showInitPage("main");
}
private void showInitPage(string state)
{
mainScreen.Visibility = Visibility.Collapsed;
fsTabControl.Visibility = Visibility.Collapsed;
LoadAircraft.Visibility = Visibility.Collapsed;
RescanFiles.Visibility = Visibility.Collapsed;
ImportForm.Visibility = Visibility.Collapsed;
AircraftProcess.Visibility = Visibility.Collapsed;
switch (state)
{
case "load":
mainScreen.Visibility = Visibility.Collapsed;
fsTabControl.Visibility = Visibility.Visible;
LoadAircraft.Visibility = Visibility.Visible;
break;
case "import":
mainScreen.Visibility = Visibility.Collapsed;
fsTabControl.Visibility = Visibility.Visible;
ImportForm.Visibility = Visibility.Visible;
break;
case "loaded":
case "imported":
fsTabControl.Visibility = Visibility.Visible;
RescanFiles.Visibility = Visibility.Visible;
AircraftProcess.Visibility = Visibility.Visible;
break;
case "main":
mainScreen.Visibility = Visibility.Visible;
currentMode = "";
aircraftDirectory = "";
CfgHelper.resetCfgfiles();
SummaryUpdate(true);
break;
}
}
private void BtnOpenFile_Click(object sender, RoutedEventArgs e)
{
try
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
string defaultPath = !String.IsNullOrEmpty(communityPath) ? communityPath : HKLMRegistryHelper.GetRegistryValue("SOFTWARE\\Microsoft\\microsoft games\\Flight Simulator\\11.0\\", "CommunityPath");
dialog.InitialDirectory = defaultPath;
dialog.IsFolderPicker = true;
dialog.RestoreDirectory = (String.IsNullOrEmpty(defaultPath) || defaultPath == Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) ? true : false;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
setAircraftDirectory(dialog.FileName);
if (aircraftDirectory != "")
showInitPage("loaded");
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
public void setAircraftDirectory(string directory)
{
if (File.Exists(directory + "\\layout.json") &&
File.Exists(directory + "\\manifest.json") &&
Directory.Exists(directory + "\\SimObjects"))
{
if (String.IsNullOrEmpty(communityPath))
{
try { Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\microsoft games\\Flight Simulator\\11.0\\", "CommunityPath", System.IO.Path.GetDirectoryName(directory)); }
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
// CLEAN FIELDS
btnSourceFolderPath.Text = "";
PackageTitle.Text = "";
PackageDir.Text = "";
PackageManufacturer.Text = "";
PackageAuthor.Text = "";
//extractingCabs = false;
projectDirectory = directory;
aircraftDirectory = Get_aircraft_directory();
if (aircraftDirectory != "")
{
LoadedHeader.Text = CsvHelper.trans("init_curr_aircraft") + ": " + new DirectoryInfo(projectDirectory).Name;
//btnOpenFile.Content = "Select another aircraft";
btnOpenFilePath.Text = projectDirectory;
backUpFile(aircraftDirectory + "\\aircraft.cfg");
CfgHelper.processCfgfiles(aircraftDirectory + "\\", true);
// TRACK CFG FILES
if (fileTrackWatcher != null)
fileTrackWatcher.Dispose();
fileTrackWatcher = new FileSystemWatcher();
fileTrackWatcher.Filter = "*.cfg";
fileTrackWatcher.Changed += new FileSystemEventHandler(trackCfgEdit);
fileTrackWatcher.NotifyFilter = NotifyFilters.LastWrite;
fileTrackWatcher.IncludeSubdirectories = true;
fileTrackWatcher.Path = aircraftDirectory + "\\";
fileTrackWatcher.EnableRaisingEvents = true;
LoadLabel.Text = CsvHelper.trans("init_tabs_click");
LoadLabel.Foreground = new SolidColorBrush(Colors.Black);
SummaryUpdate();
// START BACKGROUND CABS EXTRACTION
/*if (!string.IsNullOrEmpty(SourceFolder) && (Directory.Exists(SourceFolder + "..\\..\\..\\Gauges") || Directory.Exists(SourceFolder + "..\\..\\..\\SimObjects")))
{
Console.WriteLine("Trying to extract FSX cabs from " + SourceFolder + "..\\..\\..\\");
fsTabControl.IsEnabled = false;
extractingCabs = true;
extractDefaultCabsAsync(btnScan, SourceFolder + "..\\..\\..\\");
}*/
}
// CLEAN FIELDS
SourceFolder = "";
}
else
{
MessageBox.Show(string.Format(CsvHelper.trans("init_simobject_missing"), directory));
}
}
public void trackCfgEdit(object sender, FileSystemEventArgs e)
{
if (DateTime.UtcNow.Ticks - CfgHelper.lastChangeTimestamp > 10000000)
{
Dispatcher.Invoke(() => fsTabControl.IsEnabled = false);
MessageBoxResult messageBoxResult = MessageBox.Show(string.Format(CsvHelper.trans("file_edited_outside"), System.IO.Path.GetFileName(e.FullPath)), CsvHelper.trans("file_edited"), MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
CfgHelper.processCfgfiles(aircraftDirectory + "\\", true);
Dispatcher.Invoke(() => SummaryUpdate());
Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
CfgHelper.lastChangeTimestamp = DateTime.UtcNow.Ticks;
} else
{
CfgHelper.lastChangeTimestamp = DateTime.UtcNow.Ticks;
Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
}
}
}
private void SummaryUpdate(bool reset = false)
{
// RESET TABS COLOR
foreach (TabItem item in fsTabControl.Items)
{
if (item.Name != "tabAbout")
((TabItem)item).Background = new SolidColorBrush(Colors.Transparent);
}
if (!reset)
{
SummaryAircraft();
SummaryEngines();
SummarySections();
SummarySystems();
SummaryFlightModel();
SummaryTextures();
SummaryModels();
SummarySound();
SummaryPanel();
}
foreach (TabItem item in fsTabControl.Items)
{
if (!reset)
{
switch (item.Name)
{
case "tabAircraft":
if (CfgHelper.cfgFileExists("aircraft.cfg"))
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
break;
case "tabCockpit":
if (CfgHelper.cfgFileExists("cockpit.cfg"))
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
break;
case "tabSystems":
if (CfgHelper.cfgFileExists("systems.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
break;
case "tabFlightModel":
if (CfgHelper.cfgFileExists("flight_model.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
break;
case "tabEngines":
if (CfgHelper.cfgFileExists("engines.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
break;
case "tabRunway":
if (CfgHelper.cfgFileExists("engines.cfg") || CfgHelper.cfgFileExists("aircraft.cfg") /*&& CfgHelper.cfgFileExists("flight_model.cfg")*/)
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
break;
case "tabPanel":
if (aircraftDirectory != "" && Directory.Exists(aircraftDirectory) && Directory.EnumerateFiles(aircraftDirectory, "panel.cfg", SearchOption.AllDirectories).Count() > 0)
item.Visibility = Visibility.Visible;
else
item.Visibility = Visibility.Collapsed;
break;
default:
item.Visibility = Visibility.Visible;
break;
}
} else if (item.Name != "tabInit" && item.Name != "tabAbout")
item.Visibility = Visibility.Collapsed;
}
// SET BACKUP BUTTONS LABEL
foreach (Button btn in new Button[] { AircraftBackupButton, EnginesBackupButton, CockpitBackupButton, SystemsBackupButton, FlightModelBackupButton, RunwayBackupButton, RunwayBackupButton, ModelBackupButton, PanelBackupButton })
{
if (!reset)
{
btn.Visibility = Visibility.Visible;
SetButtonAtts(btn, false);
if (!String.IsNullOrEmpty(btn.Tag.ToString()))
{
string filenames = btn.Tag.ToString();
if (!btn.Tag.ToString().Contains(','))
filenames += ',';
bool backup_not_found = false;
foreach (var filename in filenames.Split(','))
{
if (!String.IsNullOrEmpty(filename))
{
if (CfgHelper.cfgFileExists(filename) ||
!(new string[] { "aircraft.cfg", "cameras.cfg", "cockpit.cfg", "engines.cfg", "flight_model.cfg", "gameplay.cfg", "systems.cfg" }).Contains(filename))
{
string mainFile = aircraftDirectory + "\\" + filename;
string backupFile = System.IO.Path.GetDirectoryName(mainFile) + "\\." + System.IO.Path.GetFileName(mainFile);
if (!File.Exists(backupFile))
{
backup_not_found = true;
break;
}
}
else
{
btn.Visibility = Visibility.Hidden;
}
}
}
if (FindName(btn.Name) != null) {
if (!backup_not_found)
{
((Button)FindName(btn.Name)).Content = CsvHelper.trans("restore_backup");
Console.WriteLine("Backup of " + btn.Tag.ToString() + " FOUND");
}
else
{
((Button)FindName(btn.Name)).Content = CsvHelper.trans("make_backup");
Console.WriteLine("Backup of " + btn.Tag.ToString() + " NOT FOUND");
}
}
}
} else
btn.Visibility = Visibility.Hidden;
}
foreach (Button btn in new Button[] { AircraftEditButton, EnginesEditButton, CockpitEditButton, CockpitEditButton, SystemsEditButton, FlightModelEditButton, RunwayEditButton })
{
if (!reset)
{
btn.Visibility = Visibility.Visible;
if (!String.IsNullOrEmpty(btn.Tag.ToString()))
{
string filenames = btn.Tag.ToString();
if (!btn.Tag.ToString().Contains(','))
filenames += ',';
foreach (var filename in filenames.Split(','))
if (!String.IsNullOrEmpty(filename) && !CfgHelper.cfgFileExists(filename))
btn.Visibility = Visibility.Hidden;
}
SetButtonAtts(btn, false);
} else
btn.Visibility = Visibility.Hidden;
}
// UPDATE TITLE
if (!reset)
this.Title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title + " " +
Assembly.GetExecutingAssembly().GetName().Version.ToString() + (currentMode != "" ? " (" + currentMode + ")" : "");
else
this.Title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title + " " +
Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
// AIRCRAFT START
public void SummaryAircraft()
{
int status = 2;
TabPanel myPanel = new TabPanel();
// AIRCRAFT.CFG SPLIT
AircraftProcess.Children.Clear();
tabAircraft.Background = new SolidColorBrush(Color.FromArgb(10, 0, 255, 0));
if (aircraftDirectory != "" && File.Exists(aircraftDirectory + @"\aircraft.cfg"))
{
List<string> presentedFiles = new List<string>();
List<TextBlock> presentedFilesLabels = new List<TextBlock>();
foreach (var file in new[] { "aircraft.cfg", "cameras.cfg", "cockpit.cfg", "engines.cfg", "flight_model.cfg", "gameplay.cfg", "systems.cfg", ".unknown.cfg" })
{
TextBlock myBlock = null;
if (file == ".unknown.cfg" && File.Exists(aircraftDirectory + "\\" + file))
{
myBlock = addTextBlock(file + ": "+ CsvHelper.trans("init_cfg_ignored"), HorizontalAlignment.Left, VerticalAlignment.Top, Colors.DarkOrange, new Thickness(0));
}
else if (file == ".unknown.cfg")
{
myBlock = addTextBlock("", HorizontalAlignment.Left, VerticalAlignment.Top, Colors.DarkOrange, new Thickness(0));
}
else if (!File.Exists(aircraftDirectory + "\\" + file))
{
myBlock = addTextBlock(file + ": "+ CsvHelper.trans("init_cfg_missing"), HorizontalAlignment.Left, VerticalAlignment.Top, Colors.DarkRed, new Thickness(0));
status = 0;
}
else
{
myBlock = addTextBlock(file + ": " + CsvHelper.trans("init_cfg_loaded"), HorizontalAlignment.Left, VerticalAlignment.Top, Colors.DarkGreen, new Thickness(0));
presentedFiles.Add(file);
}
presentedFilesLabels.Add(myBlock);
}
TextBlock modeHeader = addTextBlock("", HorizontalAlignment.Center, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 0), TextWrapping.Wrap);
modeHeader.FontSize = 21;
TextBlock modeDescr = addTextBlock("", HorizontalAlignment.Left, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 0), TextWrapping.Wrap);
modeDescr.FontSize = 14;
TextBlock modeDescr2 = addTextBlock("", HorizontalAlignment.Left, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 0), TextWrapping.Wrap);
modeDescr2.FontSize = 14;
if (presentedFiles.Count == 1 && presentedFiles.Contains("aircraft.cfg"))
{
currentMode = CsvHelper.trans("init_basic_mode");
modeHeader.Text = currentMode + " " + CsvHelper.trans("init_mode_active");
AircraftProcess.Children.Add(modeHeader);
modeDescr.Text =
CsvHelper.trans("init_basic_notice1") + Environment.NewLine +
CsvHelper.trans("init_basic_notice2") + Environment.NewLine +
CsvHelper.trans("init_basic_notice3") + Environment.NewLine + Environment.NewLine +
CsvHelper.trans("init_basic_notice4") + Environment.NewLine +
CsvHelper.trans("init_basic_notice5") + Environment.NewLine;
myPanel.Children.Add(modeDescr);
}
else
{
currentMode = CsvHelper.trans("init_full_mode");
modeHeader.Text = currentMode + " " + CsvHelper.trans("init_mode_active");
AircraftProcess.Children.Add(modeHeader);
modeDescr.Text =
CsvHelper.trans("init_full_notice1") + Environment.NewLine +
CsvHelper.trans("init_full_notice2") + Environment.NewLine;
modeDescr.Width = 460;
myPanel.Children.Add(modeDescr);
StackPanel cfgsList = new StackPanel();
cfgsList.Width = 150;
cfgsList.Margin = new Thickness(0, 20, 0, 0);
cfgsList.HorizontalAlignment = HorizontalAlignment.Right;
foreach (var presentedFilesLabel in presentedFilesLabels)
cfgsList.Children.Add(presentedFilesLabel);
myPanel.Children.Add(cfgsList);
modeDescr2.Text = CsvHelper.trans("init_full_notice3") + Environment.NewLine + CsvHelper.trans("init_full_notice4");
myPanel.Children.Add(modeDescr2);
}
// SHOW PROCESS INSTRUMENTS BUTTON
Button btn = new Button();
btn = SetButtonAtts(btn);
btn.Click += BtnAircraftProcess_Click;
if (presentedFiles.Count == 1 && presentedFiles.Contains("aircraft.cfg")) {
btn.Content = CsvHelper.trans("init_full_enable");
myPanel.Children.Add(btn);
}
else if (status == 0)
{
btn.Content = CsvHelper.trans("init_parse_cfg");
myPanel.Children.Add(btn);
}
AircraftProcess.Children.Add(myPanel);
AircraftProcess.Children.Add(sectiondivider());
//AircraftContent.Text = @"List of CFG files:" + Environment.NewLine + Environment.NewLine + cfgsList;
//tabAircraft.Foreground = new SolidColorBrush(status > 1 ? Colors.DarkGreen : Colors.DarkRed);
}
else
{
//AircraftContent.Text = "aircraft.cfg file not exists!";
tabAircraft.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
// DESCRIPTION FIXES
StackPanel myPanel2 = new StackPanel();
AircraftPerformance.Children.Clear();
if (CfgHelper.cfgFileExists("flight_model.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
int i = 0;
for (int k = 0; k <= 99; k++)
{
string[] requiredValues = new string[] { "ui_certified_ceiling", "ui_max_range", "ui_autonomy", "cruise_speed", "ui_typerole" };
foreach (var requiredValue in requiredValues)
{
if (CfgHelper.cfgSectionExists("aircraft.cfg", "[FLTSIM." + k + "]"))
{
string value = CfgHelper.getCfgValue(requiredValue, "aircraft.cfg", "[FLTSIM." + k + "]").ToLower().Trim('"').Trim();
if (String.IsNullOrEmpty(value) || value == "0" ||
//!int.TryParse(value.Contains('.') ? value.Trim('"').Trim().Split('.')[0] : value.Trim('"').Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out int num) ||
requiredValue == "ui_typerole" && (value == "glider" || value == "rotorcraft" ))
{
if (requiredValue == "ui_typerole")
{
AircraftPerformance = AddGroupCheckBox(AircraftPerformance, "[FLTSIM." + k + "] " + requiredValue + " " + CsvHelper.trans("aircraft_parameter_invalid"), Colors.DarkRed, i++);
tabAircraft.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
else
AircraftPerformance = AddGroupCheckBox(AircraftPerformance, "[FLTSIM." + k + "] " + requiredValue + " " + CsvHelper.trans("aircraft_parameter_missing"), Colors.DarkOrange, i++);
}
}
}
}
Button btn = new Button();
btn = SetButtonAtts(btn);
btn.Content = CsvHelper.trans("aircraft_add_missing_parameters");
btn.Click += AddDescriptionClick;
myPanel2.Children.Add(btn);
TextBlock notice = addTextBlock(CsvHelper.trans("aircraft_missing_parameter_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
AircraftPerformance.Children.Insert(0, notice);
}
AircraftPerformance.Children.Add(myPanel2);
AircraftPerformance.Children.Add(sectiondivider());
}
private void BtnAircraftProcess_Click(object sender, RoutedEventArgs e)
{
if (!File.Exists(aircraftDirectory + "\\aircraft.cfg"))
{
MessageBox.Show(CsvHelper.trans("aircraft_cfg_not_found"), "", MessageBoxButton.OK);
}
else
{
// PROCESS AIRCRAFT FILE
if (File.Exists(aircraftDirectory + "\\.aircraft.cfg"))
{
try
{
File.Delete(aircraftDirectory + "\\.aircraft.cfg");
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
MessageBox.Show(CsvHelper.trans("aircraft_cfg_split_failed"));
return;
}
}
if (!File.Exists(aircraftDirectory + "\\.aircraft.cfg"))
{
MessageBoxResult messageBoxResult = MessageBox.Show(CsvHelper.trans("aircraft_split_notice"), CsvHelper.trans("aircraft_split_header"), System.Windows.MessageBoxButton.YesNoCancel);
if (messageBoxResult == MessageBoxResult.Yes || messageBoxResult == MessageBoxResult.No)
{
CfgHelper.splitCfg(aircraftDirectory, "", messageBoxResult == MessageBoxResult.Yes);
} else
{
return;
}
}
JSONHelper.scanTargetFolder(projectDirectory);
SummaryUpdate();
}
}
public void AddDescriptionClick(object sender, RoutedEventArgs e)
{
int i = 0;
foreach (var checkboxLabel in getCheckedOptions(AircraftPerformance)) {
string section = checkboxLabel.Split(']')[0] + "]";
string val = checkboxLabel.Replace(section, "").Trim().Split(' ')[0].ToLower().Trim();
string name = "";
string newValue = "";
if (val == "ui_certified_ceiling")
name = "ceiling";
else if (val == "ui_max_range")
name = "range";
else if (val == "ui_autonomy")
name = "endurance";
else if (val == "cruise_speed")
name = "cruise speed";
else if (val == "ui_typerole")
newValue = "\"Aircraft\"";
//Console.WriteLine("### " + val);
if (name != "")
{
string value = "";
if (val != "cruise_speed")
{
Regex regex = new Regex(@"(?i)(.*)" + name + @"(\\t\\n|\\n)([\d,]+)(.+)(?-i)");
Match match = regex.Match(CfgHelper.getCfgValue("performance", "aircraft.cfg", "[GENERAL]"));
if (match.Success && match.Groups.Count >= 3)
value = match.Groups[3].Value.Replace(",", "");
}
else
{
value = CfgHelper.getCfgValue(val, "flight_model.cfg", "[REFERENCE SPEEDS]");
}
if (value != "")
{
CfgHelper.setCfgValue(aircraftDirectory, val, value, "aircraft.cfg", section);
i++;
}
}
else if (newValue != "")
{
CfgHelper.setCfgValue(aircraftDirectory, val, newValue, "aircraft.cfg", section);
i++;
}
}
if (i > 0)
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "aircraft.cfg" });
SummaryUpdate();
}
// AIRCRAFT END
// ENGINES START
public void SummaryEngines()
{
EnginesData.Children.Clear();
tabEngines.Background = new SolidColorBrush(Color.FromArgb(10, 0, 255, 0));
AfterburnerData.Children.Clear();
EnginesAir.Children.Clear();
if (CfgHelper.cfgFileExists("engines.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
int criticalIssues = 0;
// ENGINE TYPE
string engine_type = CfgHelper.getCfgValue("engine_type", "engines.cfg", "[GENERALENGINEDATA]");
if (engine_type == "2" || engine_type == "3" || engine_type == "4" || engine_type == "")
EnginesData = AddGroupCheckBox(EnginesData, "engine_type = " + (engine_type != "" ? engine_type : "missing"), Colors.DarkRed, criticalIssues++);
// IGNITION
if (CfgHelper.getCfgValue("master_ignition_switch", "engines.cfg", "[GENERALENGINEDATA]") == "")
EnginesData = AddGroupCheckBox(EnginesData, "master_ignition_switch = missing", Colors.DarkRed, criticalIssues++);
// STARTER
if (CfgHelper.getCfgValue("starter_type", "engines.cfg", "[GENERALENGINEDATA]") == "")
EnginesData = AddGroupCheckBox(EnginesData, "starter_type = missing", Colors.DarkRed, criticalIssues++);
// THRUST ANGLE
for (int engine = 0; engine < 4; engine++)
{
if (CfgHelper.getCfgValue("engine."+ engine, "engines.cfg", "[GENERALENGINEDATA]") != "" &&
CfgHelper.getCfgValue("thrustanglespitchheading."+ engine, "engines.cfg", "[GENERALENGINEDATA]") == "")
EnginesData = AddGroupCheckBox(EnginesData, "thrustanglespitchheading."+ engine +" = missing", Colors.DarkRed, criticalIssues++);
}
/*string engine0 = CfgHelper.getCfgValue("engine.0", "engines.cfg", "[GENERALENGINEDATA]");
if (engine0 == "")
EnginesData = AddGroupCheckBox(EnginesData, "engine.0 = missing", Colors.DarkRed, criticalIssues++);*/
// AB
string afterburner_available = CfgHelper.getCfgValue("afterburner_available", "engines.cfg", "[TURBINEENGINEDATA]");
if (afterburner_available != "" && afterburner_available != "0")
EnginesData = AddGroupCheckBox(EnginesData, "afterburner_available = " + afterburner_available, Colors.DarkRed, criticalIssues++);
// IDLE N1
if (CfgHelper.cfgSectionExists("engines.cfg", "[TURBINEENGINEDATA]") && (engine_type == "1" || engine_type == "5"))
{
if (CfgHelper.getCfgValue("low_idle_n1", "engines.cfg", "[TURBINEENGINEDATA]") == "")
EnginesData = AddGroupCheckBox(EnginesData, "low_idle_n1 = missing", Colors.DarkRed, criticalIssues++);
if (CfgHelper.getCfgValue("low_idle_n2", "engines.cfg", "[TURBINEENGINEDATA]") == "")
EnginesData = AddGroupCheckBox(EnginesData, "low_idle_n2 = missing", Colors.DarkRed, criticalIssues++);
if (CfgHelper.getCfgValue("high_n1", "engines.cfg", "[TURBINEENGINEDATA]") == "")
EnginesData = AddGroupCheckBox(EnginesData, "high_n1 = missing", Colors.DarkRed, criticalIssues++);
if (CfgHelper.getCfgValue("high_n2", "engines.cfg", "[TURBINEENGINEDATA]") == "")
EnginesData = AddGroupCheckBox(EnginesData, "high_n2 = missing", Colors.DarkRed, criticalIssues++);
}
StackPanel myPanel2 = new StackPanel();
Button btn = new Button();
btn = SetButtonAtts(btn);
if (criticalIssues > 0)
{
btn.Content = CsvHelper.trans("engines_fix_issues");
btn.Click += FixengineClick;
TextBlock notice = addTextBlock(CsvHelper.trans("engines_issues_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
EnginesData.Children.Insert(0, notice);
tabEngines.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
else
{
btn.Content = CsvHelper.trans("engines_no_issues");
btn.IsEnabled = false;
}
myPanel2.Children.Add(btn);
EnginesData.Children.Add(myPanel2);
if (CfgHelper.cfgFileExists("engines.cfg"))
getAirCheckboxes(EnginesAir, "engines.cfg");
/*****/ EnginesData.Children.Add(sectiondivider());
// AFTERBURNER
if (engine_type == "1" && CfgHelper.cfgSectionExists("engines.cfg", "[TURBINEENGINEDATA]"))
{
double[] ABdata = getABdata();
string default_n1_and_mach_on_thrust_table = "0.000000:0.000000:0.900000,0.000000:0.000000:0.000000,20.000000:0.025000:0.025000,25.000000:0.051000:0.051000,30.000000:0.080000:0.080000,35.000000:0.112000:0.112000,40.000000:0.200000:0.200000,45.000000:0.281000:0.281000,50.000000:0.368000:0.370000,55.000000:0.431000:0.430000,60.000000:0.521000:0.520000,65.000000:0.629000:0.650000,70.000000:0.726000:0.800000,75.000000:0.818000:1.050000,80.000000:0.900000:1.230000,85.000000:0.992000:1.350000,90.000000:1.043000:1.420000,95.000000:1.077000:1.450000,100.000000:1.125000:1.470000,105.000000:1.145000:1.480000,110.000000:1.170000:1.478000";
string current_n1_and_mach_on_thrust_table = CfgHelper.getCfgValue("n1_and_mach_on_thrust_table", "engines.cfg", "[TURBINEENGINEDATA]");
StackPanel myPanel3 = new StackPanel();
Button btn3 = SetButtonAtts(new Button());
if (ABdata[4] > 0)
{
btn3.Content = CsvHelper.trans("engines_fix_afterburner");
btn3.Click += FixAfterburnerClick;
} else
{
btn3.Content = CsvHelper.trans("engines_fix_afterburner_not_available");
btn3.IsEnabled = false;
}
List<double[]>[] graphs = CfgHelper.parseCfgDoubleTable(!string.IsNullOrEmpty(current_n1_and_mach_on_thrust_table) ?
current_n1_and_mach_on_thrust_table : default_n1_and_mach_on_thrust_table);
Canvas painting = new Canvas();
painting.Width = 600;
painting.Height = 200;
painting.Children.Add(getGraphLine(Colors.Black, 0, 0, 0, 1, painting.Width, painting.Height, 2));
painting.Children.Add(getGraphLine(Colors.Black, 0, 0, 1/1.1, 0, painting.Width, painting.Height, 2));
for (float k = 1; k <= 5; k++)
painting.Children.Add(getGraphLine(k % 5 == 0 ? Colors.Black : Colors.Gray, k / 5.0 / 1.1, 0, k / 5.0 / 1.1, 1, painting.Width, painting.Height, 1));
for (float l = 1; l <= 6; l++)
painting.Children.Add(getGraphLine(l % 2 == 0 ? Colors.Black : Colors.Gray, 0, l/6.0, 1/1.1, l/6.0, painting.Width, painting.Height, 1));
// RENDER GRAPH
for (int i = 0; i <= 1; i++)
{
double x1 = -1;
double y1 = -1;
foreach (var val in graphs[i])
{
if (x1 != -1 && y1 != -1)
painting.Children.Add(getGraphLine(i==0?Colors.Black:Colors.DarkRed, x1 / 110, y1, val[0] / 110, val[1] / 3, painting.Width, painting.Height, 1));
x1 = val[0];
y1 = val[1] / 3;
}
}
List<TextBlock> notices = new List<TextBlock>();
notices.Add(addTextBlock(CsvHelper.trans("engines_afterburner_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 0, 0, 10), TextWrapping.Wrap, 600));
notices.Add(addTextBlock(ABdata[4] >= 1 ?
string.Format(CsvHelper.trans("engines_afterburners_stages"), ABdata[4]) :
CsvHelper.trans("engines_afterburners_disabled"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, ABdata[4] >= 0 ? Colors.Black : Colors.DarkRed, new Thickness(0, 0, 0, 0), TextWrapping.Wrap, 600));
if (string.IsNullOrEmpty(current_n1_and_mach_on_thrust_table))
notices.Add(addTextBlock(CsvHelper.trans("engines_afterburners_table_missing"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.DarkRed, new Thickness(0, 0, 0, 0), TextWrapping.Wrap, 600));
notices.Add(addTextBlock(ABdata[3] != -1 ?
string.Format(CsvHelper.trans("engines_afterburners_consumption"), ABdata[3], (100 + 100*ABdata[3]/3).ToString(".")) :
string.Format(CsvHelper.trans("engines_afterburners_consumption_missing"), ABdata[2], (100 + 100*ABdata[2]/3).ToString(".")),
HorizontalAlignment.Stretch, VerticalAlignment.Top, ABdata[3] != -1 ? Colors.Black : Colors.DarkRed, new Thickness(0, 0, 0, 0), TextWrapping.Wrap, 600));
notices.Add(addTextBlock(ABdata[1] != -1 ?
string.Format(CsvHelper.trans("engines_afterburners_threshold"), ABdata[1]) :
string.Format(CsvHelper.trans("engines_afterburners_threshold_missing"), ABdata[0]),
HorizontalAlignment.Stretch, VerticalAlignment.Top, ABdata[1] != -1 ? Colors.Black : Colors.DarkRed, new Thickness(0, 0, 0, 10), TextWrapping.Wrap, 600));
foreach (var notice in notices)
AfterburnerData.Children.Add(notice);
myPanel3.Children.Add(btn3);
AfterburnerData.Children.Add(painting);
AfterburnerData.Children.Add(myPanel3);
/*****/
AfterburnerData.Children.Add(sectiondivider());
}
}
}
private Line getGraphLine(Color color, double x1, double y1, double x2, double y2, double width, double height, int thickness = 1)
{
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
line.StrokeThickness = thickness;
line.X1 = x1 * width;
line.Y1 = height * (1 - y1);
line.X2 = x2 * width;
line.Y2 = height * (1 - y2);
return line;
}
private void FixengineClick(object sender, RoutedEventArgs e) {
int i = 0;
if (CfgHelper.cfgFileExists("engines.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
foreach (var checkboxLabel in getCheckedOptions(EnginesData, "="))
{
string[] val = checkboxLabel.Split('=');
/*if (val[0].Trim() == "engine.0")
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "0,0,0", "engines.cfg", "[GENERALENGINEDATA]");*/
if (val[0].Trim() == "low_idle_n1")
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "20", "engines.cfg", "[TURBINEENGINEDATA]");
else if (val[0].Trim() == "low_idle_n2")
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "60", "engines.cfg", "[TURBINEENGINEDATA]");
else if (val[0].Trim() == "high_n1")
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "100", "engines.cfg", "[TURBINEENGINEDATA]");
else if (val[0].Trim() == "high_n2")
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "100", "engines.cfg", "[TURBINEENGINEDATA]");
else if (val[0].Trim() == "afterburner_available")
{
CfgHelper.setCfgValue(aircraftDirectory, "afterburner_stages", val[1].Trim(), "engines.cfg", "[TURBINEENGINEDATA]", false);
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "0", "engines.cfg");
}
else if (val[0].Trim().Contains("thrustanglespitchheading"))
{
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "0,0", "engines.cfg", "[GENERALENGINEDATA]");
}
else if (checkboxLabel.Contains("missing")) {
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "0", "engines.cfg", "[GENERALENGINEDATA]");
}
else
CfgHelper.setCfgValue(aircraftDirectory, val[0].Trim(), "0", "engines.cfg");
i++;
}
}
if (i > 0)
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "engines.cfg" });
SummaryUpdate();
}
private void FixAfterburnerClick(object sender, RoutedEventArgs e)
{
if (CfgHelper.cfgFileExists("engines.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
string resultTable = "";
double[] ABdata = getABdata();
double threshold = ABdata[1] != -1 ? ABdata[1] : ABdata[0];
double consumption = ABdata[3] != -1 ? ABdata[3] : ABdata[2];
string default_n1_and_mach_on_thrust_table = "0.000000:0.000000:0.900000,0.000000:0.000000:0.000000,20.000000:0.025000:0.025000,25.000000:0.051000:0.051000,30.000000:0.080000:0.080000,35.000000:0.112000:0.112000,40.000000:0.200000:0.200000,45.000000:0.281000:0.281000,50.000000:0.368000:0.370000,55.000000:0.431000:0.430000,60.000000:0.521000:0.520000,65.000000:0.629000:0.650000,70.000000:0.726000:0.800000,75.000000:0.818000:1.050000,80.000000:0.900000:1.230000,85.000000:0.992000:1.350000,90.000000:1.043000:1.420000,95.000000:1.077000:1.450000,100.000000:1.125000:1.470000,105.000000:1.145000:1.480000,110.000000:1.170000:1.478000";
string current_n1_and_mach_on_thrust_table = CfgHelper.getCfgValue("n1_and_mach_on_thrust_table", "engines.cfg", "[TURBINEENGINEDATA]");
List<double[]>[] graphs = CfgHelper.parseCfgDoubleTable(!string.IsNullOrEmpty(current_n1_and_mach_on_thrust_table) ? current_n1_and_mach_on_thrust_table : default_n1_and_mach_on_thrust_table);
for(int i = 0; i < graphs[0].Count && i < graphs[1].Count; i++)
{
double val1 = graphs[0].ElementAt(i)[0];
double val2 = graphs[0].ElementAt(i)[1];
double val3 = graphs[1].ElementAt(i)[1];
if (threshold != 0 && consumption != 0 && val1 > 100 * threshold)
{
val2 *= 1 + consumption / 3;
val3 *= 1 + consumption / 3;
}
resultTable += val1 + ":" + val2 + ":" + val3 + ",";
}
resultTable = resultTable.TrimEnd(',');
Console.WriteLine("Afterburner final table: " + resultTable);
MessageBoxResult messageBoxResult = MessageBox.Show(string.Format(CsvHelper.trans("engines_afterburner_warning_notice"), threshold, consumption), CsvHelper.trans("engines_afterburner_warning_header"), System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
CfgHelper.setCfgValue(aircraftDirectory, "n1_and_mach_on_thrust_table", resultTable, "engines.cfg", "[TURBINEENGINEDATA]", true);
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "engines.cfg" });
}
}
SummaryUpdate();
}
public double[] getABdata()
{
string current_afterburner_throttle_threshold = CfgHelper.getCfgValue("afterburner_throttle_threshold", "engines.cfg", "[TURBINEENGINEDATA]");
string current_afterburnthrustspecificfuelconsumption = CfgHelper.getCfgValue("afterburnthrustspecificfuelconsumption", "engines.cfg", "[TURBINEENGINEDATA]");
string current_afterburner_available = CfgHelper.getCfgValue("afterburner_stages", "engines.cfg", "[TURBINEENGINEDATA]", true);
double val1 = 0.85;
double.TryParse(!string.IsNullOrEmpty(current_afterburner_throttle_threshold) ? current_afterburner_throttle_threshold : "-1", out double val2);
double val3 = 1.5;
double.TryParse(!string.IsNullOrEmpty(current_afterburnthrustspecificfuelconsumption) ? current_afterburnthrustspecificfuelconsumption : "-1", out double val4);
double.TryParse(!string.IsNullOrEmpty(current_afterburner_available) ? current_afterburner_available : "-1", out double val5);
return new double[] { val1, val2, val3, val4, val5 };
}
private void BtnEnginePowerClick(object sender, RoutedEventArgs e)
{
if (CfgHelper.cfgFileExists("engines.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
Button btn = (Button)sender;
CfgHelper.adjustEnginesPower(aircraftDirectory, double.Parse(btn.Tag.ToString()));
}
}
// ENGINES END
// AIR START
private void getAirCheckboxes(StackPanel parent, string filename)
{
airFilename = "";
var airFiles = Directory.EnumerateFiles(aircraftDirectory, "*.air", SearchOption.TopDirectoryOnly);
foreach (string currentFile in airFiles)
{
string tempName = System.IO.Path.GetFileName(currentFile);
if (!String.IsNullOrEmpty(tempName) /*&& tempName[0] != '.'*/)
airFilename = tempName;
}
if (airFilename == "")
airFilename = System.IO.Path.GetFileName(aircraftDirectory).Trim('\\') + ".air";
int values = 0;
StackPanel myPanel = new StackPanel();
string airExported = aircraftDirectory + "\\" + airFilename.Replace(".air", ".txt");
string conversionTable = AppDomain.CurrentDomain.BaseDirectory + "\\airTbls\\AIR to CFG Master Sheet - " + filename + ".csv";
string buttonLabel = "";
bool download = false;
bool launch = false;
// NO TABLES
if (!File.Exists(conversionTable))
{
buttonLabel = CsvHelper.trans("air_tbl_not_found");
TextBlock notice = addTextBlock(string.Format(CsvHelper.trans("air_tbl_not_found_notice"), conversionTable), HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black,
new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
parent.Children.Insert(0, notice);
}
// NO AIRUPDATE
else if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "AirDat\\AirUpdate.exe"))
{
buttonLabel = CsvHelper.trans("airupdate_not_found");
TextBlock notice = addTextBlock(CsvHelper.trans("airupdate_not_found_notice"), HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black,
new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
parent.Children.Insert(0, notice);
download = true;
}
// NO AIR DUMP
else if (!File.Exists(airExported))
{
buttonLabel = CsvHelper.trans("air_dump_not_found");
TextBlock notice = addTextBlock(string.Format(CsvHelper.trans("air_dump_notice"), airExported) + Environment.NewLine +
CsvHelper.trans("air_dump_notice1") + Environment.NewLine +
string.Format(CsvHelper.trans("air_dump_notice2"), aircraftDirectory) + Environment.NewLine + "" +
CsvHelper.trans("air_dump_notice3") + Environment.NewLine +
CsvHelper.trans("air_dump_notice4") + Environment.NewLine +
CsvHelper.trans("air_dump_notice5") + Environment.NewLine +
CsvHelper.trans("air_dump_notice6"), HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black,
new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
parent.Children.Insert(0, notice);
launch = true;
}
//CHECK AIR VALUES
else
{
// GET FSX->ASOBO TABLE
// NAME VALUE
var fsx2msfsTable = CsvHelper.processAirTable(conversionTable, new string[] { "Table/Record", "Asobo" });
// GET AIR DUMP
// NAME COMMENT VALUE
//var fsxAirTable = CsvHelper.processAirFile(airExported);
var fsxAirTable = CsvHelper.processAirDump(airExported);
// compute_aero_center = 0
if (fsx2msfsTable != null && fsx2msfsTable.Count > 0 && fsxAirTable != null && fsxAirTable.Count > 0)
{
foreach (string[] asoboLine in fsx2msfsTable)
{
string id = asoboLine[0];
string attr = asoboLine[1];
foreach (string[] airLine in fsxAirTable)
{
if (airLine[0] == id && !String.IsNullOrEmpty(attr))
{
string oldVal = CfgHelper.getCfgValue(attr, filename, "", false);
string defVal = CfgHelper.getCfgValue(attr, filename, "", true);
if (defVal != "" && airLine[2] != oldVal)
{
parent = AddGroupCheckBox(parent, attr, Colors.Black, values++, attr + "=" + airLine[2]);
Grid DynamicGrid = new Grid();
ColumnDefinition gridCol1 = new ColumnDefinition();
ColumnDefinition gridCol2 = new ColumnDefinition();
RowDefinition gridRow1 = new RowDefinition();
RowDefinition gridRow2 = new RowDefinition();
DynamicGrid.ColumnDefinitions.Add(gridCol1);
DynamicGrid.ColumnDefinitions.Add(gridCol2);
TextBlock myBlock2 = addTextBlock(CsvHelper.trans("air_new_val") + ": " + airLine[2], HorizontalAlignment.Left, VerticalAlignment.Top,
airLine[2] == "0" || airLine[2] == "0.0" || Regex.IsMatch(airLine[2], @"(0,){8,}") || String.IsNullOrWhiteSpace(Regex.Replace(airLine[2], @"[0-9-.]+:([1][.0]+)[,]*", ""))
? Colors.DarkRed : Colors.Black, new Thickness(0));
myBlock2.ToolTip = airLine[2].Replace(",", Environment.NewLine);
Grid.SetColumn(myBlock2, 0);
Grid.SetRow(myBlock2, 0);
DynamicGrid.Children.Add(myBlock2);
TextBlock myBlock3;
if (oldVal != "")
{
myBlock3 = addTextBlock(CsvHelper.trans("air_old_val") + ": " + oldVal, HorizontalAlignment.Left, VerticalAlignment.Top, Colors.Black, new Thickness(0));
myBlock3.ToolTip = oldVal.Replace(",", Environment.NewLine);
} else
{
myBlock3 = addTextBlock(CsvHelper.trans("air_default_val") + ": " + defVal, HorizontalAlignment.Left, VerticalAlignment.Top, Colors.Black, new Thickness(0));
myBlock3.ToolTip = defVal.Replace(",", Environment.NewLine);
}
myBlock2.MaxWidth = myBlock3.MaxWidth = 295;
Grid.SetColumn(myBlock3, 1);
Grid.SetRow(myBlock3, 0);
DynamicGrid.Children.Add(myBlock3);
Border myBorder = new Border() { BorderThickness = new Thickness() { Bottom = 1, Left = 0, Right = 0, Top = 0 }, BorderBrush = new SolidColorBrush(Colors.Black) };
myBorder.Margin = new Thickness(0, 0, 0, -5);
Grid.SetRow(myBorder, 1);
Grid.SetColumn(myBorder, 0);
DynamicGrid.Children.Add(myBorder);
Border myBorder2 = new Border() { BorderThickness = new Thickness() { Bottom = 1, Left = 0, Right = 0, Top = 0 }, BorderBrush = new SolidColorBrush(Colors.Black) };
myBorder2.Margin = new Thickness(0, 0, 0, -5);
Grid.SetRow(myBorder2, 1);
Grid.SetColumn(myBorder2, 1);
DynamicGrid.Children.Add(myBorder2);
DynamicGrid.Margin = new Thickness(0, 0, 0, 10);
parent.Children.Add(DynamicGrid);
}
break;
}
}
}
}
else
{
TextBlock notice = addTextBlock(CsvHelper.trans("air_loading_failed"), HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.DarkRed, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
parent.Children.Insert(0, notice);
}
if (values > 0)
{
TextBlock notice = addTextBlock(CsvHelper.trans("air_import_notice"), HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
parent.Children.Insert(0, notice);
buttonLabel = CsvHelper.trans("air_insert_values");
}
else
{
TextBlock notice = addTextBlock(CsvHelper.trans("air_no_values_to_import_notice"), HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
parent.Children.Insert(0, notice);
buttonLabel = CsvHelper.trans("air_no_values_to_import");
}
}
Button btn = new Button();
btn = SetButtonAtts(btn);
btn.Content = buttonLabel;
if (values > 0)
btn.Click += InsertAirValues;
else
{
if (download)
btn.Click += GetAirUpdate;
else if (launch)
btn.Click += LaunchAirUpdate;
else
btn.IsEnabled = false;
}
myPanel.Children.Add(btn);
// REMOVE BUTTON
if (airFilename.Length > 1 && airFilename[0] != '.' && File.Exists(aircraftDirectory + "\\" + airFilename) && !File.Exists(aircraftDirectory + "\\." + airFilename) &&
!download && !launch)
{
Button btn2 = new Button();
btn2 = SetButtonAtts(btn2);
btn2.Content = CsvHelper.trans("air_remove");
btn2.Click += backupAirFile;
myPanel.Children.Add(btn2);
}
parent.Children.Add(myPanel);
parent.Children.Add(sectiondivider());
}
private void LaunchAirUpdate(object sender, RoutedEventArgs e)
{
Process prcs = new Process();
try
{
prcs.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "AirDat\\AirUpdate.exe";
prcs.StartInfo.CreateNoWindow = true;
prcs.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory + "AirDat\\";
prcs.EnableRaisingEvents = true;
prcs.Exited += new EventHandler(AirUpdateClosed);
prcs.Start();
}
catch
{
Dispatcher.Invoke(() => SummaryUpdate());
return;
}
}
private void AirUpdateClosed(object sender, System.EventArgs e)
{
Dispatcher.Invoke(() => SummaryUpdate());
}
private void GetAirUpdate(object sender, RoutedEventArgs e)
{
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\AirDat\\"))
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\AirDat\\");
Dispatcher.Invoke(() => fsTabControl.IsEnabled = false);
WebClient _webClient = new WebClient();
_webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(OnAirDownloadCompleted);
_webClient.DownloadFileAsync(new Uri("http://www.mudpond.org/AirDat.ZIP"), AppDomain.CurrentDomain.BaseDirectory + "\\AirDat\\" + TEMP_FILE);
}
private void OnAirDownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if ((e == null || !e.Cancelled && e.Error == null) && File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\AirDat\\" + TEMP_FILE) && new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\AirDat\\" + TEMP_FILE).Length > 10)
{
Extract extract = new Extract();
extract.Run(AppDomain.CurrentDomain.BaseDirectory + "\\AirDat\\" + TEMP_FILE, "", AppDomain.CurrentDomain.BaseDirectory + "\\AirDat\\");
}
Stopwatch sw = new Stopwatch();
sw.Start();
while (true) { if (sw.ElapsedMilliseconds > 1000 || File.Exists(AppDomain.CurrentDomain.BaseDirectory + "AirDat\\AirUpdate.exe")) break; }
Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
SummaryUpdate();
}
private void InsertAirValues(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
StackPanel myPanel = (StackPanel)button.Parent;
StackPanel parentPanel = (StackPanel)myPanel.Parent;
if (parentPanel != null)
{
string filename = parentPanel.Tag.ToString();
if (CfgHelper.cfgFileExists(filename))
{
string[] values = new string[1000];
int i = 0;
foreach (var checkboxLabel in getCheckedOptions(parentPanel, "", true))
{
values[i] = checkboxLabel;
i++;
}
if (i > 0)
{
// CFG BACKUP
if (File.Exists(aircraftDirectory + "\\" + filename) && !File.Exists(aircraftDirectory + "\\." + filename))
{
CfgHelper.lastChangeTimestamp = DateTime.UtcNow.Ticks;
File.Copy(aircraftDirectory + "\\" + filename, aircraftDirectory + "\\." + filename);
}
for (int k = 0; k < i; k++)
{
string[] value = values[k].Split('=');
CfgHelper.setCfgValue(aircraftDirectory, value[0].Trim(), value[1].Trim(), filename);
}
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { filename });
}
}
SummaryUpdate();
}
}
private void backupAirFile(object sender, RoutedEventArgs e)
{
// AIR BACKUP
if (airFilename.Length > 1 && airFilename[0] != '.' &&
File.Exists(aircraftDirectory + "\\" + airFilename) && !File.Exists(aircraftDirectory + "\\." + airFilename))
{
MessageBoxResult messageBoxResult = MessageBox.Show(string.Format(CsvHelper.trans("air_delete_warning_notice"), "." + airFilename, airFilename), CsvHelper.trans("air_delete_warning_header"), System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
try
{
if (File.Exists(aircraftDirectory + "\\." + airFilename))
File.Delete(aircraftDirectory + "\\." + airFilename);
File.Move(aircraftDirectory + "\\" + airFilename, aircraftDirectory + "\\." + airFilename);
if (File.Exists(aircraftDirectory + "\\." + airFilename.Replace(".air", ".txt")))
File.Delete(aircraftDirectory + "\\." + airFilename.Replace(".air", ".txt"));
File.Move(aircraftDirectory + "\\" + airFilename.Replace(".air", ".txt"), aircraftDirectory + "\\." + airFilename.Replace(".air", ".txt"));
}
catch { }
JSONHelper.scanTargetFolder(projectDirectory);
SummaryUpdate();
}
}
}
// AIR END
// SYSTEMS START
public void SummarySystems()
{
SystemsData.Children.Clear();
if (CfgHelper.cfgFileExists("systems.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
int lightsBroken = 0;
int lightsToInsert = 0;
foreach (var light in CfgHelper.getLights(aircraftDirectory))
if (!String.IsNullOrEmpty(light))
SystemsData = AddGroupCheckBox(SystemsData, light, Colors.DarkRed, lightsBroken++);
StackPanel myPanel2 = new StackPanel();
Button btn = new Button();
btn = SetButtonAtts(btn);
if (lightsBroken > 0)
{
btn.Content = CsvHelper.trans("systems_convert_lights");
btn.Click += FixLightsClick;
TextBlock notice = addTextBlock(CsvHelper.trans("systems_convert_lights_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
SystemsData.Children.Insert(0, notice);
tabSystems.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
else
{
List<string> contactPoints = CfgHelper.getContactPoints(aircraftDirectory, "1");
if (CfgHelper.getTaxiLights(aircraftDirectory) == 0 && contactPoints.Count > 0)
{
foreach (var point in contactPoints)
if (!String.IsNullOrEmpty(point))
SystemsData = AddGroupCheckBox(SystemsData, point, Colors.DarkOrange, lightsToInsert++);
btn.Content = CsvHelper.trans("systems_insert_lights");
btn.Click += InsertLightsClick;
TextBlock notice = addTextBlock(CsvHelper.trans("systems_insert_lights_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
SystemsData.Children.Insert(0, notice);
tabSystems.Background = new SolidColorBrush(Color.FromArgb(10, 255, 150, 0));
}
else
{
btn.Content = CsvHelper.trans("systems_no_light_issues");
btn.IsEnabled = false;
tabSystems.Background = new SolidColorBrush(Color.FromArgb(10, 0, 255, 0));
}
}
myPanel2.Children.Add(btn);
SystemsData.Children.Add(myPanel2);
//SystemContent.Foreground = new SolidColorBrush(Colors.Black);
SystemsData.Children.Add(sectiondivider());
}
}
private void FixLightsClick(object sender, RoutedEventArgs e)
{
if (CfgHelper.cfgFileExists("systems.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
int i = 0;
foreach (var checkboxLabel in getCheckedOptions(SystemsData))
{
if (checkboxLabel.ToLower().Trim().StartsWith("light."))
{
// CONVERTS LIGHT DATA
// light\.(\d+)(.*)=(.*)(\d+),(.*)(\d+),(.*)(\d+),(.*)(fx_[A-Za-z]+)(.*)
// MSFS lightdef.0 = Type:1#Index:1#LocalPosition:-11.5,0,11.6#LocalRotation:0,0,0#EffectFile:LIGHT_ASOBO_BeaconTop#Node:#PotentiometerIndex:1#EmMesh:LIGHT_ASOBO_BeaconTop
// FSX light.0 = 3, -39.00, -23.6, -0.25, fx_navredm ,
string[] fsxLight = checkboxLabel.Split('=');
if (fsxLight.Length >= 2)
{
string fsxNum = fsxLight[0].Trim().Replace("light.", "");
string[] fsxData = fsxLight[1].Split(',');
if (fsxData.Length >= 5)
{
string type = fsxData[0].Replace(" ", "").Trim();
string x = fsxData[1].Replace(" ", "").Trim();
string y = fsxData[2].Replace(" ", "").Trim();
string z = fsxData[3].Replace(" ", "").Trim();
Regex regex = new Regex(@"(fx_[A-Za-z]*)");
Match match = regex.Match(fsxData[4]);
Regex digRregex = new Regex("[0-9.-]+");
if (match.Success && digRregex.IsMatch(fsxNum) && digRregex.IsMatch(type) && digRregex.IsMatch(x) && digRregex.IsMatch(y) && digRregex.IsMatch(z))
{
string newLight = "Type:" + getMfsfLightType(type) + "#Index:0#LocalPosition:" + x + "," + y + "," + z + "#LocalRotation:0,0,0#EffectFile:" + getMfsfLightEff(match.Value) + "#Node:#PotentiometerIndex:1#EmMesh:" + getMfsfLightEff(match.Value);
CfgHelper.setCfgValue(aircraftDirectory, "lightdef." + fsxNum, newLight, "systems.cfg", "[LIGHTS]");
CfgHelper.setCfgValueStatus(aircraftDirectory, "light." + fsxNum, "systems.cfg", "[LIGHTS]", false);
i++;
}
}
}
}
}
if (i > 0)
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "systems.cfg" });
}
SummaryUpdate();
}
private void InsertLightsClick(object sender, RoutedEventArgs e)
{
if (CfgHelper.cfgFileExists("systems.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
int i = 100;
foreach (var checkboxLabel in getCheckedOptions(SystemsData))
{
if (checkboxLabel.ToLower().Trim().StartsWith("point."))
{
string[] fsxLight = checkboxLabel.Split('=');
if (fsxLight.Length >= 2)
{
if (fsxLight[1].Contains(',') && fsxLight[1].Split(',').Length >= 4)
{
string[] fsxData = fsxLight[1].Split(',');
if (fsxData.Length >= 5)
{
string x = fsxData[1].Replace(" ", "").Trim() + (!fsxData[1].Contains('.') ? ".0" : "");
string z = fsxData[2].Replace(" ", "").Trim() + (!fsxData[2].Contains('.') ? ".0" : "");
string y = fsxData[3].Replace(" ", "").Trim() + (!fsxData[3].Contains('.') ? ".0" : "");
if (double.TryParse(x, out double xVal) && double.TryParse(y, out double yVal) && double.TryParse(z, out double zVal))
{
string newLight = "Type:6#Index:0#LocalPosition:" + (xVal + 1.0).ToString() + "," + zVal.ToString() + "," + (yVal + 2.0).ToString() + "#LocalRotation:0,0,0#EffectFile:LIGHT_ASOBO_Taxi#PotentiometerIndex:1#EmMesh:LIGHT_ASOBO_Taxi";
CfgHelper.setCfgValue(aircraftDirectory, "lightdef." + i, newLight, "systems.cfg", "[LIGHTS]");
i++;
}
}
}
}
}
}
if (i > 100)
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "systems.cfg" });
}
SummaryUpdate();
}
public string getMfsfLightEff(string fsxEff)
{
switch (fsxEff)
{
case "fx_beacon":
return "LIGHT_ASOBO_BeaconTop";
case "fx_beaconb":
return "LIGHT_ASOBO_BeaconBelly";
case "fx_beaconh":
return "LIGHT_ASOBO_BeaconTop_POS";
case "fx_landing":
return "LIGHT_ASOBO_Landing";
case "fx_navgre":
return "LIGHT_ASOBO_NavigationGreen";
case "fx_navgrem":
return "LIGHT_ASOBO_NavigationGreen";
case "fx_navred":
return "LIGHT_ASOBO_NavigationRed";
case "fx_navredm":
return "LIGHT_ASOBO_NavigationRed";
case "fx_navwhi":
return "LIGHT_ASOBO_NavigationWhite";
case "fx_navwhih":
return "LIGHT_ASOBO_NavigationWhite";
case "fx_recog":
return "LIGHT_ASOBO_RecognitionLeft";
case "fx_strobe":
return "LIGHT_ASOBO_StrobeSimple";
case "fx_strobeh":
return "LIGHT_ASOBO_StrobeBelly";
case "fx_vclight":
return "LIGHT_ASOBO_CabinBounce";
case "fx_vclightwhi":
return "LIGHT_ASOBO_CabinBounceSmall";
case "fx_vclighth":
return "LIGHT_ASOBO_CabinBounceLarge";
default:
return "LIGHT_ASOBO_BeaconTop";
}
}
public string getMfsfLightType(string fsxType)
{
return fsxType;
}
// SYSTEMS END
// FLIGHT MODEL START
public void SummaryFlightModel()
{
FlightModelData.Children.Clear();
FlightModelAir.Children.Clear();
if (CfgHelper.cfgFileExists("flight_model.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
int contactPointsBroken = 0;
List<string> contactPoints = CfgHelper.getContactPoints(aircraftDirectory, "1");
string[] possiblyDamaged = new string[100];
int possiblyDamagedCounter = 0;
int firstCounter = 0;
foreach (string firstContactPoint in contactPoints)
{
int secondCounter = 0;
if (String.IsNullOrEmpty(firstContactPoint))
continue;
foreach (string secondContactPoint in contactPoints)
{
if (String.IsNullOrEmpty(secondContactPoint))
continue;
if (!String.IsNullOrEmpty(firstContactPoint) && !String.IsNullOrEmpty(secondContactPoint) && firstContactPoint != secondContactPoint &&
secondCounter > firstCounter)
{
double[] testOne = parseContactPoint(firstContactPoint);
double[] testTwo = parseContactPoint(secondContactPoint);
if (testOne.Length >= 5 && testTwo.Length >= 5)
{
double distance = Math.Pow(
Math.Pow(testTwo[2] - testOne[2], 2) +
Math.Pow(testTwo[3] - testOne[3], 2) +
Math.Pow(testTwo[4] - testOne[4], 2),
0.5);
//Console.WriteLine(firstContactPoint + " " + secondContactPoint + " distance: " + distance.ToString());
double minDistance = 3.0;
if (distance > 0 && distance < minDistance)
{
Color color = Colors.DarkOrange;
FlightModelData = AddGroupCheckBox(FlightModelData, firstContactPoint, color, contactPointsBroken++);
FlightModelData = AddGroupCheckBox(FlightModelData, secondContactPoint, color, contactPointsBroken);
StackPanel myPanel = new StackPanel();
myPanel.Height = 16;
myPanel.VerticalAlignment = VerticalAlignment.Top;
myPanel.Margin = new Thickness(30, 0, 0, 10);
TextBlock myBlock = addTextBlock(string.Format(CsvHelper.trans("fm_contact_point_data"), distance.ToString("N2")), HorizontalAlignment.Left, VerticalAlignment.Top, color, new Thickness(0));
myPanel.Children.Add(myBlock);
FlightModelData.Children.Add(myPanel);
}
}
else if (firstCounter == 0 && (testOne.Length < 5 ? testOne.Length == 1 : testTwo.Length == 1))
{
possiblyDamaged[possiblyDamagedCounter] = testOne.Length < 5 ? firstContactPoint : secondContactPoint;
possiblyDamagedCounter++;
}
}
secondCounter++;
}
firstCounter++;
}
StackPanel myPanel2 = new StackPanel();
Button btn = new Button();
btn = SetButtonAtts(btn);
if (contactPointsBroken > 0)
{
btn.Content = CsvHelper.trans("fm_fix_contact_points");
btn.Click += FixContactsClick;
TextBlock notice = addTextBlock(CsvHelper.trans("fm_fix_contact_points_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600 );
FlightModelData.Children.Insert(0, notice);
//tabFlightModel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
else
{
btn.Content = CsvHelper.trans("fm_contact_points_issues");
btn.IsEnabled = false;
tabFlightModel.Background = new SolidColorBrush(Color.FromArgb(10, 0, 255, 0));
}
myPanel2.Children.Add(btn);
// BROKEN POINTS WARNING
string lastPoint = "";
if (possiblyDamagedCounter > 0)
{
TextBlock notice = addTextBlock(CsvHelper.trans("fm_contact_points_issues_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
myPanel2.Children.Add(notice);
foreach (string val in possiblyDamaged)
{
if (lastPoint != val)
{
lastPoint = val;
TextBlock myBlock = addTextBlock(val, HorizontalAlignment.Left, VerticalAlignment.Top, Colors.DarkRed, new Thickness(0));
myPanel2.Children.Add(myBlock);
}
}
tabFlightModel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
FlightModelData.Children.Add(myPanel2);
FlightModelData.Children.Add(sectiondivider());
// FM ISSUES
FlightModelIssues.Children.Clear();
int criticalIssues = 0;
foreach (string attr in new string[] { "compute_aero_center", "fuselage_length", "fuselage_diameter" })
{
string value = CfgHelper.getCfgValue(attr, "flight_model.cfg");
if (value == "" && !String.IsNullOrEmpty(CfgHelper.getCfgValue(attr, "flight_model.cfg", "", true)))
FlightModelIssues = AddGroupCheckBox(FlightModelIssues, attr + " = " + (value != "" ? value : "missing"), Colors.DarkRed, criticalIssues++);
}
foreach (string attr in new string[] { "elevator_scaling_table", "aileron_scaling_table", "rudder_scaling_table" })
{
string value = CfgHelper.getCfgValue(attr, "flight_model.cfg");
string result = Regex.Replace(value, @"[0-9-.]+:([1][.0]+)[,]*", "");
if ((String.IsNullOrEmpty(value) || String.IsNullOrEmpty(result.Trim())) && !String.IsNullOrEmpty(CfgHelper.getCfgValue(attr, "flight_model.cfg", "", true)))
{
FlightModelIssues = AddGroupCheckBox(FlightModelIssues, attr + " = " + (value != "" ? value : "missing"), Colors.DarkRed, criticalIssues++);
}
}
StackPanel myPanel3 = new StackPanel();
Button btn3 = new Button();
btn3 = SetButtonAtts(btn3);
if (criticalIssues > 0)
{
btn3.Content = CsvHelper.trans("fm_fix_flight_model");
btn3.Click += FixFlightModelClick;
TextBlock notice = addTextBlock(CsvHelper.trans("fm_fix_flight_model_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
FlightModelIssues.Children.Insert(0, notice);
tabFlightModel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
else
{
btn3.Content = CsvHelper.trans("fm_no_flight_model_issues");
btn3.IsEnabled = false;
}
myPanel3.Children.Add(btn3);
FlightModelIssues.Children.Add(myPanel3);
FlightModelIssues.Children.Add(sectiondivider());
if (CfgHelper.cfgFileExists("flight_model.cfg"))
getAirCheckboxes(FlightModelAir, "flight_model.cfg");
}
}
private void FixFlightModelClick(object sender, RoutedEventArgs e)
{
int i = 0;
if (CfgHelper.cfgFileExists("flight_model.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
string message = "";
foreach (var checkboxLabel in getCheckedOptions(FlightModelIssues, "="))
{
string val = checkboxLabel.Split('=')[0].Trim();
if (val.Contains("_table"))
CfgHelper.setCfgValue(aircraftDirectory, val, "-0.785:1,0:0.4,0.785:1", "flight_model.cfg");
else if (val == "compute_aero_center")
CfgHelper.setCfgValue(aircraftDirectory, val, "1", "flight_model.cfg");
else if (val == "fuselage_length")
{
string length = CfgHelper.getCfgValue("wing_span", "flight_model.cfg", "[AIRPLANE_GEOMETRY]");
double num;
string stringNewVal = (Double.TryParse(length, out num) ? 1.1 * num : 50).ToString();
CfgHelper.setCfgValue(aircraftDirectory, val, stringNewVal, "flight_model.cfg");
message += string.Format(CsvHelper.trans("fm_value_generated_notice"), val, stringNewVal, val) + Environment.NewLine + Environment.NewLine;
}
else if (val == "fuselage_diameter")
{
string length = CfgHelper.getCfgValue("wing_span", "flight_model.cfg", "[AIRPLANE_GEOMETRY]");
double num;
string weight = CfgHelper.getCfgValue("max_gross_weight", "flight_model.cfg", "[WEIGHT_AND_BALANCE]");
double num2;
string stringNewVal = Math.Max(5, (Double.TryParse(length, out num) && Double.TryParse(length, out num2) ? num * num2 / 666 : 5)).ToString();
CfgHelper.setCfgValue(aircraftDirectory, val, stringNewVal, "flight_model.cfg");
message += string.Format(CsvHelper.trans("fm_value_generated_notice2"), val, stringNewVal) + Environment.NewLine + Environment.NewLine;
}
i++;
}
if (message != "")
MessageBox.Show(message, "", MessageBoxButton.OK);
}
if (i > 0)
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "flight_model.cfg" });
SummaryUpdate();
}
private double[] parseContactPoint(string val)
{
// point.0 = 1, 43.00, -0.05, -9.70, 1600, 0, 1.442, 55.92, 0.6, 2.5, 0.9, 4.0, 4.0, 0, 220.0, 250.0 ;
//Console.WriteLine("Trying to parse point: " + val);
string[] contactPoint = val.Split('=');
if (contactPoint.Length >= 2)
{
string fsxNum = contactPoint[0].Replace("point.", "").Trim();
string[] fsxData = contactPoint[1].Split(',');
if (fsxData.Length >= 4)
{
Regex digRregex = new Regex("[0-9.-]+");
if (digRregex.IsMatch(fsxNum))
{
double[] msfsData = new double[fsxData.Length + 1];
int.TryParse(fsxNum.Contains('.') ? fsxNum.Trim('"').Split('.')[0] : fsxNum.Trim('"'), NumberStyles.Any, CultureInfo.InvariantCulture, out int numInt);
msfsData[0] = numInt;
int i = 0;
for (; i < fsxData.Length; i++)
{
string word = Regex.Replace(fsxData[i], "[^-0-9.]", "").TrimEnd('.'); ;
if (!word.Contains('.'))
word += ".0";
if (double.TryParse(word, NumberStyles.Any, CultureInfo.InvariantCulture, out double num))
msfsData[i + 1] = num;
else
{
Console.WriteLine(string.Format(CsvHelper.trans("fm_bad_contact_point"), fsxData[i].Replace(" ", "").Trim()));
return new double[] { 1 };
}
}
return msfsData;
}
}
}
return new double[] { };
}
private void FixContactsClick(object sender, RoutedEventArgs e)
{
if (CfgHelper.cfgFileExists("flight_model.cfg") || CfgHelper.cfgFileExists("aircraft.cfg"))
{
int i = 0;
string lastPoint = null;
foreach (var pnl in FlightModelData.Children)
{
if (pnl.GetType() != typeof(StackPanel))
continue;
StackPanel panel = (StackPanel)pnl;
if (panel.Children.Count > 0)
{
if (panel.Children[0].GetType() == typeof(CheckBox))
{
CheckBox a = (CheckBox)panel.Children[0];
if ((string)a.Content != CsvHelper.trans("toggle_all"))
{
string val = a.Content.ToString();
if (lastPoint == null)
{
lastPoint = a.IsChecked == true ? val : "";
}
else
{
// CALCULATE AVERAGE
if (!String.IsNullOrEmpty(lastPoint) && a.IsChecked == true)
{
double[] testOne = parseContactPoint(lastPoint.ToLower().Replace(" ", "").Trim());
double[] testTwo = parseContactPoint(val.ToLower().Replace(" ", "").Trim());
if (testOne.Length >= 3 && testTwo.Length >= 3)
{
/*double minDistance = 3.0;
double distance = Math.Pow(
Math.Pow(testTwo[2] - testOne[2], 2) +
Math.Pow(testTwo[3] - testOne[3], 2) +
Math.Pow(testTwo[4] - testOne[4], 2),
0.5);
double[] magnitude1 = new double[] { testTwo[2] - testOne[2], testTwo[3] - testOne[3], testTwo[4] - testOne[4] };
double max1 = 0;
foreach (double mag in magnitude1)
if (Math.Abs(mag) > max1)
max1 = Math.Abs(mag);
double[] magnitude2 = new double[] { testOne[2] - testTwo[2], testOne[3] - testTwo[3], testOne[4] - testTwo[4] };
double max2 = 0;
foreach (double mag in magnitude2)
if (Math.Abs(mag) > max2)
max2 = Math.Abs(mag);
if (max1 > 0 && max2 > 0)
{
testOne[2] -= magnitude1[0] / max1 * (minDistance - distance) / 2.0;
testOne[3] -= magnitude1[1] / max1 * (minDistance - distance) / 2.0;
testOne[4] -= magnitude1[2] / max1 * (minDistance - distance) / 2.0;
testTwo[2] -= magnitude2[0] / max2 * (minDistance - distance) / 2.0;
testTwo[3] -= magnitude2[1] / max2 * (minDistance - distance) / 2.0;
testTwo[4] -= magnitude2[2] / max2 * (minDistance - distance) / 2.0;*/
testOne[2] = testTwo[2] = ((testOne[2] + testTwo[2]) / 2);
testOne[3] = testTwo[3] = ((testOne[3] + testTwo[3]) / 2);
testOne[4] = testTwo[4] = ((testOne[4] + testTwo[4]) / 2);
string value1 = String.Join(", ", testOne);
int index = value1.IndexOf(",");
value1 = index >= 0 ? value1.Substring(index + 1) : value1;
string value2 = String.Join(", ", testTwo);
index = value2.IndexOf(",");
value2 = index >= 0 ? value2.Substring(index + 1) : value2;
CfgHelper.setCfgValue(aircraftDirectory, "point." + testOne[0], value1, "flight_model.cfg", "[CONTACT_POINTS]");
CfgHelper.setCfgValue(aircraftDirectory, "point." + testTwo[0], value2, "flight_model.cfg", "[CONTACT_POINTS]");
i++;
//}
}
}
lastPoint = null;
}
}
}
}
}
if (i > 0)
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "flight_model.cfg" });
}
SummaryUpdate();
}
// FLIGHT MODEL END
// GLOBAL SECTIONS START
public void SummarySections()
{
List<StackPanel> parentPanelsList = new List<StackPanel>();
parentPanelsList.Add(AircraftSections);
parentPanelsList.Add(EnginesSections);
parentPanelsList.Add(CockpitSections);
parentPanelsList.Add(SystemsSections);
parentPanelsList.Add(FlightModelSections);
parentPanelsList.Add(RunwaySections);
foreach (var pnl in parentPanelsList)
{
if (pnl.GetType() != typeof(StackPanel))
continue;
StackPanel parentPanel = (StackPanel)pnl;
string filename = parentPanel.Tag.ToString();
parentPanel.Children.Clear();
if (CfgHelper.cfgFileExists(filename) || CfgHelper.cfgFileExists("aircraft.cfg"))
{
//Console.WriteLine(filename + " " + CfgHelper.getSectionsList(aircraftDirectory, filename).Length);
int sectionsMissing = 0;
int requiredMissing = 0;
foreach (var secton in CfgHelper.getSectionsList(aircraftDirectory, filename))
{
if (!String.IsNullOrEmpty(secton) && !secton.Contains("VERSION"))
{
if (secton[0] == '-')
{
string engine_type = CfgHelper.getCfgValue("engine_type", "engines.cfg", "[GENERALENGINEDATA]");
if (engine_type.Contains('.'))
engine_type = engine_type.Split('.')[0];
if (secton.Contains("[FUEL_QUANTITY]") || secton.Contains("[AIRSPEED]") ||
secton.Contains("[RPM]") && engine_type == "0" ||
secton.Contains("[TORQUE]") && (engine_type == "1" || engine_type == "5") ||
secton.Contains("[THROTTLE_LEVELS]") || secton.Contains("[FLAPS_LEVELS]") ||
secton.Contains("[CONTROLS.") || secton.Contains("[FUELSYSTEM.") || secton.Contains("[SIMVARS.") ||
(secton.Contains("[PROPELLER]") || secton.Contains("[PISTON_ENGINE]")) && engine_type == "0" ||
(secton.Contains("[PROPELLER]") || secton.Contains("[TURBOPROP_ENGINE]") || secton.Contains("[TURBINEENGINEDATA]")) && engine_type == "5" ||
(secton.Contains("[TURBINEENGINEDATA]") || secton.Contains("[JET_ENGINE]")) && engine_type == "1" ||
!String.IsNullOrEmpty(airFilename) && File.Exists(aircraftDirectory + "\\" + airFilename.Replace(".air", ".txt")) && secton.Contains("[AERODYNAMICS]")
/*|| secton.Contains("ENGINE PARAMETERS.")*/
)
{
AddGroupCheckBox(parentPanel, secton.Substring(1), Colors.DarkRed, sectionsMissing++);
requiredMissing++;
}
else
AddGroupCheckBox(parentPanel, secton.Substring(1), Colors.Black, sectionsMissing++);
}
else
{
StackPanel myPanel = new StackPanel();
myPanel.Height = 16;
myPanel.VerticalAlignment = VerticalAlignment.Top;
myPanel.HorizontalAlignment = HorizontalAlignment.Left;
TextBlock myBlock = addTextBlock(secton, HorizontalAlignment.Left, VerticalAlignment.Top, Colors.DarkGreen, new Thickness(20, 0, 0, 0));
myPanel.Children.Add(myBlock);
parentPanel.Children.Add(myPanel);
}
}
}
if (sectionsMissing > 0)
{
StackPanel myPanel = new StackPanel();
Button btn = new Button();
btn = SetButtonAtts(btn);
btn.Content = CsvHelper.trans("cfg_insert_sections");
btn.Click += InsertSectionsClick;
myPanel.Children.Add(btn);
parentPanel.Children.Add(myPanel);
TextBlock notice = addTextBlock("", HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
if (filename == "cockpit.cfg")
{
notice.Text = CsvHelper.trans("cfg_insert_cockpit_sections_notice");
parentPanel.Children.Insert(0, notice);
}
else if (filename == "runway.flt")
{
notice.Text = CsvHelper.trans("cfg_insert_flt_sections_notice");
parentPanel.Children.Insert(0, notice);
}
}
foreach (var item in fsTabControl.Items)
{
if (((TabItem)item).Name == "tab" + parentPanel.Name.Replace("Sections", ""))
{
if (requiredMissing > 0)
((TabItem)item).Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
else if (((TabItem)item).Background.ToString() == "#00000000")
((TabItem)item).Background = new SolidColorBrush(Color.FromArgb(10, 0, 255, 0));
break;
}
}
}
parentPanel.Children.Add(sectiondivider());
}
}
private void InsertSectionsClick(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
StackPanel myPanel = (StackPanel)button.Parent;
StackPanel parentPanel = (StackPanel)myPanel.Parent;
if (parentPanel != null)
{
string sourceFilename = parentPanel.Tag.ToString();
string targetFilename = sourceFilename;
if (!CfgHelper.cfgFileExists(sourceFilename))
targetFilename = "aircraft.cfg";
string[] sections = new string[100];
int i = 0;
foreach (var checkboxLabel in getCheckedOptions(parentPanel))
{
sections[i] = checkboxLabel;
i++;
}
if (i > 0)
{
MessageBoxResult messageBoxResult;
if (sourceFilename == "cockpit.cfg")
messageBoxResult = MessageBoxResult.Yes;
else
messageBoxResult = MessageBox.Show(CsvHelper.trans("cfg_insert_sections_notice"),
string.Format(i > 1 ? CsvHelper.trans("cfg_insert_sections_header") : CsvHelper.trans("cfg_insert_section_header"), i, targetFilename), System.Windows.MessageBoxButton.YesNoCancel);
if (messageBoxResult != MessageBoxResult.Cancel)
{
CfgHelper.insertSections(aircraftDirectory, sourceFilename, targetFilename, sections, messageBoxResult == MessageBoxResult.Yes);
JSONHelper.scanTargetFolder(projectDirectory);
SummaryUpdate();
}
}
}
}
// GLOBAL SECTIONS END
// TEXTURES START
public void SummaryTextures()
{
TexturesList.Children.Clear();
int texturesToConvert = 0;
if (aircraftDirectory != "")
{
foreach (var subdir in Directory.GetDirectories(aircraftDirectory))
{
string folderName = subdir.Split('\\').Last().ToLower().Trim();
if (folderName[0] != '.' && folderName.Contains("texture"))
{
var txtFiles = Directory.EnumerateFiles(subdir, "*.bmp", SearchOption.TopDirectoryOnly);
foreach (string currentFile in txtFiles)
{
string fileName = currentFile.Replace(projectDirectory, "");
if (System.IO.Path.GetFileName(fileName)[0] != '.')
TexturesList = AddGroupCheckBox(TexturesList, fileName, Colors.DarkRed, texturesToConvert++);
}
}
}
}
StackPanel myPanel2 = new StackPanel();
Button btn = new Button();
btn = SetButtonAtts(btn);
btn.Name = "ImageTools";
Button btn2 = new Button();
btn2 = SetButtonAtts(btn2);
btn2.Name = "nvdxt";
if (texturesToConvert > 0)
{
btn.Content = CsvHelper.trans("textures_imagetools");
btn.Click += ConvertTexturesClick;
btn2.Content = CsvHelper.trans("textures_nvdxt");
btn2.Click += ConvertTexturesClick;
tabTextures.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
myPanel2.Children.Add(btn);
TextBlock notice = addTextBlock(CsvHelper.trans("textures_convert_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
TexturesList.Children.Insert(0, notice);
}
else
{
btn2.Content = CsvHelper.trans("textures_no_issues");
btn2.IsEnabled = false;
tabTextures.Background = new SolidColorBrush(Color.FromArgb(10, 0, 255, 0));
}
myPanel2.Children.Add(btn2);
TexturesList.Children.Add(myPanel2);
TexturesList.Children.Add(sectiondivider());
}
private void ConvertTexturesClick(object sender, EventArgs e)
{
fsTabControl.IsEnabled = false;
ConvertTexturesAsync(sender, getCheckedOptions(TexturesList), ((Button)sender).Name.ToString());
}
private async void ConvertTexturesAsync(object sender, List<string> values, string buttonLabel)
{
await Task.Run(() => ConvertTexturesTask(sender, values, buttonLabel));
}
private async Task ConvertTexturesTask(object sender, List<string> values, string buttonLabel)
{
// COUNT
int count = 0;
int converted = 0;
string[] bmp = new string[10000];
string[] dds = new string[10000];
foreach (var value in values)
{
bmp[count] = projectDirectory + value.ToString().ToLower();
dds[count] = projectDirectory + value.ToString().ToLower().Replace("bmp", "dds");
count++;
}
// CONVERT
for (int i = 0; i < count; i++)
{
Application.Current.Dispatcher.Invoke(() => {
if (sender.GetType() == typeof(Button))
((Button)sender).Content = string.Format(CsvHelper.trans("textures_conversion_process"), i, count);
});
if (File.Exists(dds[i]))
{
try { File.Delete(dds[i]); }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
if (!File.Exists(dds[i]))
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
if (buttonLabel.Contains("ImageTool"))
Process.Start(AppDomain.CurrentDomain.BaseDirectory + "ImageTool.exe", "-nogui -dds -dxt5 -32 -nostop -o \"" + dds[i] + "\" \"" + bmp[i] + "\"");
else
Process.Start(AppDomain.CurrentDomain.BaseDirectory + "nvdxt.exe", "-dxt5 -quality_highest -flip -file \"" + bmp[i] + "\" -output \"" + dds[i] + "\"");
Stopwatch sw = new Stopwatch();
sw.Start();
while (true)
{
if (sw.ElapsedMilliseconds > 5000 || File.Exists(dds[i])) break;
}
if (File.Exists(dds[i]))
{
File.Move(System.IO.Path.GetDirectoryName(bmp[i]) + "\\" + System.IO.Path.GetFileName(bmp[i]),
System.IO.Path.GetDirectoryName(bmp[i]) + "\\." + System.IO.Path.GetFileName(bmp[i]));
}
converted++;
}
}
JSONHelper.scanTargetFolder(projectDirectory);
Application.Current.Dispatcher.Invoke(() => SummaryUpdate());
Application.Current.Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
}
// TEXTURES END
// MODELS START
public void SummaryModels()
{
ModelAfterburnerList.Children.Clear();
ModelsList.Children.Clear();
int modelsWithoutBackup = 0;
int modelsToConvert = 0;
int modelsFound = 0;
int modelsAfterburnerToConvert = 0;
int modelsAfterburnerFound = 0;
List<string> warnings = new List<String>();
List<string> warningsAfterburner = new List<String>();
List<string> modelFiles;
ModelBackupButton.Tag = "";
if (aircraftDirectory != "")
{
// CHECK EXTERNAL MODEL FOR AFTERBURNER VALUES
if (CfgHelper.getCfgValue("engine_type", "engines.cfg", "[GENERALENGINEDATA]") == "1" && CfgHelper.cfgSectionExists("engines.cfg", "[TURBINEENGINEDATA]"))
{
modelFiles = CfgHelper.getExteriorModels(aircraftDirectory);
foreach (string modelFile in modelFiles)
{
if (modelFile != "" && File.Exists(modelFile))
{
string fileName = modelFile.Replace(aircraftDirectory, "").Trim('\\');
ModelBackupButton.Tag += fileName + ",";
if (System.IO.Path.GetFileName(fileName)[0] != '.')
{
bool hasBackup = File.Exists(System.IO.Path.GetDirectoryName(modelFile) + "\\." + System.IO.Path.GetFileName(modelFile));
if (!hasBackup)
modelsWithoutBackup++;
modelsAfterburnerFound++;
string contents = File.ReadAllText(modelFile);
// IF AB VARIABLE NOT SET
if (CfgHelper.getCfgValue("afterburner_stages", "engines.cfg", "[TURBINEENGINEDATA]") == "0" ||
CfgHelper.getCfgValue("afterburner_stages", "engines.cfg", "[TURBINEENGINEDATA]", true) == "")
{
int topABstage = -1;
bool varsToReplace = false;
var regex = new Regex(@"([A-Za-z])?\s*:\s*TURB\s*ENG(\d)?\s*AFTERBURNER\s*STAGE\s*ACTIVE\s*(:\s*\d)?,\s*number\s*\)\s*(\d)");
foreach (Match match in regex.Matches(contents))
{
foreach (var group in match.Groups)
{
if (group.ToString().Length == 1 && group.ToString().ToUpper()[0] == 'A')
varsToReplace = true;
if (group.ToString().Length == 1 && int.TryParse(group.ToString(), out int num))
{
if (num > 0 && num > topABstage)
topABstage = num;
}
}
}
// SET AB VARIABLE
Console.WriteLine("Top afterburner stage in model is " + topABstage.ToString());
if (topABstage != -1)
{
CfgHelper.setCfgValue(aircraftDirectory, "afterburner_stages", topABstage.ToString(), "engines.cfg", "[TURBINEENGINEDATA]", false);
CfgHelper.saveCfgFiles(aircraftDirectory, new string[] { "engines.cfg" });
SummaryEngines();
}
if (varsToReplace)
ModelAfterburnerList = AddGroupCheckBox(ModelAfterburnerList, fileName, Colors.Black, modelsAfterburnerToConvert++);
}
else
{
if (contents.Contains("A:TURB ENG AFTERBURNER") || contents.Contains("A:TURB ENG1 AFTERBURNER"))
ModelAfterburnerList = AddGroupCheckBox(ModelAfterburnerList, fileName, Colors.Black, modelsAfterburnerToConvert++);
}
}
}
}
}
// CHECK INTERIOR MODELS FOR CLICKABLES
modelFiles = CfgHelper.getInteriorModels(aircraftDirectory);
foreach (string modelFile in modelFiles)
{
if (modelFile != "" && File.Exists(modelFile))
{
string fileName = modelFile.Replace(aircraftDirectory, "").Trim('\\');
ModelBackupButton.Tag += fileName + ",";
if (System.IO.Path.GetFileName(fileName)[0] != '.')
{
bool hasBackup = File.Exists(System.IO.Path.GetDirectoryName(modelFile) + "\\." + System.IO.Path.GetFileName(modelFile));
if (!hasBackup)
modelsWithoutBackup++;
modelsFound++;
string contents = File.ReadAllText(modelFile);
if (contents.Contains("MREC"))
ModelsList = AddGroupCheckBox(ModelsList, fileName, Colors.Black, modelsToConvert++);
if (!contents.Contains("MDLXMDLH"))
warnings.Add(string.Format(CsvHelper.trans("model_format_is_not_compatible"), fileName) + Environment.NewLine);
}
}
}
ModelBackupButton.Tag = ModelBackupButton.Tag.ToString().TrimEnd(',');
}
if (CfgHelper.getCfgValue("engine_type", "engines.cfg", "[GENERALENGINEDATA]") == "1" && CfgHelper.cfgSectionExists("engines.cfg", "[TURBINEENGINEDATA]"))
{
StackPanel myPanel1 = new StackPanel();
Button btn1 = new Button();
btn1 = SetButtonAtts(btn1);
if (modelsAfterburnerToConvert > 0)
{
btn1.Content = CsvHelper.trans("model_replace_afterburner");
btn1.Click += ReplaceAfterburnerClick;
TextBlock notice = addTextBlock(CsvHelper.trans("model_replace_afterburner_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.DarkRed, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
ModelAfterburnerList.Children.Insert(0, notice);
}
else
{
btn1.Content = modelsAfterburnerFound > 0 ? CsvHelper.trans("model_no_afterburner") : CsvHelper.trans("model_no_exterior_model");
btn1.IsEnabled = false;
}
if (modelsAfterburnerFound == 0 || warningsAfterburner.Count > 0 || modelsAfterburnerToConvert > 0)
tabModel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
myPanel1.Children.Add(btn1);
ModelAfterburnerList.Children.Add(myPanel1);
if (warningsAfterburner.Count > 0)
{
foreach (var warning in warningsAfterburner)
ModelAfterburnerList.Children.Add(addTextBlock(warning, HorizontalAlignment.Center, VerticalAlignment.Center, Colors.DarkRed, new Thickness(0)));
}
ModelAfterburnerList.Children.Add(sectiondivider());
}
StackPanel myPanel2 = new StackPanel();
Button btn2 = new Button();
btn2 = SetButtonAtts(btn2);
if (modelsToConvert > 0)
{
btn2.Content = CsvHelper.trans("model_remove_clickable");
btn2.Click += RemoveSwitchesClick;
TextBlock notice = addTextBlock(CsvHelper.trans("model_remove_clickable_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
ModelsList.Children.Insert(0, notice);
}
else
{
/*if (modelsFound <= 0)
MessageBox.Show(CsvHelper.trans("model_no_interior_model_warning"), CsvHelper.trans("model_no_interior_model"));*/
btn2.Content = modelsFound > 0 ? CsvHelper.trans("model_no_clickable_switches") : CsvHelper.trans("model_no_interior_model");
btn2.IsEnabled = false;
}
if (modelsFound == 0 || warnings.Count > 0 /*|| modelsToConvert > 0 && modelsWithoutBackup > 0*/)
tabModel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
myPanel2.Children.Add(btn2);
ModelsList.Children.Add(myPanel2);
if (warnings.Count > 0)
{
foreach (var warning in warnings)
ModelsList.Children.Add(addTextBlock(warning, HorizontalAlignment.Center, VerticalAlignment.Center, Colors.DarkRed, new Thickness(0)));
}
ModelsList.Children.Add(sectiondivider());
}
private void ReplaceAfterburnerClick(object sender, EventArgs e)
{
fsTabControl.IsEnabled = false;
ReplaceAfterburnerClickAsync(sender, getCheckedOptions(ModelAfterburnerList));
}
private async void ReplaceAfterburnerClickAsync(object sender, List<string> values)
{
await Task.Run(() => ReplaceAfterburnerClickTask(sender, values));
}
private async Task ReplaceAfterburnerClickTask(object sender, List<string> values)
{
// COUNT
foreach (var checkboxLabel in values)
{
string mainFile = aircraftDirectory + "\\" + checkboxLabel;
if (File.Exists(mainFile))
{
//(A:TURB ENG AFTERBURNER STAGE ACTIVE:1,number)
//(A:TURB ENG1 AFTERBURNER,bool)
//(A:TURB ENG AFTERBURNER:1,bool)
//(A:TURB ENG AFTERBURNER PCT ACTIVE,percent)
Application.Current.Dispatcher.Invoke(() => {
if (sender.GetType() == typeof(Button))
((Button)sender).Content = string.Format(CsvHelper.trans("models_processing_file"), System.IO.Path.GetFileName(mainFile));
});
byte[] cache = new byte[22];
byte[] buf = File.ReadAllBytes(mainFile);
for (int i = 0; i < buf.Length; i++)
{
for (int k = 0; k < cache.Length - 1; k++)
{
cache[k] = cache[k + 1];
}
cache[cache.Length - 1] = buf[i];
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string s = enc.GetString(cache).ToUpper();
if (s == "A:TURB ENG AFTERBURNER" || s == "A:TURB ENG1 AFTERBURNE" || s == "A:TURB ENG2 AFTERBURNE" || s == "A:TURB ENG3 AFTERBURNE" || s == "A:TURB ENG4 AFTERBURNE" ||
s == "A :TURB ENG AFTERBURNE" || s == "A: TURB ENG AFTERBURNE" || s == "A : TURB ENG AFTERBURN")
buf[i - 21] = (byte)'L';
}
// MAKE MDL BACKUP
backUpFile(mainFile);
// CLEAR AIRCRAFT CACHE
deleteCVCfolder();
try { File.WriteAllBytes(mainFile, buf); }
catch (Exception ex) { MessageBox.Show("Can't save MDL file" + Environment.NewLine + "Error: " + ex.Message); }
}
}
Application.Current.Dispatcher.Invoke(() => SummaryUpdate());
Application.Current.Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
}
private void RemoveSwitchesClick(object sender, RoutedEventArgs e)
{
// COUNT
MessageBoxResult messageBoxResult = MessageBox.Show(CsvHelper.trans("model_remove_clickable_warning"), CsvHelper.trans("model_remove_clickable_warning_header"), System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
foreach (var checkboxLabel in getCheckedOptions(ModelsList))
{
string mainFile = aircraftDirectory + "\\" + checkboxLabel;
if (File.Exists(mainFile))
{
byte[] cache = new byte[4];
byte[] MDLDsize = new byte[4];
int MDLDsizeInt = -1;
byte[] MRECsize = new byte[4];
int MRECsizeInt = -1;
int MDLDpos = -1;
int MRECpos = -1;
byte[] buf = File.ReadAllBytes(mainFile);
for (int i = 0; i < buf.Length; i++)
{
for (int k = 0; k < cache.Length - 1; k++)
{
cache[k] = cache[k + 1];
}
cache[cache.Length - 1] = buf[i];
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string s = enc.GetString(cache);
if (s == "MDLD")
MDLDpos = i - 3;
else if (s == "MREC")
MRECpos = i - 3;
if (MDLDpos > 0 && i == MDLDpos + 7) // CAPTURE MDLD SIZE
{
if (BitConverter.IsLittleEndian)
Array.Reverse(cache);
MDLDsizeInt = cache[3] | (cache[2] << 8) | (cache[1] << 16) | (cache[0] << 24);
//Console.WriteLine(BitConverter.ToString(cache));
}
else if (MRECpos > 0 && i == MRECpos + 7) // CAPTURE MREC SIZE
{
if (BitConverter.IsLittleEndian)
Array.Reverse(cache);
MRECsizeInt = cache[3] | (cache[2] << 8) | (cache[1] << 16) | (cache[0] << 24);
//Console.WriteLine(BitConverter.ToString(cache));
}
else if (MRECpos > 0 && MRECsizeInt > 0 && i < MRECpos + MRECsizeInt + 7) // FILL MREC WITH ZEROES
{
buf[i] = 0x00;
}
}
if (MRECpos > 0 && MRECsizeInt > 0)
{
// MAKE MDL BACKUP
backUpFile(mainFile);
// CLEAR AIRCRAFT CACHE
deleteCVCfolder();
Console.WriteLine("MDLD pos" + MDLDpos + " lng" + MDLDsizeInt + "; MREC pos" + MRECpos + " lng" + MRECsizeInt);
try { File.WriteAllBytes(mainFile, buf); }
catch (Exception ex) { MessageBox.Show("Can't save MDL file" + Environment.NewLine + "Error: " + ex.Message); }
}
else
{
MessageBox.Show(string.Format(CsvHelper.trans("model_clickable_removal_failed"), checkboxLabel));
}
}
}
}
SummaryUpdate();
}
// MODELS END
// SOUND START
public void SummarySound()
{
SoundList.Children.Clear();
//int soundsToDisable = 0;
int soundsFound = 0;
if (aircraftDirectory != "")
{
List<string> soundFiles = CfgHelper.getSounds(aircraftDirectory);
if (soundFiles.Count() > 0)
{
foreach (string soundFile in soundFiles)
{
if (soundFile != "")
{
/*if (soundFile[0] != '-' && (soundFile.Contains("[GEAR_DOWN]") || soundFile.Contains("[GEAR_UP]")))
{
SoundList = AddGroupCheckBox(SoundList, soundFile, Colors.DarkRed, soundsFound++, "", true);
soundsToDisable++;
}
else*/
{
if (soundFile[0] == '-')
SoundList = AddGroupCheckBox(SoundList, soundFile.Substring(1), Colors.Black, soundsFound++, "", false);
else
SoundList = AddGroupCheckBox(SoundList, soundFile, Colors.Black, soundsFound++, "", true);
}
}
}
TextBlock notice = addTextBlock(CsvHelper.trans("sounds_toggle_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
SoundList.Children.Insert(0, notice);
}
}
StackPanel myPanel2 = new StackPanel();
Button btn = new Button();
btn = SetButtonAtts(btn);
if (soundsFound > 0)
{
btn.Content = CsvHelper.trans("sounds_update");
btn.Click += UpdateSoundsClick;
}
else
{
btn.Content = CsvHelper.trans("sounds_not_found");
btn.IsEnabled = false;
}
/*if (soundsToDisable > 0)
tabSound.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));*/
myPanel2.Children.Add(btn);
SoundList.Children.Add(myPanel2);
SoundList.Children.Add(sectiondivider());
if (Directory.Exists(aircraftDirectory + "\\sound\\") && !File.Exists(aircraftDirectory + "\\sound\\sound.xml") &&
File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\sound.xml"))
{
StackPanel myPanel3 = new StackPanel();
TextBlock volumeCorr = addTextBlock(string.Format(CsvHelper.trans("sounds_tone_volume"), "0", "30", "100"), HorizontalAlignment.Left, VerticalAlignment.Center, Colors.Black,
new Thickness(0, 10, 0, 0));
myPanel3.Children.Add(volumeCorr);
if (this.FindName("VarioVolimeSlider") != null)
UnregisterName("VarioVolimeSlider");
Slider varioVolimeSlider = new Slider();
RegisterName("VarioVolimeSlider", varioVolimeSlider);
varioVolimeSlider.Value = 30;
varioVolimeSlider.Minimum = 0;
varioVolimeSlider.Maximum = 100;
varioVolimeSlider.AutoToolTipPlacement = AutoToolTipPlacement.TopLeft;
varioVolimeSlider.AutoToolTipPrecision = 1;
myPanel3.Children.Add(varioVolimeSlider);
Button btn1 = new Button();
btn1 = SetButtonAtts(btn1);
btn1.Content = CsvHelper.trans("sounds_insert_tone");
btn1.Click += InsertVarioClick;
myPanel3.Children.Add(btn1);
SoundList.Children.Add(myPanel3);
} else if (Directory.Exists(aircraftDirectory + "\\sound\\") && File.Exists(aircraftDirectory + "\\sound\\sound.xml"))
{
StackPanel myPanel3 = new StackPanel();
Button btn1 = new Button();
btn1 = SetButtonAtts(btn1);
btn1.Content = CsvHelper.trans("sounds_remove_tone");
btn1.Click += DeleteSoundXmlClick;
myPanel3.Children.Add(btn1);
SoundList.Children.Add(myPanel3);
}
}
public void UpdateSoundsClick(object sender, RoutedEventArgs e)
{
CfgHelper.updateSounds(aircraftDirectory, getCheckedOptions(SoundList));
SummaryUpdate();
}
public void DeleteSoundXmlClick(object sender, RoutedEventArgs e)
{
if (Directory.Exists(aircraftDirectory + "\\sound\\") && File.Exists(aircraftDirectory + "\\sound\\sound.xml"))
{
MessageBoxResult messageBoxResult = MessageBox.Show(CsvHelper.trans("sounds_remove_notice"), CsvHelper.trans("sounds_warning"), System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
try
{
File.Delete(aircraftDirectory + "\\sound\\sound.xml");
}
catch { }
JSONHelper.scanTargetFolder(projectDirectory);
SummaryUpdate();
}
}
}
public void InsertVarioClick(object sender, RoutedEventArgs e)
{
if (Directory.Exists(aircraftDirectory + "\\sound\\") && !File.Exists(aircraftDirectory + "\\sound\\sound.xml") && File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\sound.xml"))
{
try
{
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\sound.xml", aircraftDirectory + "\\sound\\sound.xml");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_solid.wav", aircraftDirectory + "\\sound\\variotone_solid.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle100.wav", aircraftDirectory + "\\sound\\variotone_cycle100.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle200.wav", aircraftDirectory + "\\sound\\variotone_cycle200.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle250.wav", aircraftDirectory + "\\sound\\variotone_cycle250.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle300.wav", aircraftDirectory + "\\sound\\variotone_cycle300.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle400.wav", aircraftDirectory + "\\sound\\variotone_cycle400.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle500.wav", aircraftDirectory + "\\sound\\variotone_cycle500.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle550.wav", aircraftDirectory + "\\sound\\variotone_cycle550.wav");
File.Copy(AppDomain.CurrentDomain.BaseDirectory + "\\varioSound\\variotone_cycle600.wav", aircraftDirectory + "\\sound\\variotone_cycle600.wav");
float varioVolime = 30;
var varioVolimeSlider = FindName("VarioVolimeSlider");
if (varioVolimeSlider != null)
varioVolime = (float)((Slider)varioVolimeSlider).Value;
try { File.WriteAllText(aircraftDirectory + "\\sound\\sound.xml", File.ReadAllText(aircraftDirectory + "\\sound\\sound.xml").Replace("[VOLUME]", varioVolime.ToString())); }
catch (Exception ex) { MessageBox.Show("Can't save sound.xml file" + Environment.NewLine + "Error: " + ex.Message); }
}
catch { }
JSONHelper.scanTargetFolder(projectDirectory);
SummaryUpdate();
}
}
// SOUND END
// PANEL START
public void SummaryPanel()
{
PanelsList.Children.Clear();
CabsList.Children.Clear();
int panelsWithoutBackup = 0;
int panelsToConvert = 0;
int cabsWithoutBackup = 0;
int cabsToConvert = 0;
PanelBackupButton.Tag = "";
if (aircraftDirectory != "")
{
var panelFiles = Directory.EnumerateFiles(aircraftDirectory, "panel.cfg", SearchOption.AllDirectories);
foreach (string panelFile in panelFiles)
{
string fileName = panelFile.Replace(aircraftDirectory, "").Trim('\\');
if (panelFile != "" && fileName[0] != '.' && System.IO.Path.GetFileName(panelFile)[0] != '.')
{
PanelBackupButton.Tag += fileName + ",";
bool PanelHasBackup = File.Exists(System.IO.Path.GetDirectoryName(panelFile) + "\\." + System.IO.Path.GetFileName(panelFile));
if (!PanelHasBackup)
panelsWithoutBackup++;
PanelsList = AddGroupCheckBox(PanelsList, fileName, PanelHasBackup ? Colors.Black : Colors.DarkRed, panelsToConvert++);
var cabFiles = Directory.EnumerateFiles(System.IO.Path.GetDirectoryName(panelFile), "*.cab", SearchOption.TopDirectoryOnly);
foreach (string cabFile in cabFiles)
{
string cabFileName = cabFile.Replace(aircraftDirectory, "").Trim('\\');
if (cabFile != "" && System.IO.Path.GetFileName(cabFileName)[0] != '.')
{
PanelBackupButton.Tag += cabFileName + ",";
bool cabHasBackup = File.Exists(System.IO.Path.GetDirectoryName(cabFile) + "\\." + System.IO.Path.GetFileName(cabFile));
if (!cabHasBackup)
cabsWithoutBackup++;
CabsList = AddGroupCheckBox(CabsList, cabFileName, cabHasBackup ? Colors.Black : Colors.DarkRed, cabsToConvert++);
}
}
continue;
}
}
PanelBackupButton.Tag = PanelBackupButton.Tag.ToString().TrimEnd(',');
}
StackPanel myPanel1 = new StackPanel();
// CHECK FOR DLL FILES
if (Directory.GetFiles(aircraftDirectory, "*.dll", SearchOption.AllDirectories).Length > 0 || Directory.GetFiles(aircraftDirectory, "*.gau", SearchOption.AllDirectories).Length > 0)
{
TextBlock dllWarning = new TextBlock();
dllWarning.Text = CsvHelper.trans("panel_dll_detected");
dllWarning.Foreground = new SolidColorBrush(Colors.DarkRed);
myPanel1.Children.Add(dllWarning);
tabPanel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
Button btn1 = new Button();
btn1 = SetButtonAtts(btn1);
if (cabsToConvert > 0)
{
TextBlock extractGaugesNotice = addTextBlock(CsvHelper.trans("panel_extract_ac_cabs_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
CabsList.Children.Insert(0, extractGaugesNotice);
btn1.Content = CsvHelper.trans("panel_extract_gauges");
btn1.Click += extractCabClick;
} else
{
btn1.Content = CsvHelper.trans("panel_no_panel");
btn1.IsEnabled = false;
}
myPanel1.Children.Add(btn1);
/*----*/myPanel1.Children.Add(sectiondivider());
Button btn3 = new Button();
btn3 = SetButtonAtts(btn3);
TextBlock extractGaugesNotice2 = addTextBlock(string.Format(CsvHelper.trans("panel_extract_fsx_cabs_notice"),
System.IO.Path.GetDirectoryName(projectDirectory.TrimEnd('\\')) + "\\legacy-vcockpits-instruments\\.FSX\\"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
myPanel1.Children.Add(extractGaugesNotice2);
btn3.Content = CsvHelper.trans("panel_extract_fsx_resources");
btn3.Click += extractDefaultCabsClick;
myPanel1.Children.Add(btn3);
/*----*/myPanel1.Children.Add(sectiondivider());
if (cabsToConvert > 0 || cabsWithoutBackup > 0)
tabPanel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
CabsList.Children.Add(myPanel1);
StackPanel myPanel4 = new StackPanel();
myPanel4.Margin = new Thickness(0, 10, 0, 5);
Button btn4 = new Button();
btn4 = SetButtonAtts(btn4);
TextBlock brokenSwitches = addTextBlock(CsvHelper.trans("panel_broken_switches_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 0), TextWrapping.Wrap, 600);
myPanel4.Children.Add(brokenSwitches);
btn4.Content = CsvHelper.trans("panel_broken_switches");
btn4.Tag = "https://forums.flightsimulator.com/t/make-legacy-cockpit-buttons-work-again/325942";
btn4.Click += Button_RequestNavigate;
myPanel4.Children.Add(btn4);
/*----*/myPanel4.Children.Add(sectiondivider());
CabsList.Children.Add(myPanel4);
StackPanel myPanel2 = new StackPanel();
myPanel2.Margin = new Thickness(0, 10, 0, 5);
Button btn2 = new Button();
btn2 = SetButtonAtts(btn2);
if (panelsToConvert > 0)
{
btn2.Content = CsvHelper.trans("panel_import_gauges");
btn2.Click += importPanelGaugeClick;
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_force_gauge_background"), 600, HorizontalAlignment.Left, "ForceBackground");
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_transparent_mask"), 600, HorizontalAlignment.Left, "TransparentMask");
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_preserve_size"), 600, HorizontalAlignment.Left, "PreservePanelSize");
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_scale_up_gauge"), 600, HorizontalAlignment.Left, "ScaleUpGauge");
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_taxi_lights_switch"), 600, HorizontalAlignment.Left, "TaxiLightsSwitch");
string engine_type = CfgHelper.getCfgValue("engine_type", "engines.cfg", "[GENERALENGINEDATA]");
string afterburner_available = CfgHelper.getCfgValue("afterburner_stages", "engines.cfg", "[TURBINEENGINEDATA]", true);
if (engine_type == "1" && afterburner_available != "" && afterburner_available != "0")
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_afterburner_vars"), 600, HorizontalAlignment.Left, "AfterburnerVars");
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_ignore_errors"), 600, HorizontalAlignment.Left, "IgnorePanelErrors");
myPanel2 = AddSingleCheckBox(myPanel2, CsvHelper.trans("panel_js_validation"), 600, HorizontalAlignment.Left, "PanelJSValidation");
TextBlock gammaCorr = addTextBlock(string.Format(CsvHelper.trans("panel_gamma_correction"), "0", "1", "2"), HorizontalAlignment.Left, VerticalAlignment.Center, Colors.Black,
new Thickness(0, 10, 0, 0));
myPanel2.Children.Add(gammaCorr);
if (this.FindName("GammaSlider") != null)
UnregisterName("GammaSlider");
Slider gammaSlider = new Slider();
RegisterName("GammaSlider", gammaSlider);
gammaSlider.Value = gammaSliderPos;
gammaSlider.Minimum = 0.1;
gammaSlider.Maximum = 2.0;
gammaSlider.AutoToolTipPlacement = AutoToolTipPlacement.TopLeft;
gammaSlider.AutoToolTipPrecision = 1;
myPanel2.Children.Add(gammaSlider);
TextBlock extractGaugesNotice3 = addTextBlock(CsvHelper.trans("panel_convert_gauges_notice"),
HorizontalAlignment.Stretch, VerticalAlignment.Top, Colors.Black, new Thickness(0, 10, 0, 10), TextWrapping.Wrap, 600);
PanelsList.Children.Insert(0, extractGaugesNotice3);
}
else
{
btn2.Content = CsvHelper.trans("panel_not_found");
btn2.IsEnabled = false;
}
if (panelsToConvert > 0 && panelsWithoutBackup > 0)
tabPanel.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
myPanel2.Children.Add(btn2);
PanelsList.Children.Add(myPanel2);
/*----*/PanelsList.Children.Add(sectiondivider());
}
// AC CAB EXTRACT
private void extractCabClick(object sender, EventArgs e)
{
fsTabControl.IsEnabled = false;
extractAcCabAsync(sender, getCheckedOptions(CabsList));
}
private async void extractAcCabAsync(object sender, List<string> values)
{
await Task.Run(() => extractAcCabTask(sender, values));
}
private async Task extractAcCabTask(object sender, List<string> values)
{
foreach (var value in values)
{
string mainFile = aircraftDirectory + "\\" + value;
string backupFile = System.IO.Path.GetDirectoryName(mainFile) + "\\." + System.IO.Path.GetFileName(mainFile);
if (File.Exists(mainFile))
{
Application.Current.Dispatcher.Invoke(() => {
if (sender.GetType() == typeof(Button))
((Button)sender).Content = string.Format(CsvHelper.trans("panel_extracting_cab"), System.IO.Path.GetFileName(mainFile));
});
try
{
string extractDirectory = System.IO.Path.GetDirectoryName(mainFile) + "\\." + System.IO.Path.GetFileNameWithoutExtension(mainFile);
if (!Directory.Exists(extractDirectory))
Directory.CreateDirectory(extractDirectory);
if (File.Exists(backupFile))
File.Delete(backupFile);
CabInfo cab = new CabInfo(mainFile);
cab.Unpack(extractDirectory);
File.Move(mainFile, backupFile);
}
catch (Exception e)
{
Console.WriteLine("Exception " + e.Message);
}
}
}
JSONHelper.scanTargetFolder(projectDirectory);
Application.Current.Dispatcher.Invoke(() => SummaryUpdate());
Application.Current.Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
}
// DEFAULT CAB EXTRACT
private void extractDefaultCabsClick(object sender, RoutedEventArgs e)
{
string selectedPath = HKLMRegistryHelper.GetRegistryValue("SOFTWARE\\Microsoft\\microsoft games\\Flight Simulator\\10.0\\", "SetupPath", RegistryView.Registry32);
if (selectedPath != Environment.SpecialFolder.MyDocuments.ToString())
{
MessageBoxResult messageBoxResult = MessageBox.Show(string.Format(CsvHelper.trans("panel_current_fsx_path"), selectedPath) + Environment.NewLine + Environment.NewLine +
CsvHelper.trans("panel_fsx_extract_notice1") + Environment.NewLine +
CsvHelper.trans("panel_fsx_extract_notice2") + Environment.NewLine +
CsvHelper.trans("panel_fsx_extract_notice3"), CsvHelper.trans("panel_fsx_header"), MessageBoxButton.YesNoCancel);
if (messageBoxResult == MessageBoxResult.Cancel)
{
selectedPath = "";
}
else if (messageBoxResult == MessageBoxResult.No)
{
selectedPath = FileDialogHelper.getFolderPath(HKLMRegistryHelper.GetRegistryValue("SOFTWARE\\Microsoft\\microsoft games\\Flight Simulator\\10.0\\", "SetupPath", RegistryView.Registry32));
}
}
if (!String.IsNullOrEmpty(selectedPath))
{
if (Directory.Exists(selectedPath + "\\Gauges\\") && Directory.Exists(selectedPath + "\\SimObjects\\Airplanes\\"))
{
fsTabControl.IsEnabled = false;
extractDefaultCabsAsync(sender, selectedPath);
}
else
{
MessageBox.Show(string.Format(CsvHelper.trans("panel_gauges_not_found"), selectedPath));
}
}
}
private async void extractDefaultCabsAsync(object sender, string selectedPath)
{
Console.WriteLine("Extracting FSX cabs");
await Task.Run(() => extractDefaultCabsTask(sender, selectedPath));
}
private async Task extractDefaultCabsTask(object sender, string selectedPath)
{
var cabFiles = Directory.EnumerateFiles(selectedPath + "\\Gauges\\", "*.cab", SearchOption.AllDirectories);
var cabFiles2 = Directory.EnumerateFiles(selectedPath + "\\SimObjects\\Airplanes\\", "*.cab", SearchOption.AllDirectories);
IEnumerable<string> combined = cabFiles.Concat(cabFiles2);
foreach (string cabFile in combined)
{
if (File.Exists(cabFile))
{
Console.WriteLine("Extracting " + cabFile);
string extractDirectory = System.IO.Path.GetDirectoryName(projectDirectory.TrimEnd('\\')) + "\\legacy-vcockpits-instruments\\.FSX\\" + System.IO.Path.GetFileNameWithoutExtension(cabFile);
if (!Directory.Exists(extractDirectory))
{
Application.Current.Dispatcher.Invoke(() => {
if (sender.GetType() == typeof(Button))
((Button)sender).Content = string.Format(CsvHelper.trans("panel_extracting_cab"), System.IO.Path.GetFileName(cabFile));
});
Directory.CreateDirectory(extractDirectory);
try
{
CabInfo cab = new CabInfo(cabFile);
cab.Unpack(extractDirectory);
}
catch (Exception e)
{
Console.WriteLine("Exception " + e.Message);
}
await Task.Delay(100);
}
else
{
Console.WriteLine("Already extracted, skipping " + cabFile);
}
}
}
Application.Current.Dispatcher.Invoke(() => SummaryUpdate());
Application.Current.Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
//Application.Current.Dispatcher.Invoke(() => extractingCabs = false);
Application.Current.Dispatcher.Invoke(() => btnScan.Content = CsvHelper.trans("btnScan"));
}
// PANEL IMPORT
private void importPanelGaugeClick(object sender, EventArgs e)
{
gammaSliderPos = FindName("GammaSlider") != null ? (float)((Slider)FindName("GammaSlider")).Value : 1;
fsTabControl.IsEnabled = false;
importPanelGaugeAsync(sender, getCheckedOptions(PanelsList),
new float[] {
gammaSliderPos,
FindName("ForceBackground") != null && ((CheckBox)FindName("ForceBackground")).IsChecked == true ? 1 : 0,
FindName("IgnorePanelErrors") != null && ((CheckBox)FindName("IgnorePanelErrors")).IsChecked == true ? 1 : 0,
FindName("PreservePanelSize") != null && ((CheckBox)FindName("PreservePanelSize")).IsChecked == true ? 1 : 0,
FindName("TaxiLightsSwitch") != null && ((CheckBox)FindName("TaxiLightsSwitch")).IsChecked == true ? 1 : 0,
FindName("TransparentMask") != null && ((CheckBox)FindName("TransparentMask")).IsChecked == true ? 1 : 0,
FindName("ScaleUpGauge") != null && ((CheckBox)FindName("ScaleUpGauge")).IsChecked == true ? 1 : 0,
FindName("AfterburnerVars") != null && ((CheckBox)FindName("AfterburnerVars")).IsChecked == true ? 1 : 0,
FindName("PanelJSValidation") != null && ((CheckBox)FindName("PanelJSValidation")).IsChecked == true ? 1 : 0,
}
);
}
private async void importPanelGaugeAsync(object sender, List<string> values, float[] atts)
{
await Task.Run(() => importPanelGaugeTask(sender, values, atts));
JSONHelper.scanTargetFolder(projectDirectory);
Application.Current.Dispatcher.Invoke(() => SummaryUpdate());
Application.Current.Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
}
private async Task importPanelGaugeTask(object sender, List<string> values, float[] atts)
{
foreach (var value in values)
{
XmlHelper.insertFsxGauge(this, sender, aircraftDirectory, projectDirectory, value, atts, CfgHelper, FsxVarHelper, JSONHelper);
}
}
private void TextExpressionClick(object sender, RoutedEventArgs e)
{
TextExpressionField.Visibility = Visibility.Visible;
TextExpressionResult.Visibility = Visibility.Visible;
TextExpressionResult.Text = FsxVarHelper.fsx2msfsSimVar(TextExpressionField.Text, new xmlHelper(), true, "False");
}
// PANEL END
public string Get_aircraft_directory()
{
if (Directory.Exists(projectDirectory + @"\SimObjects\Airplanes\"))
{
String[] childFolders = Directory.GetDirectories(projectDirectory + @"\SimObjects\Airplanes\");
if (childFolders.Length > 0)
{
return childFolders[0];
}
else
{
return "";
}
} else
{
MessageBox.Show(string.Format(CsvHelper.trans("directory_not_found"), projectDirectory + @"\SimObjects\Airplanes\"));
return "";
}
}
public Button SetButtonAtts(Button btn, bool large = true)
{
if (large)
{
btn.MinHeight = 30;
btn.FontSize = 20;
btn.Margin = new Thickness(5, 20, 5, 20);
btn.Padding = new Thickness(5, 5, 5, 5);
btn.HorizontalAlignment = HorizontalAlignment.Stretch;
btn.Width = double.NaN;
}
btn.FontFamily = new FontFamily("Arial Black");
btn.VerticalAlignment = VerticalAlignment.Top;
btn.BorderBrush = new SolidColorBrush(Color.FromRgb(90, 90, 255));
btn.Background = new SolidColorBrush(Color.FromRgb(190, 221, 255));
if (btn.Name != null && !String.IsNullOrEmpty(btn.Name.ToString()))
btn.Content = CsvHelper.trans(btn.Name.ToString());
return btn;
}
public TextBlock SetHeaderAtts (TextBlock header, bool large = true)
{
if (header.Name != null && !String.IsNullOrEmpty(header.Name.ToString()))
{
if (header.ToolTip != null)
header.ToolTip = CsvHelper.trans(header.Name.ToString());
else
header.Text = CsvHelper.trans(header.Name.ToString());
}
return header;
}
private void CfgBackupClick(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string filenames = btn.Tag.ToString();
if (!btn.Tag.ToString().Contains(','))
filenames += ',';
foreach (var filename in filenames.Split(','))
{
if (!String.IsNullOrEmpty(filename))
{
string mainFile = aircraftDirectory + "\\" + filename;
string backupFile = System.IO.Path.GetDirectoryName(mainFile) + "\\." + System.IO.Path.GetFileName(mainFile);
if (File.Exists(backupFile))
{
MessageBoxResult messageBoxResult = MessageBox.Show(string.Format(CsvHelper.trans("restore_backup_notice"), filename), string.Format(CsvHelper.trans("restore_backup_header"), filename), MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
CfgHelper.lastChangeTimestamp = DateTime.UtcNow.Ticks;
try
{
File.Delete(mainFile);
File.Copy(backupFile, mainFile);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
else if (File.Exists(mainFile))
{
CfgHelper.lastChangeTimestamp = DateTime.UtcNow.Ticks;
File.Copy(mainFile, backupFile);
btn.Content = CsvHelper.trans("restore_backup");
}
}
}
CfgHelper.processCfgfiles(aircraftDirectory + "\\", true);
SummaryUpdate();
JSONHelper.scanTargetFolder(projectDirectory);
}
private void CfgEditClick(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string filename = btn.Tag.ToString();
if (File.Exists(aircraftDirectory + "\\" + filename))
{
Process.Start(aircraftDirectory + "\\" + filename);
}
}
public TextBlock addTextBlock(string text, HorizontalAlignment ha, VerticalAlignment va, Color clr, Thickness margin, TextWrapping wrapping = TextWrapping.NoWrap, int width = 0 )
{
TextBlock myBlock = new TextBlock();
myBlock.HorizontalAlignment = ha;
myBlock.VerticalAlignment = va;
myBlock.Text = text;
myBlock.Foreground = new SolidColorBrush(clr);
myBlock.Margin = margin;
myBlock.TextWrapping = wrapping;
if (width > 0)
myBlock.Width = width;
return myBlock;
}
private void BtnOpenTargetFile_Click(object sender, RoutedEventArgs e)
{
try
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
string defaultPath = !String.IsNullOrEmpty(communityPath) ? communityPath : HKLMRegistryHelper.GetRegistryValue("SOFTWARE\\Microsoft\\microsoft games\\Flight Simulator\\11.0\\", "CommunityPath");
dialog.InitialDirectory = defaultPath;
dialog.IsFolderPicker = true;
dialog.RestoreDirectory = (String.IsNullOrEmpty(defaultPath) || defaultPath == Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) ? true : false;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
TargetFolder = dialog.FileName + "\\";
btnTargetFolderPath.Text = string.Format(CsvHelper.trans("destination_path"), TargetFolder + XmlHelper.sanitizeString(PackageDir.Text.ToLower().Trim()) + "\\");
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void TextBlockTargetFile_Input(object sender, RoutedEventArgs e)
{
if (TargetFolder != "")
{
btnTargetFolderPath.Text = string.Format(CsvHelper.trans("destination_path"), TargetFolder + XmlHelper.sanitizeString(PackageDir.Text.ToLower().Trim()) + "\\");
}
}
private void BtnOpenSourceFile_Click(object sender, RoutedEventArgs e)
{
try
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
string defaultPath = HKLMRegistryHelper.GetRegistryValue("SOFTWARE\\Microsoft\\microsoft games\\Flight Simulator\\10.0\\", "SetupPath", RegistryView.Registry32);
dialog.InitialDirectory = defaultPath;
dialog.IsFolderPicker = true;
dialog.RestoreDirectory = (String.IsNullOrEmpty(defaultPath) || defaultPath == Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) ? true : false;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
string selectedPath = dialog.FileName;
if (File.Exists(selectedPath + "\\aircraft.cfg"))
{
SourceFolder = selectedPath + "\\";
btnSourceFolderPath.Text = string.Format(CsvHelper.trans("source_path"), SourceFolder);
// POPULATE INPUT FIELDS
string content = File.ReadAllText(selectedPath + "\\aircraft.cfg");
List<msfsLegacyImporter.cfgHelper.CfgLine> panelLines = CfgHelper.readCSV(content + "\r\n[]");
var title = panelLines.Find(x => x.Name == "title");
if (title != null) { PackageTitle.Text = title.Value.Trim('"').Trim(); }
var ui_manufacturer = panelLines.Find(x => x.Name == "ui_manufacturer");
if (ui_manufacturer != null) { PackageManufacturer.Text = ui_manufacturer.Value.Trim('"').Trim(); }
var ui_createdby = panelLines.Find(x => x.Name == "ui_createdby");
if (ui_createdby != null) { PackageAuthor.Text = ui_createdby.Value.Trim('"').Trim(); }
var sim = panelLines.Find(x => x.Name == "sim");
if (sim != null) { PackageDir.Text = sim.Value.Trim('"').Trim(); }
}
else
{
SourceFolder = "";
MessageBox.Show(string.Format(CsvHelper.trans("aircraft_not_found_in"), selectedPath));
}
}
} catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void BtnImportSubmit_Click(object sender, RoutedEventArgs e)
{
// VALIDATE FIELDS
if (TargetFolder == "" || SourceFolder == "")
MessageBox.Show(CsvHelper.trans("import_folders_not_selected"));
else if (String.IsNullOrWhiteSpace(PackageTitle.Text) || String.IsNullOrWhiteSpace(PackageDir.Text) || String.IsNullOrWhiteSpace(PackageManufacturer.Text) || String.IsNullOrWhiteSpace(PackageAuthor.Text) ||
String.IsNullOrWhiteSpace(PackageVer1.Text) || String.IsNullOrWhiteSpace(PackageVer2.Text) || String.IsNullOrWhiteSpace(PackageVer3.Text) ||
String.IsNullOrWhiteSpace(PackageMinVer1.Text) || String.IsNullOrWhiteSpace(PackageMinVer2.Text) || String.IsNullOrWhiteSpace(PackageMinVer3.Text))
MessageBox.Show(CsvHelper.trans("import_fields_are_empty"));
else if (Directory.Exists(TargetFolder + XmlHelper.sanitizeString(PackageDir.Text.ToLower().Trim()) + "\\"))
{
MessageBox.Show(string.Format(CsvHelper.trans("import_already_exists"), TargetFolder + XmlHelper.sanitizeString(PackageDir.Text.ToLower().Trim())));
} else if (SourceFolder == TargetFolder + XmlHelper.sanitizeString(PackageDir.Text.ToLower().Trim()) + "\\")
{
MessageBox.Show(CsvHelper.trans("import_same_directory"));
}
else
{
string[] data = new string[] { "", "AIRCRAFT", PackageTitle.Text, PackageManufacturer.Text, PackageAuthor.Text,
PackageVer1.Text + "." + PackageVer2.Text + "." + PackageVer3.Text, PackageMinVer1.Text + "." + PackageMinVer2.Text + "." + PackageMinVer3.Text, "" };
JSONHelper.createManifest(this, SourceFolder, TargetFolder + XmlHelper.sanitizeString(PackageDir.Text.ToLower().Trim()) + "\\", data);
showInitPage("imported");
}
}
private void BtnScan_Click(object sender, RoutedEventArgs e)
{
int filesCount = JSONHelper.scanTargetFolder(projectDirectory);
if (filesCount > 0)
{
btnScan.Content = string.Format(CsvHelper.trans("json_files_added"), filesCount);
} else
{
btnScan.Content = CsvHelper.trans("json_no_files_added");
}
var t = Task.Run(async delegate
{
await Task.Delay(2000);
Dispatcher.Invoke(() => btnScan.Content = CsvHelper.trans("btnScan"));
return;
});
}
private void Hyperlink_RequestNavigate(object sender,
System.Windows.Navigation.RequestNavigateEventArgs e)
{
if (e.Uri.ToString().Contains("msfs.touching.cloud"))
{
resetMissedUpdates(null, null);
}
Process.Start(e.Uri.ToString().Contains("//") ? e.Uri.AbsoluteUri : e.Uri.ToString());
}
private void Button_RequestNavigate(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
System.Diagnostics.Process.Start(btn.Tag.ToString());
}
public StackPanel AddGroupCheckBox(StackPanel mainPanel, string content, Color color, int index = 1, string tag = "", bool isChecked = false)
{
StackPanel myPanel = new StackPanel();
myPanel.Height = 17;
myPanel.VerticalAlignment = VerticalAlignment.Top;
// ADD TOGGLE CHECKBOX
if (index == 0)
{
StackPanel myPanel2 = new StackPanel();
myPanel2.Height = myPanel.Height;
myPanel2.VerticalAlignment = myPanel.VerticalAlignment;
myPanel2.Margin = new Thickness(0, 0, 0, 5);
CheckBox ToggleCheckBox = new CheckBox();
ToggleCheckBox.Content = CsvHelper.trans("toggle_all");
ToggleCheckBox.Tag = CsvHelper.trans("toggle_all");
ToggleCheckBox.MaxWidth = 600;
ToggleCheckBox.HorizontalAlignment = HorizontalAlignment.Left;
ToggleCheckBox.Foreground = new SolidColorBrush(Colors.Black);
ToggleCheckBox.Click += toggleCheckboxes;
myPanel2.Children.Add(ToggleCheckBox);
mainPanel.Children.Insert(0,myPanel2);
}
CheckBox checkBox = new CheckBox();
checkBox.Content = content;
checkBox.MaxWidth = 600;
checkBox.HorizontalAlignment = HorizontalAlignment.Left;
checkBox.Foreground = new SolidColorBrush(color);
checkBox.IsChecked = isChecked;
if (tag != "")
checkBox.Tag = tag;
myPanel.Children.Add(checkBox);
mainPanel.Children.Add(myPanel);
return mainPanel;
}
public StackPanel AddSingleCheckBox(StackPanel mainPanel, string content, int width = 0, HorizontalAlignment alignment = HorizontalAlignment.Left, string name = "")
{
CheckBox checkBox = new CheckBox();
checkBox.Content = content;
if (width > 0)
checkBox.MaxWidth = width;
checkBox.HorizontalAlignment = alignment;
if (!string.IsNullOrEmpty(name))
{
if (FindName(name) != null)
UnregisterName(name);
RegisterName(name, checkBox);
}
mainPanel.Children.Add(checkBox);
return mainPanel;
}
private void toggleCheckboxes(object sender, RoutedEventArgs e)
{
CheckBox ToggleCheckBox = (CheckBox)sender;
StackPanel myPanel = (StackPanel) ToggleCheckBox.Parent;
StackPanel parentPanel = (StackPanel)myPanel.Parent;
if (parentPanel.Children.Count > 0)
{
bool state = false;
int i = 0;
foreach (var tmpPanel in parentPanel.Children)
{
StackPanel tmp = new StackPanel();
if (tmpPanel.GetType() != tmp.GetType())
continue;
StackPanel panel = (StackPanel)tmpPanel;
if (panel.Children.Count > 0)
{
foreach (var checkBox in panel.Children)
{
if (checkBox.GetType() == typeof(CheckBox))
{
CheckBox thisCheckBox = (CheckBox)checkBox;
if (i <= 0 && thisCheckBox.IsChecked == true)
state = true;
else
thisCheckBox.IsChecked = state;
i++;
}
}
}
}
}
}
public void deleteCVCfolder()
{
if (projectDirectory != "")
{
if (Directory.Exists(projectDirectory.TrimEnd('\\') + "_CVT_"))
{
try
{
Directory.Delete(projectDirectory.TrimEnd('\\') + "_CVT_", true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show(CsvHelper.trans("cvt_remove_failed"));
}
}
}
}
public void backUpFile(string mainFile, bool force = false)
{
string backupFile = System.IO.Path.GetDirectoryName(mainFile) + "\\." + System.IO.Path.GetFileName(mainFile);
CfgHelper.lastChangeTimestamp = DateTime.UtcNow.Ticks;
if (File.Exists(backupFile) && force)
{
try
{
File.Delete(backupFile);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show(CsvHelper.trans("backup_creation_failed"));
}
}
if (!File.Exists(backupFile)) {
File.Copy(mainFile, backupFile);
}
}
// UPDATES START
private void setNewsLabel(string counter)
{
if (counter != "0")
{
Application.Current.Dispatcher.Invoke(() => newsLink.Text = "(" + counter + ")");
tabAbout.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
else
{
Application.Current.Dispatcher.Invoke(() => newsLink.Text = "");
tabAbout.Background = new SolidColorBrush(Colors.Transparent);
}
}
private void resetMissedUpdates(object sender, RoutedEventArgs e)
{
JSONHelper.importerSettings["last_read"] = DateTime.Now.ToUniversalTime().ToString();
setNewsLabel("0");
JSONHelper.saveSettings();
}
public async Task CheckUpdateAsync()
{
string pubVer = Assembly.GetExecutingAssembly().GetName().Version.ToString();
{
var client = new HttpClient();
if (!JSONHelper.importerSettings.TryGetValue("last_read", out string date))
date = "2000-01-01";
string data = await client.GetStringAsync(updatedirectory + "?last_read=" + date);
// GET NES COUNT
Regex regexNews = new Regex(@"news=(\d+)");
Match matchNews = regexNews.Match(data);
if (matchNews.Groups.Count >= 2)
{
setNewsLabel(matchNews.Groups[1].ToString());
}
//Console.WriteLine(data);
Version nullVer = Version.Parse("0.0.0.0");
var regex = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))");
foreach (var match in regex.Matches(data))
{
string url = match.ToString().Replace("href=", "").Replace("\"", "");
if (url.Contains(".exe") || url.Contains(".zip"))
{
// COMPARE VERSIONS
if (Version.TryParse(Regex.Replace(url, "[^0-9.]", "").TrimEnd('.'), out nullVer))
{
Version ver = Version.Parse(Regex.Replace(url, "[^0-9.]", "").TrimEnd('.'));
if (ver <= Version.Parse(pubVer))
{
break;
}
else
{
Console.WriteLine("online" + ver + " curr" + pubVer);
if (updateVersion == "")
{
updateVersion = ver.ToString();
updateURL = updatedirectory + url;
}
if (url.Contains("_full"))
{
updateVersion = ver.ToString();
updateURL = updatedirectory + url;
break;
}
}
}
}
}
Button btn = null;
Button btn2 = null;
StackPanel myPanel = new StackPanel();
TextBlock myBlock = addTextBlock("", HorizontalAlignment.Center, VerticalAlignment.Top, Colors.DarkGreen, new Thickness(0));
if (updateVersion != "")
{
btn = new Button();
btn2 = new Button();
btn = SetButtonAtts(btn);
btn.Content = CsvHelper.trans("update_auto");
btn.Click += UpdateAutomaticallyClick;
btn2 = SetButtonAtts(btn2);
btn2.Content = CsvHelper.trans("update_manually");
btn2.Click += UpdateManuallyClick;
myBlock.Text = string.Format(CsvHelper.trans("update_available"), updateVersion);
myBlock.Foreground = new SolidColorBrush(Colors.DarkRed);
tabAbout.Background = new SolidColorBrush(Color.FromArgb(10, 255, 0, 0));
}
else
{
myBlock.Text = string.Format(CsvHelper.trans("update_current_version"), pubVer);
myBlock.Foreground = new SolidColorBrush(Colors.Black);
}
myPanel.Children.Add(myBlock);
if (btn != null)
myPanel.Children.Add(btn);
if (btn2 != null)
myPanel.Children.Add(btn2);
AboutContent.Children.Add(myPanel);
}
}
public void UpdateAutomaticallyClick(object sender, RoutedEventArgs e)
{
if (updateURL != "")
{
Dispatcher.Invoke(() => fsTabControl.IsEnabled = false);
WebClient _webClient = new WebClient();
_webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadCompleted);
StackPanel myPanel = new StackPanel();
TextBlock myBlock = addTextBlock(string.Format(CsvHelper.trans("update_applying_version"), updateVersion), HorizontalAlignment.Center, VerticalAlignment.Top, Colors.Black, new Thickness(0));
myPanel.Children.Add(myBlock);
AboutContent.Children.Add(myPanel);
_webClient.DownloadFileAsync(new Uri(updateURL), AppDomain.CurrentDomain.BaseDirectory + "\\" + TEMP_FILE);
}
}
public void UpdateManuallyClick(object sender, RoutedEventArgs e)
{
if (updateURL != "")
{
Process.Start(updateURL);
}
}
private void OnDownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if ((e == null || !e.Cancelled && e.Error == null) && File.Exists(TEMP_FILE) && new FileInfo(TEMP_FILE).Length > 10)
{
// CHECK EXE BACKUP
if (File.Exists(EXE_PATH + ".BAK"))
{
try {
File.Delete(EXE_PATH + ".BAK");
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show(CsvHelper.trans("update_cant_delete_backup"));
}
}
if (!File.Exists(EXE_PATH + ".BAK"))
{
File.Move(EXE_PATH, EXE_PATH + ".BAK");
Stopwatch sw = new Stopwatch();
sw.Start();
while (true) { if (sw.ElapsedMilliseconds > 1000 || !File.Exists(EXE_PATH)) break; }
if (File.Exists(EXE_PATH))
MessageBox.Show(CsvHelper.trans("update_cant_delete_exe"));
Extract extract = new Extract();
extract.Run(TEMP_FILE, EXE_PATH, AppDomain.CurrentDomain.BaseDirectory + "\\");
}
}
Dispatcher.Invoke(() => fsTabControl.IsEnabled = true);
}
public void SetUpdateReady()
{
if (File.Exists(EXE_PATH))
{
Process.Start(EXE_PATH);
Environment.Exit(0);
StackPanel myPanel = new StackPanel();
TextBlock myBlock = addTextBlock(CsvHelper.trans("update_failed"), HorizontalAlignment.Center, VerticalAlignment.Top, Colors.Black, new Thickness(0));
myPanel.Children.Add(myBlock);
AboutContent.Children.Add(myPanel);
}
}
// UPDATES END
public class HKLMRegistryHelper
{
public static RegistryKey GetRegistryKey(string keyPath, RegistryView view)
{
RegistryKey localMachineRegistry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
return string.IsNullOrEmpty(keyPath) ? localMachineRegistry : localMachineRegistry.OpenSubKey(keyPath);
}
public static string GetRegistryValue(string keyPath, string keyName, RegistryView view = RegistryView.Registry64)
{
try
{
RegistryKey registry = GetRegistryKey(keyPath, view);
if (registry != null)
{
object defaultPathObj = registry.GetValue(keyName);
if (defaultPathObj != null)
{
string defaultPath = defaultPathObj.ToString();
if (!String.IsNullOrEmpty(defaultPath) && Directory.Exists(defaultPath))
return defaultPath;
}
}
}
catch {
Console.WriteLine("failed to get registry value");
}
return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
}
private Separator sectiondivider()
{
Separator sectn = new Separator();
sectn.Margin = new Thickness(0, 0, 0, 10);
return sectn;
}
private List<string> getCheckedOptions(StackPanel panel, string additionalCondition = "", bool tagValue = false)
{
List<string> values = new List<string>();
foreach (var pnl in panel.Children)
{
if (pnl.GetType() != typeof(StackPanel))
continue;
if (((StackPanel)pnl).Children.Count > 0 && ((StackPanel)pnl).Children[0].GetType() == typeof(CheckBox))
{
CheckBox a = (CheckBox)((StackPanel)pnl).Children[0];
string content = tagValue ? a.Tag.ToString() : a.Content.ToString();
if (((CheckBox)((StackPanel)pnl).Children[0]).IsChecked == true && content != CsvHelper.trans("toggle_all") &&
( additionalCondition == "" || content.Contains(additionalCondition) ) )
{
values.Add(content);
}
}
}
return values;
}
}
}
| ffe1ef181a6abb5c7da6f24dd3ffa9044279abd0 | [
"Markdown",
"C#",
"Text",
"JavaScript"
] | 13 | Markdown | AlexMcArdle/msfsLegacyImporter | bf4fe3f28c2138d37ff5c4d0d890fc30e7335cd7 | de25bb269914f54c722661d4fae037ec53107731 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Student(scrapy.Item):
username = scrapy.Field()
name = scrapy.Field()
class ExamItem(scrapy.Item):
class_no = scrapy.Field()
class_name = scrapy.Field()
class_score = scrapy.Field()
class_update_time = scrapy.Field()
<file_sep># -*- coding: utf-8 -*-
import scrapy
from exam.items import ExamItem, Student
class ExamSpider(scrapy.Spider):
name = "exam"
username = "1453xxx"
password = "<PASSWORD>"
allowed_domains = ["tongji.edu.cn"]
start_urls = ['http://xuanke.tongji.edu.cn']
def parse(self, response):
self.logger.info("Visited %s", response.url)
return scrapy.http.FormRequest.from_response(
response,
formdata={'goto': 'http://xuanke.tongji.edu.cn/pass.jsp',
'gotoOnFail': 'http://xuanke.tongji.edu.cn/deny.jsp',
'Login.Token1': self.username,
'Login.Token2': self.password,
'T3': ''
},
callback=self.after_login
)
def after_login(self, response):
return scrapy.Request("http://xuanke.tongji.edu.cn/tj_login/info.jsp", callback=self.get_info)
def get_info(self, response):
student = Student()
student['username'] = response.xpath('//tr/td[2]/text()').extract()[0][1:]
student['name'] = response.xpath('//tr/td[2]/text()').extract()[1][1:]
# yield student
return scrapy.Request(
"http://xuanke.tongji.edu.cn/tj_login/redirect.jsp?" +
"link=/tj_xuankexjgl/score/query/student/cjcx.jsp?" +
"qxid=20051013779916&mkid=20051013779901&qxid=20051013779916",
callback=self.parse_cj)
def parse_cj(self, response):
classes = response.xpath("//form/table[@id='T1']/tr")
for item in classes:
no = item.xpath('td[1]/div/font/text()').extract()
name = item.xpath('td[2]/div/font/text()').extract()
score = item.xpath('td[3]/div/font/text()').extract()
update_time = item.xpath('td[9]/div/font/text()').extract()
if len(score) is not 0:
exam = ExamItem()
exam['class_no']= no[0]
exam['class_name'] = name[0]
exam['class_score']= score[0]
exam['class_update_time'] = update_time[0]
print(no[0], name[0], score[0], update_time[0])
yield exam
| c044b288c04b990833f8163c89cfdfb49ff5915b | [
"Python"
] | 2 | Python | dcalsky/getExamScore | f679eb460ea5fbe5bd928531d492ac9928152a56 | 36732f40b64bfae8b361d6e4426d41ed2dd4568b |
refs/heads/master | <file_sep># album
a simple web album use by express<file_sep>let utils = require('../utils/utils.js')
/**
* 相册分类页面
* @param {*} req
* @param {*} res
*/
exports.showIndex = function(req, res) {
let albums = utils.getDirectoryeNames('../album')
res.render('index', {
albums
})
}
/**
* 相册详情页面
* @param {*} req
* @param {*} res
* @param {*} next
*/
exports.showAlbum = function (req, res, next) {
let albums = utils.getDirectoryeNames('../album')
let picArray = utils.getFilesNames(`../album/${req.params.albumName}`)
if (!utils.isInArray(req.params.albumName, albums)) {
console.log(1)
next()
return
}
res.render('album', {
albumName: req.params.albumName,
albums: picArray
})
}
/**
* 404页面
* @param {*} req
* @param {*} res
*/
exports.error = function(req, res) {
res.render('404')
}<file_sep>
let fs = require('fs')
let path = require('path')
/**
* 获取所给目录下所有的文件夹
* @param {string} folder
*/
exports.getDirectoryeNames = function (folder) {
let dir = path.resolve(__dirname, folder)
let arr = fs.readdirSync(dir)
let arr1 = arr.filter((item) => {
let isDirectory = fs.statSync(`${dir}/${item}`).isDirectory()
return isDirectory
})
return arr1
}
exports.getFilesNames = function (folder) {
let dir = path.resolve(__dirname, folder)
let arr = fs.readdirSync(dir)
let arr1 = arr.filter((item) => {
let isDirectory = fs.statSync(`${dir}/${item}`).isDirectory()
return !isDirectory
})
return arr1
}
exports.isInArray = function(item, arr) {
let i = arr.filter(single => {
return single === item
})
return !!i.length
}
<file_sep>let express = require('express')
let router = require('./router')
let app = express()
app.use(express.static('./album'))
app.use(express.static('./public'))
app.set('view engine', 'ejs')
app.get('/', router.showIndex)
app.get('/:albumName', router.showAlbum)
app.use(router.error)
app.listen(8080, () => {
console.log('服务器已启动端口: 8080')
}) | 2dc07655af22cfe7c178f3d061c814f31d60467b | [
"Markdown",
"JavaScript"
] | 4 | Markdown | yusifeng/album | a1c57bc7cfa1e01eb55e9b068ce44273a9bc4e1d | 1217dff51e7c9c4a42c9246b5ba2ab3a0c2ebdae |
refs/heads/master | <file_sep>var sourceFolder = 'E:\\temp\\post_04_extracts\\';
var targetFolder = 'E:\\temp\\post_04_output\\';
var logPath = 'E:\\temp\\post_04_output\\logpath.log';
var fs = require('fs');
var newLine = '\r\n';
var tab = '\t';
var filesInDirectory = fs.readdirSync(sourceFolder);
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/joinc';
var validFileTypes = [{
regx : /^HR\d\d/,
validTabs: 38
},{
regx : /^HRFS/,
validTabs: 39
}];
var checkValidFileType = function(filename){
var returnType = undefined,
breakException;
try {
validFileTypes.forEach(function(validFileType){
if(validFileType.regx.test(filename)){
returnType = validFileType;
throw breakException;
}
});
} catch (e) {
if (e!== breakException) {
throw e;
}
}
return returnType;
};
var findRecords = function(collection, query, callback){
collection.find(query).toArray(function(err, found){
callback(err, found);
})
};
run(function* generatorF(resume){
var db = yield MongoClient.connect(url, resume);
var lookupData = db.collection('hartlinkmembers');
for(var iny = 0; iny < filesInDirectory.length; iny = iny + 1){
var filename = filesInDirectory[iny];
var fileType = checkValidFileType(filename);
if(!fileType){
continue;
}
var fileText = fs.readFileSync(sourceFolder+filename,'utf8');
var fileLines = fileText.split(newLine);
var headerLine = fileLines.shift(); // remove the headerline
fs.appendFileSync(targetFolder+filename,headerLine+newLine);
for(var inx = 0;inx < fileLines.length;inx=inx+1){
var fileRow = fileLines[inx];
var rowData = fileRow.split(tab);
if(rowData.length!==fileType.validTabs){
if(rowData.length>1){
console.log('incorrect number of tabs');
console.log(fileRow);
}
continue;
}
/*
this is the bit where we need to connect to the
mongo database and reference the data.
*/
var data = yield findRecords(lookupData,{
"Nino" : rowData[6].substr(0,8) // first 8 characters
}, resume);
var prevData = {
Surname : rowData[4],
DOB: rowData[7],
"First name": rowData[5]
};
var status;
if(data&&data.length>0){
status = 'matched on nino';
rowData[4] = data[0].Surname;
rowData[7] = data[0].DOB;
rowData[5] = data[0]["First name"];
} else {
//data = yield lookupData.findOne({
// "Surname": rowData[4],
// "DOB" : rowData[7]
//}, resume);
//if(data){
// status = 'matched on surname dob';
// rowData[6] = data.Nino;
// rowData[4] = data.Surname;
//} else {
status = 'not found';
data = [{
Surname : 'not found',
DOB: 'not found',
"First name": 'not found'
}];
//}
}
var output = rowData.join(tab);
fileLines[inx] = output;
fs.appendFileSync(logPath,
filename + tab +
(inx + 2) + tab +
status + tab +
rowData[6] + tab +
prevData["First name"] + tab +
data[0]["First name"] + tab +
(status !== 'not found' && (prevData["First name"]!==data[0]["First name"]) ? 'Changed' : '') + tab +
prevData.Surname + tab +
data[0].Surname + tab +
(status !== 'not found' && (prevData.Surname!==data[0].Surname) ? 'Changed' : '') + tab +
prevData.DOB + tab +
data[0].DOB + tab +
(status !== 'not found' && (prevData.DOB!==data[0].DOB) ? 'Changed' : '') + newLine
);
fs.appendFileSync(targetFolder+filename,output+newLine);
}
// fileLines
}
// filesInDirectory
db.close();
console.log('done');
});
// run generatorF
function run(generatorFunction){
var generatorItr = generatorFunction(resume);
function resume(err, callbackValue){
if(err){
console.log(err);
generatorItr.next(null);
} else {
generatorItr.next(callbackValue);
}
}
generatorItr.next();
}; | 70d58c66548caeb0ea11d66c8eff41fa4fc3e4dc | [
"JavaScript"
] | 1 | JavaScript | pyram1de/data-extract-inject | 568dc0da6e7bf596a22d3010ebbafd28307c4021 | 72c2bf3e9109db236930d930190ddb867a837b5b |
refs/heads/master | <file_sep>## Zadanie
## Napisac funkcje ktora zamienia slowo opisujace liczbe w systemi binarnym na liczbe w systemie
## dziesietnym
liczba = '1100' # to jest 12
na_dziesietny = function(liczba_binarna){
}
na_dziesietny(liczba)<file_sep>## Zadanie
## Napisz funkcje wyznaczajaca liczbe cyfr podanych w tekscie
ilosc_cyfr = function(zdanie){
}<file_sep>## Zadanie
## Przygotować funkcję która dla danej liczby znajduje największą liczbę całkowitę mniejszą
## od pierwiastka z danej
mniejsza_od_pierwiastka = function(liczba){
}<file_sep>## Zadanie
## Napisać funkcję znajduja miejsce zerowe pewnej funkcji stosujac algorytm bisekcji
bisekcja = function(f, lewa_krawedz_przedzialu, prawa_krawedz_przedzialu, dokladnosc){
}
bisekcja(sin, 3, 4)
sin(3)
sin(4)
<file_sep>## Zadanie
## Przygotowac funkcje, ktora sprawdza czy w danym slowie znajduje sie litera a potem zwraca
## wektor pozycji na ktorych zostaly odszukane te litery. Niech domyslnie ignoruje wielkosc liter
znajdz_litere = function(slowo, litera){
}
## przyklad
## znajdz_litere('Matematyka', 'a') -> c(2,6,10) <file_sep>## Zadanie
## Napisac funkcje, ktora dla podanego dnia, miesiaca i roku podaje jaki jest dzien nastepny
dzien_nastepny = function(data){
}
przykladowa_data = c(28,2,2019) #28 luty 2019
poprawna_odpowiedz = c(1,3,2019) #nastepny dzien to 1 marca 2019
<file_sep>## Zadanie
## Napisać funkcje, ktora znajduje najczesciej powtarzajaca litere się w tekscie
moda_z_tekstu = function(zdanie){
}<file_sep>## Zadanie
## Przygotowac funkcje ktora rysuje podroz pewnego 'X' tj przesuwa w prawo X w kolejnych linijkach
## pelny -
podrozujacy_x = function(dlugosc_linii){
}
## np
## podrozujacy_x(5)
## X----
## -X---
## --X--
## ---X-
## ----X<file_sep>## Zadanie
## Przygotowac funkcje, ktora podaje liczbe spółgłosek w zadanym słowie
ilosc_spolglosek = function(){
}<file_sep>## Zadanie
## Przygotować funkcję, ktora oblicza sume wszystkich dzielnikow pierwszych danej liczby
suma_dzielikow_pierwszych = function(liczba){
}<file_sep>## Zadanie
## Przygotowac funkcje, która w zależności od podanego parametru wypisuje litery
## alfabetu w pętli (po 'z' znowu 'a') i przerywa po wypisaniu n liter
alfabet = function(n){
aaa
}<file_sep>## Zadanie
## Napisz program generujacy macierz z tabliczka mnozenia o okreslonym rozmiarze
tabliczka_mnozenia = function(rozmiar){
}
## np. tabliczka_mnozenia(4)
## 1 2 3 4
## 2 4 6 8
## 3 6 9 12
## 4 8 12 16<file_sep>## Zadanie
## Napisać funkcje szyfrujaca i deszyfrujaca za pomoca szyfru Cezara o okreslonym kroku
## Szyfr Cezara polega na przesuniecia kazdego znaku w slowie o stala liczbe znakow
szyfrowanie = function(slowo, przesuniecie){
}
deszyfrowanie = function(zaszyfrowane, przesuniecie){
}
p = 5
zdanie = 'Ala ma kota'
kod = szyfrowanie(zdanie, przesuniecie = p)
print(kod)
odkodowane = deszyfrowanie(kod, przesuniecie = p)
print(odkodowane)
<file_sep>## Zadanie
## Przygotowac funkcje, ktora w zaleznosci od podanego rysuje na ekranie odpowiednia duza choinke
## np dla n=5 powinno narysować
## *
## * *
## * * *
## * * * *
##* * * * *
## *
choinka = function(n){
}asd | 6ab9d6f32d47d63652f944763ca0c78a879b32bf | [
"R"
] | 14 | R | szumickim/Cwiczenia | 12fbd4e22276419080fd1d92fdf868df0599146f | 81334c6c49b171403f9094ad7aa42e41c231a9da |
refs/heads/master | <file_sep>/**
* CS 345 Proj04_AVL
*
* Author: <NAME>
*
* Represents an AVL tree where difference in height between subtrees of a node cannot be more than 1.
* Has methods to get and set nodes, remove nodes, get inorder, postorder, and a dot file for debugging.
*
*/
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class Proj04_AVL_student<K extends Comparable<K>, V> implements Proj04_Dictionary {
public int dotCount;
private Proj04_Node<K,V> root;
private String debugStr;
/*
* Constructor
*
* debugStr and dotCount used to name dot files. Root set to null.
*/
public Proj04_AVL_student(String str){
this.debugStr = str;
this.root = null;
this.dotCount = 0;
}
/*
* takes int a and int b and returns the max of the two.
*/
public int max (int a, int b) {
if (a<b) {
return b;
}
else {
return a;
}
}
/*
* Returns the height of a node. If null, return -1.
*/
public int height(Proj04_Node<K,V> node) {
if (node == null) {
return -1;
}
return node.height;
}
/*
* Get Balance factor of node N to check height requirement
*/
int getBalance(Proj04_Node<K,V> node) {
if (node == null)
return 0;
return height(node.left) - height(node.right);
}
/*
* get count of all nodes in that subtree
*/
public int count(Proj04_Node<K,V> node) {
if (node == null) {
return 0;
}
return node.count;
}
/*
* (non-Javadoc)
* @see Proj04_Dictionary#set(java.lang.Comparable, java.lang.Object)
*
* Inserts a new node into the tree, rebalancing when needed to maintain height requirements.
*/
@Override
public void set(Comparable key, Object value) {
root = set_helper(root, (K)key,(V)value);
}
//helper function for set recursively
private Proj04_Node<K,V> set_helper(Proj04_Node<K,V> oldRoot,
K key, V value)
{
if (oldRoot == null) {
//add new node
Proj04_Node<K,V> node = new Proj04_Node<K,V>(key,value);
node.height = 0;
node.aux ="h="+String.valueOf(node.height);
return node;
}
int ct = oldRoot.key.compareTo(key);
//new key is smaller
if (oldRoot.key.compareTo(key)>0) {
oldRoot.left = set_helper(oldRoot.left,key,value);
}
//new key is larger
else if(oldRoot.key.compareTo(key)<0) {
oldRoot.right = set_helper(oldRoot.right,key,value);
}
else { //key already in tree, update value
oldRoot.value = value;
return oldRoot;
}
//update height and aux
oldRoot.height = 1+max(height(oldRoot.left),height(oldRoot.right));
oldRoot.aux = "h="+String.valueOf(oldRoot.height);
//update count
oldRoot.count = 1+count(oldRoot.left)+count(oldRoot.right);
//get balance factor- four cases
int balance = getBalance(oldRoot);
// Left Left Case
if (balance > 1 && key.compareTo(oldRoot.left.key)<0) {
return rotateRight(oldRoot);
}
// Right Right Case
if (balance < -1 && key.compareTo(oldRoot.right.key)>0) {
return rotateLeft(oldRoot);
}
// Left Right Case
if (balance > 1 && key.compareTo(oldRoot.left.key)>0) {
oldRoot.left = rotateLeft(oldRoot.left);
return rotateRight(oldRoot);
}
// Right Left Case
if (balance < -1 && key.compareTo(oldRoot.right.key)<0) {
oldRoot.right = rotateRight(oldRoot.right);
return rotateLeft(oldRoot);
}
return oldRoot;
}
/**
* Returns the value of a key in the tree, null if not found
*/
@Override
public Object get(Comparable key) {
return get_helper(root,(K)key);
}
//helper function for get recursion
private V get_helper(Proj04_Node<K,V> currNode, K key) {
if (currNode == null) {
return null;
}
int compare = key.compareTo(currNode.key);
//go left
if (compare < 0) {
return get_helper(currNode.left,key);
}
//go right
else if (compare > 0) {
return get_helper(currNode.right,key);
}
//found the node
else {
return currNode.value;
}
}
/*
* gets predecessor of node for removal purposes.
*/
public Proj04_Node<K,V> getPred(Proj04_Node<K,V> node) {
Proj04_Node<K,V> curr = node.left;
while (curr.right !=null) {
curr = curr.right;
}
return curr;
/*
* removes the node with the given key from the tree, returns null if node doesn't exist.
* performs balance rotations if necessary after removal.
*/
}
@Override
public void remove(Comparable key) {
root = remove_helper(root,(K)key);
}
//helper function for remove recursively
private Proj04_Node<K,V> remove_helper (Proj04_Node<K,V> root, K key){
//base case, key doesn't exist
if (root == null) {
return root;
}
int compare = key.compareTo(root.key);
//go left
if (compare < 0) {
root.left = remove_helper(root.left,key);
}
//go right
else if (compare > 0) {
root.right = remove_helper(root.right,key);
}
//delete
else {
//1 or no children
if (root.left == null || root.right == null) {
Proj04_Node<K,V> temp = null;
if (temp == root.right) {
temp = root.left;
}
else {
temp = root.right;
}
//no children
if (temp == null) {
temp = root;
root = null;
}
//one child
else {
root = temp;
}
}
else {
//get predecessor
Proj04_Node<K,V> pred = getPred(root);
//swap root with predecessor
root.key = pred.key;
root.value = pred.value;
root.left = remove_helper(root.left,pred.key);
}
}
//if tree is now empty then return null
if (root == null) {
return root;
}
//update height
root.height = 1+max(height(root.left),height(root.right));
root.aux = "h="+String.valueOf(root.height);
//update count
root.count = 1+count(root.left)+count(root.right);
//get balance factor
int balance = getBalance(root);
// Left Left Case
if (balance > 1 && getBalance(root.left) >= 0) {
return rotateRight(root);
}
// Left Right Case
if (balance > 1 && getBalance(root.left) < 0) {
root.left = rotateLeft(root.left);
return rotateRight(root);
}
// Right Right Case
if (balance < -1 && getBalance(root.right) <= 0) {
return rotateLeft(root);
}
// Right Left Case
if (balance < -1 && getBalance(root.right) > 0) {
root.right = rotateRight(root.right);
return rotateLeft(root);
}
return root;
}
/* void rotateLeft(K)
*
* Finds a node with given K key and performs left rotation at
* that node. Updates the counts after.
*
*/
public Proj04_Node<K,V> rotateLeft(Proj04_Node<K,V> at) {
Proj04_Node<K,V> y = at.right;
Proj04_Node<K,V> t2 =at.right.left;
//do rotation
y.left = at;
at = y;
at.left.right = t2;
//update heights
at.left.height = 1+max(height(at.left.left),height(at.left.right));
at.left.aux = "h="+String.valueOf(at.left.height);
at.height = 1+max(height(at.left),height(at.right));
at.aux = "h="+String.valueOf(at.height);
//update counts
at.left.count = 1+count(at.left.left)+count(at.left.right);
at.count = 1+count(at.left)+count(at.right);
return at;
}
/* void rotateRight(K)
*
* Finds a node with given K key and performs right rotation at
* that node. Updates the counts after.
*
*/
public Proj04_Node<K,V> rotateRight(Proj04_Node<K,V> at) {
Proj04_Node<K,V> y = at.left;
Proj04_Node<K,V> t2 =at.left.right;
//do rotation
y.right = at;
at = y;
at.right.left = t2;
//update heights
at.right.height = 1+max(height(at.right.left),height(at.right.right));
at.right.aux = "h="+ String.valueOf(at.right.height);
at.height = 1+max(height(at.left),height(at.right));
at.aux = "h="+String.valueOf(at.height);
//update counts
at.right.count = 1+count(at.right.left)+count(at.right.right);
at.count = 1+count(at.left)+count(at.right);
return at;
}
/*
* (non-Javadoc)
* @see Proj04_Dictionary#getSize()
*
* Returns the size of the tree.
*/
@Override
public int getSize()
{
return getCount(root);
}
/*
* returns the count of a node.
*/
private int getCount(Proj04_Node<K,V> node)
{
if (node == null)
return 0;
return node.count;
}
/*
* returns the parent node of a given node, and null if it has no parent.
*/
public Proj04_Node<K,V> getParent(Proj04_Node<K,V> node){
Proj04_Node<K,V> curr = root;
//the node is the root
if (curr == node) {
return null;
}
while(curr!=null) {
//found parent
if (curr.left == node) {
return curr;
}
if (curr.right == node) {
return curr;
}
System.out.println(curr);
System.out.println(node);
int compare = node.key.compareTo(curr.key);
if (compare<0) {
curr = curr.left;
}
else if (compare>0) {
curr = curr.right;
}
}
return null;
}
/*
* (non-Javadoc)
* @see Proj04_Dictionary#inOrder(java.lang.Comparable[], java.lang.Object[], java.lang.String[])
*
* gets the inorder traversal of keys, values, and aux values of all nodes.
*/
@Override
public void inOrder(Comparable[] keysOut, Object[] valuesOut, String[] auxOut) {
//stores nodes in inorder in an ArrayList
ArrayList<Proj04_Node<K,V>> inorder = new ArrayList<Proj04_Node<K,V>>();
inOrder_helper(root, inorder);
//transfer correct values to the three arrays
for (int i = 0; i<inorder.size();i++) {
keysOut[i] = inorder.get(i).key;
valuesOut[i] = inorder.get(i).value;
auxOut[i] = inorder.get(i).aux;
}
}
//helper function to get inorder recursively
private void inOrder_helper (Proj04_Node<K,V> root, ArrayList<Proj04_Node<K,V>> inorder) {
if (root == null) {
return;
}
//go left
inOrder_helper(root.left, inorder);
//add node
inorder.add(root);
//go right
inOrder_helper(root.right,inorder);
}
/*
* (non-Javadoc)
* @see Proj04_Dictionary#postOrder(java.lang.Comparable[], java.lang.Object[], java.lang.String[])
*
* Gets the postorder traversal of keys, values, and aux values of all nodes.
*/
@Override
public void postOrder(Comparable[] keysOut, Object[] valuesOut, String[] auxOut) {
//stores postorder of the nodes in an ArrayList
ArrayList<Proj04_Node<K,V>> postorder = new ArrayList<Proj04_Node<K,V>>();
postOrder_helper(root, postorder);
//transfer values from arrayList to the three arrays
for (int i = 0; i<postorder.size();i++) {
keysOut[i] = postorder.get(i).key;
valuesOut[i] = postorder.get(i).value;
auxOut[i] = postorder.get(i).aux;
}
}
//helper function to get postorder recursively
private void postOrder_helper (Proj04_Node<K,V> root, ArrayList<Proj04_Node<K,V>> postorder) {
if (root == null) {
return;
}
//go left
postOrder_helper(root.left, postorder);
//go right
postOrder_helper(root.right,postorder);
//add node
postorder.add(root);
}
/*
* (non-Javadoc)
* @see Proj04_Dictionary#genDebugDot()
*
* Generates a dot file for debugging of the current tree.
*/
@Override
public void genDebugDot() {
String dot="";
try {
File file = new File(dotCount+debugStr+".dot");
dotCount++;
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("digraph\n{\n");
dot_helper(writer,root);
writer.write("}");
writer.close();
} catch (IOException e) {
System.out.println("Could not create dot file");
}
}
//helper function for writing dot file recursively
private void dot_helper (FileWriter writer, Proj04_Node<K,V> node) throws IOException {
if (node == null) {
return;
}
if (node.left!= null) {
writer.write(node.key+"->"+node.left.key+"\n");
}
if (node.right!=null) {
writer.write(node.key+"->"+node.right.key+"\n");
}
dot_helper(writer,node.left);
dot_helper(writer,node.right);
writer.write(node.key+"\n");
}
}
| 7231d70038e8a4c2d51bd4be9d4035114294da48 | [
"Java"
] | 1 | Java | jcwangg/Trees | f9f368ab01f43a7582ad2fc69ef0a5e45e566723 | ab8991bbba22bdf66a3a336f5b1e666b59876403 |
refs/heads/master | <file_sep>package msgcopy.com.rxjavademo;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by liang on 2017/4/6.
*/
public class HttpUser {
private static final String TAG = "HttpMethods";
public static final int HTTP_CACHE_SIZE = 20 * 1024 * 1024;
public static final int HTTP_CONNECT_TIMEOUT = 15 * 1000;
public static final int HTTP_READ_TIMEOUT = 20 * 1000;
private static final String HTTP_CACHE_DIR = "http";
public static final String BASE_URL = "http://cloud1.kaoke.me/iapi/";
private static final int DEFAULT_TIMEOUT = 5;
private Retrofit retrofit;
private UserService userService;
//私有化构造方法
private HttpUser() {
//手动创建一个okhttpClient并设置超时时间
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.readTimeout(HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS);
builder.cache(new Cache(getHttpCacheDir(ListenerApp.getContext()), HTTP_CACHE_SIZE));
retrofit = new Retrofit.Builder()
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
userService = retrofit.create(UserService.class);
}
//在访问httpmethods时候创建单例
private static class SingletonHolder {
private static final HttpUser INSTANCE = new HttpUser();
}
//获取单例
public static HttpUser getInstance() {
return SingletonHolder.INSTANCE;
}
public void getHttpData(Subscriber<UserEntity> subscriber, String type, String reg_ver,String device) {
userService.getUserDtat(type, reg_ver,device)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
//缓存
public static File getHttpCacheDir(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return new File(context.getExternalCacheDir(), HTTP_CACHE_DIR);
}
return new File(context.getCacheDir(), HTTP_CACHE_DIR);
}
}
| a76c631cc773c928c031479b60479102d70447d8 | [
"Java"
] | 1 | Java | androidlinpeng/RxjavaDemo | 48646105001043fd45e98998af32b9a1534b6fab | 3101fb06d9faad0b3de638106452553bd4e09f05 |
refs/heads/master | <repo_name>simsek97/filterPage<file_sep>/filterPage.php
<?php
//autoload
require_once "vendor/autoload.php";
class SmartClass_FilterPage {
private $actionButtons = array();
private $boxId = "simsBoxId";
private $boxType = "primary";
private $boxTitle = "SmartClass";
private $actionsColumn = 2;
private $filtersColumn = 10;
private $criteriaInputId = "simsDivBoxIdFilterCriteria";
/* function */
function setBoxId($id)
{
$this->boxId = $id;
}
/* function */
function setBoxType($type)
{
$this->boxType = $type;
}
/* function */
function setBoxTitle($title)
{
$this->boxTitle = $title;
}
/* function */
function setCriteriaInputId($id)
{
$this->criteriaInputId = $id;
}
/* function */
function setActionsColumn($column)
{
$this->actionsColumn = $column;
$this->filtersColumn = 12 - $column;
}
/* function */
function addActionButton($btn)
{
$this->actionButtons[] = $btn;
}
/* function */
function createBox()
{
global $theme;
if(empty($this->actionButtons)) $this->filtersColumn = 12;
$loader = new \Twig\Loader\FilesystemLoader('themes/' . $theme . '/templates');
$twig = new \Twig\Environment($loader, ['cache' => false]);
$portlet = $twig->render('filter_page.html', ['portlet_id' => $this->boxId, 'title' => $this->boxTitle, 'portlet_type' => $this->boxType, 'actions_column' => $this->actionsColumn, 'actions_title' => _ACTIONS, 'actions' => $this->actionButtons, 'filters_column' => $this->filtersColumn, 'filter_title' => _FILTERS . ' / ' . _LAYOUT, 'criteria_id' => $this->criteriaInputId]);
return $portlet;
}
}
?>
| 32098e4774419b435535a4a42874da696fc6a50f | [
"PHP"
] | 1 | PHP | simsek97/filterPage | e6b9491fa48f4ebd3d794b97621ee4260113087d | 69b794835298b998d5f00f21c66270a56eac2461 |
refs/heads/master | <file_sep>class CardsController < ApplicationController
before_action :block_new, only: :new
before_action :block_double, only: :new
def new
@card = Card.new
end
def create
Payjp.api_key = ENV['PAYJP_SECRET_KEY']
customer = Payjp::Customer.create(
description: 'test',
card: params[:card_token]
)
card = Card.new(
card_token: params[:card_token],
customer_token: customer.id,
user_id: current_user.id
)
if card.save
move_to_mypage
else
move_to_mypage
end
end
def destroy
card = Card.find(params[:user_id])
if card.destroy
move_to_mypage
else
move_to_mypage
end
end
private
def move_to_mypage
redirect_to user_path(current_user.id)
end
def block_new
user = User.find(params[:user_id])
redirect_to root_path if !current_user || current_user != user
end
def block_double
move_to_mypage if current_user.card
end
end
<file_sep>require 'rails_helper'
RSpec.describe Item, type: :model do
describe '作品新規登録' do
before do
@item = FactoryBot.build(:item)
end
context '新規登録がうまくいくとき' do
it 'image,name,info,priceが存在し、category_id,from_id,day_idが2以上であれば登録できる' do
expect(@item).to be_valid
end
it 'priceが¥100~¥9,999,999の間の場合は登録できる' do
@item.price = 100
expect(@item).to be_valid
end
end
context '新規登録がうまくいかないとき' do
it 'imageが空では登録できない' do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include('画像を入力してください')
end
it 'nameが空では登録できない' do
@item.name = nil
@item.valid?
expect(@item.errors.full_messages).to include('商品名を入力してください')
end
it 'infoが空では登録できない' do
@item.info = nil
@item.valid?
expect(@item.errors.full_messages).to include('説明文を入力してください')
end
it 'category_idが「1」の場合は登録できない' do
@item.category_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('カテゴリーを選んでください')
end
it 'from_idが「1」の場合は登録できない' do
@item.from_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('発送元の地域を選んでください')
end
it 'day_idが「1」の場合は登録できない' do
@item.day_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('発送までの日数を選んでください')
end
it 'priceが空では登録できない' do
@item.price = nil
@item.valid?
expect(@item.errors.full_messages).to include('販売価格を入力してください')
end
it 'priceが¥100未満では登録できない' do
@item.price = 99
@item.valid?
expect(@item.errors.full_messages).to include('販売価格が範囲外です')
end
it 'priceが¥10,000,000以上では登録できない' do
@item.price = 10_000_000
@item.valid?
expect(@item.errors.full_messages).to include('販売価格が範囲外です')
end
it 'priceに半角数字以外が含まれている場合は登録できない' do
@item.price = 1, 0o00
@item.valid?
expect(@item.errors.full_messages).to include('販売価格は半角数字で入力してください')
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Comment, type: :model do
describe 'コメント投稿機能' do
before do
@comment = FactoryBot.build(:comment)
end
context 'コメント投稿がうまくいくとき' do
it 'messageが存在すれば投稿できる' do
expect(@comment).to be_valid
end
end
context 'コメント投稿がうまくいかないとき' do
it 'messageが空では投稿できない' do
@comment.message = nil
@comment.valid?
expect(@comment.errors.full_messages).to include("Message can't be blank")
end
it 'messageが140文字以内でなければ投稿できない' do
@comment.message = Faker::Lorem.characters(141)
@comment.valid?
expect(@comment.errors.full_messages).to include('Message is too long (maximum is 140 characters)')
end
end
end
end
<file_sep>class ItemsController < ApplicationController
before_action :set_item, only: [:edit, :update, :show]
before_action :block_new, only: :new
before_action :block_edit, only: :edit
def index
@items = Item.includes(:order).order('created_at DESC')
end
def new
@item = Item.new
end
def create
@item = Item.new(item_params)
if @item.save
redirect_to root_path
else
render :new
end
end
def edit
end
def update
if @item.update(item_params)
redirect_to root_path
else
render :edit
end
end
def destroy
item = Item.find(params[:id])
if item.destroy
redirect_to root_path
else
render :show
end
end
def show
@comment = Comment.new
@comments = @item.comments.includes(:user).order('created_at DESC')
@likes_count = Like.where(item_id: @item.id).count
end
def search
@items = Item.search(params[:keyword])
end
private
def item_params
params.require(:item).permit(:image, :name, :info, :price, :category_id, :from_id, :day_id).merge(user_id: current_user.id)
end
def set_item
@item = Item.find(params[:id])
end
def block_new
redirect_to new_user_registration_path unless current_user
end
def block_edit
redirect_to item_path(@item.id) if current_user != @item.user || @item.order
end
end
<file_sep># # < User登録 >
# 5.times do |i|
# User.create(id: "#{i+1}", name: "tester#{i+1}", nickname: "tester#{i+1}", email: "tester@#{i+1}", password: "<PASSWORD>}")
# end
# # < /User登録 >
# # < Item登録 >
# 10.times do |i|
# # Furniture Category (id:2)
# funiture = Item.new(category_id: '2',name: "Furniture test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# funiture.image.attach(io: File.open('./app/assets/test_images/furniture.jpg'), filename: 'furniture.jpg')
# funiture.save
# # Accessory Category (id:3)
# accessory = Item.new(category_id: '3',name: "Accessory test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# accessory.image.attach(io: File.open('./app/assets/test_images/accessory.jpg'), filename: 'accessory.jpg')
# accessory.save
# # Fashion Category (id:4)
# fashion = Item.new(category_id: '4',name: "Fashion test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# fashion.image.attach(io: File.open('./app/assets/test_images/fashion.jpg'), filename: 'fashion.jpg')
# fashion.save
# # Designed_Mask Category (id:5)
# designed_mask = Item.new(category_id: '5',name: "Designed_mask test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# designed_mask.image.attach(io: File.open('./app/assets/test_images/designed_mask.jpg'), filename: 'designed_mask.jpg')
# designed_mask.save
# # Bag & Pouch Category (id:6)
# bag = Item.new(category_id: '6',name: "Bag test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# bag.image.attach(io: File.open('./app/assets/test_images/bag.jpg'), filename: 'bag.jpg')
# bag.save
# # Knitting Category (id:7)
# knitting = Item.new(category_id: '7',name: "Knitting test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# knitting.image.attach(io: File.open('./app/assets/test_images/knitting.jpg'), filename: 'knitting.jpg')
# knitting.save
# # Toy Category (id:8)
# toy = Item.new(category_id: '8',name: "Toy test#{i+1}",info: 'Information is displayed here ', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# toy.image.attach(io: File.open('./app/assets/test_images/toy.jpg'), filename: 'toy.jpg')
# toy.save
# # Art Category (id:9)
# art = Item.new(category_id: '9',name: "Art test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# art.image.attach(io: File.open('./app/assets/test_images/art.jpg'), filename: 'art.jpg')
# art.save
# # Other Category (id:10)
# other = Item.new(category_id: '10',name: "Other test#{i+1}",info: 'Information is displayed here', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# other.image.attach(io: File.open('./app/assets/test_images/other.jpg'), filename: 'other.jpg')
# other.save
# # 日本語データ登録 (全角チェック)
# japanese = Item.new(category_id: '10',name: "日本らしい写真 テスト#{i+1}",info: 'ここに説明文が入ります', price: '9999', from_id: '2', day_id: '2', user_id: '1')
# japanese.image.attach(io: File.open('./app/assets/test_images/japanese.jpg'), filename: 'jananese.jpg')
# japanese.save
# end
# # < /Item登録 >
# # < Comment登録 >
# 10.times do |i|
# Comment.create(message: "出品しました!", user_id: '1', item_id: "#{901+(10*i)}")
# Comment.create(message: "素敵な商品ですね", user_id: '2', item_id: "#{901+(10*i)}")
# Comment.create(message: "Looks good to me !", user_id: '3', item_id: "#{901+(10*i)}")
# end
# # < /Comment登録 >
# # < Like登録 >
# 10.times do |i|
# Like.create(user_id: '1', item_id: "#{901+(10*i)}")
# Like.create(user_id: '2', item_id: "#{901+(10*i)}")
# Like.create(user_id: '3', item_id: "#{901+(10*i)}")
# Like.create(user_id: '4', item_id: "#{901+(10*i)}")
# Like.create(user_id: '5', item_id: "#{901+(10*i)}")
# end
# # < /Like登録 >
# # < Order & Address登録 >
# Order.create(user_id: '2', item_id: "981")
# Address.create(postal_code: '000-0000', city: 'Sapporo', house_num: '1-1-1', phone: '09012345678', order_id: '1')
# Order.create(user_id: '2', item_id: "961")
# Address.create(postal_code: '012-3456', city: 'Kushiro', house_num: 'onbetsucho', phone: '09099999999', order_id: '2')
# # < /Order & Address登録 ><file_sep>class LikesController < ApplicationController
before_action :find_item
def create
@like = Like.create(user_id: current_user.id, item_id: params[:item_id])
redirect_to item_path(@item.id)
end
def destroy
@like = Like.find_by(user_id: current_user.id, item_id: params[:item_id])
@like.destroy
redirect_to item_path(@item.id)
end
def find_item
@item = Item.find(params[:item_id])
end
end
<file_sep>class Item < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
has_one :order
has_many :comments, dependent: :destroy
has_many :commented_users, through: :comments, source: :user
has_many :likes, dependent: :destroy
has_many :liked_users, through: :likes, source: :user
belongs_to :user
has_one_attached :image
belongs_to_active_hash :category
belongs_to_active_hash :from
belongs_to_active_hash :day
with_options presence: true do
validates :name, length: { maximum: 40 }
validates :info, length: { maximum: 1000 }
validates :image
validates :price
end
validates :price, format: { with: /\A[0-9]+\z/, message: 'は半角数字で入力してください' }
validates :price, numericality: { greater_than_or_equal_to: 100, less_than_or_equal_to: 9_999_999, message: 'が範囲外です' }
validates :category_id, :from_id, :day_id, numericality: { other_than: 1, message: 'を選んでください' }
def self.search(search)
if search != ''
Item.where('name LIKE(?)', "%#{search}%").order('created_at DESC')
else
Item.includes(:order).order('created_at DESC')
end
end
def previous
user.items.order('created_at desc, id desc').where('created_at <= ? and id < ?', created_at, id).first
end
def next
user.items.order('created_at desc, id desc').where('created_at >= ? and id > ?', created_at, id).reverse.first
end
end
<file_sep>class UsersController < ApplicationController
before_action :set_user, only: [:edit, :update, :show]
before_action :block_mypage, only: :show
before_action :block_edit, only: :edit
def edit
end
def update
if @user.update(user_params)
redirect_to root_path
else
render :edit
end
end
def destroy
user = User.find(params[:id])
if user.destroy
redirect_to root_path
else
render :show
end
end
def show
Payjp.api_key = ENV['PAYJP_SECRET_KEY']
card = Card.find_by(user_id: current_user.id)
if @user.card
customer = Payjp::Customer.retrieve(card.customer_token)
@card = customer.cards.first
end
@items = Item.where(user_id: current_user.id).order('created_at DESC')
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :nickname, :email)
end
def block_mypage
user = User.find(params[:id])
return redirect_to new_user_registration_path unless current_user
redirect_to root_path if current_user != user
end
def block_edit
user = User.find(params[:id])
redirect_to root_path if !current_user || current_user != user
end
end<file_sep>require 'rails_helper'
RSpec.describe Card, type: :model do
describe 'カード登録' do
before do
@card = FactoryBot.build(:card)
end
context 'カード登録がうまくいくとき' do
it 'card_token,customer_tokenが存在すれば登録できる' do
expect(@card).to be_valid
end
end
context '新規登録がうまくいかないとき' do
it 'card_tokenが空では登録できない' do
@card.card_token = nil
@card.valid?
expect(@card.errors.full_messages).to include('Card tokenを入力してください')
end
it 'customer_tokenが空では登録できない' do
@card.customer_token = nil
@card.valid?
expect(@card.errors.full_messages).to include('Customer tokenを入力してください')
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe User, type: :model do
describe 'ユーザー新規登録' do
before do
@user = FactoryBot.build(:user)
end
context '新規登録がうまくいくとき' do
it 'name,nickname,email,password,password_confirmationが存在すれば登録できる' do
expect(@user).to be_valid
end
it 'passwordが6文字以上の半角英数字であれば登録できる' do
@user.password = '<PASSWORD>'
@user.password_confirmation = '<PASSWORD>'
expect(@user).to be_valid
end
end
context '新規登録がうまくいかないとき' do
it 'nameが空では登録できない' do
@user.name = nil
@user.valid?
expect(@user.errors.full_messages).to include('氏名を入力してください')
end
it 'nicknameが空では登録できない' do
@user.nickname = nil
@user.valid?
expect(@user.errors.full_messages).to include('ユーザー名を入力してください')
end
it '重複したnicknameが存在する場合は登録できない' do
@user.save
another_user = FactoryBot.build(:user, nickname: @user.nickname)
another_user.valid?
expect(another_user.errors.full_messages).to include('ユーザー名はすでに存在します')
end
it 'emailが空では登録できない' do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include('Eメールを入力してください')
end
it '重複したemailが存在する場合は登録できない' do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include('Eメールはすでに存在します')
end
it 'emailに@が含まれていなければ登録できない' do
@user.email = 'test'
@user.valid?
expect(@user.errors.full_messages).to include('Eメールは不正な値です')
end
it 'passwordが空では登録できない' do
@user.password = nil
@user.valid?
expect(@user.errors.full_messages).to include('パスワードを入力してください')
end
it 'passwordが5文字以下であれば登録できない' do
@user.password = '<PASSWORD>'
@user.password_confirmation = '<PASSWORD>'
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは6文字以上で入力してください')
end
it 'passwordが存在してもpassword_confirmationが空では登録できない' do
@user.password_confirmation = ''
@user.valid?
expect(@user.errors.full_messages).to include('パスワード(確認用)とパスワードの入力が一致しません')
end
end
end
end
<file_sep>class CommentsController < ApplicationController
def create
@comment = Comment.new(comment_params)
if @comment.save
redirect_to item_path(@comment.item_id)
else
redirect_to item_path(@comment.item_id)
end
end
def destroy
comment = Comment.find(params[:id])
if comment.destroy
redirect_to item_path(comment.item_id)
else
redirect_to item_path(comment.item.id)
end
end
def comment_params
params.require(:comment).permit(:message).merge(user_id: current_user.id, item_id: params[:item_id])
end
end
<file_sep>FactoryBot.define do
factory :item do
name { Faker::Food.fruits }
info { Faker::Food.description }
price { Faker::Number.between(from: 100, to: 9_999_999) }
category_id { 2 }
from_id { 2 }
day_id { 2 }
association :user
after(:build) do |i|
i.image.attach(io: File.open('public/images/test_image.png'), filename: 'test_image.png')
end
end
end
<file_sep>class From < ActiveHash::Base
self.data = [
{ id: 1, name: '--' },
{ id: 2, name: '札幌' },
{ id: 3, name: '旭川' },
{ id: 4, name: '函館' },
{ id: 5, name: '帯広' },
{ id: 6, name: '釧路' },
{ id: 7, name: '北見' },
{ id: 8, name: '稚内' },
{ id: 9, name: '苫小牧' },
{ id: 10, name: '室蘭' },
{ id: 11, name: '小樽' },
{ id: 12, name: '江別' },
{ id: 13, name: '恵庭' },
{ id: 14, name: '北広島' },
{ id: 15, name: 'その他' }
]
end
<file_sep>class Category < ActiveHash::Base
self.data = [
{ id: 1, name: '--' },
{ id: 2, name: '家具・雑貨' },
{ id: 3, name: 'アクセサリー' },
{ id: 4, name: '服・ファッション' },
{ id: 5, name: 'デザインマスク' },
{ id: 6, name: 'バッグ・財布・ポシェット' },
{ id: 7, name: 'ニット・編み物' },
{ id: 8, name: 'ぬいぐるみ・おもちゃ' },
{ id: 9, name: 'アート' },
{ id: 10, name: 'その他' }
]
end
<file_sep>class OrderAddress
include ActiveModel::Model
attr_accessor :postal_code, :city, :house_num, :building, :phone, :user_id, :item_id, :token
with_options presence: true do
validates :postal_code, format: { with: /\A[0-9]{3}-[0-9]{4}\z/, message: 'を正しく入力してください' }
validates :city
validates :house_num
validates :phone, format: { with: /\A\d{10}$|^\d{11}\z/, message: 'を正しく入力してください' }
end
def save
order = Order.create(user_id: user_id, item_id: item_id)
Address.create(postal_code: postal_code, city: city, house_num: house_num, building: building, phone: phone, order_id: order.id)
end
end
<file_sep>class CategoriesController < ApplicationController
def id2
@items = Item.where(category_id: 2).order('created_at DESC')
end
def id3
@items = Item.where(category_id: 3).order('created_at DESC')
end
def id4
@items = Item.where(category_id: 4).order('created_at DESC')
end
def id5
@items = Item.where(category_id: 5).order('created_at DESC')
end
def id6
@items = Item.where(category_id: 6).order('created_at DESC')
end
def id7
@items = Item.where(category_id: 7).order('created_at DESC')
end
def id8
@items = Item.where(category_id: 8).order('created_at DESC')
end
def id9
@items = Item.where(category_id: 9).order('created_at DESC')
end
def id10
@items = Item.where(category_id: 10).order('created_at DESC')
end
end
<file_sep>class OrdersController < ApplicationController
before_action :find_item, only: [:index, :create]
before_action :block_index, only: :index
before_action :block_no_card, only: :index
def index
@order = OrderAddress.new
find_card
end
def create
@order = OrderAddress.new(order_params)
if @order.valid?
pay_item
@order.save
redirect_to root_path
else
find_card
render :index
end
end
private
def find_item
@item = Item.find(params[:item_id])
end
def order_params
params.require(:order_address).permit(:postal_code, :city, :house_num, :building, :phone).merge(user_id: current_user.id, item_id: params[:item_id], token: params[:token])
end
def find_card
Payjp.api_key = ENV['PAYJP_SECRET_KEY']
card = Card.find_by(user_id: current_user.id)
customer = Payjp::Customer.retrieve(card.customer_token)
@card = customer.cards.first
end
def pay_item
Payjp.api_key = ENV['PAYJP_SECRET_KEY']
customer_token = current_user.card.customer_token
Payjp::Charge.create(
amount: @item.price,
customer: customer_token,
currency: 'jpy'
)
end
def block_index
redirect_to item_path(@item.id) if @item.order || @item.user == current_user
end
def block_no_card
redirect_to user_path(current_user.id) unless current_user.card
end
end
<file_sep>class Day < ActiveHash::Base
self.data = [
{ id: 1, name: '--' },
{ id: 2, name: '在庫あり/即日出荷' },
{ id: 3, name: '2〜3日で発送' },
{ id: 4, name: '1週間以内に発送' },
{ id: 5, name: '2週間以内に発送' },
{ id: 6, name: '1ヵ月以内に発送' },
{ id: 7, name: '1ヵ月以上かかります' }
]
end
<file_sep>class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: [:facebook, :google_oauth2]
has_many :items, dependent: :destroy
has_many :orders
has_many :comments, dependent: :destroy
has_many :commented_items, through: :comments, source: :item
has_many :sns_credentials, dependent: :destroy
has_one :card, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :liked_items, through: :likes, source: :item
with_options presence: true do
validates :name
validates :nickname, uniqueness: { case_sensitive: true }
end
def already_liked?(item)
likes.exists?(item_id: item.id)
end
def self.from_omniauth(auth)
sns = SnsCredential.where(provider: auth.provider, uid: auth.uid).first_or_create
user = User.where(email: auth.info.email).first_or_initialize(
nickname: auth.info.name,
email: auth.info.email
)
if user.persisted?
sns.user = user
sns.save
end
{ user: user, sns: sns }
end
end
<file_sep>require 'rails_helper'
RSpec.describe OrderAddress, type: :model do
describe '商品購入機能' do
before do
@order_address = FactoryBot.build(:order_address)
end
context '商品購入がうまくいくとき' do
it '必要な情報がすべて存在すれば購入できる' do
expect(@order_address).to be_valid
end
it 'buildingがなくても購入できる' do
@order_address.building = nil
expect(@order_address).to be_valid
end
end
context '商品購入がうまくいかないとき' do
it 'tokenが不正値では購入できない' do
@order_address.token = nil
@order_address.valid?
expect(@order_address.errors.full_messages).to include('カード情報を入力してください')
end
it 'postal_codeが空では購入できない' do
@order_address.postal_code = nil
@order_address.valid?
expect(@order_address.errors.full_messages).to include('郵便番号を入力してください')
end
it 'postal_codeにハイフン(-)が含まれていない場合は購入できない' do
@order_address.postal_code = '1234567'
@order_address.valid?
expect(@order_address.errors.full_messages).to include('郵便番号を正しく入力してください')
end
it 'cityが空では購入できない' do
@order_address.city = nil
@order_address.valid?
expect(@order_address.errors.full_messages).to include('市区町村を入力してください')
end
it 'house_numが空では購入できない' do
@order_address.house_num = nil
@order_address.valid?
expect(@order_address.errors.full_messages).to include('番地を入力してください')
end
it 'phoneが空では購入できない' do
@order_address.phone = nil
@order_address.valid?
expect(@order_address.errors.full_messages).to include('電話番号を入力してください')
end
it 'phoneにハイフン(-)が含まれている場合は購入できない' do
@order_address.phone = '090-1234-5678'
@order_address.valid?
expect(@order_address.errors.full_messages).to include('電話番号を正しく入力してください')
end
end
end
end
<file_sep>FactoryBot.define do
factory :order_address do
postal_code { '000-0000' }
city { '札幌市' }
house_num { '1-1-1' }
building { 'build' }
phone { '09012345678' }
user_id { 1 }
item_id { 1 }
token { 1 }
end
end
<file_sep>
## アプリケーション名
DosancoHans
## 概要
北海道地域に特化したハンドメイド作品の専門フリーマーケットアプリです。
<kbd><img width="1179" alt="スクリーンショット 2020-10-20 17 32 47" src="https://user-images.githubusercontent.com/70306357/96561464-93756380-12fa-11eb-9f65-00a667d08d2f.png"></kbd>
## リンク
- URL : https://dosancohans.herokuapp.com/
- GitHubリポジトリ : https://github.com/tatsuhiko-nakayama/dosanco_hans
## 使用技術
- MySQL
- Javascript
- Ruby 2.6.5 / Rails 6.0.3.4
- Rspec
- Amazon S3
- Git / GitHub
- Heroku
## 利用方法
どのユーザーも出品されている商品を閲覧することができます。
出品、購入を行うためにはユーザー登録を行いログインする必要があります。
## テスト用アカウント
- 出品者用
- Email : tester@1
- Pass : <PASSWORD>
- 購入者用
- Email : tester@2
- Pass : <PASSWORD>
- 購入者用テストカード情報(登録済)
- 番号 : 4242424242424242
- 期限 : 現在以降
- CVC : 123
## アプリの目的・意義・着想
北海道にはクリエイターがたくさんいるにも関わらず、クリエイターとユーザーを結びつける場所がなかったため、地域に特化したマーケットサイトを作成しました。
「北海道」というつながりを大切にするため、ユーザー同士がコミュニケーションしやすいアプリケーションになるよう設計、実装を行いました。
## 機能一覧
◆ユーザー機能
- deviseを使用
- SNSログイン認証
- Google
- Facebook
- マイページ機能
- 「いいね」した商品のリスト表示
- 出品した商品のリスト表示
- クレジットカード登録機能
- ユーザー情報編集、削除機能
◆出品機能
- 出品、編集、削除機能
- 画像のアップロードはActiveStorageを使用
◆購入機能
- PAYJPを使用
- JavaScriptを用いたトークン処理を実装
◆レビューコメント機能(for商品)
- コメント表示、投稿、削除機能
◆いいね機能(for商品)
◆コメント数・いいね数表示機能
- 一覧表示内にコメント数、いいね数を掲載
◆商品検索機能
- カテゴリ別検索
- 商品名フリーワード検索
◆サジェスト機能
- 閲覧商品の前後に登録された商品をサジェスト
## 今後実装したい項目
- 出品物の選択(一括)削除機能
- 出品した商品の閲覧数の表示
- 出品した商品のアナリティクス機能
- お気に入りの出品者を記録できる機能
- 商品画像の複数登録&スライド表示
## ER図

## テーブル設計
### users テーブル
| Column | Type | Options |
| ------------ | ------- | ------------------------- |
| name | string | null: false |
| nickname | string | null: false, unique: true |
| email | string | null: false |
| password | string | null: false |
### Association
- has_many :items
- has_many :orders
- has_many :comments
- has_many :sns_credentials
- has_one :card
- has_many :likes
### sns_credentials テーブル
| Column | Type | Options |
| --------- | ---------- | ------------------------------- |
| provider | string | null: false |
| uid | string | null: false |
| user | references | null: false, foreign_key: true |
### Association
- belongs_to :user
### cards テーブル
| Column | Type | Options |
| -------------- | ---------- | ------------------------------- |
| card_token | string | null: false |
| customer_token | string | null: false |
| user | references | null: false, foreign_key: true |
### Association
- belongs_to :user
### items テーブル
| Column | Type | Options |
| ----------- | ---------- | ------------------------------ |
| name | string | null: false |
| info | text | null: false |
| price | integer | null: false |
| category_id | integer | null: false |
| from_id | integer | null: false |
| day_id | integer | null: false |
| user | references | null: false, foreign_key: true |
### Association
- has_one :order
- has_many :comments
- has_many :likes
- belongs_to :user
- has_one_attached :image
- belongs_to_active_hash :category
- belongs_to_active_hash :from
- belongs_to_active_hash :day
### orders テーブル
| Column | Type | Options |
| ------- | ---------- | ------------------------------ |
| user | references | null: false, foreign_key: true |
| item | references | null: false, foreign_key: true |
### Association
- has_one :address
- belongs_to :user
- belongs_to :item
### addresses テーブル
| Column | Type | Options |
| ----------- | ---------- | ------------------------------ |
| postal_code | string | null: false |
| city | string | null: false |
| house_num | string | null: false |
| building | string | |
| phone | string | null: false |
| order | references | null: false, foreign_key: true |
### Association
- belongs_to :order
### comments テーブル
| Column | Type | Options |
| ------- | ---------- | ------------------------------ |
| message | text | null: false |
| user | references | null: false, foreign_key: true |
| item | references | null: false, foreign_key: true |
### Association
- belongs_to :user
- belongs_to :item
### likes テーブル
| Column | Type | Options |
| ------ | ---------- | ----------------- |
| user | references | foreign_key: true |
| item | references | foreign_key: true |
### Association
- belongs_to :user
- belongs_to :item | d19c3d9f4f8606912a89e67fc83cf555a2bb7fac | [
"Markdown",
"Ruby"
] | 22 | Ruby | tatsuhiko-nakayama/dosanco_hans | a6c640d90909e7df2f63e8c704e463d62611e698 | 51f0872a58860ef372252a1c0110f6e4305f7acf |
refs/heads/master | <file_sep>
var moveList = function(item)
{
//var addList = document.getElementById("listFlexId");
//addList.removeAttribute("id");
//addList.setAttribute("id", "reverseAnimation");
var tFinal = document.createTextNode(item.parentElement.textContent);
var liFinal = document.createElement("li");
liFinal.setAttribute("class", "animat");
var containerFinal= document.getElementById("finalList");
// var container= document.getElementById("finalList") = "<li>"+item.parentElement.innerHTML + "<button>"+ "Clear"+ "</button> </li>";
liFinal.appendChild(tFinal);
containerFinal.appendChild(liFinal);
//item.parentNode.removeChild(item);
var DelButton = document.createElement('input');
DelButton.type = "button";
DelButton.id = "delButton";
DelButton.value="Delete";
DelButton.setAttribute("onclick", "DelFinalList(this)");
liFinal.appendChild(DelButton);
item.parentElement.style.display= "none";
}
var DelFinalList =(item) => {
item.parentElement.style.display= "none";
};
var addToList = () => {
var input = document.getElementById("info").value;
var t = document.createTextNode(input);
var li = document.createElement("li");
li.setAttribute("class", "listFlex");
li.setAttribute("id", "listFlexId");
var container= document.getElementById("initialList");
li.appendChild(t);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "checkBox";
checkbox.setAttribute("onclick", "moveList(this)");
li.appendChild(checkbox);
container.appendChild(li);
//container.appendChild(checkbox);
document.getElementById("info").value= " ";
};
document.getElementById("btn").onclick = addToList;
//document.getElementById("checkBox").onclick = move();
| 22fed6521e4790ee4a80effe3fc3d8a8bd4fd420 | [
"JavaScript"
] | 1 | JavaScript | mohsinrahman/To-Do-List | 4143bd33097a649e56c3b9af7093ac537b84f8dd | 9e865fb979d554ec51d862caf3dc68b0e3ffb959 |
refs/heads/main | <repo_name>Gibbs249/cargo-hold<file_sep>/Item.java
package FinalProject;
public abstract class Item implements Comparable<Item> {
// Declare attributes here
private String strClass;
private String strName;
private int intDurability;
private int intWeight;
private int intValue;
private int intID;
public Item(String strClass, String strName, int intWeight, int intValue, int intDurability, int intID) {
this.strClass = strClass;
this.strName = strName;
this.intDurability = intDurability;
this.intWeight = intWeight;
this.intValue = intValue;
this.intID = intID;
}
public String getStrClass() {
return strClass;
}
public void setStrClass(String strClass) {
this.strClass = strClass;
}
public String getStrName() {
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
}
public int getIntDurability() {
return intDurability;
}
public void setIntDurability(int intDurability) {
this.intDurability = intDurability;
}
public int getIntWeight() {
return intWeight;
}
public void setIntWeight(int intWeight) {
this.intWeight = intWeight;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public int getIntID() {
return intID;
}
public void setIntID(int intID) {
this.intID = intID;
}
public int getValueRatio() {
return this.intValue / this.intWeight;
}
public int compareTo(Item o) {
return ((this.getIntValue()) - (o.getIntValue()));
}
@Override
public String toString() {
return "Class: " + strClass + " Name: " + strName + " Weight: " + intWeight + " Value: " + intValue
+ " Durability: " + intDurability + " ID: " + intID;
}
// + " Damage: " + intDamage + " Defense: " + intDefense + " Color: " + strColor
// + " Metal: " + strMetal + " Plastic: " + strPlastic + " Fabric: " + strFabric
// + " Food Type: " + strFoodType + " Medicinal: " + strMedicinal + " Expiration Year: " + intExpireYear
}<file_sep>/AndrewsList.java
package FinalProject;
public class AndrewsList {
private Node start, tail;
public void add(Item item) {
if (start == null) {
start = new Node(item, null);
tail = start;
} else {
tail.setNext(new Node(item, null));
tail = tail.getNext();
}
}
public int size() {
int count = 0;
Node p = start;
while (p != null) {
p = p.getNext();
count++;
}
return count;
}
public Item get(int i) {
int count = 0;
Node p = start;
while (p != null) {
if(count == i) {
return p.getItem();
}
p = p.getNext();
count++;
}
return null;
}
public int getTotal() {
int total = 0;
Node p = start;
while (p != null) {
total += p.getItem().getIntWeight();
p = p.getNext();
}
return total;
}
public boolean remove(String strItem) {
Node prev = null, del = start;
while (del != null && !del.getItem().getStrName().equals(strItem)) {
prev = del;
del = del.getNext();
}
if (del == null) {
return false;
} else {
if (del == start) {
start = start.getNext();
} else {
if (del == tail) {
tail = prev;
}
prev.setNext(del.getNext());
}
return true;
}
}
public Node getStart() {
return start;
}
} | 38fc8ca3b5fc2ba6e5f7c4134581d631229ea794 | [
"Java"
] | 2 | Java | Gibbs249/cargo-hold | bc01c6103f3743a522fc5c3c8b31003ed98888bf | ea137b4f21dce24226b96b66f1326c6aa80796c4 |
refs/heads/master | <repo_name>m0x/workspace<file_sep>/git/hooks/pre-commit
#!/bin/sh
if OCCURENCES=$(git grep -In -e byebug -e debugger -e console.log -- `git ls-files | grep -v Gemfile`);
then
echo "Debugger calls found in project files: \n"
echo "$OCCURENCES\n"
while true
do
read -p " Are you sure you want to commit ? (y/n): " alternative
case $alternative in
[Yy]* ) exit 0; break;;
[Nn]* ) exit 1;;
* ) echo "Please answer yes (y) or no (n)";;
esac
done
fi
exit 0
<file_sep>/git/custom_commands/git-graph
#!/bin/sh
# shows a formatted graph of the log
git log --graph --pretty=format:'%C(yellow)%h %Cred%ad %Cblue%an%Cgreen%d %Creset%s' --date=short
<file_sep>/git/custom_commands/git-check
#!/bin/sh
# searches occurences of "debugger", "byebug" or "console.log" inside tracked files
git grep -In -e byebug -e debugger -e console.log -- $(git ls-files | grep -v Gemfile)
<file_sep>/git/custom_commands/README.md
How to install
---
Just add this folder to PATH:
`export PATH = $PATH:$(pwd)`
| 1eca1fdb2f45ffc8ebdd6ce9881ceaeeb7c0e5c2 | [
"Markdown",
"Shell"
] | 4 | Shell | m0x/workspace | 80e550b939cbd61a503d8c0adda75158f0f01435 | c570f0bdb78bfbe9a97ac63be44cc3301474d622 |
refs/heads/master | <file_sep>let mongoose = require('mongoose')
const server = 'ds039007.mlab.com:39007'
const database = 'test-api-jkeen-v1'
const user = 'jkeen-v1'
const password = '<PASSWORD>'
mongoose.connect(`mongodb://${user}:${password}@${server}/${database}`)
let CustomerSchema = new mongoose.Schema({
name: String,
email: {
type: String,
required: true,
unique: true
}
})
module.exports = mongoose.model('Customer', CustomerSchema)<file_sep>test-api-v1
<!-- Stopped working at 1:18 mark -->
video: 1:01(need m-lab)
following: https://www.youtube.com/watch?v=o3ka5fYysBM
https://mlab.com/databases/test-api-jkeen-v1
build api with node express, mongoDb
steps:
1. npm install express
2. npm i nodemon -D
3. npm i mongoose
4. npm i body-parser
| 830fa8d4a849a8f5f3620c22d72d5ae686cedf55 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | jordankeen/test-api-v1 | 55e0cb7e7fd75d6ff810b7ed6a5e95d67ca5024f | e98f5b1659d80bd51f7f9405b7ec7f96d09604b8 |
refs/heads/master | <repo_name>Shetin/project-big-work<file_sep>/TankWarIII/icon.cpp
#include "icon.h"
#include <vector>
#include<iostream>
#include <map>
int ICON::GRID_SIZE = 32;
pair<string,ICON> pairArray[] =
{
make_pair("playerTank",ICON("PlayerTank",0,8, 2, 2,":/pic/tank.png")),
make_pair("house",ICON("house",8,0, 5, 5,":/pic/wall2.png")),//can't be shoot
make_pair("brick",ICON("brick",5,9,2,2,":/pic/brick2.png")),//can be shoot
make_pair("stone",ICON("stone",2,0,2,2,":/pic/brick2.png")),//can't be shoot
make_pair("clock",ICON("clock",0,0,2,2,":/pic/clock.png")),//Props:slow enemy's speed
make_pair("blood",ICON("blood",0,0,2,2,":/pic/blood.png")),//Props:supply blood
make_pair("magic",ICON("magic",0,0,2,2,":/pic/magic.png")),//enemy can't move for several seconds
make_pair("EnemyTank",ICON("EnemyTank",4,8,2,2,":/pic/tank.png")),
make_pair("tree",ICON("tree",0,0,2,2,":/pic/tree.png")),
make_pair("boss",ICON("boss",0,0,2,2,":/pic/boss.png")),
make_pair("2brick",ICON("2brick",0,2,2,2,":/pic/wall.png")),//map2
make_pair("2wall",ICON("2wall",0,0,2,2,":/pic/wall.png")),//map2
make_pair("2fence",ICON("2fence",0,6,2,2,":/pic/wall3.png")),//can cover the tank
make_pair("2stone",ICON("2stone",3,0,2,2,":/pic/wall.png")),//map2
make_pair("3brick",ICON("3brick",0,0,2,2,":/pic/wall3.png")),//map3
make_pair("3stone",ICON("3stone",0,0,2,2,":/pic/3stone.png")),//map3
make_pair("3stee",ICON("3stee",0,0,2,2,":/pic/tree.png")),//map3
make_pair("life",ICON("life",0,0,1,1,":/pic/life.png")),
make_pair("dead",ICON("dead",0,0,1,1,":/pic/dead.png")),
make_pair("magicshot",ICON("magicshot",0,0,2,2,":/pic/magicshot.png")),
make_pair("HelpTank",ICON("HelpTank",8,12,2,2,":/pic/tank.png")),
};
map<string,ICON> ICON::GAME_ICON_SET(pairArray,pairArray+sizeof(pairArray)/sizeof(pairArray[0]));
ICON::ICON(string name, int x, int y, int w, int h,string path){
this->typeName = name;
this->srcX = x;
this->srcY = y;
this->width = w;
this->height = h;
}
ICON ICON::findICON(string type){
map<string,ICON>::iterator kv;
kv = ICON::GAME_ICON_SET.find(type);
if (kv==ICON::GAME_ICON_SET.end()){
cout<<"Error: cannot find ICON"<<endl;
return ICON();
}
else{
return kv->second;
}
}
<file_sep>/TankWarIII/two.cpp
#include "two.h"
#include "ui_two.h"
#include "QProcess"
int flag_two=0;
Two::Two(QWidget *parent) :
QWidget(parent),
ui(new Ui::Two)
{
ui->setupUi(this);
_game.initWorld("map2.txt");//TODO 应该是输入有效的地图文件
connect(this,&Two::AfterEat,this,&Two::showDialogTwo);
dlg=new DialogTwo(this);
connect(dlg,&DialogTwo::ToLevelThree,this,&Two::win2);
connect(&this->GetWorld(),World::lose1,this,&Two::showlose2);
//connect(dlg,&DialogTwo::ToManu,this,&Two::ReturnManu);
timer3 = new QTimer(this);
connect(timer3,SIGNAL(timeout()),this,SLOT(handle_Bullet()));//timeoutslot()为自定义槽
//时钟事件与handle_bullet函数绑定
timer3->start(100);
timer3->setInterval(100);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));//设置随机数种子
timer4 = new QTimer(this);
connect(timer4,SIGNAL(timeout()),this,SLOT(randomMove()));//timeoutslot()为自定义槽
//时钟事件与randomMove函数绑定
timer4->start(100);
timer4->setInterval(500);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
timer5 = new QTimer(this);
connect(timer5,SIGNAL(timeout()),this,SLOT(handleenemy()));
timer5->start(0);
timer5->setInterval(6000);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
}
Two::~Two()
{
delete ui;
}
void Two::LevelTwoOver()
{
emit AfterEat();
}
void Two::win2()
{
qApp->closeAllWindows();
QProcess::startDetached(qApp->applicationFilePath(), QStringList());
emit display(4);
}
void Two::showDialogTwo()
{
close();
dlg->show();
}
void Two::showlose2(){
close();
dlg2=new Dlglose2(this);
dlg2->show();
}
const World &Two::GetWorld()
{
return _game;
}
void Two::paintEvent(QPaintEvent *){
//setFixedSize(1040,980);
QPainter *pa;
QPainter painter(this);
painter.drawPixmap(rect(),QPixmap(":/pic/map003.png"));
pa = new QPainter();
pa->begin(this);
this->_game.show(pa);
//this->_pic.load(":/pic/life.png");
//pa->drawImage(0,0,this->_pic);
//pa->drawImage(32,0,this->_pic);
//pa->drawImage(64,0,this->_pic);
vector<Player_Bullet>::iterator it;
for(it=this->_game._bullets.begin();it!=this->_game._bullets.end();it++){
(*it).show(pa);
}
vector<Enemy_bullet>::iterator it1;
for(it1=this->_game.e_bullets.begin();it1!=this->_game.e_bullets.end();it1++){
(*it1).show(pa);
}
if(flag_two==1)
{
_game.handleEnemyBulletShow(pa);
}
pa->end();
delete pa;
}
void Two::keyPressEvent(QKeyEvent *e)
{
flag_two=0;
//direction = 1,2,3,4 for 上下左右
if(e->key() == Qt::Key_A)
{
this->_game.handleTankMove(3,1);
}
else if(e->key() == Qt::Key_D)
{
this->_game.handleTankMove(4,1);
}
else if(e->key() == Qt::Key_W)
{
this->_game.handleTankMove(1,1);
}
else if(e->key() == Qt::Key_S)
{
this->_game.handleTankMove(2,1);
}
if(e->key() ==Qt::Key_Space){
QPainter *pa;
pa = new QPainter();
pa->begin(this);
this->_game.handleBulletShow(pa);//利用空格键操纵使发射子弹
pa->end();
delete pa;
}
this->repaint();//repaint的作用是再调用一次paintEvent函数
}
void Two::randomMove(){
flag_two=0;
this->_game.handleEnemyMove();
flag_two=1;
this->repaint();
}
void Two::handleenemy(){
flag_two=0;
_game.addenemy();
this->repaint();
}
void Two::handle_Bullet(){
_game.handleBulletMove();
_game.handleEnemyBulletMove();
flag_two=0;
this->repaint();
}
<file_sep>/icon.cpp
#include "icon.h"
#include <vector>
#include<iostream>
#include <map>
int ICON::GRID_SIZE = 32;
pair<string,ICON> pairArray[] =
{
make_pair("playerTank",ICON("PlayerTank",0,8, 2, 2,"C:\\Users\\asus\\Desktop\\TankWarI\\tank.png")),
make_pair("wall",ICON("wall",3,2, 3, 1,"C:\\Users\\asus\\Desktop\\TankWarI\\TileB.png")),//can't be shoot
make_pair("brick",ICON("brick",5,9,2,2,"C:\\Users\\asus\\Desktop\\TankWarI\\brick2.png")),//can be shoot
make_pair("stone",ICON("stone",1,3,3,1,"C:\\Users\\asus\\Desktop\\TankWarI\\brick2.png")),//can't be shoot
make_pair("clock",ICON("clock",0,0,2,2,"C:\\Users\\asus\\Desktop\\TankWarI\\clock.png")),//Props:slow enemy's speed
make_pair("blood",ICON("blood",0,0,2,2,"C:\\Users\\asus\\Desktop\\TankWarI\\blood.png")),//Props:supply blood
make_pair("magic",ICON("magic",0,0,2,2,"C:\\Users\\asus\\Desktop\\TankWarI\\magic.png")),//enemy can't move for several seconds
make_pair("EnemyTank",ICON("EnemyTank",4,8,2,2,"C:\\Users\\asus\\Desktop\\TankWarI\\tank.png")),
make_pair("boss",ICON("boss",0,0,3,3,"C:\\Users\\asus\\Desktop\\TankWarI\\boss.png")),
make_pair("brick2",ICON("brick2",1,11,1,1,"C:\\Users\\asus\\Desktop\\TankWarI\\brick2.png")),//protect the boss
};
map<string,ICON> ICON::GAME_ICON_SET(pairArray,pairArray+sizeof(pairArray)/sizeof(pairArray[0]));
ICON::ICON(string name, int x, int y, int w, int h,string path){
this->typeName = name;
this->srcX = x;
this->srcY = y;
this->width = w;
this->height = h;
}
ICON ICON::findICON(string type){
map<string,ICON>::iterator kv;
kv = ICON::GAME_ICON_SET.find(type);
if (kv==ICON::GAME_ICON_SET.end()){
cout<<"Error: cannot find ICON"<<endl;
return ICON();
}
else{
return kv->second;
}
}
<file_sep>/TankWarIII/world.cpp
#include "world.h"
#include "ui_world.h"
#include "icon.h"
#include "string"
#include "rpgobj.h"
#include <fstream>
#include <iostream>
#include <vector>
#include "one.h"
#include "widget.h"
using namespace std;
int num=3;
int flag=0;
int flag1=0;
int flag2=0;
int flag4=0;
int flag5=0;
int flag6=0;
World::World(QWidget *parent):
QWidget(parent),
ui(new Ui::World)
{
ui->setupUi(this);
}
World::~World()
{
delete ui;
}
void World::initWorld(string mapFile){
//TODO 下面这部分逻辑应该是读入地图文件,生成地图上的对象
//player 5 5
this->_tank.initObj("playerTank",":/pic/tank.png");
this->_tank.setPosX(5);
this->_tank.setPosY(5);
RPGObj obj1;
ifstream inf;
inf.open(mapFile.c_str());
string a,p;
int b,c;
while(inf >> a){
inf >>p;
inf >> b;
inf >> c;
obj1.initObj(a,p);
obj1.setPosX(b);
obj1.setPosY(c);
this->_objs.push_back(obj1);
}
}
void World::handleTankMove(int direction, int steps){
this->_tank.move(direction, steps);
this->act(direction, steps);
}
void World::handleBulletShow(QPainter *painter){
this->_bullets.push_back(_tank.shoot(painter));
}
void World::handleEnemyBulletShow(QPainter *painter){
vector<Enemy>::iterator it;
for(it = this->_enemy.begin();it !=this->_enemy.end();it++){
this->e_bullets.push_back((*it).shoot(painter));
}
if(flag6==1){
this->_bullets.push_back(_helper[0].shoot(painter));
this->_bullets.push_back(_helper[1].shoot(painter));
}
}
void World::handleBulletMove(){
vector<Player_Bullet>::iterator it;
for(it=this->_bullets.begin();it!=this->_bullets.end();it++){
int direction=(*it).get_direction();
(*it).move(direction);
}
this->bullet_act1();
this->bullet_act2();
this->bullet_act3();
this->bullet_act4();
}
void World::handleEnemyBulletMove(){
vector<Enemy_bullet>::iterator it;
for(it=this->e_bullets.begin();it!=this->e_bullets.end();it++){
int direction=(*it).get_direction();
(*it).move(direction);
}
this->e_bullet_act1();
this->e_bullet_act2();
this->e_bullet_act3();
this->e_bullet_act4();
}
void World::act(int direction, int steps){
vector<RPGObj>::iterator it;
if(this->_tank.getPosX()<0||this->_tank.getPosX()>30||this->_tank.getPosY()<0||this->_tank.getPosY()>29){ this->_tank.move(direction, -1); }
for(it = this->_objs.begin(); it != this->_objs.end(); it++){
flag=0;
if(
(abs(this->_tank.getPosX()-(*it).getPosX())<2)//(*it).getWidth())
&&(abs(this->_tank.getPosY()-(*it).getPosY())<2)//(*it).getHeight())
)
{
if((*it).canEat() == true)
{
if((*it).getObjType()=="magic"){
this->addhelper();
}
if((*it).getObjType()=="blood"){
this->addlife();
num++;
}
if((*it).getObjType()=="magicshot"){
_tank.change_mybullet();
}
this->_objs.erase(it);
}
if((*it).canCover() == false)
{
this->_tank.move(direction, -1);
break;
}
if((*it).canCover()==true)
{
flag=1;
}
}
if(it == this->_objs.end()) {
break;
}
}
}
void World::bullet_act1(){
vector<Player_Bullet>::iterator it1;
vector<RPGObj>::iterator it2;
flag2=0;
for(it1=this->_bullets.begin();it1!=this->_bullets.end();it1++){
for(it2=this->_objs.begin();it2!=this->_objs.end();it2++){
if((((*it1).get_x()) >(*it2).getPosX()*32) &&
( ((*it1).get_x()) <((*it2).getPosX()*32)+((*it2).getWidth()*32) ) &&
( ((*it1).get_y()) >=((*it2).getPosY()*32) ) &&
( ((*it1).get_y()) <= ((*it2).getPosY()*32)+((*it2).getHeight()*32 ))
)
{
if((*it2).canShoot()==true){
if((*it2).getObjType()=="boss") {
emit eatBoss();
}
(*it2).onErase();
it2 = this->_objs.erase(it2);
it1 =this->_bullets.erase(it1);
flag2=1;
break;
}
}
}
if(1==flag2) break;
}
}
void World::bullet_act2(){
vector<Player_Bullet>::iterator it1;
vector<RPGObj>::iterator it2;
flag1=0;
for(it1=this->_bullets.begin();it1!=this->_bullets.end();it1++){
for(it2=this->_objs.begin();it2!=this->_objs.end();it2++){
if((((*it1).get_x()) >=(*it2).getPosX()*32) &&
( ((*it1).get_x()) <=((*it2).getPosX()*32)+((*it2).getWidth()*32) ) &&
( ((*it1).get_y()) >=((*it2).getPosY()*32) ) &&
( ((*it1).get_y()) <= ((*it2).getPosY()*32)+((*it2).getHeight()*32 ))
)
{
if((*it2).canShoot()==false){
it1 = this->_bullets.erase(it1);
(*it2).onErase();
flag2=1;
break;
}
}
}
if(flag2==1) break;
}
}
void World::bullet_act3(){
vector<Player_Bullet>::iterator it1;
vector<Enemy>::iterator it2;
flag2=0;
for(it1=this->_bullets.begin();it1!=this->_bullets.end();it1++){
for(it2=this->_enemy.begin();it2!=this->_enemy.end();it2++){
if((((*it1).get_x()) >(*it2).getPosX()*32) &&
( ((*it1).get_x()) <((*it2).getPosX()*32)+((*it2).getWidth()*32) ) &&
( ((*it1).get_y()) >=((*it2).getPosY()*32) ) &&
( ((*it1).get_y()) <= ((*it2).getPosY()*32)+((*it2).getHeight()*32 ))
)
{
it2 = this->_enemy.erase(it2);
(*it2).onErase();
it1 =this->_bullets.erase(it1);
flag2=1;
break;
}
}
if(1==flag2) break;
}
}
void World::bullet_act4(){
vector<Player_Bullet >::iterator it1;
for(it1=this->_bullets.begin();it1!=this->_bullets.end();it1++){
if(((*it1).get_x()>1024)||((*it1).get_y()>992)||((*it1).get_x()<0)||((*it1).get_y()<0))
{
this->_bullets.erase(it1);
break;
}
}
}
void World::e_bullet_act1(){
vector<Enemy_bullet>::iterator it1;
vector<RPGObj>::iterator it2;
flag4=0;
for(it1=this->e_bullets.begin();it1!=this->e_bullets.end();it1++){
for(it2=this->_objs.begin();it2!=this->_objs.end();it2++){
if((((*it1).get_x()) >(*it2).getPosX()*32) &&
( ((*it1).get_x()) <((*it2).getPosX()*32)+((*it2).getWidth()*32) ) &&
( ((*it1).get_y()) >=((*it2).getPosY()*32) ) &&
( ((*it1).get_y()) <= ((*it2).getPosY()*32)+((*it2).getHeight()*32 ))
)
{
if((*it2).canShoot()==true&&(*it2).getObjType()!="boss"){
(*it2).onErase();
it2 = this->_objs.erase(it2);
it1 =this->e_bullets.erase(it1);
flag4=1;
break;
}
}
}
if(1==flag4) break;
}
}
void World::e_bullet_act4(){
vector<Enemy_bullet >::iterator it1;
for(it1=this->e_bullets.begin();it1!=this->e_bullets.end();it1++){
if(((*it1).get_x()>1024)||((*it1).get_y()>992)||((*it1).get_x()<0)||((*it1).get_y()<0))
{
this->e_bullets.erase(it1);
break;
}
}
}
void World::e_bullet_act2(){
vector<Enemy_bullet>::iterator it1;
vector<RPGObj>::iterator it2;
flag5=0;
for(it1=this->e_bullets.begin();it1!=this->e_bullets.end();it1++){
for(it2=this->_objs.begin();it2!=this->_objs.end();it2++){
if((((*it1).get_x()) >=(*it2).getPosX()*32) &&
( ((*it1).get_x()) <=((*it2).getPosX()*32)+((*it2).getWidth()*32) ) &&
( ((*it1).get_y()) >=((*it2).getPosY()*32) ) &&
( ((*it1).get_y()) <= ((*it2).getPosY()*32)+((*it2).getHeight()*32 ))
)
{
if((*it2).canShoot()==false){
(*it2).onErase();
it1 = this->e_bullets.erase(it1);
flag5=1;
break;
}
}
}
if(flag5==1) break;
}
}
void World::e_bullet_act3(){
vector<Enemy_bullet>::iterator it1;
for(it1=this->e_bullets.begin();it1!=this->e_bullets.end();it1++){
if((((*it1).get_x()) >=_tank.getPosX()*32) &&
( ((*it1).get_x()) <=(_tank.getPosX()*32)+(_tank.getWidth()*32) ) &&
( ((*it1).get_y()) >=(_tank.getPosY()*32) ) &&
( ((*it1).get_y()) <= (_tank.getPosY()*32)+(_tank.getHeight()*32 ))
)
{
_tank.onErase();
it1 = this->e_bullets.erase(it1);
_tank.setPosX(5);
_tank.setPosY(5);
_tank.showdown();
this->deletelife();
num--;
if(num==0)emit lose1();
break;
}
}
}
void World::show(QPainter * painter){
this->_tank.show(painter);
vector<RPGObj>::iterator it;
for(it=this->_objs.begin();it!=this->_objs.end();it++){
(*it).show(painter);
}
vector<Enemy>::iterator it1;
for(it1=this->_enemy.begin();it1!=this->_enemy.end();it1++){
(*it1).show(painter);
}
vector<Helper>::iterator it2;
for(it2=this->_helper.begin();it2!=this->_helper.end();it2++)
{
(*it2).show(painter);
}
}
void World::handleEnemyMove(){
vector<Enemy>::iterator it;
for(it = this->_enemy.begin(); it != this->_enemy.end(); it++){
int x=(*it).getPosX(),y=(*it).getPosY();
int s1=(x-_tank.getPosX())*(x-_tank.getPosX())+(y-1-_tank.getPosY())*(y-1-_tank.getPosY()),
s2=(x-_tank.getPosX())*(x-_tank.getPosX())+(y+1-_tank.getPosY())*(y+1-_tank.getPosY()),
s3=(x-1-_tank.getPosX())*(x-1-_tank.getPosX())+(y-_tank.getPosY())*(y-_tank.getPosY()),
s4=(x+1-_tank.getPosX())*(x+1-_tank.getPosX())+(y-_tank.getPosY())*(y-_tank.getPosY());
int d=1,min=s1,d1=2,min1=s2;
if(s2<min){
d=2,d1=1;
min=s2,min1=s1;
}
if(s3<min){
d1=d,d=3;
min1=min,min=s3;
}
if(s3>=min&&s3<min1&&d!=3){
d1=3;
min1=s3;
}
if(s4<min){
d1=d,d=4;
min1=min,min=s4;
}
if(s4>=min&&s4<min1&&d!=4){
d1=4;
min1=s4;
}
(*it).Move(d,1);
this->Act(d,1);
if(((d==1||d==2)&&y==(*it).getPosY())||((d==3||d==4)&&x==(*it).getPosX())){
(*it).Move(d1,1);
this->Act(d1,1);
}
}
}
void World::Act(int direction, int steps){
vector<RPGObj>::iterator it;
vector<Enemy>::iterator it1;
for(it1=this->_enemy.begin();it1!=this->_enemy.end();it1++){
for(it = this->_objs.begin(); it != this->_objs.end(); it++){
flag=0;
if(
(abs((*it1).getPosX()-(*it).getPosX())<2)//(*it).getWidth())
&&(abs((*it1).getPosY()-(*it).getPosY())<2)//(*it).getHeight())
)
{
if((*it).canEat() == true)
{
this->_objs.erase(it);
}
if((*it).canCover() == false)
{
(*it1).Move(direction, -1);
flag=1;
break;
}
}
if(it == this->_objs.end()) {
break;
}
}}
}
void World::addenemy(){
Enemy enemy;
enemy.initObj("EnemyTank",":/pic/tank.png");
enemy.setPosX(3);
enemy.setPosY(20);
this->_enemy.push_back(enemy);
}
void World::addhelper(){
Helper helper;
helper.initObj("HelpTank",":/pic/tank.png");
this->_helper.push_back(helper);
this->_helper.push_back(helper);
_helper[0].setPosX(7),_helper[0].setPosY(1);
_helper[0].ShowDown();
_helper[1].setPosX(23),_helper[1].setPosY(1);
_helper[1].ShowDown();
flag6=1;
}
void World::addlife(){
RPGObj obj1;
obj1.initObj("life",":/pic/life.png");
obj1.setPosX(num);
obj1.setPosY(0);
this->_objs.push_back(obj1);
}
void World::deletelife(){
RPGObj obj1;
obj1.initObj("dead",":/pic/dead.png");
obj1.setPosX(num-1);
obj1.setPosY(0);
this->_objs.push_back(obj1);
}
<file_sep>/TankWarIII/enemy.h
#ifndef ENEMY_H
#define ENEMY_H
#include "rpgobj.h"
#include <QPainter>
#include <QImage>
#include <enemy_bullet.h>
#include <tank.h>
class Enemy:public Tank
{
public:
Enemy(){}
~Enemy(){}
void Move(int direction, int steps=1);
void Showup();
void Showdown();
void Showleft();
void Showright();
int Getdir(){return tankdir;}
Enemy_bullet get_bullet(){
return e_myBullet;
}
void set_mybullet();
Enemy_bullet shoot(QPainter *painter);
private:
int tankdir;
Enemy_bullet e_myBullet;
};
#endif // ENEMY_H
<file_sep>/TankWarIII/enemy.cpp
#include "enemy.h"
#include "world.h"
#include <QPainter>
#include <QApplication>
#include <iostream>
using namespace std;
void Enemy::Move(int direction, int steps){
switch (direction){
case 1:
this->_pos_y -= steps;
this->_pos_y -= steps;
this->Showup();
tankdir=1;
break;
case 2:
this->_pos_y += steps;
this->_pos_y += steps;
this->Showdown();
tankdir=2;
break;
case 3:
this->_pos_x -= steps;
this->_pos_x -= steps;
this->Showleft();
tankdir=3;
break;
case 4:
this->_pos_x += steps;
this->_pos_x += steps;
this->Showright();
tankdir=4;
break;
}
}
void Enemy::Showup(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(128,256,64,64));
}
void Enemy::Showdown(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(128,384,64,64));
}
void Enemy::Showleft(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(128,448,64,64));
}
void Enemy::Showright(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(128,320,64,64));
}
Enemy_bullet Enemy::shoot(QPainter *painter){
this->set_mybullet();
Enemy_bullet new_bullet=this->get_bullet();
//painter->setPen(QPen(Qt::black,4));
new_bullet.show(painter);
return new_bullet;
}
void Enemy::set_mybullet(){
e_myBullet._speed=1*32;
e_myBullet._radius=8;
e_myBullet._x=((this->getPosX()+1)*32);
e_myBullet._y=((this->getPosY()+1)*32);//这个地方定义每辆坦克的子弹射出的初始位置
e_myBullet._direction=this->tankdir;
}
<file_sep>/TankWarIII/dialogthree.cpp
#include "dialogthree.h"
#include "ui_dialogthree.h"
DialogThree::DialogThree(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogThree)
{
ui->setupUi(this);
}
DialogThree::~DialogThree()
{
delete ui;
}
void DialogThree::on_pushButton_2_clicked()
{
myPlayer=new QMediaPlayer;
videoWidget=new QVideoWidget;
mainLayout=new QHBoxLayout(this);
myPlayer->setVideoOutput(videoWidget);
QPalette* palette = new QPalette();
palette->setBrush(QPalette::Background, Qt::black);
videoWidget->setPalette(*palette);
videoWidget->setAutoFillBackground(true);
delete palette;
// videoWidget->setAspectRatioMode(Qt::IgnoreAspectRatio);
myPlayer->setMedia(QUrl::fromLocalFile("C:\\Users\\asus\\Desktop\\TankWarIII\\endshow.avi"));
mainLayout->addWidget(videoWidget);
myPlayer->play();
}
<file_sep>/TankWarIII/dialogtwo.cpp
#include "dialogtwo.h"
#include "ui_dialogtwo.h"
DialogTwo::DialogTwo(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogTwo)
{
ui->setupUi(this);
}
DialogTwo::~DialogTwo()
{
delete ui;
}
void DialogTwo::on_pushButton_clicked()
{
emit ToLevelThree();
close();
}
void DialogTwo::on_pushButton_2_clicked()
{
emit display(0);
close();
}
<file_sep>/TankWarIII/helper.h
#ifndef HELPER_H
#define HELPER_H
#include "rpgobj.h"
#include <QPainter>
#include <QImage>
#include "tank.h"
class Helper: public Tank
{
public:
Helper(){}
~Helper(){}
void ShowUp();
void ShowDown();
void ShowLeft();
void ShowRight();
Player_Bullet shoot(QPainter *painter);
void set_mybullet();
Player_Bullet get_bullet();
private:
Player_Bullet my_bullet;
};
#endif // HELPER_H
<file_sep>/TankWarIII/player_bullet.cpp
#include "player_bullet.h"
#include <QPainter>
#include "QPen"
#include <iostream>
using namespace std;
int bullet_flag=0;
Player_Bullet::Player_Bullet(double radius,double x, double y,int direction,int speed): _radius(radius),_x(x),_y(y),_direction(direction),_speed(speed){
}
Player_Bullet::Player_Bullet(const Player_Bullet &player_bul):_radius(player_bul._radius), _x(player_bul._x),_y(player_bul._y),_direction(player_bul._direction),_speed(player_bul._speed){}
void Player_Bullet::show(QPainter *pa){
pa->setPen(QPen(Qt::black,4));
pa->setBrush(Qt::yellow);
pa->drawEllipse(_x,_y,_radius,_radius);
}
void Player_Bullet::set_speed(int speed){
_speed=speed;
}
void Player_Bullet::set_direction(int dire){
_direction=dire;
}
void Player_Bullet::set_radius(double radius){
_radius=radius;
}
void Player_Bullet::erase(){
//flag=1;
}
void Player_Bullet::move(int direction){
switch (direction) {
case 1:
this->_y-=(get_speed());
break;
case 2:
this->_y+=(get_speed());
break;
case 3:
this->_x-=(get_speed());
break;
case 4:
this->_x+=(get_speed());
default:
break;//使子弹改变位置的函数,其实体现了子弹的速度,或许想要增加子弹的威力的时候可以加快它的速度,那么就在这里面改
}
}
<file_sep>/TankWarIII/enemy_bullet.h
#ifndef ENEMY_BULLET
#define ENEMY_BULLET
#include <player_bullet.h>
class Enemy_bullet:public Player_Bullet{
friend class Enemy;
public:
Enemy_bullet(){_radius=0,_speed=0;_x=0;_y=0;_direction=0;}
void show(QPainter *pa);
int get_direction(){
return _direction;
}
int get_x(){return this->_x;}
int get_y(){return this->_y;}
void move(int direction);
private:
double _radius;
int _speed;
double _x;
double _y;
int _direction;
};
#endif // ENEMY_BULLET*/
<file_sep>/TankWarIII/widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "one.h"
#include "two.h"
#include "three.h"
#include "level.h"
#include "world.h"
#include "iostream"
#include "start.h"
#include <QStackedLayout>
#include <QPushButton>
#include <QVBoxLayout>
#include "dialogone.h"
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
//setFixedSize(400,300);
level =new Level;
setFixedSize(1024,992);
start = new Start;
one = new One;
two = new Two;
three = new Three;
world= new World;
//dlg1=new DialogOne;
stackLayout = new QStackedLayout;
stackLayout->addWidget(start);
stackLayout->addWidget(level);
stackLayout->addWidget(one);
stackLayout->addWidget(two);
stackLayout->addWidget(three);
//cout<<dlg1<<endl;
//cout<<&one->GetDialogOne()<<endl;
connect(&one->GetWorld(), &World::eatBoss, one, &One::LevelOneOver);
connect(&two->GetWorld(), &World::eatBoss, two, &Two::LevelTwoOver);
connect(world,&World::eatBoss,one,&One::LevelOneOver);
connect(world,&World::eatBoss,two,&Two::LevelTwoOver);
connect(&three->GetWorld(), &World::eatBoss, three, &Three::LevelThreeOver);
connect(start, &Start::display, stackLayout, &QStackedLayout::setCurrentIndex);//0
connect(level, &Level::display, stackLayout, &QStackedLayout::setCurrentIndex); //1
connect(one, &One::display, stackLayout, &QStackedLayout::setCurrentIndex); // 2
connect(two, &Two::display, stackLayout, &QStackedLayout::setCurrentIndex); // 3
connect(three, &Three::display, stackLayout, &QStackedLayout::setCurrentIndex); // 4
mainLayout = new QVBoxLayout;
mainLayout->addLayout(stackLayout);
setLayout(mainLayout);
}
Widget::~Widget()
{
}
<file_sep>/TankWarIII/dialogthree.h
#ifndef DIALOGTHREE_H
#define DIALOGTHREE_H
#include <QDialog>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QVideoWidget>
#include <QWidget>
#include <QVBoxLayout>
namespace Ui {
class DialogThree;
}
class DialogThree : public QDialog
{
Q_OBJECT
public:
explicit DialogThree(QWidget *parent = 0);
~DialogThree();
signals:
void display(int number);
private slots:
void on_pushButton_2_clicked();
private:
Ui::DialogThree *ui;
QMediaPlayer*myPlayer;
QHBoxLayout *mainLayout;
QVideoWidget *videow;
QVideoWidget*videoWidget;
};
#endif // DIALOGTHREE_H
<file_sep>/TankWarIII/start.cpp
#include "start.h"
#include "ui_start.h"
#include "QProcess"
Start::Start(QWidget *parent) :
QWidget(parent),
ui(new Ui::Start)
{
ui->setupUi(this);
setFixedSize(1000,800);
myPlayer=new QMediaPlayer;
videoWidget=new QVideoWidget;
mainLayout=new QHBoxLayout(this);
myPlayer->setVideoOutput(videoWidget);
/*QPalette* palette = new QPalette();
palette->setBrush(QPalette::Background, Qt::black);
videoWidget->setPalette(*palette);
videoWidget->setAutoFillBackground(true);
delete palette;*/
// videoWidget->setAspectRatioMode(Qt::IgnoreAspectRatio);
myPlayer->setMedia(QUrl::fromLocalFile("C:\\Users\\asus\\Desktop\\TankWarIII\\startshow.avi"));
mainLayout->addWidget(videoWidget);
myPlayer->play();
}
Start::~Start()
{
delete ui;
}
void Start::on_pushButton_clicked()
{
emit display(1);
QMediaPlaylist *playlist = new QMediaPlaylist;
playlist->setCurrentIndex(1);
QMediaPlayer *player = new QMediaPlayer;
player->setPlaylist(playlist);
player->setMedia(QUrl::fromLocalFile("C:\\Users\\asus\\Desktop\\TankWarIII\\back.mp3"));
player->setVolume(150);
player->play();
}
<file_sep>/TankWarIII/three.h
#ifndef THREE_H
#define THREE_H
#include <QWidget>
#include <QImage>
#include <QPainter>
#include<QKeyEvent>
#include "rpgobj.h"
#include "world.h"
#include<QTime>
#include<QTimer>
#include "dialogthree.h"
#include "dlglose3.h"
namespace Ui {
class Three;
}
class Three : public QWidget
{
Q_OBJECT
public:
explicit Three(QWidget *parent = 0);
~Three();
void paintEvent(QPaintEvent *e);
void keyPressEvent(QKeyEvent *);
const World &GetWorld();
signals:
void display(int number);
void AfterEat();
public slots:
void LevelThreeOver();
private slots:
void showDialogThree();
void showlose3();
protected slots:
void handle_Bullet();
void randomMove();
void handleenemy();
private:
Ui::Three *ui;
World _game;
QImage _pic;
DialogThree *dlg;
Dlglose3 *dlg3;
QTimer *timer,*timer1,*timer2;
};
#endif // THREE_H
<file_sep>/TankWarIII/tank.cpp
#include "tank.h"
#include "icon.h"
#include "world.h"
#include <iostream>
#include <QPainter>
#include <QApplication>
using namespace std;
int flag8=0;
Tank::Tank()
{
}
void Tank::set_mybullet(){
my_bullet._speed=1*32;
my_bullet._radius=8;
my_bullet._x=((this->getPosX()+1)*32);
my_bullet._y=((this->getPosY()+1)*32);//这个地方定义每辆坦克的子弹射出的初始位置
my_bullet._direction=tankdir;
}
void Tank::change_mybullet(){
flag8=1;
my_bullet._speed=2*32;
my_bullet._radius=12;
}
Player_Bullet Tank::get_bullet(){
return my_bullet;
}
Tank::~Tank()
{
}
void Tank::move(int direction, int steps){
switch (direction){
case 1:
this->_pos_y -= steps;
this->showup();
tankdir=1;
break;
case 2:
this->_pos_y += steps;
this->showdown();
tankdir=2;
break;
case 3:
this->_pos_x -= steps;
this->showleft();
tankdir=3;
break;
case 4:
this->_pos_x += steps;
this->showright();
tankdir=4;
break;
}
}
void Tank::showup(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(0,256,64,64));
}
void Tank::showdown(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(0,384,64,64));
}
void Tank::showleft(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(0,448,64,64));
}
void Tank::showright(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(0,320,64,64));
}
Player_Bullet Tank::shoot(QPainter *painter){
this->set_mybullet();
if(flag8==1) change_mybullet();
Player_Bullet new_bullet=my_bullet;
//painter->setPen(QPen(Qt::black,4));
new_bullet.show(painter);
return new_bullet;
}
<file_sep>/TankWarIII/one.h
#ifndef ONE_H
#define ONE_H
#include <QWidget>
#include <QImage>
#include <QPainter>
#include<QKeyEvent>
#include "rpgobj.h"
#include "world.h"
#include<QTime>
#include<QTimer>
#include "dialogone.h"
#include "dlglose1.h"
namespace Ui {
class One;
}
class One : public QWidget
{
Q_OBJECT
public:
explicit One(QWidget *parent = 0);
~One();
void paintEvent(QPaintEvent *e);
void keyPressEvent(QKeyEvent *);
const World &GetWorld();
//const DialogOne &GetDialogOne();
//DialogOne *dlg;
signals:
// void eatBoss();
void display(int number);
void AfterEat();
//void showDialogOne();
public slots:
void LevelOneOver();
private slots:
void showDialogOne();
void win1();
void showlose1();
protected slots:
void handle_Bullet();
void randomMove();
void handleenemy();
private:
Ui::One *ui;
World _game;
DialogOne *dlg;
Dlglose1 *dlg1;
QTimer *timer,*timer1,*timer2;
};
#endif // ONE_H
<file_sep>/TankWarIII/three.cpp
#include "three.h"
#include "ui_three.h"
int flag_three=0;
Three::Three(QWidget *parent) :
QWidget(parent),
ui(new Ui::Three)
{
ui->setupUi(this);
_game.initWorld("map3.txt");//TODO 应该是输入有效的地图文件
connect(this,&Three::AfterEat,this,&Three::showDialogThree);
dlg=new DialogThree(this);
connect(&this->GetWorld(),World::lose1,this,&Three::showlose3);
//connect(dlg,&DialogThree::ToLevelThree,this,&Two::win2);
//connect(dlg,&DialogThree::ToManu,this,&Three::ReturnManu);
timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(handle_Bullet()));//timeoutslot()为自定义槽
//时钟事件与handle_bullet函数绑定
timer->start(100);
timer->setInterval(100);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));//设置随机数种子*/
timer1 = new QTimer(this);
connect(timer1,SIGNAL(timeout()),this,SLOT(randomMove()));//timeoutslot()为自定义槽
//时钟事件与randomMove函数绑定
timer1->start(100);
timer1->setInterval(500);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
timer2 = new QTimer(this);
connect(timer2,SIGNAL(timeout()),this,SLOT(handleenemy()));
timer2->start(0);
timer2->setInterval(6000);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
}
Three::~Three()
{
delete ui;
}
void Three::LevelThreeOver()
{
//cout<<"WELL"<<endl;
//emit display(2);
emit AfterEat();
}
void Three::showDialogThree()
{
close();
dlg->show();
}
void Three::showlose3(){
close();
dlg3=new Dlglose3(this);
dlg3->show();
}
const World &Three::GetWorld()
{
return _game;
}
void Three::paintEvent(QPaintEvent *){
setFixedSize(1040,980);
QPainter *pa;
QPainter painter(this);
painter.drawPixmap(rect(),QPixmap(":/pic/map.jpg"));
pa = new QPainter();
pa->begin(this);
this->_game.show(pa);
//this->_pic.load(":/pic/life.png");
//pa->drawImage(0,0,this->_pic);
//pa->drawImage(32,0,this->_pic);
//pa->drawImage(64,0,this->_pic);
vector<Player_Bullet>::iterator it;
for(it=this->_game._bullets.begin();it!=this->_game._bullets.end();it++){
(*it).show(pa);
}
vector<Enemy_bullet>::iterator it1;
for(it1=this->_game.e_bullets.begin();it1!=this->_game.e_bullets.end();it1++){
(*it1).show(pa);
}
if(flag_three==1)
{
_game.handleEnemyBulletShow(pa);
}
pa->end();
delete pa;
}
void Three::keyPressEvent(QKeyEvent *e)
{
flag_three=0;
//direction = 1,2,3,4 for 上下左右
if(e->key() == Qt::Key_A)
{
this->_game.handleTankMove(3,1);
}
else if(e->key() == Qt::Key_D)
{
this->_game.handleTankMove(4,1);
}
else if(e->key() == Qt::Key_W)
{
this->_game.handleTankMove(1,1);
}
else if(e->key() == Qt::Key_S)
{
this->_game.handleTankMove(2,1);
}
//this->repaint();//repaint的作用是再调用一次paintEvent函数
if(e->key() ==Qt::Key_Space){
QPainter *pa;
pa = new QPainter();
pa->begin(this);
this->_game.handleBulletShow(pa);//利用空格键操纵使发射子弹
pa->end();
delete pa;
}
this->repaint();//repaint的作用是再调用一次paintEvent函数
}
void Three::handle_Bullet(){
_game.handleBulletMove();
_game.handleEnemyBulletMove();
flag_three=0;
this->repaint();
}
void Three::randomMove(){
flag_three=0;
this->_game.handleEnemyMove();
flag_three=1;
this->repaint();
}
void Three::handleenemy(){
flag_three=0;
_game.addenemy();
this->repaint();
}
<file_sep>/TankWarIII/level.h
#ifndef LEVEL_H
#define LEVEL_H
#include <QDialog>
namespace Ui {
class Level;
}
class Level : public QDialog
{
Q_OBJECT
public:
explicit Level(QWidget *parent = 0);
~Level();
signals:
void display(int number);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private:
Ui::Level *ui;
};
#endif // LEVEL_H
<file_sep>/TankWarIII/player_bullet.h
#ifndef PLAYER_BULLET_H
#define PLAYER_BULLET_H
#include "rpgobj.h"
#include "QMainWindow"
#include <QImage>
#include <QPainter>
class Player_Bullet/*public QMainWindow*/
{
public:
//explicit Player_Bullet(QWidget *parent=0);
//~Player_Bullet();
friend class Tank;
Player_Bullet(){_radius=0,_speed=0;_x=0;_y=0;_direction=0;}
//explicit Player_Bullet(QWidget *parent=0,const char *name=0);
Player_Bullet(double radius,double x,double y, int direction,int speed);
Player_Bullet(const Player_Bullet &player_bul);
void set_speed(int speed);
void set_direction(int dire);
void set_radius(double radius);
int get_speed(){return _speed;}
int get_direction(){return _direction;}
int get_x(){return this->_x;}
int get_y(){return this->_y;}
int get_radius(){return this->_radius;}
void erase();
void show(QPainter *pa);
void move(int direction);
void setposx(int x){
this->_x=x;
}
void setposy(int y){
this->_y=y;
}
private:
double _radius;
double _x;
double _y;
int _speed;
int _direction;
QImage _pic;
//QTimer *shoot_timer;
};
#endif // PLAYER_BULLET_H
<file_sep>/TankWarIII/level.cpp
#include "level.h"
#include "ui_level.h"
#include "QProcess"
Level::Level(QWidget *parent) :
QDialog(parent),
ui(new Ui::Level)
{
ui->setupUi(this);
}
Level::~Level()
{
delete ui;
}
void Level::on_pushButton_clicked()
{
emit display(2);
}
void Level::on_pushButton_2_clicked()
{
emit display(3);
}
void Level::on_pushButton_3_clicked()
{
emit display(4);
}
<file_sep>/TankWarIII/enemy_bullet.cpp
#include <enemy_bullet.h>
#include <QPainter>
#include "QPen"
#include <iostream>
using namespace std;
void Enemy_bullet::show(QPainter *pa){
pa->setPen(QPen(Qt::black,4));
pa->setBrush(Qt::red);
pa->drawEllipse(_x,_y,_radius,_radius);
}
void Enemy_bullet::move(int direction){
switch (direction) {
case 1:
this->_y-=(_speed);
break;
case 2:
this->_y+=(_speed);
break;
case 3:
this->_x-=(_speed);
break;
case 4:
this->_x+=(_speed);
default:
break;//使子弹改变位置的函数,其实体现了子弹的速度,或许想要增加子弹的威力的时候可以加快它的速度,那么就在这里面改
}
}
<file_sep>/TankWarIII/rpgobj.cpp
#include "rpgobj.h"
#include "QPainter.h"
#include <iostream>
void RPGObj::initObj(string type,string path)
{
//TODO 所支持的对象类型应定义为枚举
if (type.compare("wall")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = false;
}
else if (type.compare("brick")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = true;
}
else if (type.compare("tree")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = false;
}
else if (type.compare("clock")==0){
this->_coverable = false;
this->_eatable = true;
this->_shootable = false;
}
else if(type.compare("blood")==0){
this->_coverable = false;
this->_eatable = true;
this->_shootable = false;
}
else if(type.compare("stone")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = false;
}
else if(type.compare("magic")==0){
this->_coverable = false;
this->_eatable = true;
this->_shootable = false;
}
else if(type.compare("EnemyTank")==0){
this->_coverable = false;
this->_eatable = true;
this->_shootable = true;
this->_dieable=true;
}
else if(type.compare("boss")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = true;
}
else if(type.compare("playerTank")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = true;
}
else if(type.compare("2stone")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = false;
}
else if(type.compare("2brick")==0){
this->_coverable = false;
this->_eatable = true;
this->_shootable = true;
}
else if(type.compare("2fence")==0){
this->_coverable = true;
this->_eatable = false;
this->_shootable = false;
}
else if(type.compare("2wall")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = true;
}
else if(type.compare("3brick")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable =true;
}
else if(type.compare("3stone")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = false;
}
else if(type.compare("3stee")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = true;
}
else if(type.compare("dead")==0){
this->_coverable = false;
this->_eatable = false;
}
else if(type.compare("magicshot")==0){
this->_coverable = true;
this->_eatable = true;
}
else if(type.compare("life")==0){
this->_coverable = false;
this->_eatable = false;
}
else if(type.compare("HelpTank")==0){
this->_coverable = false;
this->_eatable = false;
this->_shootable = true;
}
else{
//TODO 应由专门的错误日志文件记录
cout<<"invalid ICON type."<<endl;
return;
}
QImage all;
this->_icon = ICON::findICON(type);
all.load(path.c_str());
this->_pic = all.copy(QRect(_icon.getSrcX()*ICON::GRID_SIZE, _icon.getSrcY()*ICON::GRID_SIZE, _icon.getWidth()*ICON::GRID_SIZE, _icon.getHeight()*ICON::GRID_SIZE));
}
void RPGObj::show(QPainter * pa){
int gSize = ICON::GRID_SIZE;
pa->drawImage(this->_pos_x*gSize,this->_pos_y*gSize,this->_pic);
}
void RPGObj::onErase(){
QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QUrl::fromLocalFile("C:\\Users\\asus\Desktop\\TankWarIII\\cannot.mp3"));
player->setVolume(150);
player->play();
}
<file_sep>/TankWarIII/dialogone.cpp
#include "dialogone.h"
#include "ui_dialogone.h"
#include "one.h"
#include "two.h"
#include "widget.h"
#include <QApplication>
#include "QProcess"
#include <QBitmap>
#include <QHBoxLayout>
DialogOne::DialogOne(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogOne)
{
ui->setupUi(this);
}
DialogOne::~DialogOne()
{
delete ui;
}
void DialogOne::on_pushButton_clicked()
{
emit ToLevelTwo();
close();
}
void DialogOne::on_pushButton_2_clicked()
{
emit display(0);
close();
}
<file_sep>/TankWarIII/helper.cpp
#include "helper.h"
#include "world.h"
#include <QPainter>
#include <QApplication>
#include <iostream>
#include "player_bullet.h"
using namespace std;
void Helper::set_mybullet(){
my_bullet.set_speed(32);
my_bullet.set_radius(8.0);
my_bullet.setposx((this->getPosX()+1)*32);
my_bullet.setposy((this->getPosY()+1)*32);//这个地方定义每辆坦克的子弹射出的初始位置
my_bullet.set_direction(2);
}
Player_Bullet Helper::get_bullet(){
return my_bullet;
}
void Helper::ShowUp(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(256,256,64,64));
}
void Helper::ShowDown(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(256,384,64,64));
}
void Helper::ShowLeft(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(256,448,64,64));
}
void Helper::ShowRight(){
this->_pic.load(":/pic/tank.png");
_pic=_pic.copy(QRect(256,320,64,64));
}
Player_Bullet Helper::shoot(QPainter *painter){
this->set_mybullet();
Player_Bullet new_bullet=this->get_bullet();
//painter->setPen(QPen(Qt::black,4));
new_bullet.show(painter);
return new_bullet;
}
<file_sep>/TankWarIII/dlglose2.h
#ifndef DLGLOSE2_H
#define DLGLOSE2_H
#include <QDialog>
namespace Ui {
class Dlglose2;
}
class Dlglose2 : public QDialog
{
Q_OBJECT
public:
explicit Dlglose2(QWidget *parent = 0);
~Dlglose2();
signals:
void display(int number);
private slots:
void on_pushButton_clicked();
private:
Ui::Dlglose2 *ui;
};
#endif // DLGLOSE2_H
<file_sep>/TankWarIII/dialogtwo.h
#ifndef DIALOGTWO_H
#define DIALOGTWO_H
#include <QDialog>
namespace Ui {
class DialogTwo;
}
class DialogTwo : public QDialog
{
Q_OBJECT
public:
explicit DialogTwo(QWidget *parent = 0);
~DialogTwo();
signals:
void display(int number);
void ToLevelThree();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::DialogTwo *ui;
};
#endif // DIALOGTWO_H
<file_sep>/world.cpp
#include "world.h"
#include "icon.h"
#include "string"
#include "rpgobj.h"
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int flag=0;
void World::initWorld(string mapFile){
//TODO 下面这部分逻辑应该是读入地图文件,生成地图上的对象
//player 5 5
this->_tank.initObj("playerTank","C:\\Users\\asus\\Desktop\\TankWarI\\tank.png");
this->_tank.setPosX(5);
this->_tank.setPosY(5);
RPGObj obj1;
ifstream inf;
inf.open(mapFile.c_str());
string a,p;
int b,c;
while(inf >> a){
inf >>p;
inf >> b;
inf >> c;
obj1.initObj(a,p);
obj1.setPosX(b);
obj1.setPosY(c);
this->_objs.push_back(obj1);
}
}
void World::show(QPainter * painter){
vector<RPGObj>::iterator it;
for(it=this->_objs.begin();it!=this->_objs.end();it++){
(*it).show(painter);
}
if(flag==0) this->_tank.show(painter);
}
void World::handleTankMove(int direction, int steps){
this->_tank.move(direction, steps);
this->act(direction, steps);
}
void World::act(int direction, int steps){
vector<RPGObj>::iterator it;
for(it = this->_objs.begin(); it != this->_objs.end(); it++){
flag=0;
if(
this->_tank.getPosX()==(*it).getPosX() &&
this->_tank.getPosY()== ((*it).getPosY()-1)
)
{
if((*it).canEat() == true)
{
this->_objs.erase(it);
}
if((*it).canCover() == false)
{
this->_tank.move(-1*direction, steps);
break;
}
if((*it).canCover()==true)
{
flag=1;
}
}
if(it == this->_objs.end()) {
break;
}
}
}
<file_sep>/TankWarIII/tank.h
#ifndef TANK_H
#define TANK_H
#include "rpgobj.h"
#include "player_bullet.h"
#include <QImage>
class Tank:public RPGObj
{
public:
public:
Tank();
~Tank();
void move(int direction, int steps=1);
void showup();
void showdown();
void showleft();
void showright();
int Getdir(){return tankdir;}
Player_Bullet shoot(QPainter *painter);
void set_mybullet();
void change_mybullet();
Player_Bullet get_bullet();
private:
Player_Bullet my_bullet;
int tankdir;
};
#endif // TANK_H
<file_sep>/TankWarIII/dlglose1.cpp
#include "dlglose1.h"
#include "ui_dlglose1.h"
#include "QProcess"
Dlglose1::Dlglose1(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dlglose1)
{
ui->setupUi(this);
}
Dlglose1::~Dlglose1()
{
delete ui;
}
void Dlglose1::on_pushButton_clicked()
{
close();
qApp->closeAllWindows();
QProcess::startDetached(qApp->applicationFilePath(), QStringList());
}
<file_sep>/TankWarIII/one.cpp
#include "one.h"
#include "ui_one.h"
#include "two.h"
#include "widget.h"
#include <QApplication>
#include <QPainter>
#include <QBitmap>
#include <QHBoxLayout>
#include "iostream"
#include "dialogone.h"
#include "QProcess"
int flag_one=0;
using namespace std;
One::One(QWidget *parent) :
QWidget(parent),
ui(new Ui::One)
{
ui->setupUi(this);
_game.initWorld("map1.txt");//TODO 应该是输入有效的地图文件
connect(this,&One::AfterEat,this,&One::showDialogOne);
dlg=new DialogOne(this);
connect(dlg,&DialogOne::ToLevelTwo,this,&One::win1);
//connect(dlg,&DialogOne::ToManu,this,&One::ReturnManu);
connect(&this->GetWorld(),World::lose1,this,&One::showlose1);
//connect(ui->showChildButton,&QPushButton::clicked,this,&One::showDialogOne);
timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(handle_Bullet()));//timeoutslot()为自定义槽
//时钟事件与handle_bullet函数绑定
timer->start(100);
timer->setInterval(100);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));//设置随机数种子*/
timer1 = new QTimer(this);
connect(timer1,SIGNAL(timeout()),this,SLOT(randomMove()));//timeoutslot()为自定义槽
//时钟事件与randomMove函数绑定
timer1->start(100);
timer1->setInterval(1000);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
timer2 = new QTimer(this);
connect(timer2,SIGNAL(timeout()),this,SLOT(handleenemy()));
timer2->start(0);
timer2->setInterval(6000);
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
}
One::~One()
{
delete ui;
}
void One::LevelOneOver()
{
//cout<<"WELL"<<endl;
//emit display(2);
emit AfterEat();
}
void One::win1()
{
qApp->closeAllWindows();
QProcess::startDetached(qApp->applicationFilePath(), QStringList());
emit display(3);
}
void One::showlose1()
{
close();
dlg1=new Dlglose1(this);
dlg1->show();
}
void One::showDialogOne()
{
close();
dlg->show();
}
const World &One::GetWorld()
{
return _game;
}
void One::paintEvent(QPaintEvent *){
setFixedSize(1040,980);
QPainter *pa;
QPainter painter(this);
painter.drawPixmap(rect(),QPixmap(":/pic/map006.png"));
pa = new QPainter();
pa->begin(this);
this->_game.show(pa);
vector<Player_Bullet>::iterator it;
for(it=this->_game._bullets.begin();it!=this->_game._bullets.end();it++){
(*it).show(pa);
}
vector<Enemy_bullet>::iterator it1;
for(it1=this->_game.e_bullets.begin();it1!=this->_game.e_bullets.end();it1++){
(*it1).show(pa);
}
if(flag_one==1)
{
_game.handleEnemyBulletShow(pa);
}
pa->end();
delete pa;
}
void One::keyPressEvent(QKeyEvent *e)
{
flag_one=0;
//direction = 1,2,3,4 for 上下左右
if(e->key() == Qt::Key_A)
{
this->_game.handleTankMove(3,1);
}
else if(e->key() == Qt::Key_D)
{
this->_game.handleTankMove(4,1);
}
else if(e->key() == Qt::Key_W)
{
this->_game.handleTankMove(1,1);
}
else if(e->key() == Qt::Key_S)
{
this->_game.handleTankMove(2,1);
}
//this->repaint();//repaint的作用是再调用一次paintEvent函数
if(e->key() ==Qt::Key_Space){
QPainter *pa;
pa = new QPainter();
pa->begin(this);
this->_game.handleBulletShow(pa);//利用空格键操纵使发射子弹
pa->end();
delete pa;
}
this->repaint();//repaint的作用是再调用一次paintEvent函数
}
void One::handle_Bullet(){
_game.handleBulletMove();
_game.handleEnemyBulletMove();
flag_one=0;
this->repaint();
}
void One::randomMove(){
flag_one=0;
this->_game.handleEnemyMove();
flag_one=1;
this->repaint();
}
void One::handleenemy(){
flag_one=0;
_game.addenemy();
//flag_one=1;
this->repaint();
}
<file_sep>/README.md
# project-big-work
<file_sep>/TankWarIII/dlglose3.cpp
#include "dlglose3.h"
#include "ui_dlglose3.h"
Dlglose3::Dlglose3(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dlglose3)
{
ui->setupUi(this);
}
Dlglose3::~Dlglose3()
{
delete ui;
}
void Dlglose3::on_pushButton_clicked()
{
close();
emit display(1);
}
<file_sep>/TankWarIII/dlglose2.cpp
#include "dlglose2.h"
#include "ui_dlglose2.h"
Dlglose2::Dlglose2(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dlglose2)
{
ui->setupUi(this);
}
Dlglose2::~Dlglose2()
{
delete ui;
}
void Dlglose2::on_pushButton_clicked()
{
close();
emit display(1);
}
<file_sep>/TankWarIII/start.h
#ifndef START_H
#define START_H
#include <QWidget>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QVideoWidget>
#include <QWidget>
#include <QVBoxLayout>
#include <QPainter>
#include <QImage>
class One;
namespace Ui {
class Start;
}
class Start : public QWidget
{
Q_OBJECT
public:
explicit Start(QWidget *parent = 0);
~Start();
signals:
void display(int number);
private slots:
void on_pushButton_clicked();
private:
Ui::Start *ui;
One *one;
QMediaPlayer*myPlayer;
QHBoxLayout *mainLayout;
QVideoWidget *videow;
QVideoWidget*videoWidget;
};
#endif // START_H
<file_sep>/TankWarIII/widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Level;
class Start;
class One;
class Two;
class Three;
class QStackedLayout;
class QVBoxLayout;
class World;
//class DialogOne;
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Level *level;
One *one;
Two *two;
Three *three;
World *world;
Start *start;
QStackedLayout *stackLayout;
QVBoxLayout *mainLayout;
//DialogOne *dlg1;
};
#endif // WIDGET_H
<file_sep>/TankWarIII/world.h
#ifndef WORLD_H
#define WORLD_H
#include <QWidget>
#include "rpgobj.h"
#include <vector>
#include <string>
#include <QPainter>
#include "tank.h"
#include "widget.h"
#include "enemy.h"
#include "helper.h"
#include "enemy_bullet.h"
#include <QObject>
namespace Ui {
class World;
}
class World : public QWidget
{
Q_OBJECT
friend class One;
friend class Two;
friend class Three;
public:
explicit World(QWidget *parent = 0);
~World();
void act(int direction, int steps);
void bullet_act1();
void bullet_act2();
void bullet_act3();
void bullet_act4();
void e_bullet_act1();
void e_bullet_act2();
void e_bullet_act3();
void e_bullet_act4();
void initWorld(string mapFile);
void Act(int direction,int steps);
void Act1(int direction,int steps);
void show(QPainter * painter);
//显示游戏世界所有对象
void addenemy();
void handleTankMove(int direction, int steps);
void handleBulletMove();
void handleBulletShow(QPainter *painter);
void handleEnemyMove();
void handleEnemyBulletShow(QPainter *painter);
void handleEnemyBulletMove();
void addhelper();
void addlife();
void deletelife();
signals:
void eatBoss();
void lose1();
private:
vector<RPGObj> _objs;
Tank _tank;
Ui::World *ui;
vector<Enemy> _enemy;
vector<Player_Bullet> _bullets;
vector<Enemy_bullet> e_bullets;
vector<Helper> _helper;
};
#endif // WORLD_H
<file_sep>/TankWarIII/dlglose1.h
#ifndef DLGLOSE1_H
#define DLGLOSE1_H
#include <QDialog>
namespace Ui {
class Dlglose1;
}
class Dlglose1 : public QDialog
{
Q_OBJECT
public:
explicit Dlglose1(QWidget *parent = 0);
~Dlglose1();
signals:
void display(int number);
private slots:
void on_pushButton_clicked();
private:
Ui::Dlglose1 *ui;
};
#endif // DLGLOSE1_H
<file_sep>/TankWarIII/two.h
#ifndef TWO_H
#define TWO_H
#include <QWidget>
#include <QImage>
#include <QPainter>
#include<QKeyEvent>
#include "rpgobj.h"
#include "world.h"
#include<QTime>
#include<QTimer>
#include "dialogtwo.h"
#include "dlglose2.h"
namespace Ui {
class Two;
}
class Two : public QWidget
{
Q_OBJECT
public:
explicit Two(QWidget *parent = 0);
~Two();
void paintEvent(QPaintEvent *e);
void keyPressEvent(QKeyEvent *);
const World &GetWorld();
signals:
void display(int number);
void AfterEat();
public slots:
void LevelTwoOver();
private slots:
void showDialogTwo();
void win2();
void showlose2();
protected slots:
void handle_Bullet();
void randomMove();
void handleenemy();
private:
Ui::Two *ui;
World _game;
QImage _pic;
DialogTwo *dlg;
Dlglose2 *dlg2;
QTimer *timer3,*timer4,*timer5;
};
#endif // TWO_H
<file_sep>/TankWarIII/dialogone.h
#ifndef DIALOGONE_H
#define DIALOGONE_H
#include <QDialog>
namespace Ui {
class DialogOne;
}
class DialogOne : public QDialog
{
Q_OBJECT
public:
explicit DialogOne(QWidget *parent = 0);
~DialogOne();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
signals:
void display(int number);
void ToLevelTwo();
private:
Ui::DialogOne *ui;
};
#endif // DIALOGONE_H
| c2bd6d9e39cc58a5b943734aab5539d5ce2e7ddb | [
"Markdown",
"C++"
] | 40 | C++ | Shetin/project-big-work | e55414ec3852996b7eb82cef2f25afb16937fdf9 | dc6a12a4f7cf20badc37a9648817eac471480abe |
refs/heads/master | <repo_name>TrentSterling/horse-protect<file_sep>/src/main/java/net/chiisana/horseprotect/listener/EntityEventListener.java
package net.chiisana.horseprotect.listener;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.*;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
public class EntityEventListener implements Listener
{
// TODO: SEARCH AND REPLACE WOLF -> HORSE; Wolf -> Horse
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event)
{
if (event.getEntity().getType() != EntityType.WOLF)
{
// Break out if we're not dealing with a horse
return;
}
Wolf horse = (Wolf)event.getEntity();
if (!horse.isTamed()) {
// Break out if we're not dealing with a tamed horse
return;
}
Player owner;
if (horse.getOwner() instanceof Player)
{
// Simple case, we have an owner
owner = (Player)horse.getOwner();
} else if (horse.getOwner() instanceof OfflinePlayer) {
// More tricky, for now, we'll just try to get a Player, if we can't get it, we can't guard it (yet)
if (((OfflinePlayer) horse.getOwner()).getPlayer() != null)
{
owner = ((OfflinePlayer) horse.getOwner()).getPlayer();
} else {
return;
}
} else {
// Human entity, NPC owned, we don't care at this point
return;
}
if (!((event.getDamager() instanceof Player) || (event.getDamager() instanceof Projectile)))
{
// Break out if we're not dealing with a player damage source or projectile damage source, no invincible horses!
return;
}
Player attacker;
if (event.getDamager() instanceof Player)
{
attacker = (Player)event.getDamager();
_helperCheckPermission(event, owner, horse, attacker);
return;
}
if (event.getDamager() instanceof Projectile)
{
Projectile projectile = (Projectile)event.getDamager();
if (projectile.getShooter() == null) {
// Came from a dispenser, we should check whether or not to allow this
_helperCheckPermission(event, owner, horse, null);
return;
}
if (!(projectile.getShooter() instanceof Player))
{
// Other mobs shot a projectile at it
return;
}
attacker = (Player) projectile.getShooter();
_helperCheckPermission(event, owner, horse, attacker);
return;
}
}
private void _helperCheckPermission(EntityDamageByEntityEvent event, Player owner, Wolf horse, Player attacker)
{
if (attacker == null)
{
if (owner.hasPermission("horseprotect.protecthorses"))
{
event.setCancelled(true);
}
return;
}
if (attacker.getName().equals(owner.getName()))
{
// Owner killing own horse, allow it
return;
} else {
// Another player attacking horse
if (owner.hasPermission("horseprotect.protecthorses"))
{
event.setCancelled(true);
}
if (owner.hasPermission("horseprotect.reflectdamages"))
{
// Reflect the damage
int damage = event.getDamage();
attacker.damage(damage, horse);
}
return;
}
}
}
<file_sep>/README.md
horse-protect
=============
A simple plugin to make sure other people don't kill your horses... | 460762db1239a78e538c946b5f49041984513042 | [
"Markdown",
"Java"
] | 2 | Java | TrentSterling/horse-protect | 7808c060481cf428e0ee00aa276ca7911f72c268 | 0d13d1959cd49eb00baf1c27fbdcaecbf900166f |
refs/heads/master | <repo_name>Falcinspire/ScriptBlock<file_sep>/compiler/back/values/valuelibrary.go
package values
type ValueLibrary struct {
Exported ValueBook
Internal ValueBook
}
func NewValueLibrary() *ValueLibrary {
return &ValueLibrary{NewValueBook(), NewValueBook()}
}
func InsertValueTable(module, unit string, table ValueTable, book ValueBook) {
_, exists := book[module]
if !exists {
book[module] = NewValueUnitBook()
}
book[module][unit] = table
}
func LookupValueTable(module, unit string, book ValueBook) ValueTable {
return book[module][unit]
}
type ValueBook map[string]ValueUnitBook
func NewValueBook() ValueBook {
return make(ValueBook)
}
type ValueUnitBook map[string]ValueTable
func NewValueUnitBook() ValueUnitBook {
return make(ValueUnitBook)
}
<file_sep>/compiler/front/imports/importsbook.go
package imports
import "github.com/falcinspire/scriptblock/compiler/ast/location"
type ImportBook map[string]ImportUnitBook
func NewImportBook() ImportBook {
return make(ImportBook)
}
func LookupImportList(module string, unit string, book ImportBook) ImportList {
return book[module][unit]
}
func InsertImportList(module string, unit string, list ImportList, book ImportBook) {
_, exists := book[module]
if !exists {
book[module] = make(ImportUnitBook)
}
book[module][unit] = list
}
type ImportUnitBook map[string]ImportList
type ImportList []*location.UnitLocation
<file_sep>/compiler/back/tags/locationlist.go
package tags
type LocationList []string
<file_sep>/compiler/back/dumper/dumper.go
package dumper
import (
"fmt"
"os"
"path/filepath"
"github.com/sirupsen/logrus"
)
func DumpFunction(module string, unit string, name string, lines []string, output string) {
path := fmt.Sprintf("%s/%s/functions/%s/%s.mcfunction", output, module, unit, name)
logrus.WithFields(logrus.Fields{
"path": path,
"unit": unit,
"lines": len(lines),
}).Info("dumping function")
os.MkdirAll(filepath.Dir(path), os.ModePerm)
file, error := os.Create(path)
if error != nil {
panic(error)
}
defer file.Close()
for _, line := range lines {
file.WriteString(line)
file.WriteString("\n")
}
}
<file_sep>/compiler/front/resolver/functionframe.go
package resolver
import "github.com/falcinspire/scriptblock/compiler/ast"
type FunctionFrame struct {
Parameters []string
Body []ast.Statement
}
<file_sep>/compiler/ast/meta.go
package ast
type Metadata struct {
StartLine, StartColumn int
EndLine, EndColumn int
Text string
}
<file_sep>/compiler/front/imports/import_simple.go
package imports
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
)
func TakeImports(astree *ast.Unit) []*location.UnitLocation {
imports := make([]*location.UnitLocation, len(astree.ImportLines))
for i, importLine := range astree.ImportLines {
imports[i] = location.NewUnitLocation(importLine.Module, importLine.Unit)
}
return imports
}
<file_sep>/home/config.go
package home
import (
"io/ioutil"
"path/filepath"
"gopkg.in/yaml.v2"
)
type ModuleData struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Author string `yaml:"author"`
Dependencies []Dependency `yaml:"dependencies"`
}
type Dependency struct {
Location string `yaml:"location"`
Version string `yaml:"version"`
Name string `yaml:"name"`
}
func ReadModuleData(modulepath string) *ModuleData {
filePath := filepath.Join(modulepath, "module.yaml")
return ReadModuleFile(filePath)
}
func ReadModuleFile(path string) *ModuleData {
data := ModuleData{}
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
yaml.Unmarshal(file, &data)
return &data
}
func WriteModuleData(data *ModuleData, path string) {
bytes, _ := yaml.Marshal(data)
ioutil.WriteFile(path, bytes, 0644)
}
<file_sep>/compiler/back/evaluator/reduce_simple.go
package evaluator
import (
"fmt"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
"github.com/falcinspire/scriptblock/compiler/back/values"
)
func ReduceIdentifier(identifier *ast.IdentifierExpression, data *EvaluateData) values.Value {
visitor := NewReduceExpressionVisitor(data)
visitor.VisitIdentifier(identifier)
return visitor.Result
}
func ReduceExpression(expression ast.Expression, data *EvaluateData) values.Value {
return NewReduceExpressionVisitor(data).QuickVisitExpression(expression)
}
func ReduceArgumentList(arguments []ast.Expression, data *EvaluateData) []values.Value {
argumentValues := make([]values.Value, len(arguments))
expressionVisitor := NewReduceExpressionVisitor(data)
for i, argument := range arguments {
argumentValues[i] = expressionVisitor.QuickVisitExpression(argument)
}
return argumentValues
}
func GetValueForAddress(address *symbol.AddressBox, data *EvaluateData) values.Value {
switch address.Type {
case symbol.UNIT:
unitAddress := address.Data.(*symbol.UnitAddress)
if unitAddress.Module == data.Location.Module && unitAddress.Unit == data.Location.Unit {
// this unit
selfExported := values.LookupValueTable(unitAddress.Module, unitAddress.Unit, data.ValueLibrary.Exported)
result, exists := values.LookupUnitValue(unitAddress.Module, unitAddress.Unit, unitAddress.Name, selfExported)
if exists {
return result
}
selfInternal := values.LookupValueTable(unitAddress.Module, unitAddress.Unit, data.ValueLibrary.Internal)
internalResult, exists := values.LookupUnitValue(unitAddress.Module, unitAddress.Unit, unitAddress.Name, selfInternal)
if exists {
return internalResult
}
panic(fmt.Errorf("Could not get value for address %s", unitAddress))
} else {
// imported unit
table := values.LookupValueTable(unitAddress.Module, unitAddress.Unit, data.ValueLibrary.Exported)
result, exists := values.LookupUnitValue(unitAddress.Module, unitAddress.Unit, unitAddress.Name, table)
if !exists {
panic(fmt.Errorf("Could not get value for address %s", unitAddress))
}
return result
}
case symbol.PARAMETER:
paramAddress := address.Data.(*symbol.ParameterAddress)
result, exists := values.LookupParameterValue(paramAddress.Name, data.LocalValues)
if !exists {
panic(fmt.Errorf("Could not get value for address %s", paramAddress))
}
return result
case symbol.CAPTURE:
captureAddress := address.Data.(*symbol.CaptureAddress)
result, exists := values.LookupCaptureValue(captureAddress.Name, data.LocalValues)
if !exists {
panic(fmt.Errorf("Could not get value for address %s", captureAddress))
}
return result
}
panic(fmt.Errorf("Fell out of switch? %s", address))
}
<file_sep>/compiler/back/evaluator/callframe.go
package evaluator
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/falcinspire/scriptblock/compiler/ast/location"
)
type CallFrame struct {
// this function
Location *location.UnitLocation
Name string
// which has internals
Body []ast.Statement
Parameters []string
Closes []string
// with these arguments
Arguments []values.Value
Captures []values.Value
}
<file_sep>/compiler/back/evaluator/callstack.go
package evaluator
// TODO need function location
type CallStack struct {
stack []string
}
func PushCallStack(function string, stack *CallStack) {
stack.stack = append(stack.stack, function)
}
func PopCallStack(stack *CallStack) {
stack.stack = stack.stack[0 : len(stack.stack)-1]
}
func ListCallStack(stack *CallStack) []string {
return stack.stack
}
func NewCallStack() *CallStack {
return &CallStack{[]string{}}
}
<file_sep>/compiler/ast/location/unitpath.go
package location
// func InformalPath(location *UnitLocation) string {
// return fmt.Sprintf("%s:%s:%s", location.Location, location.Module, location.Unit)
// }
// func LocationFromInformal(path string) *UnitLocation {
// data := strings.Split(path, ":")
// return NewUnitLocation(data[0], data[1], data[2])
// }
<file_sep>/compiler/back/evaluator/README.txt
Want:
value of <expression>:
expression -(reduce)-> value -(rawify)-> string
invoke <expression>:
expression -(reduce)->value -(invoke)-> []string<file_sep>/downloader/downloader.go
package downloader
import (
"log"
"os"
"os/exec"
"path/filepath"
"github.com/sirupsen/logrus"
"github.com/falcinspire/scriptblock/environment"
"github.com/falcinspire/scriptblock/home"
)
// BUG: works first time, but cannot be run twice on same input without failing
// git clone probably fails bc folder is not empty
func Download(data environment.ModuleDescription) { //TODO maybe make ModuleDescription a pointer
home.MakeModulePath(data)
logrus.WithFields(logrus.Fields{
"from": "https://" + data.Location,
}).Info("Cloning")
cmd := exec.Command("git", "clone", "https://"+data.Location, data.Version) //TODO maybe include this in input? or filter it out?
cmd.Dir = environment.GetAbreviatedModulePath(data)
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
if data.Version != "latest" {
versionCmd := exec.Command("git", "checkout", "tags/"+data.Version)
versionCmd.Dir = environment.GetModulePath(data)
versionErr := versionCmd.Run()
if versionErr != nil {
log.Fatal(err)
}
}
gitHome := filepath.Join(environment.GetModulePath(data), ".git")
logrus.WithFields(logrus.Fields{
"folder": gitHome,
}).Info("Deleting git home")
os.RemoveAll(gitHome)
}
<file_sep>/cmd/scriptblock-config/main.go
package main
import (
"fmt"
"os"
"github.com/falcinspire/scriptblock/environment"
"github.com/falcinspire/scriptblock/home"
)
func main() {
location := os.Args[1]
version := os.Args[2]
data := home.GetModuleConfig(environment.ModuleDescription{
Location: location,
Version: version,
})
fmt.Println(data.Name)
fmt.Println(data.Description)
fmt.Println(data.Author)
fmt.Println(data.Dependencies)
}
<file_sep>/compiler/back/evaluator/evaluate_data.go
package evaluator
import (
"github.com/falcinspire/scriptblock/compiler/back/addressbook"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/falcinspire/scriptblock/compiler/ast/location"
)
type EvaluateData struct {
Location *location.UnitLocation
LocalValues *values.LocalValueTable
ValueLibrary *values.ValueLibrary
AddressBook addressbook.AddressBook
CallStack *CallStack
LoopInject *LoopInject
ModulePath string
Output string
}
<file_sep>/compiler/dependency/dependency.go
package dependency
type DependencyGraph struct {
Nodes [][]int
}
func NewDependencyGraph() *DependencyGraph {
return &DependencyGraph{make([][]int, 0)}
}
func AddVertex(graph *DependencyGraph) int {
graph.Nodes = append(graph.Nodes, make([]int, 0))
return len(graph.Nodes) - 1
}
func AddDependency(src, depends int, graph *DependencyGraph) {
graph.Nodes[src] = append(graph.Nodes[src], depends)
}
type VisitState int
const (
UNSEEN = 0
RESOLVING = 1
RESOLVED = 2
)
func MakeDependencyOrder(graph *DependencyGraph) (order []int, circular bool) {
order = make([]int, 0)
used := make([]VisitState, len(graph.Nodes))
for i := 0; i < len(graph.Nodes); i++ {
order, circular = dependencyRecursive(i, order, used, graph)
if circular {
order = make([]int, 0)
return
}
}
return
}
func dependencyRecursive(src int, order []int, used []VisitState, graph *DependencyGraph) (orderNew []int, circular bool) {
if used[src] == RESOLVED {
return order, false
}
used[src] = RESOLVING
for _, dependsOn := range graph.Nodes[src] {
if used[dependsOn] == UNSEEN {
order, circular = dependencyRecursive(dependsOn, order, used, graph)
if circular {
order = make([]int, 0)
return
}
} else if used[dependsOn] == RESOLVING {
order = make([]int, 0)
circular = true
return
}
}
order = append(order, src)
used[src] = RESOLVED
return order, false
}
<file_sep>/compiler/front/pretty/resolved.go
package pretty
type ResolvedUnit struct {
Imports []*ResolvedImport
Definitions []ResolvedTopDefinition
}
type ResolvedImport struct {
Module string
Unit string
}
type ResolvedTopDefinition interface{}
type ResolvedConstantDefinition struct {
Type string
Name string
Internal bool
Documentation string
Value ResolvedExpression
}
type ResolvedFunctionDefinition struct {
Type string
Name string
Internal bool
Documentation string
Body []ResolvedStatement
}
type ResolvedTemplateDefinition struct {
Type string
Name string
Internal bool
Documentation string
Parameters []string
Captures []string
Body []ResolvedStatement
}
type ResolvedStatement interface{}
type ResolvedFunctionCall struct {
Type string
Callee ResolvedExpression
Arguments []ResolvedExpression
Trailing *TrailingFunction
}
type TrailingFunction struct {
Type string
Parameters []string
Body []ResolvedStatement
}
type ResolvedNativeCall struct {
Type string
Arguments []ResolvedExpression
}
type ResolvedExpression interface{}
type ResolvedIdentifierExpression struct {
Type string
Address ResolvedAddress
}
type ResolvedOperatorExpression struct {
Operator string
Left, Right ResolvedExpression
}
type ResolvedNumberExpression struct {
Type string
Value float64
}
type ResolvedStringExpression struct {
Type string
Value string
}
type ResolvedAddress interface{}
type ResolvedUnitAddress struct {
Module, Unit, Name string
}
type ResolvedParameterAddress struct {
FunctorDepth int
ParameterName string
}
type ResolvedCaptureAddress struct {
CaptureName string
}
<file_sep>/compiler/ast/functions.go
package ast
// FunctionDefinition is a node representing a top level definition of a function
type FunctionDefinition struct {
Name string
Body []Statement
Internal bool
Tag Tag
Documentation string
Metadata *Metadata
}
// NewFunctionDefinition is a constructor for FunctionDefinition
func NewFunctionDefinition(name string, body []Statement, internal bool, tag Tag, docs string, metadata *Metadata) *FunctionDefinition {
return &FunctionDefinition{name, body, internal, tag, docs, metadata}
}
// Accept runs the double dispatch for the visitor
func (definition *FunctionDefinition) Accept(visitor TopVisitor) {
visitor.VisitFunctionDefinition(definition)
}
// FunctionShortcutDefinition is a node representing a top level definition of a function shortcut
type FunctionShortcutDefinition struct {
// shortcut name
Name string
// shortcut for
FunctionCall *FunctionCall
Internal bool
Tag Tag
Documentation string
Metadata *Metadata
}
// NewFunctionShortcutDefinition is a constructor for FunctionShortcutDefinition
func NewFunctionShortcutDefinition(name string, functionCall *FunctionCall, internal bool, tag Tag, docs string, metadata *Metadata) *FunctionShortcutDefinition {
return &FunctionShortcutDefinition{name, functionCall, internal, tag, docs, metadata}
}
// Accept runs the double dispatch for the visitor
func (definition *FunctionShortcutDefinition) Accept(visitor TopVisitor) {
visitor.VisitFunctionShortcutDefinition(definition)
}
// TemplateDefinition is a node representing an (injected) top level definition of a closure
type TemplateDefinition struct {
Name string
Parameters []string
Capture []string
Body []Statement
Internal bool
Documentation string
Metadata *Metadata
}
// NewTemplateDefinition is a constructor for TemplateDefinition
func NewTemplateDefinition(name string, parameters []string, capture []string, body []Statement, internal bool, docs string, metadata *Metadata) *TemplateDefinition {
return &TemplateDefinition{name, parameters, capture, body, internal, docs, metadata}
}
// Accept runs the double dispatch for the visitor
func (definition *TemplateDefinition) Accept(visitor TopVisitor) {
visitor.VisitTemplateDefinition(definition)
}
// Tag is a node representing the tag for a function
type Tag struct {
Namespace string
Identity string
Metadata *Metadata
}
<file_sep>/compiler/front/parser/.antlr/ScriptBlockLexer.java
// Generated from c:\Falcinspire\go\src\github.com\falcinspire\scriptblock\front\parser/ScriptBlockLexer.g4 by ANTLR 4.7.1
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.*;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class ScriptBlockLexer extends Lexer {
static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
WS=1, COMMENT=2, DOC_START=3, DOC_END=4, DOC_LINE=5, NEWLINES=6, FUNCTION=7,
TEMPLATE=8, NATIVE=9, CONSTANT=10, RUN=11, RAISE=12, DELAY=13, IMPORT=14,
INTERNAL=15, ARROW=16, OPAREN=17, CPAREN=18, OCURLY=19, CCURLY=20, OSQUARE=21,
CSQUARE=22, COMMA=23, EQUALS=24, SEMICOLON=25, COLON=26, POWER=27, MULTIPLY=28,
DIVIDE=29, INTEGER_DIVIDE=30, PLUS=31, SUBTRACT=32, DOT=33, GREATER_THAN=34,
LESS_THAN=35, POUND=36, IDENTIFIER=37, SIGN=38, DIGITS=39, STRING=40;
public static String[] channelNames = {
"DEFAULT_TOKEN_CHANNEL", "HIDDEN"
};
public static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"WS", "COMMENT", "DOC_START", "DOC_END", "DOC_LINE", "NEWLINES", "FUNCTION",
"TEMPLATE", "NATIVE", "CONSTANT", "RUN", "RAISE", "DELAY", "IMPORT", "INTERNAL",
"ARROW", "OPAREN", "CPAREN", "OCURLY", "CCURLY", "OSQUARE", "CSQUARE",
"COMMA", "EQUALS", "SEMICOLON", "COLON", "POWER", "MULTIPLY", "DIVIDE",
"INTEGER_DIVIDE", "PLUS", "SUBTRACT", "DOT", "GREATER_THAN", "LESS_THAN",
"POUND", "IDENTIFIER", "SIGN", "DIGITS", "STRING"
};
private static final String[] _LITERAL_NAMES = {
null, null, null, "'/*'", "'*/'", null, null, "'func'", "'script'", "'command'",
"'const'", "'run'", "'raise'", "'delay'", "'import'", "'internal'", "'->'",
"'('", "')'", "'{'", "'}'", "'['", "']'", "','", "'='", "';'", "':'",
"'^'", "'*'", "'/'", "'//'", "'+'", "'-'", "'.'", "'>'", "'<'", "'#'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, "WS", "COMMENT", "DOC_START", "DOC_END", "DOC_LINE", "NEWLINES",
"FUNCTION", "TEMPLATE", "NATIVE", "CONSTANT", "RUN", "RAISE", "DELAY",
"IMPORT", "INTERNAL", "ARROW", "OPAREN", "CPAREN", "OCURLY", "CCURLY",
"OSQUARE", "CSQUARE", "COMMA", "EQUALS", "SEMICOLON", "COLON", "POWER",
"MULTIPLY", "DIVIDE", "INTEGER_DIVIDE", "PLUS", "SUBTRACT", "DOT", "GREATER_THAN",
"LESS_THAN", "POUND", "IDENTIFIER", "SIGN", "DIGITS", "STRING"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
public ScriptBlockLexer(CharStream input) {
super(input);
_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
@Override
public String getGrammarFileName() { return "ScriptBlockLexer.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public String[] getChannelNames() { return channelNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2*\u00fe\b\1\4\2\t"+
"\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+
"\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+
"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31\t\31"+
"\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t \4!"+
"\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\3\2\6\2U\n\2\r"+
"\2\16\2V\3\2\3\2\3\3\3\3\3\3\3\3\7\3_\n\3\f\3\16\3b\13\3\3\3\6\3e\n\3"+
"\r\3\16\3f\3\3\3\3\3\4\3\4\3\4\3\5\3\5\3\5\3\6\3\6\3\6\3\6\7\6u\n\6\f"+
"\6\16\6x\13\6\3\6\6\6{\n\6\r\6\16\6|\3\7\6\7\u0080\n\7\r\7\16\7\u0081"+
"\3\b\3\b\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3"+
"\n\3\n\3\n\3\13\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\r\3\r\3\r\3"+
"\r\3\r\3\r\3\16\3\16\3\16\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\17"+
"\3\17\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\21\3\21\3\21\3\22"+
"\3\22\3\23\3\23\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\30\3\30\3\31"+
"\3\31\3\32\3\32\3\33\3\33\3\34\3\34\3\35\3\35\3\36\3\36\3\37\3\37\3\37"+
"\3 \3 \3!\3!\3\"\3\"\3#\3#\3$\3$\3%\3%\3&\6&\u00eb\n&\r&\16&\u00ec\3\'"+
"\3\'\3(\6(\u00f2\n(\r(\16(\u00f3\3)\3)\7)\u00f8\n)\f)\16)\u00fb\13)\3"+
")\3)\5`v\u00f9\2*\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31"+
"\16\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61\32\63\33\65"+
"\34\67\359\36;\37= ?!A\"C#E$G%I&K\'M(O)Q*\3\2\t\4\2\13\13\"\"\5\2\f\f"+
"\17\17^^\4\2\f\f\17\17\5\2C\\aac|\4\2--//\3\2\62;\3\2))\2\u0106\2\3\3"+
"\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2"+
"\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3"+
"\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2"+
"%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61"+
"\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2"+
"\2=\3\2\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I"+
"\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\3T\3\2\2\2\5Z\3\2"+
"\2\2\7j\3\2\2\2\tm\3\2\2\2\13p\3\2\2\2\r\177\3\2\2\2\17\u0083\3\2\2\2"+
"\21\u0088\3\2\2\2\23\u008f\3\2\2\2\25\u0097\3\2\2\2\27\u009d\3\2\2\2\31"+
"\u00a1\3\2\2\2\33\u00a7\3\2\2\2\35\u00ad\3\2\2\2\37\u00b4\3\2\2\2!\u00bd"+
"\3\2\2\2#\u00c0\3\2\2\2%\u00c2\3\2\2\2\'\u00c4\3\2\2\2)\u00c6\3\2\2\2"+
"+\u00c8\3\2\2\2-\u00ca\3\2\2\2/\u00cc\3\2\2\2\61\u00ce\3\2\2\2\63\u00d0"+
"\3\2\2\2\65\u00d2\3\2\2\2\67\u00d4\3\2\2\29\u00d6\3\2\2\2;\u00d8\3\2\2"+
"\2=\u00da\3\2\2\2?\u00dd\3\2\2\2A\u00df\3\2\2\2C\u00e1\3\2\2\2E\u00e3"+
"\3\2\2\2G\u00e5\3\2\2\2I\u00e7\3\2\2\2K\u00ea\3\2\2\2M\u00ee\3\2\2\2O"+
"\u00f1\3\2\2\2Q\u00f5\3\2\2\2SU\t\2\2\2TS\3\2\2\2UV\3\2\2\2VT\3\2\2\2"+
"VW\3\2\2\2WX\3\2\2\2XY\b\2\2\2Y\4\3\2\2\2Z[\7%\2\2[\\\7%\2\2\\`\3\2\2"+
"\2]_\n\3\2\2^]\3\2\2\2_b\3\2\2\2`a\3\2\2\2`^\3\2\2\2ad\3\2\2\2b`\3\2\2"+
"\2ce\t\4\2\2dc\3\2\2\2ef\3\2\2\2fd\3\2\2\2fg\3\2\2\2gh\3\2\2\2hi\b\3\2"+
"\2i\6\3\2\2\2jk\7\61\2\2kl\7,\2\2l\b\3\2\2\2mn\7,\2\2no\7\61\2\2o\n\3"+
"\2\2\2pq\7,\2\2qr\7,\2\2rv\3\2\2\2su\n\4\2\2ts\3\2\2\2ux\3\2\2\2vw\3\2"+
"\2\2vt\3\2\2\2wz\3\2\2\2xv\3\2\2\2y{\t\4\2\2zy\3\2\2\2{|\3\2\2\2|z\3\2"+
"\2\2|}\3\2\2\2}\f\3\2\2\2~\u0080\t\4\2\2\177~\3\2\2\2\u0080\u0081\3\2"+
"\2\2\u0081\177\3\2\2\2\u0081\u0082\3\2\2\2\u0082\16\3\2\2\2\u0083\u0084"+
"\7h\2\2\u0084\u0085\7w\2\2\u0085\u0086\7p\2\2\u0086\u0087\7e\2\2\u0087"+
"\20\3\2\2\2\u0088\u0089\7u\2\2\u0089\u008a\7e\2\2\u008a\u008b\7t\2\2\u008b"+
"\u008c\7k\2\2\u008c\u008d\7r\2\2\u008d\u008e\7v\2\2\u008e\22\3\2\2\2\u008f"+
"\u0090\7e\2\2\u0090\u0091\7q\2\2\u0091\u0092\7o\2\2\u0092\u0093\7o\2\2"+
"\u0093\u0094\7c\2\2\u0094\u0095\7p\2\2\u0095\u0096\7f\2\2\u0096\24\3\2"+
"\2\2\u0097\u0098\7e\2\2\u0098\u0099\7q\2\2\u0099\u009a\7p\2\2\u009a\u009b"+
"\7u\2\2\u009b\u009c\7v\2\2\u009c\26\3\2\2\2\u009d\u009e\7t\2\2\u009e\u009f"+
"\7w\2\2\u009f\u00a0\7p\2\2\u00a0\30\3\2\2\2\u00a1\u00a2\7t\2\2\u00a2\u00a3"+
"\7c\2\2\u00a3\u00a4\7k\2\2\u00a4\u00a5\7u\2\2\u00a5\u00a6\7g\2\2\u00a6"+
"\32\3\2\2\2\u00a7\u00a8\7f\2\2\u00a8\u00a9\7g\2\2\u00a9\u00aa\7n\2\2\u00aa"+
"\u00ab\7c\2\2\u00ab\u00ac\7{\2\2\u00ac\34\3\2\2\2\u00ad\u00ae\7k\2\2\u00ae"+
"\u00af\7o\2\2\u00af\u00b0\7r\2\2\u00b0\u00b1\7q\2\2\u00b1\u00b2\7t\2\2"+
"\u00b2\u00b3\7v\2\2\u00b3\36\3\2\2\2\u00b4\u00b5\7k\2\2\u00b5\u00b6\7"+
"p\2\2\u00b6\u00b7\7v\2\2\u00b7\u00b8\7g\2\2\u00b8\u00b9\7t\2\2\u00b9\u00ba"+
"\7p\2\2\u00ba\u00bb\7c\2\2\u00bb\u00bc\7n\2\2\u00bc \3\2\2\2\u00bd\u00be"+
"\7/\2\2\u00be\u00bf\7@\2\2\u00bf\"\3\2\2\2\u00c0\u00c1\7*\2\2\u00c1$\3"+
"\2\2\2\u00c2\u00c3\7+\2\2\u00c3&\3\2\2\2\u00c4\u00c5\7}\2\2\u00c5(\3\2"+
"\2\2\u00c6\u00c7\7\177\2\2\u00c7*\3\2\2\2\u00c8\u00c9\7]\2\2\u00c9,\3"+
"\2\2\2\u00ca\u00cb\7_\2\2\u00cb.\3\2\2\2\u00cc\u00cd\7.\2\2\u00cd\60\3"+
"\2\2\2\u00ce\u00cf\7?\2\2\u00cf\62\3\2\2\2\u00d0\u00d1\7=\2\2\u00d1\64"+
"\3\2\2\2\u00d2\u00d3\7<\2\2\u00d3\66\3\2\2\2\u00d4\u00d5\7`\2\2\u00d5"+
"8\3\2\2\2\u00d6\u00d7\7,\2\2\u00d7:\3\2\2\2\u00d8\u00d9\7\61\2\2\u00d9"+
"<\3\2\2\2\u00da\u00db\7\61\2\2\u00db\u00dc\7\61\2\2\u00dc>\3\2\2\2\u00dd"+
"\u00de\7-\2\2\u00de@\3\2\2\2\u00df\u00e0\7/\2\2\u00e0B\3\2\2\2\u00e1\u00e2"+
"\7\60\2\2\u00e2D\3\2\2\2\u00e3\u00e4\7@\2\2\u00e4F\3\2\2\2\u00e5\u00e6"+
"\7>\2\2\u00e6H\3\2\2\2\u00e7\u00e8\7%\2\2\u00e8J\3\2\2\2\u00e9\u00eb\t"+
"\5\2\2\u00ea\u00e9\3\2\2\2\u00eb\u00ec\3\2\2\2\u00ec\u00ea\3\2\2\2\u00ec"+
"\u00ed\3\2\2\2\u00edL\3\2\2\2\u00ee\u00ef\t\6\2\2\u00efN\3\2\2\2\u00f0"+
"\u00f2\t\7\2\2\u00f1\u00f0\3\2\2\2\u00f2\u00f3\3\2\2\2\u00f3\u00f1\3\2"+
"\2\2\u00f3\u00f4\3\2\2\2\u00f4P\3\2\2\2\u00f5\u00f9\7)\2\2\u00f6\u00f8"+
"\n\b\2\2\u00f7\u00f6\3\2\2\2\u00f8\u00fb\3\2\2\2\u00f9\u00fa\3\2\2\2\u00f9"+
"\u00f7\3\2\2\2\u00fa\u00fc\3\2\2\2\u00fb\u00f9\3\2\2\2\u00fc\u00fd\7)"+
"\2\2\u00fdR\3\2\2\2\f\2V`fv|\u0081\u00ec\u00f3\u00f9\3\b\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}<file_sep>/compiler/maintool/toolmodule.go
package maintool
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/sirupsen/logrus"
"github.com/falcinspire/scriptblock/compiler/back/tags"
"github.com/falcinspire/scriptblock/compiler/front/astgen"
"github.com/falcinspire/scriptblock/compiler/front/parser"
"github.com/falcinspire/scriptblock/compiler/back/addressbook"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/falcinspire/scriptblock/compiler/dependency"
"github.com/falcinspire/scriptblock/compiler/front/astbook"
"github.com/falcinspire/scriptblock/compiler/front/imports"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
)
type UnitLocationPath struct {
location *location.UnitLocation
filepath string
}
func DoModule(moduleQualified string, scriptblockHome string, output string, astbooko astbook.AstBook, importbooko imports.ImportBook, symbollibrary *symbols.SymbolLibrary, valuelibrary *values.ValueLibrary, addressbooko addressbook.AddressBook) {
// this could be dangerous if given wrong directory
// if _, err := os.Stat(output); !os.IsNotExist(err) {
// os.RemoveAll(output)
// os.MkdirAll(output, os.ModePerm)
// }
modulePath := filepath.Join(scriptblockHome, moduleQualified)
logrus.WithFields(logrus.Fields{
"module": modulePath,
}).Info("compiling module")
files, err := ioutil.ReadDir(modulePath)
if err != nil {
panic(err)
}
moduleName := filepath.Base(filepath.Dir(modulePath)) // module/version
locations := registerLocations(files, moduleName)
parseAllToAsts(locations, moduleName, modulePath, astbooko)
takeImportsFromAsts(locations, moduleName, astbooko, importbooko)
order := makeDependencyOrder(locations, moduleName, importbooko)
logrus.WithFields(logrus.Fields{
"order": order,
}).Info("dependency order produced")
RunFrontEnd(order, moduleName, astbooko, importbooko, symbollibrary)
theTags := make(map[string]tags.LocationList)
RunBackEnd(order, moduleName, astbooko, valuelibrary, addressbooko, theTags, modulePath, output)
tags.WriteAllTagsToFiles(theTags, output)
}
func registerLocations(files []os.FileInfo, moduleName string) []string {
locations := make([]string, 0)
for _, file := range files {
if filepath.Ext(file.Name()) == ".sb" {
unitName := strings.TrimSuffix(file.Name(), filepath.Ext(file.Name()))
locations = append(locations, unitName)
logrus.WithFields(logrus.Fields{
"module": moduleName,
"unit": unitName,
}).Info("identified unit")
} else {
logrus.WithFields(logrus.Fields{
"module": moduleName,
"file": file.Name(),
}).Info("skipping non-unit")
}
}
return locations
}
func parseAllToAsts(units []string, moduleName string, modulePath string, astbooko astbook.AstBook) {
for _, unitName := range units {
filelocation := filepath.Join(modulePath, fmt.Sprintf("%s.sb", unitName))
pstree := parser.Parse(filelocation)
astree := astgen.PSTtoAST(pstree)
astbook.InsertAst(&location.UnitLocation{Module: moduleName, Unit: unitName}, astree, astbooko)
logrus.WithFields(logrus.Fields{
"module": moduleName,
"unit": unitName,
"path": filelocation,
}).Info("ast produced")
}
}
func takeImportsFromAsts(units []string, module string, astbooko astbook.AstBook, importbooko imports.ImportBook) {
for _, unitName := range units {
astree := astbook.LookupAst(&location.UnitLocation{Module: module, Unit: unitName}, astbooko)
importList := imports.TakeImports(astree)
imports.InsertImportList(module, unitName, importList, importbooko)
importListString := make([]string, len(importList))
for i, importLine := range importList {
importListString[i] = fmt.Sprintf("%s:%s", importLine.Module, importLine.Unit)
}
logrus.WithFields(logrus.Fields{
"module": module,
"unit": unitName,
"imports": importListString,
}).Info("imports taken")
}
}
func makeDependencyOrder(units []string, module string, importbooko imports.ImportBook) []string {
logrus.WithFields(logrus.Fields{
"input": units,
})
toID := make(map[string]int)
for unitID, unitName := range units {
toID[unitName] = unitID
}
dependencyGraph := dependency.NewDependencyGraph()
for i := 0; i < len(units); i++ {
dependency.AddVertex(dependencyGraph)
}
// connect nodes
for unitID, unitName := range units {
importList := imports.LookupImportList(module, unitName, importbooko)
for _, importLine := range importList {
if importLine.Module == module {
dependency.AddDependency(unitID, toID[importLine.Unit], dependencyGraph)
}
}
}
idOrder, circular := dependency.MakeDependencyOrder(dependencyGraph)
if circular {
panic(fmt.Errorf("circular reference"))
}
order := make([]string, len(units))
for index, id := range idOrder {
order[index] = units[id]
}
return order
}
func RunFrontEnd(order []string, module string, astbooko astbook.AstBook, importbooko imports.ImportBook, symbolLibrary *symbols.SymbolLibrary) {
for _, unitName := range order {
DoUnitFront(&location.UnitLocation{Module: module, Unit: unitName}, astbooko, importbooko, symbolLibrary)
logrus.WithFields(logrus.Fields{
"module": module,
"unit": unitName,
}).Info("front end run on unit")
}
}
func RunBackEnd(order []string, module string, astbooko astbook.AstBook, valueLibrary *values.ValueLibrary, addressbooko addressbook.AddressBook, theTags map[string]tags.LocationList, modulePath string, output string) {
for _, unitName := range order {
DoUnitBack(&location.UnitLocation{Module: module, Unit: unitName}, astbooko, valueLibrary, addressbooko, theTags, modulePath, output)
logrus.WithFields(logrus.Fields{
"module": module,
"unit": unitName,
}).Info("back end run on unit")
}
}
<file_sep>/compiler/front/parser/scriptblockparser_listener.go
// Generated from ScriptBlockParser.g4 by ANTLR 4.7.
package parser // ScriptBlockParser
import "github.com/antlr/antlr4/runtime/Go/antlr"
// ScriptBlockParserListener is a complete listener for a parse tree produced by ScriptBlockParser.
type ScriptBlockParserListener interface {
antlr.ParseTreeListener
// EnterUnit is called when entering the unit production.
EnterUnit(c *UnitContext)
// EnterDocumentation is called when entering the documentation production.
EnterDocumentation(c *DocumentationContext)
// EnterParameterList is called when entering the parameterList production.
EnterParameterList(c *ParameterListContext)
// EnterArgumentList is called when entering the argumentList production.
EnterArgumentList(c *ArgumentListContext)
// EnterStructureList is called when entering the structureList production.
EnterStructureList(c *StructureListContext)
// EnterNativeCall is called when entering the nativeCall production.
EnterNativeCall(c *NativeCallContext)
// EnterFunctionCall is called when entering the functionCall production.
EnterFunctionCall(c *FunctionCallContext)
// EnterFunctionFrame is called when entering the functionFrame production.
EnterFunctionFrame(c *FunctionFrameContext)
// EnterFunctionDefinition is called when entering the functionDefinition production.
EnterFunctionDefinition(c *FunctionDefinitionContext)
// EnterFunctionDefinitionShortcut is called when entering the functionDefinitionShortcut production.
EnterFunctionDefinitionShortcut(c *FunctionDefinitionShortcutContext)
// EnterTag is called when entering the tag production.
EnterTag(c *TagContext)
// EnterTemplateDefinition is called when entering the templateDefinition production.
EnterTemplateDefinition(c *TemplateDefinitionContext)
// EnterConstantDefinition is called when entering the constantDefinition production.
EnterConstantDefinition(c *ConstantDefinitionContext)
// EnterFormatter is called when entering the formatter production.
EnterFormatter(c *FormatterContext)
// EnterImportLine is called when entering the importLine production.
EnterImportLine(c *ImportLineContext)
// EnterConstantDefinitionTop is called when entering the constantDefinitionTop production.
EnterConstantDefinitionTop(c *ConstantDefinitionTopContext)
// EnterFunctionDefinitionTop is called when entering the functionDefinitionTop production.
EnterFunctionDefinitionTop(c *FunctionDefinitionTopContext)
// EnterTemplateDefinitionTop is called when entering the templateDefinitionTop production.
EnterTemplateDefinitionTop(c *TemplateDefinitionTopContext)
// EnterFunctionShortcutTop is called when entering the functionShortcutTop production.
EnterFunctionShortcutTop(c *FunctionShortcutTopContext)
// EnterFunctionCallStatement is called when entering the functionCallStatement production.
EnterFunctionCallStatement(c *FunctionCallStatementContext)
// EnterNativeCallStatement is called when entering the nativeCallStatement production.
EnterNativeCallStatement(c *NativeCallStatementContext)
// EnterDelayStructureStatement is called when entering the delayStructureStatement production.
EnterDelayStructureStatement(c *DelayStructureStatementContext)
// EnterRaiseStatement is called when entering the raiseStatement production.
EnterRaiseStatement(c *RaiseStatementContext)
// EnterDelayStructure is called when entering the delayStructure production.
EnterDelayStructure(c *DelayStructureContext)
// EnterRaise is called when entering the raise production.
EnterRaise(c *RaiseContext)
// EnterStringExpr is called when entering the stringExpr production.
EnterStringExpr(c *StringExprContext)
// EnterDivideExpr is called when entering the divideExpr production.
EnterDivideExpr(c *DivideExprContext)
// EnterIntegerDivideExpr is called when entering the integerDivideExpr production.
EnterIntegerDivideExpr(c *IntegerDivideExprContext)
// EnterSubtractExpr is called when entering the subtractExpr production.
EnterSubtractExpr(c *SubtractExprContext)
// EnterPowerExpr is called when entering the powerExpr production.
EnterPowerExpr(c *PowerExprContext)
// EnterAddExpr is called when entering the addExpr production.
EnterAddExpr(c *AddExprContext)
// EnterNumberExpr is called when entering the numberExpr production.
EnterNumberExpr(c *NumberExprContext)
// EnterMultiplyExpr is called when entering the multiplyExpr production.
EnterMultiplyExpr(c *MultiplyExprContext)
// EnterCallExpr is called when entering the callExpr production.
EnterCallExpr(c *CallExprContext)
// EnterFormatterExpr is called when entering the formatterExpr production.
EnterFormatterExpr(c *FormatterExprContext)
// EnterIdentifierExpr is called when entering the identifierExpr production.
EnterIdentifierExpr(c *IdentifierExprContext)
// EnterParenthExpr is called when entering the parenthExpr production.
EnterParenthExpr(c *ParenthExprContext)
// EnterNumber is called when entering the number production.
EnterNumber(c *NumberContext)
// ExitUnit is called when exiting the unit production.
ExitUnit(c *UnitContext)
// ExitDocumentation is called when exiting the documentation production.
ExitDocumentation(c *DocumentationContext)
// ExitParameterList is called when exiting the parameterList production.
ExitParameterList(c *ParameterListContext)
// ExitArgumentList is called when exiting the argumentList production.
ExitArgumentList(c *ArgumentListContext)
// ExitStructureList is called when exiting the structureList production.
ExitStructureList(c *StructureListContext)
// ExitNativeCall is called when exiting the nativeCall production.
ExitNativeCall(c *NativeCallContext)
// ExitFunctionCall is called when exiting the functionCall production.
ExitFunctionCall(c *FunctionCallContext)
// ExitFunctionFrame is called when exiting the functionFrame production.
ExitFunctionFrame(c *FunctionFrameContext)
// ExitFunctionDefinition is called when exiting the functionDefinition production.
ExitFunctionDefinition(c *FunctionDefinitionContext)
// ExitFunctionDefinitionShortcut is called when exiting the functionDefinitionShortcut production.
ExitFunctionDefinitionShortcut(c *FunctionDefinitionShortcutContext)
// ExitTag is called when exiting the tag production.
ExitTag(c *TagContext)
// ExitTemplateDefinition is called when exiting the templateDefinition production.
ExitTemplateDefinition(c *TemplateDefinitionContext)
// ExitConstantDefinition is called when exiting the constantDefinition production.
ExitConstantDefinition(c *ConstantDefinitionContext)
// ExitFormatter is called when exiting the formatter production.
ExitFormatter(c *FormatterContext)
// ExitImportLine is called when exiting the importLine production.
ExitImportLine(c *ImportLineContext)
// ExitConstantDefinitionTop is called when exiting the constantDefinitionTop production.
ExitConstantDefinitionTop(c *ConstantDefinitionTopContext)
// ExitFunctionDefinitionTop is called when exiting the functionDefinitionTop production.
ExitFunctionDefinitionTop(c *FunctionDefinitionTopContext)
// ExitTemplateDefinitionTop is called when exiting the templateDefinitionTop production.
ExitTemplateDefinitionTop(c *TemplateDefinitionTopContext)
// ExitFunctionShortcutTop is called when exiting the functionShortcutTop production.
ExitFunctionShortcutTop(c *FunctionShortcutTopContext)
// ExitFunctionCallStatement is called when exiting the functionCallStatement production.
ExitFunctionCallStatement(c *FunctionCallStatementContext)
// ExitNativeCallStatement is called when exiting the nativeCallStatement production.
ExitNativeCallStatement(c *NativeCallStatementContext)
// ExitDelayStructureStatement is called when exiting the delayStructureStatement production.
ExitDelayStructureStatement(c *DelayStructureStatementContext)
// ExitRaiseStatement is called when exiting the raiseStatement production.
ExitRaiseStatement(c *RaiseStatementContext)
// ExitDelayStructure is called when exiting the delayStructure production.
ExitDelayStructure(c *DelayStructureContext)
// ExitRaise is called when exiting the raise production.
ExitRaise(c *RaiseContext)
// ExitStringExpr is called when exiting the stringExpr production.
ExitStringExpr(c *StringExprContext)
// ExitDivideExpr is called when exiting the divideExpr production.
ExitDivideExpr(c *DivideExprContext)
// ExitIntegerDivideExpr is called when exiting the integerDivideExpr production.
ExitIntegerDivideExpr(c *IntegerDivideExprContext)
// ExitSubtractExpr is called when exiting the subtractExpr production.
ExitSubtractExpr(c *SubtractExprContext)
// ExitPowerExpr is called when exiting the powerExpr production.
ExitPowerExpr(c *PowerExprContext)
// ExitAddExpr is called when exiting the addExpr production.
ExitAddExpr(c *AddExprContext)
// ExitNumberExpr is called when exiting the numberExpr production.
ExitNumberExpr(c *NumberExprContext)
// ExitMultiplyExpr is called when exiting the multiplyExpr production.
ExitMultiplyExpr(c *MultiplyExprContext)
// ExitCallExpr is called when exiting the callExpr production.
ExitCallExpr(c *CallExprContext)
// ExitFormatterExpr is called when exiting the formatterExpr production.
ExitFormatterExpr(c *FormatterExprContext)
// ExitIdentifierExpr is called when exiting the identifierExpr production.
ExitIdentifierExpr(c *IdentifierExprContext)
// ExitParenthExpr is called when exiting the parenthExpr production.
ExitParenthExpr(c *ParenthExprContext)
// ExitNumber is called when exiting the number production.
ExitNumber(c *NumberContext)
}
<file_sep>/compiler/back/valuepass/value_simple.go
package valuepass
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/addressbook"
"github.com/falcinspire/scriptblock/compiler/back/evaluator"
"github.com/falcinspire/scriptblock/compiler/back/tags"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/falcinspire/scriptblock/compiler/ast/location"
)
// ValuePass performs all the necessary passes to evaluate and create .mcfunctions for the tree
func ValuePass(unit *ast.Unit, location *location.UnitLocation, valueLibrary *values.ValueLibrary, addressBook addressbook.AddressBook, tags map[string]tags.LocationList, modulePath string, output string) {
data := &evaluator.EvaluateData{
Location: location,
LocalValues: nil,
ValueLibrary: valueLibrary,
AddressBook: addressBook,
CallStack: evaluator.NewCallStack(),
LoopInject: evaluator.NewLoopInject(),
ModulePath: modulePath,
Output: output,
}
addressbook.InsertAddressTable(location.Module, location.Unit, addressbook.NewAddressTable(), addressBook)
values.InsertValueTable(location.Module, location.Unit, values.NewValueTable(), valueLibrary.Exported)
values.InsertValueTable(location.Module, location.Unit, values.NewValueTable(), valueLibrary.Internal)
PassOne(unit, data)
PassTwo(unit, data)
PassThree(unit, data, tags)
}
<file_sep>/compiler/back/valuepass/pass_one_simple.go
package valuepass
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/evaluator"
"github.com/sirupsen/logrus"
)
func PassOne(unit *ast.Unit, data *evaluator.EvaluateData) {
logrus.WithFields(logrus.Fields{
"module": data.Location.Module,
"unit": data.Location.Unit,
}).Info("Value pass 1")
unit.Accept(newUnitOneValueVisitor(data))
}
<file_sep>/cmd/scriptblock-home/main.go
package main
import (
"fmt"
"github.com/falcinspire/scriptblock/environment"
)
func main() {
fmt.Println(environment.GetHomePath())
}
<file_sep>/TODO.txt
Include/Import snatching? "You don't need to read the entire book to pull out the chapters"
Version codes should be a string of form "a.b.c" or "LATEST"
LATEST->DEV?
Escaped \" (maybe ' is fixing this?)
Minecraft json is not vanilla json? has suffixes like 5b
Comments are broken?
Add longs
Add repeat <file_sep>/compiler/ast/visitor.go
package ast
// ExpressionVisitor is a visitor for expressions
type ExpressionVisitor interface {
// VisitNumber is the double dispatch for number expressions
VisitNumber(expr *NumberExpression)
// VisitString is the double dispatch for string expressions
VisitString(expr *StringExpression)
// VisitAdd is the double dispatch for addition expressions
VisitAdd(expr *AddExpression)
// VisitSubtract is the double dispatch for subtraction expressions
VisitSubtract(expr *SubtractExpression)
// VisitMultiply is the double dispatch for multiply expressions
VisitMultiply(expr *MultiplyExpression)
// VisitDivide is the double dispatch for divide expressions
VisitDivide(expr *DivideExpression)
// VisitIntegerDivide is the double dispatch for integer divide expressions
VisitIntegerDivide(expr *IntegerDivideExpression)
// VisitPower is the double dispatch for power expressions
VisitPower(expr *PowerExpression)
// VisitFormatter is the double dispatch for formatter expressions
VisitFormatter(expr *FormatterExpression)
// VisitIdentifier is the double dispatch for identifier expressions
VisitIdentifier(expr *IdentifierExpression)
// VisitFunctor is the double dispatch for functor expressions
VisitFunctor(expr *FunctorExpression)
// VisitCall is the double dispatch for call expressions
VisitCall(expr *CallExpression)
}
// StatementVisitor is the visitor for statements
type StatementVisitor interface {
// VisitFunctionCall is the double dispatch for function call statements
VisitFunctionCall(functionCall *FunctionCall)
// VisitNativeCall is the double dispatch for native call statements
VisitNativeCall(nativeCall *NativeCall)
// VisitDelay is the double dispatch for delay statements
VisitDelay(delay *DelayStatement)
// VisitRaise is the double dispatch for raise statements
VisitRaise(delay *RaiseStatement)
}
// TopVisitor is the visitor for top definitions
type TopVisitor interface {
// VisitConstantDefinition is the visitor for constant definitions
VisitConstantDefinition(definition *ConstantDefinition)
// VisitFunctionDefinition is the visitor for function definitions
VisitFunctionDefinition(definition *FunctionDefinition)
// VisitFunctionShortcutDefinition is the visitor for function shortcut definitions
VisitFunctionShortcutDefinition(shortcut *FunctionShortcutDefinition)
// VisitTemplateDefinition is the visitor for template definitions
VisitTemplateDefinition(definition *TemplateDefinition)
}
// UnitVisitor is the visitor for units
type UnitVisitor interface {
VisitUnit(unit *Unit)
}
<file_sep>/compiler/front/parser/scriptblockparser_base_listener.go
// Generated from ScriptBlockParser.g4 by ANTLR 4.7.
package parser // ScriptBlockParser
import "github.com/antlr/antlr4/runtime/Go/antlr"
// BaseScriptBlockParserListener is a complete listener for a parse tree produced by ScriptBlockParser.
type BaseScriptBlockParserListener struct{}
var _ ScriptBlockParserListener = &BaseScriptBlockParserListener{}
// VisitTerminal is called when a terminal node is visited.
func (s *BaseScriptBlockParserListener) VisitTerminal(node antlr.TerminalNode) {}
// VisitErrorNode is called when an error node is visited.
func (s *BaseScriptBlockParserListener) VisitErrorNode(node antlr.ErrorNode) {}
// EnterEveryRule is called when any rule is entered.
func (s *BaseScriptBlockParserListener) EnterEveryRule(ctx antlr.ParserRuleContext) {}
// ExitEveryRule is called when any rule is exited.
func (s *BaseScriptBlockParserListener) ExitEveryRule(ctx antlr.ParserRuleContext) {}
// EnterUnit is called when production unit is entered.
func (s *BaseScriptBlockParserListener) EnterUnit(ctx *UnitContext) {}
// ExitUnit is called when production unit is exited.
func (s *BaseScriptBlockParserListener) ExitUnit(ctx *UnitContext) {}
// EnterDocumentation is called when production documentation is entered.
func (s *BaseScriptBlockParserListener) EnterDocumentation(ctx *DocumentationContext) {}
// ExitDocumentation is called when production documentation is exited.
func (s *BaseScriptBlockParserListener) ExitDocumentation(ctx *DocumentationContext) {}
// EnterParameterList is called when production parameterList is entered.
func (s *BaseScriptBlockParserListener) EnterParameterList(ctx *ParameterListContext) {}
// ExitParameterList is called when production parameterList is exited.
func (s *BaseScriptBlockParserListener) ExitParameterList(ctx *ParameterListContext) {}
// EnterArgumentList is called when production argumentList is entered.
func (s *BaseScriptBlockParserListener) EnterArgumentList(ctx *ArgumentListContext) {}
// ExitArgumentList is called when production argumentList is exited.
func (s *BaseScriptBlockParserListener) ExitArgumentList(ctx *ArgumentListContext) {}
// EnterStructureList is called when production structureList is entered.
func (s *BaseScriptBlockParserListener) EnterStructureList(ctx *StructureListContext) {}
// ExitStructureList is called when production structureList is exited.
func (s *BaseScriptBlockParserListener) ExitStructureList(ctx *StructureListContext) {}
// EnterNativeCall is called when production nativeCall is entered.
func (s *BaseScriptBlockParserListener) EnterNativeCall(ctx *NativeCallContext) {}
// ExitNativeCall is called when production nativeCall is exited.
func (s *BaseScriptBlockParserListener) ExitNativeCall(ctx *NativeCallContext) {}
// EnterFunctionCall is called when production functionCall is entered.
func (s *BaseScriptBlockParserListener) EnterFunctionCall(ctx *FunctionCallContext) {}
// ExitFunctionCall is called when production functionCall is exited.
func (s *BaseScriptBlockParserListener) ExitFunctionCall(ctx *FunctionCallContext) {}
// EnterFunctionFrame is called when production functionFrame is entered.
func (s *BaseScriptBlockParserListener) EnterFunctionFrame(ctx *FunctionFrameContext) {}
// ExitFunctionFrame is called when production functionFrame is exited.
func (s *BaseScriptBlockParserListener) ExitFunctionFrame(ctx *FunctionFrameContext) {}
// EnterFunctionDefinition is called when production functionDefinition is entered.
func (s *BaseScriptBlockParserListener) EnterFunctionDefinition(ctx *FunctionDefinitionContext) {}
// ExitFunctionDefinition is called when production functionDefinition is exited.
func (s *BaseScriptBlockParserListener) ExitFunctionDefinition(ctx *FunctionDefinitionContext) {}
// EnterFunctionDefinitionShortcut is called when production functionDefinitionShortcut is entered.
func (s *BaseScriptBlockParserListener) EnterFunctionDefinitionShortcut(ctx *FunctionDefinitionShortcutContext) {
}
// ExitFunctionDefinitionShortcut is called when production functionDefinitionShortcut is exited.
func (s *BaseScriptBlockParserListener) ExitFunctionDefinitionShortcut(ctx *FunctionDefinitionShortcutContext) {
}
// EnterTag is called when production tag is entered.
func (s *BaseScriptBlockParserListener) EnterTag(ctx *TagContext) {}
// ExitTag is called when production tag is exited.
func (s *BaseScriptBlockParserListener) ExitTag(ctx *TagContext) {}
// EnterTemplateDefinition is called when production templateDefinition is entered.
func (s *BaseScriptBlockParserListener) EnterTemplateDefinition(ctx *TemplateDefinitionContext) {}
// ExitTemplateDefinition is called when production templateDefinition is exited.
func (s *BaseScriptBlockParserListener) ExitTemplateDefinition(ctx *TemplateDefinitionContext) {}
// EnterConstantDefinition is called when production constantDefinition is entered.
func (s *BaseScriptBlockParserListener) EnterConstantDefinition(ctx *ConstantDefinitionContext) {}
// ExitConstantDefinition is called when production constantDefinition is exited.
func (s *BaseScriptBlockParserListener) ExitConstantDefinition(ctx *ConstantDefinitionContext) {}
// EnterFormatter is called when production formatter is entered.
func (s *BaseScriptBlockParserListener) EnterFormatter(ctx *FormatterContext) {}
// ExitFormatter is called when production formatter is exited.
func (s *BaseScriptBlockParserListener) ExitFormatter(ctx *FormatterContext) {}
// EnterImportLine is called when production importLine is entered.
func (s *BaseScriptBlockParserListener) EnterImportLine(ctx *ImportLineContext) {}
// ExitImportLine is called when production importLine is exited.
func (s *BaseScriptBlockParserListener) ExitImportLine(ctx *ImportLineContext) {}
// EnterConstantDefinitionTop is called when production constantDefinitionTop is entered.
func (s *BaseScriptBlockParserListener) EnterConstantDefinitionTop(ctx *ConstantDefinitionTopContext) {
}
// ExitConstantDefinitionTop is called when production constantDefinitionTop is exited.
func (s *BaseScriptBlockParserListener) ExitConstantDefinitionTop(ctx *ConstantDefinitionTopContext) {}
// EnterFunctionDefinitionTop is called when production functionDefinitionTop is entered.
func (s *BaseScriptBlockParserListener) EnterFunctionDefinitionTop(ctx *FunctionDefinitionTopContext) {
}
// ExitFunctionDefinitionTop is called when production functionDefinitionTop is exited.
func (s *BaseScriptBlockParserListener) ExitFunctionDefinitionTop(ctx *FunctionDefinitionTopContext) {}
// EnterTemplateDefinitionTop is called when production templateDefinitionTop is entered.
func (s *BaseScriptBlockParserListener) EnterTemplateDefinitionTop(ctx *TemplateDefinitionTopContext) {
}
// ExitTemplateDefinitionTop is called when production templateDefinitionTop is exited.
func (s *BaseScriptBlockParserListener) ExitTemplateDefinitionTop(ctx *TemplateDefinitionTopContext) {}
// EnterFunctionShortcutTop is called when production functionShortcutTop is entered.
func (s *BaseScriptBlockParserListener) EnterFunctionShortcutTop(ctx *FunctionShortcutTopContext) {}
// ExitFunctionShortcutTop is called when production functionShortcutTop is exited.
func (s *BaseScriptBlockParserListener) ExitFunctionShortcutTop(ctx *FunctionShortcutTopContext) {}
// EnterFunctionCallStatement is called when production functionCallStatement is entered.
func (s *BaseScriptBlockParserListener) EnterFunctionCallStatement(ctx *FunctionCallStatementContext) {
}
// ExitFunctionCallStatement is called when production functionCallStatement is exited.
func (s *BaseScriptBlockParserListener) ExitFunctionCallStatement(ctx *FunctionCallStatementContext) {}
// EnterNativeCallStatement is called when production nativeCallStatement is entered.
func (s *BaseScriptBlockParserListener) EnterNativeCallStatement(ctx *NativeCallStatementContext) {}
// ExitNativeCallStatement is called when production nativeCallStatement is exited.
func (s *BaseScriptBlockParserListener) ExitNativeCallStatement(ctx *NativeCallStatementContext) {}
// EnterDelayStructureStatement is called when production delayStructureStatement is entered.
func (s *BaseScriptBlockParserListener) EnterDelayStructureStatement(ctx *DelayStructureStatementContext) {
}
// ExitDelayStructureStatement is called when production delayStructureStatement is exited.
func (s *BaseScriptBlockParserListener) ExitDelayStructureStatement(ctx *DelayStructureStatementContext) {
}
// EnterRaiseStatement is called when production raiseStatement is entered.
func (s *BaseScriptBlockParserListener) EnterRaiseStatement(ctx *RaiseStatementContext) {}
// ExitRaiseStatement is called when production raiseStatement is exited.
func (s *BaseScriptBlockParserListener) ExitRaiseStatement(ctx *RaiseStatementContext) {}
// EnterDelayStructure is called when production delayStructure is entered.
func (s *BaseScriptBlockParserListener) EnterDelayStructure(ctx *DelayStructureContext) {}
// ExitDelayStructure is called when production delayStructure is exited.
func (s *BaseScriptBlockParserListener) ExitDelayStructure(ctx *DelayStructureContext) {}
// EnterRaise is called when production raise is entered.
func (s *BaseScriptBlockParserListener) EnterRaise(ctx *RaiseContext) {}
// ExitRaise is called when production raise is exited.
func (s *BaseScriptBlockParserListener) ExitRaise(ctx *RaiseContext) {}
// EnterStringExpr is called when production stringExpr is entered.
func (s *BaseScriptBlockParserListener) EnterStringExpr(ctx *StringExprContext) {}
// ExitStringExpr is called when production stringExpr is exited.
func (s *BaseScriptBlockParserListener) ExitStringExpr(ctx *StringExprContext) {}
// EnterDivideExpr is called when production divideExpr is entered.
func (s *BaseScriptBlockParserListener) EnterDivideExpr(ctx *DivideExprContext) {}
// ExitDivideExpr is called when production divideExpr is exited.
func (s *BaseScriptBlockParserListener) ExitDivideExpr(ctx *DivideExprContext) {}
// EnterIntegerDivideExpr is called when production integerDivideExpr is entered.
func (s *BaseScriptBlockParserListener) EnterIntegerDivideExpr(ctx *IntegerDivideExprContext) {}
// ExitIntegerDivideExpr is called when production integerDivideExpr is exited.
func (s *BaseScriptBlockParserListener) ExitIntegerDivideExpr(ctx *IntegerDivideExprContext) {}
// EnterSubtractExpr is called when production subtractExpr is entered.
func (s *BaseScriptBlockParserListener) EnterSubtractExpr(ctx *SubtractExprContext) {}
// ExitSubtractExpr is called when production subtractExpr is exited.
func (s *BaseScriptBlockParserListener) ExitSubtractExpr(ctx *SubtractExprContext) {}
// EnterPowerExpr is called when production powerExpr is entered.
func (s *BaseScriptBlockParserListener) EnterPowerExpr(ctx *PowerExprContext) {}
// ExitPowerExpr is called when production powerExpr is exited.
func (s *BaseScriptBlockParserListener) ExitPowerExpr(ctx *PowerExprContext) {}
// EnterAddExpr is called when production addExpr is entered.
func (s *BaseScriptBlockParserListener) EnterAddExpr(ctx *AddExprContext) {}
// ExitAddExpr is called when production addExpr is exited.
func (s *BaseScriptBlockParserListener) ExitAddExpr(ctx *AddExprContext) {}
// EnterNumberExpr is called when production numberExpr is entered.
func (s *BaseScriptBlockParserListener) EnterNumberExpr(ctx *NumberExprContext) {}
// ExitNumberExpr is called when production numberExpr is exited.
func (s *BaseScriptBlockParserListener) ExitNumberExpr(ctx *NumberExprContext) {}
// EnterMultiplyExpr is called when production multiplyExpr is entered.
func (s *BaseScriptBlockParserListener) EnterMultiplyExpr(ctx *MultiplyExprContext) {}
// ExitMultiplyExpr is called when production multiplyExpr is exited.
func (s *BaseScriptBlockParserListener) ExitMultiplyExpr(ctx *MultiplyExprContext) {}
// EnterCallExpr is called when production callExpr is entered.
func (s *BaseScriptBlockParserListener) EnterCallExpr(ctx *CallExprContext) {}
// ExitCallExpr is called when production callExpr is exited.
func (s *BaseScriptBlockParserListener) ExitCallExpr(ctx *CallExprContext) {}
// EnterFormatterExpr is called when production formatterExpr is entered.
func (s *BaseScriptBlockParserListener) EnterFormatterExpr(ctx *FormatterExprContext) {}
// ExitFormatterExpr is called when production formatterExpr is exited.
func (s *BaseScriptBlockParserListener) ExitFormatterExpr(ctx *FormatterExprContext) {}
// EnterIdentifierExpr is called when production identifierExpr is entered.
func (s *BaseScriptBlockParserListener) EnterIdentifierExpr(ctx *IdentifierExprContext) {}
// ExitIdentifierExpr is called when production identifierExpr is exited.
func (s *BaseScriptBlockParserListener) ExitIdentifierExpr(ctx *IdentifierExprContext) {}
// EnterParenthExpr is called when production parenthExpr is entered.
func (s *BaseScriptBlockParserListener) EnterParenthExpr(ctx *ParenthExprContext) {}
// ExitParenthExpr is called when production parenthExpr is exited.
func (s *BaseScriptBlockParserListener) ExitParenthExpr(ctx *ParenthExprContext) {}
// EnterNumber is called when production number is entered.
func (s *BaseScriptBlockParserListener) EnterNumber(ctx *NumberContext) {}
// ExitNumber is called when production number is exited.
func (s *BaseScriptBlockParserListener) ExitNumber(ctx *NumberContext) {}
<file_sep>/compiler/front/astgen/ast_visitor.go
package astgen
import (
"strconv"
"strings"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/front/parser"
)
type expressionConvertVisitor struct {
*parser.BaseScriptBlockParserListener
Expression ast.Expression
}
func newExpressionConvertVisitor() *expressionConvertVisitor {
return new(expressionConvertVisitor)
}
// EnterNumberExpr is the visitor enter method for number expressions.
func (visitor *expressionConvertVisitor) EnterNumberExpr(ctx *parser.NumberExprContext) {
number, _ := strconv.ParseFloat(ctx.GetText(), 64)
visitor.Expression = ast.NewNumberExpression(number, convertMetadata(ctx))
}
// EnterStringExpr is the visitor enter method for string expressions.
func (visitor *expressionConvertVisitor) EnterStringExpr(ctx *parser.StringExprContext) {
stringV := ctx.GetText()
visitor.Expression = ast.NewStringExpression(stringV[1:len(stringV)-1], convertMetadata(ctx))
}
// EnterIdentifierExpr is the visitor enter method for identifier expressions.
func (visitor *expressionConvertVisitor) EnterIdentifierExpr(ctx *parser.IdentifierExprContext) {
visitor.Expression = ast.NewIdentifierExpression(ctx.IDENTIFIER().GetText(), convertMetadata(ctx))
}
// EnterAddExpr is the visitor enter method for addition expressions.
func (visitor *expressionConvertVisitor) EnterAddExpr(ctx *parser.AddExprContext) {
left := convertExpression(ctx.Expression(0))
right := convertExpression(ctx.Expression(1))
visitor.Expression = ast.NewAddExpression(left, right, convertMetadata(ctx))
}
// EnterSubtractExpr is the visitor enter method for subtraction expressions.
func (visitor *expressionConvertVisitor) EnterSubtractExpr(ctx *parser.SubtractExprContext) {
left := convertExpression(ctx.Expression(0))
right := convertExpression(ctx.Expression(1))
visitor.Expression = ast.NewSubtractExpression(left, right, convertMetadata(ctx))
}
// EnterMultiplyExpr is the visitor enter method for multiply expressions.
func (visitor *expressionConvertVisitor) EnterMultiplyExpr(ctx *parser.MultiplyExprContext) {
left := convertExpression(ctx.Expression(0))
right := convertExpression(ctx.Expression(1))
visitor.Expression = ast.NewMultiplyExpression(left, right, convertMetadata(ctx))
}
// EnterDivideExpr is the visitor enter method for divide expressions.
func (visitor *expressionConvertVisitor) EnterDivideExpr(ctx *parser.DivideExprContext) {
left := convertExpression(ctx.Expression(0))
right := convertExpression(ctx.Expression(1))
visitor.Expression = ast.NewDivideExpression(left, right, convertMetadata(ctx))
}
// EnterIntegerDivideExpr is the visitor enter method for integer divide expressions.
func (visitor *expressionConvertVisitor) EnterIntegerDivideExpr(ctx *parser.IntegerDivideExprContext) {
left := convertExpression(ctx.Expression(0))
right := convertExpression(ctx.Expression(1))
visitor.Expression = ast.NewIntegerDivideExpression(left, right, convertMetadata(ctx))
}
// EnterPowerExpr is the visitor enter method for power expressions.
func (visitor *expressionConvertVisitor) EnterPowerExpr(ctx *parser.PowerExprContext) {
left := convertExpression(ctx.Expression(0))
right := convertExpression(ctx.Expression(1))
visitor.Expression = ast.NewPowerExpression(left, right, convertMetadata(ctx))
}
// EnterParenthExpr is the visitor enter method for parenthesis expressions.
func (visitor *expressionConvertVisitor) EnterParenthExpr(ctx *parser.ParenthExprContext) {
visitor.Expression = convertExpression(ctx.Expression())
}
// EnterFormatterExpr is the visitor enter method for formatter expressions.
func (visitor *expressionConvertVisitor) EnterFormatterExpr(ctx *parser.FormatterExprContext) {
formatterContext := ctx.Formatter().(*parser.FormatterContext)
visitor.Expression = ast.NewFormatterExpression(formatterContext.IDENTIFIER().GetText(), convertArgumentList(formatterContext.ArgumentList()), convertMetadata(ctx))
}
// EnterCallExpr is the visitor enter method for call expressions.
func (visitor *expressionConvertVisitor) EnterCallExpr(ctx *parser.CallExprContext) {
identifier := ctx.IDENTIFIER().GetText()
argumentList := convertArgumentList(ctx.ArgumentList())
visitor.Expression = ast.NewCallExpression(ast.NewIdentifierExpression(identifier, convertTokenMetadata(ctx.IDENTIFIER())), argumentList, convertMetadata(ctx))
}
type statementConvertVisitor struct {
*parser.BaseScriptBlockParserListener
Statement ast.Statement
}
func newStatementConvertVisitor() *statementConvertVisitor {
return new(statementConvertVisitor)
}
// EnterFunctionCallStatement is the visitor enter method for function call statements.
func (visitor *statementConvertVisitor) EnterFunctionCallStatement(ctx *parser.FunctionCallStatementContext) {
visitor.Statement = convertFunctionCall(ctx.FunctionCall().(*parser.FunctionCallContext))
}
// EnterNativeCallStatement is the visitor enter method for native call statements.
func (visitor *statementConvertVisitor) EnterNativeCallStatement(ctx *parser.NativeCallStatementContext) {
nativeCall := ctx.NativeCall().(*parser.NativeCallContext)
arguments := newExpressionConvertVisitor().QuickVisitArgumentList(nativeCall.ArgumentList())
visitor.Statement = ast.NewNativeCall(arguments, convertMetadata(ctx))
}
func (visitor *statementConvertVisitor) EnterDelayStructureStatement(ictx *parser.DelayStructureStatementContext) {
ctx := ictx.DelayStructure().(*parser.DelayStructureContext)
delay := newExpressionConvertVisitor().QuickVisitExpression(ctx.StructureList().(*parser.StructureListContext).Expression(0))
body := convertFunctionFrame(ctx.FunctionFrame())
visitor.Statement = ast.NewDelayStatement(delay, body.Body, convertMetadata(ctx))
}
// EnterFunctionCallStatement is the visitor enter method for function call statements.
func (visitor *statementConvertVisitor) EnterRaiseStatement(lctx *parser.RaiseStatementContext) {
ctx := lctx.Raise().(*parser.RaiseContext)
identifierContexts := ctx.Tag().(*parser.TagContext).AllIDENTIFIER()
tag := convertTag(identifierContexts)
visitor.Statement = ast.NewRaiseStatement(tag, convertMetadata(ctx))
}
//TODO maybe merge these?
func (visitor *expressionConvertVisitor) QuickVisitArgumentList(list parser.IArgumentListContext) []ast.Expression {
expressionsContext := list.(*parser.ArgumentListContext).AllExpression()
arguments := make([]ast.Expression, len(expressionsContext))
for i, argument := range expressionsContext {
arguments[i] = visitor.QuickVisitExpression(argument)
}
return arguments
}
func (visitor *expressionConvertVisitor) QuickVisitStructureList(list parser.IStructureListContext) []ast.Expression {
expressionsContext := list.(*parser.StructureListContext).AllExpression()
arguments := make([]ast.Expression, len(expressionsContext))
for i, argument := range expressionsContext {
arguments[i] = visitor.QuickVisitExpression(argument)
}
return arguments
}
func (visitor *expressionConvertVisitor) QuickVisitExpression(expression parser.IExpressionContext) ast.Expression {
expression.EnterRule(visitor)
return visitor.Expression
}
type topConvertVisitor struct {
*parser.BaseScriptBlockParserListener
Definition ast.TopDefinition
}
func newTopConvertVisitor() *topConvertVisitor {
return &topConvertVisitor{nil, nil}
}
// EnterConstantDefinitionTop is the visitor enter method for constant definitions.
func (visitor *topConvertVisitor) EnterConstantDefinitionTop(ctxSwitch *parser.ConstantDefinitionTopContext) {
ctx := ctxSwitch.ConstantDefinition().(*parser.ConstantDefinitionContext)
name := ctx.IDENTIFIER().GetText()
expressionVisitor := newExpressionConvertVisitor()
ctx.Expression().EnterRule(expressionVisitor)
expression := expressionVisitor.Expression
internal := ctx.INTERNAL() != nil
var docs string
if ctx.Documentation() != nil {
docs = convertDoc(ctx.Documentation())
}
visitor.Definition = ast.NewConstantDefinition(name, expression, internal, docs, convertMetadata(ctx))
}
// EnterFunctionDefinitionTop is the visitor enter method for function definitions.
func (visitor *topConvertVisitor) EnterFunctionDefinitionTop(ctxSwitch *parser.FunctionDefinitionTopContext) {
ctx := ctxSwitch.FunctionDefinition().(*parser.FunctionDefinitionContext)
name := ctx.IDENTIFIER().GetText()
frame := convertFunctionFrame(ctx.FunctionFrame())
internal := ctx.INTERNAL() != nil
var tag ast.Tag
if ctx.Tag() != nil {
identifierContexts := ctx.Tag().(*parser.TagContext).AllIDENTIFIER()
tag = convertTag(identifierContexts)
}
var docs string
if ctx.Documentation() != nil {
docs = convertDoc(ctx.Documentation())
}
visitor.Definition = ast.NewFunctionDefinition(name, frame.Body, internal, tag, docs, convertMetadata(ctx))
}
// EnterTemplateDefinitionTop is the visitor enter method for template definitions.
func (visitor *topConvertVisitor) EnterTemplateDefinitionTop(ctxSwitch *parser.TemplateDefinitionTopContext) {
ctx := ctxSwitch.TemplateDefinition().(*parser.TemplateDefinitionContext)
name := ctx.IDENTIFIER().GetText()
frame := convertFunctionFrame(ctx.FunctionFrame())
internal := ctx.INTERNAL() != nil
var docs string
if ctx.Documentation() != nil {
docs = convertDoc(ctx.Documentation())
}
visitor.Definition = ast.NewTemplateDefinition(name, frame.Parameters, symbol.NoCloses(), frame.Body, internal, docs, convertMetadata(ctx))
}
// EnterFunctionShortcutTop is the visitor enter method for shortcut definitions.
func (visitor *topConvertVisitor) EnterFunctionShortcutTop(ctxSwitch *parser.FunctionShortcutTopContext) {
ctx := ctxSwitch.FunctionDefinitionShortcut().(*parser.FunctionDefinitionShortcutContext)
name := ctx.IDENTIFIER().GetText()
call := convertFunctionCall(ctx.FunctionCall().(*parser.FunctionCallContext))
internal := ctx.INTERNAL() != nil
var tag ast.Tag
if ctx.Tag() != nil {
identifierContexts := ctx.Tag().(*parser.TagContext).AllIDENTIFIER()
tag = convertTag(identifierContexts)
}
var docs string
if ctx.Documentation() != nil {
docs = convertDoc(ctx.Documentation())
}
visitor.Definition = ast.NewFunctionShortcutDefinition(name, call, internal, tag, docs, convertMetadata(ctx))
}
type unitConvertVisitor struct {
*parser.BaseScriptBlockParserListener
Unit *ast.Unit
}
func newUnitConvertVisitor() *unitConvertVisitor {
return new(unitConvertVisitor)
}
func (visitor *unitConvertVisitor) EnterUnit(ctx *parser.UnitContext) {
// TODO do not use visitor for now, only one option
iimportContexts := ctx.AllImportLine()
importLines := make([]*ast.ImportLine, len(iimportContexts))
for i, iimportContext := range iimportContexts {
importContext := iimportContext.(*parser.ImportLineContext)
entireString := importContext.STRING().GetText()
stringValue := entireString[1 : len(entireString)-1] // TODO crop quotes method? & check this in front end
module, unit := parseImportStatement(stringValue)
importLines[i] = &ast.ImportLine{Module: module, Unit: unit}
}
definitionContexts := ctx.AllTopDefinition()
definitions := make([]ast.TopDefinition, len(definitionContexts))
for i, definition := range definitionContexts {
topVisitor := newTopConvertVisitor()
definition.EnterRule(topVisitor)
definitions[i] = topVisitor.Definition
}
visitor.Unit = ast.NewUnit(importLines, definitions)
}
func parseImportStatement(stringValue string) (module string, unit string) {
data := strings.Split(stringValue, ":")
return data[0], data[1]
}
// func parseImportStatement(stringValue string) (location, module, tag, unit string) {
// importValue := strings.Replace(stringValue, "/", "\\", -1)
// pathText := strings.Split(importValue, "\\")
// location = strings.Join(pathText[0:len(pathText)-2], "\\")
// moduleSegment := pathText[len(pathText)-2]
// if strings.Contains(moduleSegment, "#") {
// moduleSplit := strings.Split(moduleSegment, "#")
// module = moduleSplit[0]
// tag = moduleSplit[1]
// } else {
// module = moduleSegment
// tag = ""
// }
// unit = pathText[len(pathText)-1]
// return
// }
<file_sep>/home/home.go
package home
import (
"os"
"path/filepath"
"github.com/falcinspire/scriptblock/environment"
)
func FindModuleInHome(name string) (path string, exists bool) {
homePath := os.Getenv("ScriptBlockPath")
modulePath := filepath.Join(homePath, "src", name)
if _, err := os.Stat(modulePath); !os.IsNotExist(err) {
return modulePath, true
} else {
return modulePath, false
}
}
func MakeModuleOutput(name string) string {
homePath := os.Getenv("ScriptBlockPath")
modulePath := filepath.Join(homePath, "bin", name)
return modulePath
}
func GetModuleConfig(data environment.ModuleDescription) *ModuleData {
configPath := filepath.Join(environment.GetModulePath(data), "module.yaml")
return ReadModuleFile(configPath)
}
func MakeModulePath(data environment.ModuleDescription) {
modulePath := filepath.Join(environment.GetHomeSourcePath(), data.Location, data.Version)
os.MkdirAll(modulePath, os.ModePerm)
}
// does not include version
func MakeAbreviatedModulePath(data environment.ModuleDescription) {
modulePath := filepath.Join(environment.GetHomeSourcePath(), data.Location)
os.MkdirAll(modulePath, os.ModePerm)
}
<file_sep>/compiler/front/astbook/book.go
package astbook
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
)
type AstBook map[string]AstUnitBook
func NewAstBook() AstBook {
return make(AstBook)
}
type AstUnitBook map[string]*ast.Unit
func NewAstUnitBook() AstUnitBook {
return make(AstUnitBook)
}
func InsertAst(location *location.UnitLocation, tree *ast.Unit, book AstBook) {
_, exists := book[location.Module]
if !exists {
book[location.Module] = NewAstUnitBook()
}
book[location.Module][location.Unit] = tree
}
func LookupAst(location *location.UnitLocation, book AstBook) *ast.Unit {
return book[location.Module][location.Unit]
}
<file_sep>/compiler/back/tags/tagwriter.go
package tags
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/falcinspire/scriptblock/compiler/ast/location"
)
// WriteAllTagsToFiles writes all of the tags and locations provided into the output directory.
func WriteAllTagsToFiles(tags map[string]LocationList, output string) {
for tagInformal, locations := range tags {
tag := location.TagLocationFromInformal(tagInformal)
WriteTagToFile(tag, locations, output)
}
}
// minecraftTagFormat is the struct used to json deserialization.
type minecraftTagFormat struct {
Values []string `json:"values"`
}
// WriteTagToFile writes a single tag and its locations to the output directory.
func WriteTagToFile(tag *location.TagLocation, locations LocationList, output string) {
tagFile := fmt.Sprintf("%s.json", tag.Identity)
parentPath := filepath.Join(output, tag.Namespace, "tags/functions/")
filePath := filepath.Join(parentPath, tagFile)
os.MkdirAll(parentPath, os.ModePerm)
data, _ := json.Marshal(minecraftTagFormat{locations})
ioutil.WriteFile(filePath, data, 0666) // TODO No idea what 0666 is. Cite it from the stackoverflow post and try to figure it out
}
<file_sep>/compiler/ast/location/tagpath.go
package location
import (
"fmt"
"strings"
)
func InformalTagPath(location *TagLocation) string {
return fmt.Sprintf("%s:%s", location.Namespace, location.Identity)
}
func TagLocationFromInformal(path string) *TagLocation {
data := strings.Split(path, ":")
return NewTagLocation(data[0], data[1])
}
<file_sep>/compiler/front/resolver/resolve_simple.go
package resolver
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
"github.com/falcinspire/scriptblock/compiler/front/imports"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
)
func ResolvePass(unit *ast.Unit, unitLocation *location.UnitLocation, symbollibrary *symbols.SymbolLibrary, importbook imports.ImportBook) {
environment := CreateResolveEnvironment(unitLocation, symbollibrary, importbook)
unit.Accept(NewResolveUnitVisitor(environment))
}
func MakeLocalTableFromParameters(parameters []string, depth int) symbols.LocalSymbolTable {
localTable := symbols.NewLocalSymbolTable()
for _, parameter := range parameters {
localTable[parameter] = symbol.NewParameterAddressBox(depth, parameter)
}
return localTable
}
func ResolveFunctionFrame(frame *FunctionFrame, environment *ResolveEnvironment, depth int) {
environment.linkedLocals.PushTable(MakeLocalTableFromParameters(frame.Parameters, depth))
for _, statement := range frame.Body {
statement.Accept(NewResolveStatementVisitor(environment, depth))
}
environment.linkedLocals.PopTable()
}
func ResolveExpressionFrame(expression ast.Expression, environment *ResolveEnvironment) {
environment.linkedLocals.PushTable(symbols.NewLocalSymbolTable())
expressionVisitor := NewResolveExpressionVisitor(environment)
expression.Accept(expressionVisitor)
environment.linkedLocals.PopTable()
}
func ResolveIdentifier(name string, metadata *ast.Metadata, environment *ResolveEnvironment) (address *symbol.AddressBox) {
tryLocal, exists := FindLocal(name, environment)
if exists {
return tryLocal
}
tryClosed, exists := FindClosed(name, environment)
if exists {
return tryClosed
}
tryUnit, exists := FindUnit(name, environment)
if exists {
return tryUnit
}
tryImport, exists := FindImported(name, environment)
if exists {
return tryImport
}
panic(NewResolveError(name, metadata))
}
<file_sep>/compiler/ast/statements.go
package ast
// Statement is any node that represents a statement
type Statement interface {
Accept(visitor StatementVisitor)
}
// TrailingFunction is any node that represents a trailing function
type TrailingFunction struct {
Parameters []string
Body []Statement
Metadata *Metadata
}
// FunctionCall is any node that represents a function call
type FunctionCall struct {
Callee Expression // TODO this is nearly always identifier, but can also be a functor
Arguments []Expression
Trailing *TrailingFunction
Metadata *Metadata
}
// NewFunctionCall is a constructor for FunctionCall
func NewFunctionCall(callee Expression, arguments []Expression, trailing *TrailingFunction, metadata *Metadata) *FunctionCall {
return &FunctionCall{callee, arguments, trailing, metadata}
}
// Accept runs the double dispatch for the visitor
func (statement *FunctionCall) Accept(visitor StatementVisitor) {
visitor.VisitFunctionCall(statement)
}
// NativeCall is any node that represents a native call
type NativeCall struct {
Arguments []Expression
Metadata *Metadata
}
// NewNativeCall is a constructor for NativeCall
func NewNativeCall(arguments []Expression, metadata *Metadata) *NativeCall {
return &NativeCall{arguments, metadata}
}
// Accept runs the double dispatch for the visitor
func (statement *NativeCall) Accept(visitor StatementVisitor) {
visitor.VisitNativeCall(statement)
}
// DelayStatement is any node that represents a delay statement
type DelayStatement struct {
TickDelay Expression
Body []Statement
Metadata *Metadata
FunctionCall *FunctionCall // for when it is resolved
}
// NewDelayStatement is a constructor for DelayStatement
func NewDelayStatement(tickDelay Expression, body []Statement, metadata *Metadata) *DelayStatement {
return &DelayStatement{tickDelay, body, metadata, nil}
}
// Accept runs the double dispatch for the visitor
func (statement *DelayStatement) Accept(visitor StatementVisitor) {
visitor.VisitDelay(statement)
}
type RaiseStatement struct {
Tag Tag
Metadata *Metadata
}
func NewRaiseStatement(tag Tag, metadata *Metadata) *RaiseStatement {
return &RaiseStatement{tag, metadata}
}
// Accept runs the double dispatch for the visitor
func (statement *RaiseStatement) Accept(visitor StatementVisitor) {
visitor.VisitRaise(statement)
}
<file_sep>/compiler/ast/importline.go
package ast
// ImportLine is any node that represents an import line
type ImportLine struct {
Location string
Module string
Unit string
Metadata *Metadata
}
<file_sep>/compiler/ast/expression.go
package ast
import "github.com/falcinspire/scriptblock/compiler/ast/symbol"
// Expression is any node that represents an expression
type Expression interface {
Accept(visitor ExpressionVisitor)
}
// NumberExpression is an expression that represents a number
type NumberExpression struct {
Value float64
Metadata *Metadata
}
// NewNumberExpression is a constructor for NumberExpression
func NewNumberExpression(value float64, metadata *Metadata) *NumberExpression {
return &NumberExpression{value, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *NumberExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitNumber(expression)
}
// StringExpression is any node that represents a string expression
type StringExpression struct {
Value string
Metadata *Metadata
}
// NewStringExpression is a constructor for StringExpression
func NewStringExpression(value string, metadata *Metadata) *StringExpression {
expr := new(StringExpression)
expr.Value = value
return expr
}
// Accept runs the double dispatch for the visitor
func (expression *StringExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitString(expression)
}
// AddExpression is any node that represents a addition expression
type AddExpression struct {
Left Expression
Right Expression
Metadata *Metadata
}
// NewAddExpression is a constructor for AddExpression
func NewAddExpression(left Expression, right Expression, metadata *Metadata) *AddExpression {
return &AddExpression{left, right, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *AddExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitAdd(expression)
}
// SubtractExpression is any node that represents a subtraction expression
type SubtractExpression struct {
Left Expression
Right Expression
Metadata *Metadata
}
// NewSubtractExpression is a constructor for SubtractExpression
func NewSubtractExpression(left Expression, right Expression, metadata *Metadata) *SubtractExpression {
return &SubtractExpression{left, right, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *SubtractExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitSubtract(expression)
}
// MultiplyExpression is any node that represents a multiply expression
type MultiplyExpression struct {
Left Expression
Right Expression
Metadata *Metadata
}
// NewMultiplyExpression is a constructor for MultiplyExpression
func NewMultiplyExpression(left Expression, right Expression, metadata *Metadata) *MultiplyExpression {
return &MultiplyExpression{left, right, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *MultiplyExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitMultiply(expression)
}
// DivideExpression is any node that represents a divide expression
type DivideExpression struct {
Left Expression
Right Expression
Metadata *Metadata
}
// NewDivideExpression is a constructor for DivideExpression
func NewDivideExpression(left Expression, right Expression, metadata *Metadata) *DivideExpression {
return &DivideExpression{left, right, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *DivideExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitDivide(expression)
}
// IntegerDivideExpression is any node that represents a integer divide expression
type IntegerDivideExpression struct {
Left Expression
Right Expression
Metadata *Metadata
}
// NewIntegerDivideExpression is a constructor for DivideExpression
func NewIntegerDivideExpression(left Expression, right Expression, metadata *Metadata) *IntegerDivideExpression {
return &IntegerDivideExpression{left, right, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *IntegerDivideExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitIntegerDivide(expression)
}
// PowerExpression is any node that represents a power expression
type PowerExpression struct {
Left Expression
Right Expression
Metadata *Metadata
}
// NewPowerExpression is a constructor for PowerExpression
func NewPowerExpression(left Expression, right Expression, metadata *Metadata) *PowerExpression {
return &PowerExpression{left, right, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *PowerExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitPower(expression)
}
// FormatterExpression is any node that represents a formatter expression
type FormatterExpression struct {
Format string
Arguments []Expression
Metadata *Metadata
}
// NewFormatterExpression is a constructor for FormatterExpression
func NewFormatterExpression(format string, arguments []Expression, metadata *Metadata) *FormatterExpression {
return &FormatterExpression{format, arguments, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *FormatterExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitFormatter(expression)
}
// IdentifierExpression is any node that represents a identifier expression
type IdentifierExpression struct {
Name string
Address *symbol.AddressBox // resolution pass
Metadata *Metadata
}
// NewIdentifierExpression is a constructor for IdentifierExpression
func NewIdentifierExpression(name string, metadata *Metadata) *IdentifierExpression {
return &IdentifierExpression{name, nil, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *IdentifierExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitIdentifier(expression)
}
// FunctorExpression is any node that represents a functor expression
type FunctorExpression struct {
Callee Expression
Capture []*IdentifierExpression
Metadata *Metadata
}
// NewFunctorExpression is a constructor for FunctorExpression
func NewFunctorExpression(callee Expression, capture []*IdentifierExpression, metadata *Metadata) *FunctorExpression {
return &FunctorExpression{callee, capture, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *FunctorExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitFunctor(expression)
}
// CallExpression is any node that represents a call expression
type CallExpression struct {
Identifier Expression
Arguments []Expression
Captures []Expression
Metadata *Metadata
}
// NewCallExpression is a constructor for CallExpression
func NewCallExpression(identifier Expression, arguments []Expression, metadata *Metadata) *CallExpression {
return &CallExpression{identifier, arguments, []Expression{}, metadata}
}
// Accept runs the double dispatch for the visitor
func (expression *CallExpression) Accept(visitor ExpressionVisitor) {
visitor.VisitCall(expression)
}
<file_sep>/compiler/back/desugar/freeset.go
package desugar
import (
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
)
type freeVariableSet struct {
list []*symbol.ParameterAddress
set map[string]bool
}
func newFreeVariableSet() *freeVariableSet {
return &freeVariableSet{[]*symbol.ParameterAddress{}, map[string]bool{}}
}
func AddToFreeSet(address *symbol.ParameterAddress, set *freeVariableSet) {
_, exists := set.set[address.Name]
if !exists {
set.set[address.Name] = true
set.list = append(set.list, address)
}
}
func ListFreeSet(set *freeVariableSet) []*symbol.ParameterAddress {
return set.list
}
<file_sep>/compiler/back/evaluator/doc.go
// Package evaluator handles converting scriptblock functions into mcfunctions
// and reducing expressions to single values that can be converted to strings.
package evaluator
<file_sep>/compiler/back/valuepass/pass_three_visitor.go
package valuepass
import (
"fmt"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/back/dumper"
"github.com/falcinspire/scriptblock/compiler/back/evaluator"
"github.com/falcinspire/scriptblock/compiler/back/tags"
"github.com/sirupsen/logrus"
)
type topThreeValueVisitor struct {
*ast.BaseTopVisitor
data *evaluator.EvaluateData
tags map[string]tags.LocationList
}
func newTopThreeValueVisitor(data *evaluator.EvaluateData, tags map[string]tags.LocationList) *topThreeValueVisitor {
return &topThreeValueVisitor{nil, data, tags}
}
func (visitor *topThreeValueVisitor) VisitFunctionDefinition(definition *ast.FunctionDefinition) {
logrus.WithFields(logrus.Fields{
"module": visitor.data.Location.Module,
"unit": visitor.data.Location.Unit,
"name": definition.Name,
}).Info("Evaluating function")
stringBody := evaluator.TranslateFunction(definition, visitor.data.Location, visitor.data)
dumper.DumpFunction(visitor.data.Location.Module, visitor.data.Location.Unit, definition.Name, stringBody, visitor.data.Output)
if definition.Tag.Namespace != "" {
informal := location.InformalTagPath(location.NewTagLocation(definition.Tag.Namespace, definition.Tag.Identity))
visitor.tags[informal] = append(visitor.tags[informal], fmt.Sprintf("%s:%s/%s", visitor.data.Location.Module, visitor.data.Location.Unit, definition.Name))
}
}
type unitThreeValueVisitor struct {
data *evaluator.EvaluateData
tags map[string]tags.LocationList
}
func newUnitThreeValueVisitor(data *evaluator.EvaluateData, tags map[string]tags.LocationList) *unitThreeValueVisitor {
return &unitThreeValueVisitor{data, tags}
}
func (visitor *unitThreeValueVisitor) VisitUnit(unit *ast.Unit) {
for _, definition := range unit.Definitions {
definition.Accept(newTopThreeValueVisitor(visitor.data, visitor.tags))
}
if len(visitor.data.LoopInject.InjectBody) > 0 {
module, unit, name := evaluator.GenerateTickFunction(visitor.data.LoopInject, visitor.data.Location, visitor.data.Output)
loopAddress := fmt.Sprintf("%s:%s/%s", module, unit, name)
visitor.tags["minecraft:tick"] = append(visitor.tags["minecraft:tick"], loopAddress)
}
}
<file_sep>/compiler/front/symbolgen/toplevel_simple.go
package symbolgen
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
)
func SymbolsPass(unit *ast.Unit, address *location.UnitLocation, symbollibrary *symbols.SymbolLibrary) {
visitor := NewUnitSymbolVisitor(address)
unit.Accept(visitor)
symbols.InsertSymbolTable(address.Module, address.Unit, visitor.Exported, symbollibrary.Exported)
symbols.InsertSymbolTable(address.Module, address.Unit, visitor.Internal, symbollibrary.Internal)
}
<file_sep>/compiler/back/values/visitor_base.go
package values
type BaseValueVisitor struct{}
func (visitor *BaseValueVisitor) VisitNumber(numberValue *NumberValue) {}
func (visitor *BaseValueVisitor) VisitString(stringValue *StringValue) {}
func (visitor *BaseValueVisitor) VisitFunction(functionValue *FunctionValue) {}
func (visitor *BaseValueVisitor) VisitTemplate(templateReference *TemplateValue) {}
func (visitor *BaseValueVisitor) VisitFunctor(functorValue *FunctorValue) {}
<file_sep>/compiler/back/valuepass/pass_three_simple.go
package valuepass
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/evaluator"
"github.com/falcinspire/scriptblock/compiler/back/tags"
"github.com/sirupsen/logrus"
)
func PassThree(unit *ast.Unit, data *evaluator.EvaluateData, tags map[string]tags.LocationList) {
logrus.WithFields(logrus.Fields{
"module": data.Location.Module,
"unit": data.Location.Unit,
}).Info("Value pass 3")
unit.Accept(newUnitThreeValueVisitor(data, tags))
}
<file_sep>/compiler/front/parser/parser_simple.go
package parser
import (
"github.com/antlr/antlr4/runtime/Go/antlr"
)
// Parse simply turns the file at the given location into a parse (concrete syntax) tree
func Parse(filePath string) IUnitContext {
input, _ := antlr.NewFileStream(filePath)
lexer := NewScriptBlockLexer(input)
stream := antlr.NewCommonTokenStream(lexer, 0)
p := NewScriptBlockParser(stream)
p.AddErrorListener(antlr.NewDiagnosticErrorListener(true))
p.BuildParseTrees = true
return p.Unit()
}
<file_sep>/compiler/front/resolver/resolve_visitor.go
package resolver
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
"github.com/sirupsen/logrus"
)
type ResolveExpressionVisitor struct {
*ast.BaseExpressionVisitor
environment *ResolveEnvironment
}
func NewResolveExpressionVisitor(environment *ResolveEnvironment) *ResolveExpressionVisitor {
visitor := new(ResolveExpressionVisitor)
visitor.environment = environment
return visitor
}
func (visitor *ResolveExpressionVisitor) VisitIdentifier(identifier *ast.IdentifierExpression) {
address := ResolveIdentifier(identifier.Name, identifier.Metadata, visitor.environment)
identifier.Address = address
logrus.WithFields(logrus.Fields{
"identifier": identifier.Name,
"addressType": address.Type,
"address": address.Data,
}).Info("resolved identifier")
}
func (visitor *ResolveExpressionVisitor) VisitAdd(add *ast.AddExpression) {
add.Left.Accept(visitor)
add.Right.Accept(visitor)
}
func (visitor *ResolveExpressionVisitor) VisitSubtract(add *ast.SubtractExpression) {
add.Left.Accept(visitor)
add.Right.Accept(visitor)
}
func (visitor *ResolveExpressionVisitor) VisitMultiply(add *ast.MultiplyExpression) {
add.Left.Accept(visitor)
add.Right.Accept(visitor)
}
func (visitor *ResolveExpressionVisitor) VisitDivide(add *ast.DivideExpression) {
add.Left.Accept(visitor)
add.Right.Accept(visitor)
}
func (visitor *ResolveExpressionVisitor) VisitIntegerDivide(add *ast.IntegerDivideExpression) {
add.Left.Accept(visitor)
add.Right.Accept(visitor)
}
func (visitor *ResolveExpressionVisitor) VisitPower(add *ast.PowerExpression) {
add.Left.Accept(visitor)
add.Right.Accept(visitor)
}
func (visitor *ResolveExpressionVisitor) VisitFormatter(format *ast.FormatterExpression) {
for _, argument := range format.Arguments {
argument.Accept(visitor)
}
}
func (visitor *ResolveExpressionVisitor) VisitCall(call *ast.CallExpression) {
call.Identifier.Accept(visitor)
for _, argument := range call.Arguments {
argument.Accept(visitor)
}
}
type ResolveStatementVisitor struct {
*ast.BaseStatementVisitor
environment *ResolveEnvironment
depth int
}
func NewResolveStatementVisitor(environment *ResolveEnvironment, depth int) *ResolveStatementVisitor {
visitor := new(ResolveStatementVisitor)
visitor.environment = environment
visitor.depth = depth
return visitor
}
func (visitor *ResolveStatementVisitor) VisitFunctionCall(call *ast.FunctionCall) {
call.Callee.Accept(NewResolveExpressionVisitor(visitor.environment))
if call.Trailing != nil {
frame := &FunctionFrame{call.Trailing.Parameters, call.Trailing.Body}
environment := visitor.environment
ResolveFunctionFrame(frame, environment, visitor.depth+1)
}
}
func (visitor *ResolveStatementVisitor) VisitNativeCall(call *ast.NativeCall) {
for _, expression := range call.Arguments {
expression.Accept(NewResolveExpressionVisitor(visitor.environment))
}
}
type ResolveTopDefinitionVisitor struct {
*ast.BaseTopVisitor
environment *ResolveEnvironment
}
func NewResolveTopDefinitionVisitor(environment *ResolveEnvironment) *ResolveTopDefinitionVisitor {
visitor := new(ResolveTopDefinitionVisitor)
visitor.environment = environment
return visitor
}
func (visitor *ResolveTopDefinitionVisitor) VisitFunctionDefinition(definition *ast.FunctionDefinition) {
visitor.environment.linkedLocals = symbols.NewLinkedSymbolTable()
frame := &FunctionFrame{make([]string, 0), definition.Body}
environment := visitor.environment
depth := 0
ResolveFunctionFrame(frame, environment, depth)
}
func (visitor *ResolveTopDefinitionVisitor) VisitFunctionShortcutDefinition(shortcut *ast.FunctionShortcutDefinition) {
expressionVisitor := NewResolveExpressionVisitor(visitor.environment)
shortcut.FunctionCall.Callee.Accept(expressionVisitor)
for _, argument := range shortcut.FunctionCall.Arguments {
argument.Accept(expressionVisitor)
}
}
func (visitor *ResolveTopDefinitionVisitor) VisitTemplateDefinition(definition *ast.TemplateDefinition) {
visitor.environment.linkedLocals = symbols.NewLinkedSymbolTable()
frame := &FunctionFrame{definition.Parameters, definition.Body}
environment := visitor.environment
depth := 0
ResolveFunctionFrame(frame, environment, depth)
}
func (visitor *ResolveTopDefinitionVisitor) VisitConstantDefinition(definition *ast.ConstantDefinition) {
visitor.environment.linkedLocals = symbols.NewLinkedSymbolTable()
expression := definition.Value
environment := visitor.environment
ResolveExpressionFrame(expression, environment)
}
type ResolveUnitVisitor struct {
environment *ResolveEnvironment
}
func NewResolveUnitVisitor(environment *ResolveEnvironment) *ResolveUnitVisitor {
return &ResolveUnitVisitor{environment}
}
func (visitor *ResolveUnitVisitor) VisitUnit(unit *ast.Unit) {
for _, definition := range unit.Definitions {
definition.Accept(NewResolveTopDefinitionVisitor(visitor.environment))
}
}
<file_sep>/compiler/back/desugar/desugar_visitor.go
package desugar
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
"github.com/sirupsen/logrus"
)
type desugarExpressionVisitor struct {
*ast.BaseExpressionVisitor
depth int
freeVariables *freeVariableSet
}
func newDesugarExpressionVisitor(depth int, freeVariables *freeVariableSet) *desugarExpressionVisitor {
return &desugarExpressionVisitor{nil, depth, freeVariables}
}
func (visitor *desugarExpressionVisitor) VisitIdentifier(identifier *ast.IdentifierExpression) {
//TODO check this
if identifier.Address.Type == symbol.PARAMETER {
parameterAddress := identifier.Address.Data.(*symbol.ParameterAddress)
if parameterAddress.ClosureDepth != visitor.depth {
logrus.WithFields(logrus.Fields{
"name": parameterAddress.Name,
"depth": parameterAddress.ClosureDepth,
"visitDepth": visitor.depth,
}).Info("passing up free identifier")
AddToFreeSet(identifier.Address.Data.(*symbol.ParameterAddress), visitor.freeVariables)
identifier.Address = symbol.NewCaptureAddressBox(identifier.Address.Data.(*symbol.ParameterAddress).Name)
}
}
// if identifier.Free {
// AddToFreeSet(identifier.Address.Data.(*symbol.ParameterAddress), visitor.freeVariables)
// identifier.Address = symbol.NewCaptureAddressBox(identifier.Address.Data.(*symbol.ParameterAddress).Name)
// identifier.Free = false
// }
}
func (visitor *desugarExpressionVisitor) VisitFunctor(functor *ast.FunctorExpression) {
functor.Callee.Accept(visitor)
for _, arg := range functor.Capture {
arg.Accept(visitor)
}
}
type desugarStatementVisitor struct {
*ast.BaseStatementVisitor
injector *functionInjector
rewriter *StatementRewriter
depth int
freeVariables *freeVariableSet
}
func newDesugarStatementVisitor(injector *functionInjector, rewriter *StatementRewriter, depth int, freeVariables *freeVariableSet) *desugarStatementVisitor {
return &desugarStatementVisitor{nil, injector, rewriter, depth, freeVariables}
}
func (visitor *desugarStatementVisitor) VisitFunctionCall(call *ast.FunctionCall) {
if call.Trailing != nil {
trailing := call.Trailing
trailingToExpression := desugarTrailing(&functionFrame{trailing.Parameters, trailing.Body}, visitor.injector, visitor.depth+1)
call.Arguments = append(call.Arguments, trailingToExpression)
call.Trailing = nil
}
for _, argument := range call.Arguments {
argument.Accept(newDesugarExpressionVisitor(visitor.depth, visitor.freeVariables))
}
}
func (visitor *desugarStatementVisitor) VisitDelay(call *ast.DelayStatement) {
logrus.WithFields(logrus.Fields{
"line_local": visitor.rewriter.index,
}).Info("rewriting delay call")
//TODO does something need to be updated here?
trailingToExpression := desugarTrailing(&functionFrame{[]string{}, call.Body}, visitor.injector, visitor.depth+1)
call.FunctionCall = ast.NewFunctionCall(trailingToExpression, []ast.Expression{}, nil, nil)
}
func (visitor *desugarStatementVisitor) VisitNativeCall(call *ast.NativeCall) {
for _, expression := range call.Arguments {
expression.Accept(newDesugarExpressionVisitor(visitor.depth, visitor.freeVariables))
}
}
type desugarTopDefinitionVisitor struct {
*ast.BaseTopVisitor
injector *functionInjector
}
func newDesugarTopDefinitionVisitor(injector *functionInjector) *desugarTopDefinitionVisitor {
visitor := new(desugarTopDefinitionVisitor)
visitor.injector = injector
return visitor
}
func (visitor *desugarTopDefinitionVisitor) VisitFunctionDefinition(definition *ast.FunctionDefinition) {
logrus.WithFields(logrus.Fields{
"function": definition.Name,
}).Info("desugaring")
frame := &functionFrame{make([]string, 0), definition.Body}
injector := visitor.injector
depth := 0
desugarFunctionFrame(frame, injector, depth)
}
func (visitor *desugarTopDefinitionVisitor) VisitFunctionShortcutDefinition(shortcut *ast.FunctionShortcutDefinition) {
logrus.WithFields(logrus.Fields{
"function-shortcut": shortcut.Name,
}).Info("desugaring")
visitor.injector.replaceFunction(shortcut.Name, []ast.Statement{shortcut.FunctionCall}, shortcut.Internal, shortcut.Tag, shortcut.Documentation)
}
func (visitor *desugarTopDefinitionVisitor) VisitTemplateDefinition(definition *ast.TemplateDefinition) {
logrus.WithFields(logrus.Fields{
"template": definition.Name,
}).Info("desugaring")
frame := &functionFrame{definition.Parameters, definition.Body}
injector := visitor.injector
depth := 0
desugarFunctionFrame(frame, injector, depth)
}
func (visitor *desugarTopDefinitionVisitor) VisitConstantDefinition(definition *ast.ConstantDefinition) {
logrus.WithFields(logrus.Fields{
"constant": definition.Name,
}).Info("desugaring")
expression := definition.Value
desugarExpressionFrame(expression)
}
type desugarUnitVisitor struct {
unit *ast.Unit
location *location.UnitLocation
}
func newDesugarUnitVisitor(unit *ast.Unit, location *location.UnitLocation) *desugarUnitVisitor {
visitor := new(desugarUnitVisitor)
visitor.unit = unit
visitor.location = location
return visitor
}
func (visitor *desugarUnitVisitor) VisitUnit(unit *ast.Unit) {
for i, definition := range unit.Definitions {
definition.Accept(newDesugarTopDefinitionVisitor(newFunctionInjector(visitor.unit, visitor.location, i)))
}
}
<file_sep>/compiler/back/nativefuncs/nativefunctions.go
package nativefuncs
import (
"fmt"
"path/filepath"
"strings"
"github.com/falcinspire/scriptblock/compiler/back/values"
)
// NativeFunction is a function that is run with arguments and returns a string
type NativeFunction func(modulepath string, args []values.Value) string
// numberAsInt converts the number given as the first argument into an integer
func numberAsInt(modulepath string, args []values.Value) string {
valueAsInt := int(args[0].(*values.NumberValue).Value)
return fmt.Sprintf("%d", valueAsInt)
}
// fromFile reads the file at the string path provided and returns its contents
// without whitespaces
func fromFile(modulepath string, args []values.Value) string {
valueAsString := args[0].(*values.StringValue).Value
resourcePath := filepath.Join(modulepath, valueAsString)
return readResource(resourcePath)
}
// joinToSelector joins all the arguments as strings into a selector
func joinToSelector(modulepath string, args []values.Value) string {
valuesAsStringArray := make([]string, len(args))
for i, arrayValue := range args {
valuesAsStringArray[i] = arrayValue.(*values.StringValue).Value
}
body := strings.Join(valuesAsStringArray, ",")
return fmt.Sprintf("@e[%s]", body)
}
// joinStrings joins all the arguments as strings into a string.
// This is useful when things need to be joined without a space inbetween.
func joinStrings(modulepath string, args []values.Value) string {
valuesAsStringArray := make([]string, len(args))
for i, arrayValue := range args {
valuesAsStringArray[i] = fmt.Sprintf("%s", arrayValue)
}
return strings.Join(valuesAsStringArray, "")
}
// giveQuotes puts quotes around the first argument provided.
// This makes the argument into a string expression.
func giveQuotes(modulepath string, args []values.Value) string {
valueAsString := args[0].(*values.StringValue).Value
return fmt.Sprintf("\"%s\"", valueAsString)
}
// CreateNativeMap creates a map of names to native functions
func CreateNativeMap() map[string]NativeFunction {
return map[string]NativeFunction{
"int": numberAsInt,
"resource": fromFile,
"selector": joinToSelector,
"join": joinStrings,
"string": giveQuotes,
}
}
<file_sep>/compiler/back/values/util.go
package values
func NoArguments() []Value {
return []Value{}
}
func NoCaptures() []Value {
return []Value{}
}
<file_sep>/environment/environment.go
package environment
import (
"os"
"path/filepath"
)
type ModuleDescription struct {
Location string
Version string
}
func GetHomePath() string {
return os.Getenv("ScriptBlockPath")
}
func GetHomeSourcePath() string {
return filepath.Join(GetHomePath(), "src")
}
func GetHomeOutputPath() string {
return filepath.Join(GetHomePath(), "bin")
}
func GetModulePath(data ModuleDescription) string {
return filepath.Join(GetHomeSourcePath(), data.Location, data.Version)
}
func GetAbreviatedModulePath(data ModuleDescription) string {
return filepath.Join(GetHomeSourcePath(), data.Location)
}
<file_sep>/compiler/back/addressbook/addressbook.go
package addressbook
import (
"github.com/falcinspire/scriptblock/compiler/ast"
)
// AddressBook stores the actual function code for each unit.
type AddressBook map[string]addressUnitBook
func NewAddressBook() AddressBook {
return make(AddressBook)
}
type addressUnitBook map[string]*AddressTable
func newAddressUnitBook() addressUnitBook {
return make(addressUnitBook)
}
func InsertAddressTable(module, unit string, table *AddressTable, book AddressBook) {
_, exists := book[module]
if !exists {
book[module] = newAddressUnitBook()
}
book[module][unit] = table
}
func LookupAddressTable(module, unit string, book AddressBook) *AddressTable {
return book[module][unit]
}
type AddressTable struct {
Functors map[string]*ast.TemplateDefinition
}
func NewAddressTable() *AddressTable {
return &AddressTable{make(map[string]*ast.TemplateDefinition)}
}
func AddressTemplate(module string, unit string, name string, book AddressBook) *ast.TemplateDefinition {
return LookupAddressTable(module, unit, book).Functors[name]
}
func InsertFunctorAddress(closure *ast.TemplateDefinition, module string, unit string, name string, book AddressBook) {
LookupAddressTable(module, unit, book).Functors[name] = closure
}
<file_sep>/compiler/front/resolver/freetable.go
package resolver
type FreeTable []string
func NewFreeTable() FreeTable {
return make(FreeTable, 0)
}
type FreeTableStack struct {
stack []FreeTable
}
func NewFreeTableStack() *FreeTableStack {
return &FreeTableStack{make([]FreeTable, 0)}
}
func (this *FreeTableStack) AppendToTop(identifier string) {
this.stack[len(this.stack)-1] = append(this.stack[len(this.stack)-1], identifier)
}
func (this *FreeTableStack) PeekFreeTable() FreeTable {
return this.stack[len(this.stack)-1]
}
func (this *FreeTableStack) PushFreeTable() {
this.stack = append(this.stack, NewFreeTable())
}
func (this *FreeTableStack) PopFreeTable() FreeTable {
remember := this.stack[len(this.stack)-1]
this.stack = this.stack[0 : len(this.stack)-1]
return remember
}
<file_sep>/compiler/back/nativefuncs/read_resource.go
package nativefuncs
import (
"io/ioutil"
"strings"
"unicode"
)
// readResource reads the file at filepath into a no whitespace string
func readResource(filepath string) string {
fileBytes, err := ioutil.ReadFile(filepath)
if err != nil {
panic(err)
}
fileString := string(fileBytes)
fileNoWs := spaceStringsBuilder(fileString)
return fileNoWs
}
// https://stackoverflow.com/questions/32081808/strip-all-whitespace-from-a-string
// author <NAME>
func spaceStringsBuilder(str string) string {
var b strings.Builder
b.Grow(len(str))
for _, ch := range str {
if !unicode.IsSpace(ch) {
b.WriteRune(ch)
}
}
return b.String()
}
<file_sep>/compiler/back/evaluator/rawify_simple.go
package evaluator
import "github.com/falcinspire/scriptblock/compiler/back/values"
func RawifyValue(value values.Value) string {
visitor := NewRawifyValueVisitor()
value.Accept(visitor)
return visitor.Result
}
<file_sep>/compiler/back/valuepass/pass_two_visitor.go
package valuepass
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/evaluator"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/sirupsen/logrus"
)
type topTwoValueVisitor struct {
*ast.BaseTopVisitor
data *evaluator.EvaluateData
}
func newTopTwoValueVisitor(data *evaluator.EvaluateData) *topTwoValueVisitor {
return &topTwoValueVisitor{nil, data}
}
func (visitor *topTwoValueVisitor) VisitConstantDefinition(definition *ast.ConstantDefinition) {
logrus.WithFields(logrus.Fields{
"module": visitor.data.Location.Module,
"unit": visitor.data.Location.Unit,
"name": definition.Name,
}).Info("Evaluating constant")
value := evaluator.ReduceExpression(definition.Value, visitor.data)
var table values.ValueTable
if definition.Internal {
table = values.LookupValueTable(visitor.data.Location.Module, visitor.data.Location.Unit, visitor.data.ValueLibrary.Internal)
} else {
table = values.LookupValueTable(visitor.data.Location.Module, visitor.data.Location.Unit, visitor.data.ValueLibrary.Exported)
}
table[definition.Name] = value
}
type unitTwoValueVisitor struct {
data *evaluator.EvaluateData
}
func newUnitTwoValueVisitor(data *evaluator.EvaluateData) *unitTwoValueVisitor {
return &unitTwoValueVisitor{data}
}
func (visitor *unitTwoValueVisitor) VisitUnit(unit *ast.Unit) {
for _, definition := range unit.Definitions {
definition.Accept(newTopTwoValueVisitor(visitor.data))
}
}
<file_sep>/compiler/ast/top.go
package ast
// TopDefinition is any node that represents a top definitino
type TopDefinition interface {
Accept(visitor TopVisitor)
}
<file_sep>/compiler/ast/location/taglocation.go
package location
type TagLocation struct {
Namespace string
Identity string
}
func NewTagLocation(namespace string, identity string) *TagLocation {
return &TagLocation{namespace, identity}
}
<file_sep>/compiler/front/resolver/resolveenv.go
package resolver
import (
"encoding/json"
"fmt"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
"github.com/falcinspire/scriptblock/compiler/front/imports"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
)
type ResolveError struct {
name string
metadata *ast.Metadata
}
func NewResolveError(symbol string, metadata *ast.Metadata) ResolveError {
return ResolveError{symbol, metadata}
}
func (this ResolveError) Error() string {
data, _ := json.Marshal(this.metadata)
return fmt.Sprintf("Cannot resolve \"%s\", %s", this.name, string(data))
}
type ResolveEnvironment struct {
linkedLocals *symbols.LinkedSymbolTable
selfInternal symbols.SymbolTable
selfExported symbols.SymbolTable
imported []symbols.SymbolTable
}
func CreateResolveEnvironment(unitLocation *location.UnitLocation, symbollibrary *symbols.SymbolLibrary, importbook imports.ImportBook) *ResolveEnvironment {
internal := symbols.LookupSymbolTable(unitLocation.Module, unitLocation.Unit, symbollibrary.Internal)
exported := symbols.LookupSymbolTable(unitLocation.Module, unitLocation.Unit, symbollibrary.Exported)
usedImports := imports.LookupImportList(unitLocation.Module, unitLocation.Unit, importbook)
importedTables := make([]symbols.SymbolTable, len(usedImports))
for i, usedImport := range usedImports {
importedTables[i] = symbols.LookupSymbolTable(usedImport.Module, usedImport.Unit, symbollibrary.Exported)
}
return NewResolveEnvironment(internal, exported, importedTables)
}
func NewResolveEnvironment(selfInternal, selfExported symbols.SymbolTable, imported []symbols.SymbolTable) *ResolveEnvironment {
return &ResolveEnvironment{symbols.NewLinkedSymbolTable(), selfInternal, selfExported, imported}
}
func FindLocal(name string, env *ResolveEnvironment) (found *symbol.AddressBox, exists bool) {
found, exists = env.linkedLocals.PeekTable()[name]
return
}
func FindClosed(name string, env *ResolveEnvironment) (found *symbol.AddressBox, exists bool) {
for i := env.linkedLocals.Length() - 2; i >= 0; i-- {
closedFound, closedExists := env.linkedLocals.GetTableAt(i)[name]
if closedExists {
found = closedFound
exists = true
return
}
}
return nil, false
}
func FindUnit(name string, env *ResolveEnvironment) (found *symbol.AddressBox, exists bool) {
exported, exists := env.selfExported[name]
if exists {
return exported, true
}
internal, exists := env.selfInternal[name]
if exists {
return internal, true
}
return nil, false
}
func FindImported(name string, env *ResolveEnvironment) (found *symbol.AddressBox, exists bool) {
for _, importedTable := range env.imported {
imported, exists := importedTable[name]
if exists {
return imported, true
}
}
return nil, false
}
<file_sep>/compiler/back/evaluator/translate_simple.go
package evaluator
import (
"github.com/sirupsen/logrus"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
"github.com/falcinspire/scriptblock/compiler/back/values"
)
func TranslateFrame(frame *CallFrame, data *EvaluateData) []string {
PushCallStack(frame.Name, data.CallStack)
logrus.WithFields(logrus.Fields{
"data": data.CallStack,
}).Info("call stack updated")
mappedArguments := make(map[string]values.Value)
for i, parameter := range frame.Parameters {
mappedArguments[parameter] = frame.Arguments[i]
}
mappedCaptures := make(map[string]values.Value)
for i, capture := range frame.Closes {
mappedCaptures[capture] = frame.Captures[i]
}
newData := &EvaluateData{
frame.Location,
values.NewLocalValueTable(mappedArguments, mappedCaptures),
data.ValueLibrary,
data.AddressBook,
data.CallStack,
data.LoopInject,
data.ModulePath,
data.Output,
}
stringBody := make([]string, 0)
statementVisitor := NewTranslateStatementVisitor(newData)
for _, statement := range frame.Body {
stringBody = append(stringBody, statementVisitor.QuickVisitStatement(statement)...)
}
PopCallStack(data.CallStack)
return stringBody
}
func TranslateFunctor(definition *ast.TemplateDefinition, arguments []values.Value, location *location.UnitLocation, captures []values.Value, data *EvaluateData) []string {
frame := &CallFrame{location, definition.Name, definition.Body, definition.Parameters, definition.Capture, arguments, captures}
return TranslateFrame(frame, data)
}
func TranslateFunction(definition *ast.FunctionDefinition, location *location.UnitLocation, data *EvaluateData) []string {
frame := &CallFrame{location, definition.Name, definition.Body, symbol.NoParameters(), symbol.NoCloses(), values.NoArguments(), values.NoCaptures()}
return TranslateFrame(frame, data)
}
<file_sep>/compiler/ast/location/unitlocation.go
package location
type UnitLocation struct {
Module string
Unit string
}
func NewUnitLocation(module string, unit string) *UnitLocation {
return &UnitLocation{module, unit}
}
func Equals(a, b *UnitLocation) bool {
return a.Module == b.Module && a.Unit == b.Unit
}
<file_sep>/compiler/dependency/dependency_test.go
package dependency
import (
"fmt"
"testing"
)
func TestDependency(t *testing.T) {
{
graph := NewDependencyGraph()
for i := 0; i < 6; i++ {
AddVertex(graph)
}
AddDependency(0, 1, graph)
AddDependency(1, 2, graph)
AddDependency(0, 3, graph)
AddDependency(3, 4, graph)
AddDependency(4, 5, graph)
order, circular := MakeDependencyOrder(graph)
t.Log(order)
if circular != false {
panic(fmt.Errorf("first graph is not circular"))
}
}
{
graph := NewDependencyGraph()
for i := 0; i < 3; i++ {
AddVertex(graph)
}
AddDependency(0, 1, graph)
AddDependency(1, 2, graph)
AddDependency(2, 0, graph)
order, circular := MakeDependencyOrder(graph)
t.Log(order)
if circular != true {
panic(fmt.Errorf("second graph is circular"))
}
}
}
<file_sep>/cmd/scriptblock-install/main.go
package main
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/falcinspire/scriptblock/downloader"
"github.com/falcinspire/scriptblock/environment"
)
func main() {
reader := bufio.NewReader(os.Stdin)
location := prompt("Enter the github url: ", reader)
version := prompt("Enter a version code: ", reader)
data := environment.ModuleDescription{Location: location, Version: version}
downloader.Download(data)
fmt.Println("Installed")
}
// ref https://tutorialedge.net/golang/reading-console-input-golang/
// duplicated code from another cmd package
func prompt(question string, reader *bufio.Reader) string {
fmt.Print(question)
input, _ := reader.ReadString('\n')
return strings.Replace(input, "\r\n", "", -1)
}
<file_sep>/compiler/front/symbols/symbolbook.go
package symbols
type SymbolLibrary struct {
Exported SymbolBook
Internal SymbolBook
}
func NewSymbolLibrary() *SymbolLibrary {
return &SymbolLibrary{make(SymbolBook), make(SymbolBook)}
}
type SymbolBook map[string]SymbolUnitBook
func LookupSymbolTable(module string, unit string, symbolbook SymbolBook) SymbolTable {
return symbolbook[module][unit]
}
func InsertSymbolTable(module string, unit string, symboltable SymbolTable, symbolbook SymbolBook) {
_, exists := symbolbook[module]
if !exists {
symbolbook[module] = make(SymbolUnitBook)
}
symbolbook[module][unit] = symboltable
}
type SymbolUnitBook map[string]SymbolTable
func NewSymbolUnitBook() SymbolUnitBook {
return make(SymbolUnitBook)
}
func NewSymbolBook() SymbolBook {
return make(SymbolBook)
}
<file_sep>/compiler/back/values/visitor.go
package values
type ValueVisitor interface {
VisitNumber(numberValue *NumberValue)
VisitString(stringValue *StringValue)
VisitFunction(functionValue *FunctionValue)
VisitTemplate(templateReference *TemplateValue)
VisitFunctor(functorValue *FunctorValue)
}
<file_sep>/compiler/ast/constants.go
package ast
// ConstantDefinition is a node representing a top level definition of a constant
type ConstantDefinition struct {
Name string
Value Expression
Internal bool
Documentation string
Metadata *Metadata
}
// NewConstantDefinition is a constructor for ConstantDefinition
func NewConstantDefinition(name string, value Expression, internal bool, docs string, metadata *Metadata) *ConstantDefinition {
return &ConstantDefinition{name, value, internal, docs, metadata}
}
// Accept runs the double dispatch for the visitor
func (definition *ConstantDefinition) Accept(visitor TopVisitor) {
visitor.VisitConstantDefinition(definition)
}
<file_sep>/compiler/back/desugar/statementrewriter.go
package desugar
import "github.com/falcinspire/scriptblock/compiler/ast"
type StatementRewriter struct {
Body []ast.Statement
index int
}
func NewStatementRewriter(body []ast.Statement, index int) *StatementRewriter {
return &StatementRewriter{body, index}
}
func RewriteStatement(newStatement ast.Statement, rewriter *StatementRewriter) {
rewriter.Body[rewriter.index] = newStatement
}
<file_sep>/cmd/scriptblock-new/main.go
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/falcinspire/scriptblock/environment"
"github.com/falcinspire/scriptblock/home"
)
func main() {
reader := bufio.NewReader(os.Stdin)
name := prompt("Enter the name of your module: ", reader)
description := prompt("Enter a one-line description: ", reader)
version := prompt("Enter a version code: ", reader)
author := prompt("Enter author name: ", reader)
location := prompt("Enter the github url: ", reader)
// ignore dependencies for now
modulePath := filepath.Join(environment.GetHomeSourcePath(), location, version)
fmt.Println(modulePath)
os.MkdirAll(modulePath, os.ModePerm)
dataPath := filepath.Join(modulePath, "module.yaml")
fmt.Println(dataPath)
home.WriteModuleData(&home.ModuleData{
Name: name,
Description: description,
Author: author,
Dependencies: []home.Dependency{},
}, dataPath)
}
// ref https://tutorialedge.net/golang/reading-console-input-golang/
func prompt(question string, reader *bufio.Reader) string {
fmt.Print(question)
input, _ := reader.ReadString('\n')
return strings.Replace(input, "\r\n", "", -1)
}
<file_sep>/README.md
# ScriptBlock
NOTE: This software was a personal experiment in language design, and was never built with the intention of being a production-ready piece of software. However, I am proud of it, and it does work on the small projects that I have tested it with.
Scripting Language for Minecraft: Java Edition. Instead of writing a bunch of .mcfunction files, ScriptBlock allows you to write something that looks more like traditional code.
## Installing
This project is not yet available by executable or installer. The only option is to clone the golang project (usually to the go home on your system), and to install it.
```
git clone https://github.com/Falcinspire/ScriptBlock.git
go install github.com/Falcinspire/scriptblock/cmd/scriptblock
go install github.com/Falcinspire/scriptblock/cmd/scriptblock-new
```
NOTE: This command sequence is untested.
## Usage
`scriptblock-new` should be used to create a new project.
If the `bin` directory of the go workspace is in the system path, then building is simple:
```
scriptblock <project>
```
i.e.
```
scriptblock github.com/Falcinspire/predator LATEST
```
If the `bin` directory of the go workspace is not in the system path, use the same command as above, but with the full path to the scriptblock executable:
```
"C:/Program Files/go/bin/scriptblock.exe" <project>
```
NOTE: This form is untested.
## Getting Started
The language workspace is modelled after Golang. There is a central workspace that contains the source code and the outputs. The workspace will be set with the environment variable "ScriptBlockPath".
Projects have a qualified name and a version. The qualified name is the location of the project both on github.com and on the local disk. The version will be included in the path on the local disk, and will be a release on github. The only exception is the version "LATEST", which signifies a developmental stage. The github representation for this is no release; the master branch, and the local disk representation is the qualified name followed by /LATEST.
An example qualified name is `github.com/Falcinspire/predator` and version is`'1.0.0`. This project would have the name "predator" and be stored at `https:/github.com/Falcinspire/predator` with the tag `1.0.0`. In a local workspace, this would be stored at `%ScriptBlockPath%/src/github.com/Falcinspire/predator/1.0.0`.
Project builds are stored in the bin folder, which is adjacent to the src folder.
Example:
%ScriptBlockPath%
├── src
| ├─ github.com
| ├── falcinspire
| ├── predator
| ├── LATEST
| ├── test.sb
| ├── helper.sb
| ├── zombie.json
├── bin
├─ github.com
├── falcinspire
├── predator
├── LATEST
├── (namespace)
├── functions
├── *.mcfunction
├── (namespace)
├── functions
├── *.mcfunction
There is also a module description file, module.yaml. This file contains basic information about the project, as well as a list of dependencies. See /examples for format. Right now the Name field is useless.
## What to do with the output
The output of the ScriptBlock compiler is the part of the data pack needed for functions. Merge this folder into the /data folder of a datapack for it to work.
## What it looks like

## Example
If the repository is cloned and the environment variable "ScriptBlockPath" is set to the repository's /example directory, then running `scriptblock github.com/Falcinspire/predator LATEST` will demonstrate the software working.
<file_sep>/compiler/front/astgen/ast_simple.go
package astgen
import (
"strings"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/front/parser"
)
// PSTtoAST converts the given parse tree into an unannotated abstract syntax tree
func PSTtoAST(root parser.IUnitContext) *ast.Unit {
visitor := newUnitConvertVisitor()
root.EnterRule(visitor)
return visitor.Unit
}
func convertExpression(expression parser.IExpressionContext) ast.Expression {
visitor := newExpressionConvertVisitor()
expression.EnterRule(visitor)
return visitor.Expression
}
func convertStatement(statement parser.IStatementContext) ast.Statement {
visitor := newStatementConvertVisitor()
statement.EnterRule(visitor)
return visitor.Statement
}
func convertArgumentList(arguments parser.IArgumentListContext) []ast.Expression {
argumentContexts := arguments.(*parser.ArgumentListContext).AllExpression()
expressionArguments := make([]ast.Expression, len(argumentContexts))
for i, argumentContext := range argumentContexts {
expressionArguments[i] = convertExpression(argumentContext)
}
return expressionArguments
}
func convertParameterList(ictx parser.IParameterListContext) []string {
parameterContexts := ictx.(*parser.ParameterListContext).AllIDENTIFIER()
parameterList := make([]string, len(parameterContexts))
for i, parameterContext := range parameterContexts {
parameterList[i] = parameterContext.GetText()
}
return parameterList
}
type functionFrame struct {
Parameters []string
Body []ast.Statement
}
func convertFunctionFrame(ictx parser.IFunctionFrameContext) *functionFrame {
ctx := ictx.(*parser.FunctionFrameContext)
var parameterList []string
parameterListContext := ctx.ParameterList()
if parameterListContext != nil {
parameterList = convertParameterList(parameterListContext)
} else {
parameterList = make([]string, 0)
}
statementContexts := ctx.AllStatement()
body := make([]ast.Statement, len(statementContexts))
for i, statementContext := range statementContexts {
body[i] = convertStatement(statementContext)
}
return &functionFrame{parameterList, body}
}
func convertFunctionCall(ctx *parser.FunctionCallContext) *ast.FunctionCall {
var trailingFrame *ast.TrailingFunction
trailingContext := ctx.FunctionFrame()
if trailingContext != nil {
frame := convertFunctionFrame(trailingContext)
trailingFrame = &ast.TrailingFunction{Parameters: frame.Parameters, Body: frame.Body}
}
var arguments []ast.Expression
argumentListContext := ctx.ArgumentList()
if argumentListContext != nil {
arguments = convertArgumentList(argumentListContext)
} else {
arguments = make([]ast.Expression, 0)
}
identifierName := ctx.IDENTIFIER().GetText()
return ast.NewFunctionCall(ast.NewIdentifierExpression(identifierName, convertTokenMetadata(ctx.IDENTIFIER())), arguments, trailingFrame, convertMetadata(ctx))
}
func convertTag(identifierCtxs []antlr.TerminalNode) ast.Tag {
namespace := identifierCtxs[0].GetText()
identity := identifierCtxs[1].GetText()
return ast.Tag{Namespace: namespace, Identity: identity}
}
func convertDoc(ictx parser.IDocumentationContext) string {
docLineContexts := ictx.(*parser.DocumentationContext).AllDOC_LINE()
docLines := make([]string, len(docLineContexts))
for i, docLineContext := range docLineContexts {
text := docLineContext.GetText()
// TODO may be unnecessary to trim
docLines[i] = strings.TrimRight(text[3:], "\n\r")
}
return strings.Join(docLines, "\n")
}
func convertMetadata(node antlr.ParserRuleContext) *ast.Metadata {
return &ast.Metadata{
StartLine: node.GetStart().GetLine(),
StartColumn: node.GetStart().GetColumn(),
EndLine: node.GetStop().GetLine(),
EndColumn: node.GetStop().GetColumn() + len(node.GetStop().GetText()),
Text: node.GetText(),
}
}
func convertTokenMetadata(inode antlr.TerminalNode) *ast.Metadata {
node := inode.GetSymbol()
return &ast.Metadata{
StartLine: node.GetLine(),
StartColumn: node.GetColumn(),
EndLine: node.GetLine(),
EndColumn: node.GetColumn() + len(node.GetText()),
Text: node.GetText(),
}
}
<file_sep>/compiler/ast/symbol/addresses.go
package symbol
import "fmt"
type AddressType int
const (
UNIT = 0
PARAMETER = 1
CAPTURE = 2
IMPORTED_UNIT = 3
FREE_PARAMETER = 4
)
type UnitAddress struct {
Module string
Unit string
Name string
}
// func (this *UnitAddress) String() string {
// return fmt.Sprintf("unit_address:\"%s:%s:%s\"", this.Module, this.Unit, this.Name)
// }
func NewUnitAddress(module string, unit string, name string) *UnitAddress {
return &UnitAddress{module, unit, name}
}
func NewUnitAddressBox(module string, unit string, name string) *AddressBox {
return NewAddressBox(UNIT, NewUnitAddress(module, unit, name))
}
type ParameterAddress struct {
ClosureDepth int
Name string
}
func NewParameterAddress(closureDepth int, name string) *ParameterAddress {
return &ParameterAddress{closureDepth, name}
}
func NewParameterAddressBox(closureDepth int, name string) *AddressBox {
return NewAddressBox(PARAMETER, NewParameterAddress(closureDepth, name))
}
func (this *ParameterAddress) String() string {
return fmt.Sprintf("parameter:\"%s\"", this.Name)
}
type CaptureAddress struct {
Name string
}
func (this *CaptureAddress) String() string {
return fmt.Sprintf("capture:\"%s\"", this.Name)
}
func NewCaptureAddress(name string) *CaptureAddress {
address := new(CaptureAddress)
address.Name = name
return address
}
func NewCaptureAddressBox(name string) *AddressBox {
return NewAddressBox(CAPTURE, NewCaptureAddress(name))
}
type AddressBox struct {
Type AddressType
Data interface{}
}
func (this *AddressBox) String() string {
return fmt.Sprintf("(%d)%s", this.Type, this.Data)
}
func NewAddressBox(addressType AddressType, data interface{}) *AddressBox {
address := new(AddressBox)
address.Type = addressType
address.Data = data
return address
}
<file_sep>/compiler/front/parser/scriptblock_parser.go
// Generated from ScriptBlockParser.g4 by ANTLR 4.7.
package parser // ScriptBlockParser
import (
"fmt"
"reflect"
"strconv"
"github.com/antlr/antlr4/runtime/Go/antlr"
)
// Suppress unused import errors
var _ = fmt.Printf
var _ = reflect.Copy
var _ = strconv.Itoa
var parserATN = []uint16{
3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 3, 42, 278,
4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7,
4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12, 4, 13,
9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 4, 18, 9,
18, 4, 19, 9, 19, 4, 20, 9, 20, 4, 21, 9, 21, 4, 22, 9, 22, 3, 2, 3, 2,
3, 2, 7, 2, 48, 10, 2, 12, 2, 14, 2, 51, 11, 2, 3, 2, 7, 2, 54, 10, 2,
12, 2, 14, 2, 57, 11, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 7, 3, 64, 10, 3,
12, 3, 14, 3, 67, 11, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 4, 3, 4, 7, 4,
76, 10, 4, 12, 4, 14, 4, 79, 11, 4, 5, 4, 81, 10, 4, 3, 4, 3, 4, 3, 5,
3, 5, 3, 5, 3, 5, 7, 5, 89, 10, 5, 12, 5, 14, 5, 92, 11, 5, 5, 5, 94, 10,
5, 3, 5, 3, 5, 3, 6, 3, 6, 3, 6, 3, 6, 7, 6, 102, 10, 6, 12, 6, 14, 6,
105, 11, 6, 5, 6, 107, 10, 6, 3, 6, 3, 6, 3, 7, 3, 7, 3, 7, 3, 8, 3, 8,
3, 8, 5, 8, 117, 10, 8, 3, 8, 5, 8, 120, 10, 8, 3, 9, 3, 9, 3, 9, 3, 9,
5, 9, 126, 10, 9, 3, 9, 3, 9, 7, 9, 130, 10, 9, 12, 9, 14, 9, 133, 11,
9, 3, 9, 3, 9, 3, 10, 5, 10, 138, 10, 10, 3, 10, 5, 10, 141, 10, 10, 3,
10, 5, 10, 144, 10, 10, 3, 10, 3, 10, 3, 10, 3, 10, 3, 11, 5, 11, 151,
10, 11, 3, 11, 5, 11, 154, 10, 11, 3, 11, 5, 11, 157, 10, 11, 3, 11, 3,
11, 3, 11, 3, 11, 3, 11, 3, 12, 3, 12, 3, 12, 3, 12, 3, 12, 3, 13, 5, 13,
170, 10, 13, 3, 13, 5, 13, 173, 10, 13, 3, 13, 3, 13, 3, 13, 3, 13, 3,
14, 5, 14, 180, 10, 14, 3, 14, 5, 14, 183, 10, 14, 3, 14, 3, 14, 3, 14,
3, 14, 3, 14, 3, 15, 3, 15, 3, 15, 3, 15, 3, 15, 3, 16, 3, 16, 3, 16, 3,
17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17, 3, 17,
3, 17, 5, 17, 210, 10, 17, 3, 18, 3, 18, 3, 18, 3, 18, 3, 18, 3, 18, 3,
18, 3, 18, 3, 18, 3, 18, 3, 18, 3, 18, 5, 18, 224, 10, 18, 3, 19, 3, 19,
3, 19, 3, 19, 3, 20, 3, 20, 3, 20, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3,
21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 5, 21, 245, 10, 21, 3, 21,
3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3,
21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 7, 21, 265, 10, 21, 12, 21,
14, 21, 268, 11, 21, 3, 22, 5, 22, 271, 10, 22, 3, 22, 3, 22, 3, 22, 5,
22, 276, 10, 22, 3, 22, 2, 3, 40, 23, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 2, 2, 2, 298, 2, 49, 3, 2,
2, 2, 4, 60, 3, 2, 2, 2, 6, 71, 3, 2, 2, 2, 8, 84, 3, 2, 2, 2, 10, 97,
3, 2, 2, 2, 12, 110, 3, 2, 2, 2, 14, 113, 3, 2, 2, 2, 16, 121, 3, 2, 2,
2, 18, 137, 3, 2, 2, 2, 20, 150, 3, 2, 2, 2, 22, 163, 3, 2, 2, 2, 24, 169,
3, 2, 2, 2, 26, 179, 3, 2, 2, 2, 28, 189, 3, 2, 2, 2, 30, 194, 3, 2, 2,
2, 32, 209, 3, 2, 2, 2, 34, 223, 3, 2, 2, 2, 36, 225, 3, 2, 2, 2, 38, 229,
3, 2, 2, 2, 40, 244, 3, 2, 2, 2, 42, 270, 3, 2, 2, 2, 44, 45, 5, 30, 16,
2, 45, 46, 7, 8, 2, 2, 46, 48, 3, 2, 2, 2, 47, 44, 3, 2, 2, 2, 48, 51,
3, 2, 2, 2, 49, 47, 3, 2, 2, 2, 49, 50, 3, 2, 2, 2, 50, 55, 3, 2, 2, 2,
51, 49, 3, 2, 2, 2, 52, 54, 5, 32, 17, 2, 53, 52, 3, 2, 2, 2, 54, 57, 3,
2, 2, 2, 55, 53, 3, 2, 2, 2, 55, 56, 3, 2, 2, 2, 56, 58, 3, 2, 2, 2, 57,
55, 3, 2, 2, 2, 58, 59, 7, 2, 2, 3, 59, 3, 3, 2, 2, 2, 60, 61, 7, 5, 2,
2, 61, 65, 7, 8, 2, 2, 62, 64, 7, 7, 2, 2, 63, 62, 3, 2, 2, 2, 64, 67,
3, 2, 2, 2, 65, 63, 3, 2, 2, 2, 65, 66, 3, 2, 2, 2, 66, 68, 3, 2, 2, 2,
67, 65, 3, 2, 2, 2, 68, 69, 7, 6, 2, 2, 69, 70, 7, 8, 2, 2, 70, 5, 3, 2,
2, 2, 71, 80, 7, 19, 2, 2, 72, 77, 7, 39, 2, 2, 73, 74, 7, 25, 2, 2, 74,
76, 7, 39, 2, 2, 75, 73, 3, 2, 2, 2, 76, 79, 3, 2, 2, 2, 77, 75, 3, 2,
2, 2, 77, 78, 3, 2, 2, 2, 78, 81, 3, 2, 2, 2, 79, 77, 3, 2, 2, 2, 80, 72,
3, 2, 2, 2, 80, 81, 3, 2, 2, 2, 81, 82, 3, 2, 2, 2, 82, 83, 7, 20, 2, 2,
83, 7, 3, 2, 2, 2, 84, 93, 7, 19, 2, 2, 85, 90, 5, 40, 21, 2, 86, 87, 7,
25, 2, 2, 87, 89, 5, 40, 21, 2, 88, 86, 3, 2, 2, 2, 89, 92, 3, 2, 2, 2,
90, 88, 3, 2, 2, 2, 90, 91, 3, 2, 2, 2, 91, 94, 3, 2, 2, 2, 92, 90, 3,
2, 2, 2, 93, 85, 3, 2, 2, 2, 93, 94, 3, 2, 2, 2, 94, 95, 3, 2, 2, 2, 95,
96, 7, 20, 2, 2, 96, 9, 3, 2, 2, 2, 97, 106, 7, 23, 2, 2, 98, 103, 5, 40,
21, 2, 99, 100, 7, 25, 2, 2, 100, 102, 5, 40, 21, 2, 101, 99, 3, 2, 2,
2, 102, 105, 3, 2, 2, 2, 103, 101, 3, 2, 2, 2, 103, 104, 3, 2, 2, 2, 104,
107, 3, 2, 2, 2, 105, 103, 3, 2, 2, 2, 106, 98, 3, 2, 2, 2, 106, 107, 3,
2, 2, 2, 107, 108, 3, 2, 2, 2, 108, 109, 7, 24, 2, 2, 109, 11, 3, 2, 2,
2, 110, 111, 7, 11, 2, 2, 111, 112, 5, 8, 5, 2, 112, 13, 3, 2, 2, 2, 113,
119, 7, 39, 2, 2, 114, 116, 5, 8, 5, 2, 115, 117, 5, 16, 9, 2, 116, 115,
3, 2, 2, 2, 116, 117, 3, 2, 2, 2, 117, 120, 3, 2, 2, 2, 118, 120, 5, 16,
9, 2, 119, 114, 3, 2, 2, 2, 119, 118, 3, 2, 2, 2, 120, 15, 3, 2, 2, 2,
121, 125, 7, 21, 2, 2, 122, 123, 5, 6, 4, 2, 123, 124, 7, 18, 2, 2, 124,
126, 3, 2, 2, 2, 125, 122, 3, 2, 2, 2, 125, 126, 3, 2, 2, 2, 126, 127,
3, 2, 2, 2, 127, 131, 7, 8, 2, 2, 128, 130, 5, 34, 18, 2, 129, 128, 3,
2, 2, 2, 130, 133, 3, 2, 2, 2, 131, 129, 3, 2, 2, 2, 131, 132, 3, 2, 2,
2, 132, 134, 3, 2, 2, 2, 133, 131, 3, 2, 2, 2, 134, 135, 7, 22, 2, 2, 135,
17, 3, 2, 2, 2, 136, 138, 5, 4, 3, 2, 137, 136, 3, 2, 2, 2, 137, 138, 3,
2, 2, 2, 138, 140, 3, 2, 2, 2, 139, 141, 5, 22, 12, 2, 140, 139, 3, 2,
2, 2, 140, 141, 3, 2, 2, 2, 141, 143, 3, 2, 2, 2, 142, 144, 7, 17, 2, 2,
143, 142, 3, 2, 2, 2, 143, 144, 3, 2, 2, 2, 144, 145, 3, 2, 2, 2, 145,
146, 7, 9, 2, 2, 146, 147, 7, 39, 2, 2, 147, 148, 5, 16, 9, 2, 148, 19,
3, 2, 2, 2, 149, 151, 5, 4, 3, 2, 150, 149, 3, 2, 2, 2, 150, 151, 3, 2,
2, 2, 151, 153, 3, 2, 2, 2, 152, 154, 5, 22, 12, 2, 153, 152, 3, 2, 2,
2, 153, 154, 3, 2, 2, 2, 154, 156, 3, 2, 2, 2, 155, 157, 7, 17, 2, 2, 156,
155, 3, 2, 2, 2, 156, 157, 3, 2, 2, 2, 157, 158, 3, 2, 2, 2, 158, 159,
7, 9, 2, 2, 159, 160, 7, 39, 2, 2, 160, 161, 7, 26, 2, 2, 161, 162, 5,
14, 8, 2, 162, 21, 3, 2, 2, 2, 163, 164, 7, 38, 2, 2, 164, 165, 7, 39,
2, 2, 165, 166, 7, 28, 2, 2, 166, 167, 7, 39, 2, 2, 167, 23, 3, 2, 2, 2,
168, 170, 5, 4, 3, 2, 169, 168, 3, 2, 2, 2, 169, 170, 3, 2, 2, 2, 170,
172, 3, 2, 2, 2, 171, 173, 7, 17, 2, 2, 172, 171, 3, 2, 2, 2, 172, 173,
3, 2, 2, 2, 173, 174, 3, 2, 2, 2, 174, 175, 7, 10, 2, 2, 175, 176, 7, 39,
2, 2, 176, 177, 5, 16, 9, 2, 177, 25, 3, 2, 2, 2, 178, 180, 5, 4, 3, 2,
179, 178, 3, 2, 2, 2, 179, 180, 3, 2, 2, 2, 180, 182, 3, 2, 2, 2, 181,
183, 7, 17, 2, 2, 182, 181, 3, 2, 2, 2, 182, 183, 3, 2, 2, 2, 183, 184,
3, 2, 2, 2, 184, 185, 7, 12, 2, 2, 185, 186, 7, 39, 2, 2, 186, 187, 7,
26, 2, 2, 187, 188, 5, 40, 21, 2, 188, 27, 3, 2, 2, 2, 189, 190, 7, 37,
2, 2, 190, 191, 7, 39, 2, 2, 191, 192, 7, 36, 2, 2, 192, 193, 5, 8, 5,
2, 193, 29, 3, 2, 2, 2, 194, 195, 7, 16, 2, 2, 195, 196, 7, 42, 2, 2, 196,
31, 3, 2, 2, 2, 197, 198, 5, 26, 14, 2, 198, 199, 7, 8, 2, 2, 199, 210,
3, 2, 2, 2, 200, 201, 5, 18, 10, 2, 201, 202, 7, 8, 2, 2, 202, 210, 3,
2, 2, 2, 203, 204, 5, 24, 13, 2, 204, 205, 7, 8, 2, 2, 205, 210, 3, 2,
2, 2, 206, 207, 5, 20, 11, 2, 207, 208, 7, 8, 2, 2, 208, 210, 3, 2, 2,
2, 209, 197, 3, 2, 2, 2, 209, 200, 3, 2, 2, 2, 209, 203, 3, 2, 2, 2, 209,
206, 3, 2, 2, 2, 210, 33, 3, 2, 2, 2, 211, 212, 5, 14, 8, 2, 212, 213,
7, 8, 2, 2, 213, 224, 3, 2, 2, 2, 214, 215, 5, 12, 7, 2, 215, 216, 7, 8,
2, 2, 216, 224, 3, 2, 2, 2, 217, 218, 5, 36, 19, 2, 218, 219, 7, 8, 2,
2, 219, 224, 3, 2, 2, 2, 220, 221, 5, 38, 20, 2, 221, 222, 7, 8, 2, 2,
222, 224, 3, 2, 2, 2, 223, 211, 3, 2, 2, 2, 223, 214, 3, 2, 2, 2, 223,
217, 3, 2, 2, 2, 223, 220, 3, 2, 2, 2, 224, 35, 3, 2, 2, 2, 225, 226, 7,
15, 2, 2, 226, 227, 5, 10, 6, 2, 227, 228, 5, 16, 9, 2, 228, 37, 3, 2,
2, 2, 229, 230, 7, 14, 2, 2, 230, 231, 5, 22, 12, 2, 231, 39, 3, 2, 2,
2, 232, 233, 8, 21, 1, 2, 233, 245, 5, 42, 22, 2, 234, 245, 7, 42, 2, 2,
235, 245, 7, 39, 2, 2, 236, 237, 7, 19, 2, 2, 237, 238, 5, 40, 21, 2, 238,
239, 7, 20, 2, 2, 239, 245, 3, 2, 2, 2, 240, 245, 5, 28, 15, 2, 241, 242,
7, 13, 2, 2, 242, 243, 7, 39, 2, 2, 243, 245, 5, 8, 5, 2, 244, 232, 3,
2, 2, 2, 244, 234, 3, 2, 2, 2, 244, 235, 3, 2, 2, 2, 244, 236, 3, 2, 2,
2, 244, 240, 3, 2, 2, 2, 244, 241, 3, 2, 2, 2, 245, 266, 3, 2, 2, 2, 246,
247, 12, 9, 2, 2, 247, 248, 7, 29, 2, 2, 248, 265, 5, 40, 21, 9, 249, 250,
12, 8, 2, 2, 250, 251, 7, 30, 2, 2, 251, 265, 5, 40, 21, 9, 252, 253, 12,
7, 2, 2, 253, 254, 7, 31, 2, 2, 254, 265, 5, 40, 21, 8, 255, 256, 12, 6,
2, 2, 256, 257, 7, 32, 2, 2, 257, 265, 5, 40, 21, 7, 258, 259, 12, 5, 2,
2, 259, 260, 7, 33, 2, 2, 260, 265, 5, 40, 21, 6, 261, 262, 12, 4, 2, 2,
262, 263, 7, 34, 2, 2, 263, 265, 5, 40, 21, 5, 264, 246, 3, 2, 2, 2, 264,
249, 3, 2, 2, 2, 264, 252, 3, 2, 2, 2, 264, 255, 3, 2, 2, 2, 264, 258,
3, 2, 2, 2, 264, 261, 3, 2, 2, 2, 265, 268, 3, 2, 2, 2, 266, 264, 3, 2,
2, 2, 266, 267, 3, 2, 2, 2, 267, 41, 3, 2, 2, 2, 268, 266, 3, 2, 2, 2,
269, 271, 7, 40, 2, 2, 270, 269, 3, 2, 2, 2, 270, 271, 3, 2, 2, 2, 271,
272, 3, 2, 2, 2, 272, 275, 7, 41, 2, 2, 273, 274, 7, 35, 2, 2, 274, 276,
7, 41, 2, 2, 275, 273, 3, 2, 2, 2, 275, 276, 3, 2, 2, 2, 276, 43, 3, 2,
2, 2, 32, 49, 55, 65, 77, 80, 90, 93, 103, 106, 116, 119, 125, 131, 137,
140, 143, 150, 153, 156, 169, 172, 179, 182, 209, 223, 244, 264, 266, 270,
275,
}
var deserializer = antlr.NewATNDeserializer(nil)
var deserializedATN = deserializer.DeserializeFromUInt16(parserATN)
var literalNames = []string{
"", "", "", "'/*'", "'*/'", "", "", "'func'", "'script'", "'command'",
"'const'", "'run'", "'raise'", "'delay'", "'import'", "'internal'", "'->'",
"'('", "')'", "'{'", "'}'", "'['", "']'", "','", "'='", "';'", "':'", "'^'",
"'*'", "'/'", "'//'", "'+'", "'-'", "'.'", "'>'", "'<'", "'#'",
}
var symbolicNames = []string{
"", "WS", "COMMENT", "DOC_START", "DOC_END", "DOC_LINE", "NEWLINES", "FUNCTION",
"TEMPLATE", "NATIVE", "CONSTANT", "RUN", "RAISE", "DELAY", "IMPORT", "INTERNAL",
"ARROW", "OPAREN", "CPAREN", "OCURLY", "CCURLY", "OSQUARE", "CSQUARE",
"COMMA", "EQUALS", "SEMICOLON", "COLON", "POWER", "MULTIPLY", "DIVIDE",
"INTEGER_DIVIDE", "PLUS", "SUBTRACT", "DOT", "GREATER_THAN", "LESS_THAN",
"POUND", "IDENTIFIER", "SIGN", "DIGITS", "STRING",
}
var ruleNames = []string{
"unit", "documentation", "parameterList", "argumentList", "structureList",
"nativeCall", "functionCall", "functionFrame", "functionDefinition", "functionDefinitionShortcut",
"tag", "templateDefinition", "constantDefinition", "formatter", "importLine",
"topDefinition", "statement", "delayStructure", "raise", "expression",
"number",
}
var decisionToDFA = make([]*antlr.DFA, len(deserializedATN.DecisionToState))
func init() {
for index, ds := range deserializedATN.DecisionToState {
decisionToDFA[index] = antlr.NewDFA(ds, index)
}
}
type ScriptBlockParser struct {
*antlr.BaseParser
}
func NewScriptBlockParser(input antlr.TokenStream) *ScriptBlockParser {
this := new(ScriptBlockParser)
this.BaseParser = antlr.NewBaseParser(input)
this.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())
this.RuleNames = ruleNames
this.LiteralNames = literalNames
this.SymbolicNames = symbolicNames
this.GrammarFileName = "ScriptBlockParser.g4"
return this
}
// ScriptBlockParser tokens.
const (
ScriptBlockParserEOF = antlr.TokenEOF
ScriptBlockParserWS = 1
ScriptBlockParserCOMMENT = 2
ScriptBlockParserDOC_START = 3
ScriptBlockParserDOC_END = 4
ScriptBlockParserDOC_LINE = 5
ScriptBlockParserNEWLINES = 6
ScriptBlockParserFUNCTION = 7
ScriptBlockParserTEMPLATE = 8
ScriptBlockParserNATIVE = 9
ScriptBlockParserCONSTANT = 10
ScriptBlockParserRUN = 11
ScriptBlockParserRAISE = 12
ScriptBlockParserDELAY = 13
ScriptBlockParserIMPORT = 14
ScriptBlockParserINTERNAL = 15
ScriptBlockParserARROW = 16
ScriptBlockParserOPAREN = 17
ScriptBlockParserCPAREN = 18
ScriptBlockParserOCURLY = 19
ScriptBlockParserCCURLY = 20
ScriptBlockParserOSQUARE = 21
ScriptBlockParserCSQUARE = 22
ScriptBlockParserCOMMA = 23
ScriptBlockParserEQUALS = 24
ScriptBlockParserSEMICOLON = 25
ScriptBlockParserCOLON = 26
ScriptBlockParserPOWER = 27
ScriptBlockParserMULTIPLY = 28
ScriptBlockParserDIVIDE = 29
ScriptBlockParserINTEGER_DIVIDE = 30
ScriptBlockParserPLUS = 31
ScriptBlockParserSUBTRACT = 32
ScriptBlockParserDOT = 33
ScriptBlockParserGREATER_THAN = 34
ScriptBlockParserLESS_THAN = 35
ScriptBlockParserPOUND = 36
ScriptBlockParserIDENTIFIER = 37
ScriptBlockParserSIGN = 38
ScriptBlockParserDIGITS = 39
ScriptBlockParserSTRING = 40
)
// ScriptBlockParser rules.
const (
ScriptBlockParserRULE_unit = 0
ScriptBlockParserRULE_documentation = 1
ScriptBlockParserRULE_parameterList = 2
ScriptBlockParserRULE_argumentList = 3
ScriptBlockParserRULE_structureList = 4
ScriptBlockParserRULE_nativeCall = 5
ScriptBlockParserRULE_functionCall = 6
ScriptBlockParserRULE_functionFrame = 7
ScriptBlockParserRULE_functionDefinition = 8
ScriptBlockParserRULE_functionDefinitionShortcut = 9
ScriptBlockParserRULE_tag = 10
ScriptBlockParserRULE_templateDefinition = 11
ScriptBlockParserRULE_constantDefinition = 12
ScriptBlockParserRULE_formatter = 13
ScriptBlockParserRULE_importLine = 14
ScriptBlockParserRULE_topDefinition = 15
ScriptBlockParserRULE_statement = 16
ScriptBlockParserRULE_delayStructure = 17
ScriptBlockParserRULE_raise = 18
ScriptBlockParserRULE_expression = 19
ScriptBlockParserRULE_number = 20
)
// IUnitContext is an interface to support dynamic dispatch.
type IUnitContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsUnitContext differentiates from other interfaces.
IsUnitContext()
}
type UnitContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyUnitContext() *UnitContext {
var p = new(UnitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_unit
return p
}
func (*UnitContext) IsUnitContext() {}
func NewUnitContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *UnitContext {
var p = new(UnitContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_unit
return p
}
func (s *UnitContext) GetParser() antlr.Parser { return s.parser }
func (s *UnitContext) EOF() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserEOF, 0)
}
func (s *UnitContext) AllImportLine() []IImportLineContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IImportLineContext)(nil)).Elem())
var tst = make([]IImportLineContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IImportLineContext)
}
}
return tst
}
func (s *UnitContext) ImportLine(i int) IImportLineContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IImportLineContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IImportLineContext)
}
func (s *UnitContext) AllNEWLINES() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserNEWLINES)
}
func (s *UnitContext) NEWLINES(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, i)
}
func (s *UnitContext) AllTopDefinition() []ITopDefinitionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*ITopDefinitionContext)(nil)).Elem())
var tst = make([]ITopDefinitionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(ITopDefinitionContext)
}
}
return tst
}
func (s *UnitContext) TopDefinition(i int) ITopDefinitionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITopDefinitionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(ITopDefinitionContext)
}
func (s *UnitContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *UnitContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *UnitContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterUnit(s)
}
}
func (s *UnitContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitUnit(s)
}
}
func (p *ScriptBlockParser) Unit() (localctx IUnitContext) {
localctx = NewUnitContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 0, ScriptBlockParserRULE_unit)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(47)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ScriptBlockParserIMPORT {
{
p.SetState(42)
p.ImportLine()
}
{
p.SetState(43)
p.Match(ScriptBlockParserNEWLINES)
}
p.SetState(49)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
p.SetState(53)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for (((_la)&-(0x1f+1)) == 0 && ((1<<uint(_la))&((1<<ScriptBlockParserDOC_START)|(1<<ScriptBlockParserFUNCTION)|(1<<ScriptBlockParserTEMPLATE)|(1<<ScriptBlockParserCONSTANT)|(1<<ScriptBlockParserINTERNAL))) != 0) || _la == ScriptBlockParserPOUND {
{
p.SetState(50)
p.TopDefinition()
}
p.SetState(55)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(56)
p.Match(ScriptBlockParserEOF)
}
return localctx
}
// IDocumentationContext is an interface to support dynamic dispatch.
type IDocumentationContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsDocumentationContext differentiates from other interfaces.
IsDocumentationContext()
}
type DocumentationContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyDocumentationContext() *DocumentationContext {
var p = new(DocumentationContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_documentation
return p
}
func (*DocumentationContext) IsDocumentationContext() {}
func NewDocumentationContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *DocumentationContext {
var p = new(DocumentationContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_documentation
return p
}
func (s *DocumentationContext) GetParser() antlr.Parser { return s.parser }
func (s *DocumentationContext) DOC_START() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserDOC_START, 0)
}
func (s *DocumentationContext) AllNEWLINES() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserNEWLINES)
}
func (s *DocumentationContext) NEWLINES(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, i)
}
func (s *DocumentationContext) DOC_END() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserDOC_END, 0)
}
func (s *DocumentationContext) AllDOC_LINE() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserDOC_LINE)
}
func (s *DocumentationContext) DOC_LINE(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserDOC_LINE, i)
}
func (s *DocumentationContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *DocumentationContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *DocumentationContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterDocumentation(s)
}
}
func (s *DocumentationContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitDocumentation(s)
}
}
func (p *ScriptBlockParser) Documentation() (localctx IDocumentationContext) {
localctx = NewDocumentationContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 2, ScriptBlockParserRULE_documentation)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(58)
p.Match(ScriptBlockParserDOC_START)
}
{
p.SetState(59)
p.Match(ScriptBlockParserNEWLINES)
}
p.SetState(63)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ScriptBlockParserDOC_LINE {
{
p.SetState(60)
p.Match(ScriptBlockParserDOC_LINE)
}
p.SetState(65)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(66)
p.Match(ScriptBlockParserDOC_END)
}
{
p.SetState(67)
p.Match(ScriptBlockParserNEWLINES)
}
return localctx
}
// IParameterListContext is an interface to support dynamic dispatch.
type IParameterListContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsParameterListContext differentiates from other interfaces.
IsParameterListContext()
}
type ParameterListContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyParameterListContext() *ParameterListContext {
var p = new(ParameterListContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_parameterList
return p
}
func (*ParameterListContext) IsParameterListContext() {}
func NewParameterListContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ParameterListContext {
var p = new(ParameterListContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_parameterList
return p
}
func (s *ParameterListContext) GetParser() antlr.Parser { return s.parser }
func (s *ParameterListContext) OPAREN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserOPAREN, 0)
}
func (s *ParameterListContext) CPAREN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCPAREN, 0)
}
func (s *ParameterListContext) AllIDENTIFIER() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserIDENTIFIER)
}
func (s *ParameterListContext) IDENTIFIER(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, i)
}
func (s *ParameterListContext) AllCOMMA() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserCOMMA)
}
func (s *ParameterListContext) COMMA(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCOMMA, i)
}
func (s *ParameterListContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ParameterListContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ParameterListContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterParameterList(s)
}
}
func (s *ParameterListContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitParameterList(s)
}
}
func (p *ScriptBlockParser) ParameterList() (localctx IParameterListContext) {
localctx = NewParameterListContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 4, ScriptBlockParserRULE_parameterList)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(69)
p.Match(ScriptBlockParserOPAREN)
}
p.SetState(78)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserIDENTIFIER {
{
p.SetState(70)
p.Match(ScriptBlockParserIDENTIFIER)
}
p.SetState(75)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ScriptBlockParserCOMMA {
{
p.SetState(71)
p.Match(ScriptBlockParserCOMMA)
}
{
p.SetState(72)
p.Match(ScriptBlockParserIDENTIFIER)
}
p.SetState(77)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
}
{
p.SetState(80)
p.Match(ScriptBlockParserCPAREN)
}
return localctx
}
// IArgumentListContext is an interface to support dynamic dispatch.
type IArgumentListContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsArgumentListContext differentiates from other interfaces.
IsArgumentListContext()
}
type ArgumentListContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyArgumentListContext() *ArgumentListContext {
var p = new(ArgumentListContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_argumentList
return p
}
func (*ArgumentListContext) IsArgumentListContext() {}
func NewArgumentListContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ArgumentListContext {
var p = new(ArgumentListContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_argumentList
return p
}
func (s *ArgumentListContext) GetParser() antlr.Parser { return s.parser }
func (s *ArgumentListContext) OPAREN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserOPAREN, 0)
}
func (s *ArgumentListContext) CPAREN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCPAREN, 0)
}
func (s *ArgumentListContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *ArgumentListContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *ArgumentListContext) AllCOMMA() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserCOMMA)
}
func (s *ArgumentListContext) COMMA(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCOMMA, i)
}
func (s *ArgumentListContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ArgumentListContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ArgumentListContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterArgumentList(s)
}
}
func (s *ArgumentListContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitArgumentList(s)
}
}
func (p *ScriptBlockParser) ArgumentList() (localctx IArgumentListContext) {
localctx = NewArgumentListContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 6, ScriptBlockParserRULE_argumentList)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(82)
p.Match(ScriptBlockParserOPAREN)
}
p.SetState(91)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if ((_la-11)&-(0x1f+1)) == 0 && ((1<<uint((_la-11)))&((1<<(ScriptBlockParserRUN-11))|(1<<(ScriptBlockParserOPAREN-11))|(1<<(ScriptBlockParserLESS_THAN-11))|(1<<(ScriptBlockParserIDENTIFIER-11))|(1<<(ScriptBlockParserSIGN-11))|(1<<(ScriptBlockParserDIGITS-11))|(1<<(ScriptBlockParserSTRING-11)))) != 0 {
{
p.SetState(83)
p.expression(0)
}
p.SetState(88)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ScriptBlockParserCOMMA {
{
p.SetState(84)
p.Match(ScriptBlockParserCOMMA)
}
{
p.SetState(85)
p.expression(0)
}
p.SetState(90)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
}
{
p.SetState(93)
p.Match(ScriptBlockParserCPAREN)
}
return localctx
}
// IStructureListContext is an interface to support dynamic dispatch.
type IStructureListContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsStructureListContext differentiates from other interfaces.
IsStructureListContext()
}
type StructureListContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyStructureListContext() *StructureListContext {
var p = new(StructureListContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_structureList
return p
}
func (*StructureListContext) IsStructureListContext() {}
func NewStructureListContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StructureListContext {
var p = new(StructureListContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_structureList
return p
}
func (s *StructureListContext) GetParser() antlr.Parser { return s.parser }
func (s *StructureListContext) OSQUARE() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserOSQUARE, 0)
}
func (s *StructureListContext) CSQUARE() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCSQUARE, 0)
}
func (s *StructureListContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *StructureListContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *StructureListContext) AllCOMMA() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserCOMMA)
}
func (s *StructureListContext) COMMA(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCOMMA, i)
}
func (s *StructureListContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *StructureListContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *StructureListContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterStructureList(s)
}
}
func (s *StructureListContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitStructureList(s)
}
}
func (p *ScriptBlockParser) StructureList() (localctx IStructureListContext) {
localctx = NewStructureListContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 8, ScriptBlockParserRULE_structureList)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(95)
p.Match(ScriptBlockParserOSQUARE)
}
p.SetState(104)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if ((_la-11)&-(0x1f+1)) == 0 && ((1<<uint((_la-11)))&((1<<(ScriptBlockParserRUN-11))|(1<<(ScriptBlockParserOPAREN-11))|(1<<(ScriptBlockParserLESS_THAN-11))|(1<<(ScriptBlockParserIDENTIFIER-11))|(1<<(ScriptBlockParserSIGN-11))|(1<<(ScriptBlockParserDIGITS-11))|(1<<(ScriptBlockParserSTRING-11)))) != 0 {
{
p.SetState(96)
p.expression(0)
}
p.SetState(101)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for _la == ScriptBlockParserCOMMA {
{
p.SetState(97)
p.Match(ScriptBlockParserCOMMA)
}
{
p.SetState(98)
p.expression(0)
}
p.SetState(103)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
}
{
p.SetState(106)
p.Match(ScriptBlockParserCSQUARE)
}
return localctx
}
// INativeCallContext is an interface to support dynamic dispatch.
type INativeCallContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsNativeCallContext differentiates from other interfaces.
IsNativeCallContext()
}
type NativeCallContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyNativeCallContext() *NativeCallContext {
var p = new(NativeCallContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_nativeCall
return p
}
func (*NativeCallContext) IsNativeCallContext() {}
func NewNativeCallContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *NativeCallContext {
var p = new(NativeCallContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_nativeCall
return p
}
func (s *NativeCallContext) GetParser() antlr.Parser { return s.parser }
func (s *NativeCallContext) NATIVE() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNATIVE, 0)
}
func (s *NativeCallContext) ArgumentList() IArgumentListContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IArgumentListContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IArgumentListContext)
}
func (s *NativeCallContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *NativeCallContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *NativeCallContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterNativeCall(s)
}
}
func (s *NativeCallContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitNativeCall(s)
}
}
func (p *ScriptBlockParser) NativeCall() (localctx INativeCallContext) {
localctx = NewNativeCallContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 10, ScriptBlockParserRULE_nativeCall)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(108)
p.Match(ScriptBlockParserNATIVE)
}
{
p.SetState(109)
p.ArgumentList()
}
return localctx
}
// IFunctionCallContext is an interface to support dynamic dispatch.
type IFunctionCallContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsFunctionCallContext differentiates from other interfaces.
IsFunctionCallContext()
}
type FunctionCallContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyFunctionCallContext() *FunctionCallContext {
var p = new(FunctionCallContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_functionCall
return p
}
func (*FunctionCallContext) IsFunctionCallContext() {}
func NewFunctionCallContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *FunctionCallContext {
var p = new(FunctionCallContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_functionCall
return p
}
func (s *FunctionCallContext) GetParser() antlr.Parser { return s.parser }
func (s *FunctionCallContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *FunctionCallContext) FunctionFrame() IFunctionFrameContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionFrameContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionFrameContext)
}
func (s *FunctionCallContext) ArgumentList() IArgumentListContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IArgumentListContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IArgumentListContext)
}
func (s *FunctionCallContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FunctionCallContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *FunctionCallContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFunctionCall(s)
}
}
func (s *FunctionCallContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFunctionCall(s)
}
}
func (p *ScriptBlockParser) FunctionCall() (localctx IFunctionCallContext) {
localctx = NewFunctionCallContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 12, ScriptBlockParserRULE_functionCall)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(111)
p.Match(ScriptBlockParserIDENTIFIER)
}
p.SetState(117)
p.GetErrorHandler().Sync(p)
switch p.GetTokenStream().LA(1) {
case ScriptBlockParserOPAREN:
{
p.SetState(112)
p.ArgumentList()
}
p.SetState(114)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserOCURLY {
{
p.SetState(113)
p.FunctionFrame()
}
}
case ScriptBlockParserOCURLY:
{
p.SetState(116)
p.FunctionFrame()
}
default:
panic(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))
}
return localctx
}
// IFunctionFrameContext is an interface to support dynamic dispatch.
type IFunctionFrameContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsFunctionFrameContext differentiates from other interfaces.
IsFunctionFrameContext()
}
type FunctionFrameContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyFunctionFrameContext() *FunctionFrameContext {
var p = new(FunctionFrameContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_functionFrame
return p
}
func (*FunctionFrameContext) IsFunctionFrameContext() {}
func NewFunctionFrameContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *FunctionFrameContext {
var p = new(FunctionFrameContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_functionFrame
return p
}
func (s *FunctionFrameContext) GetParser() antlr.Parser { return s.parser }
func (s *FunctionFrameContext) OCURLY() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserOCURLY, 0)
}
func (s *FunctionFrameContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *FunctionFrameContext) CCURLY() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCCURLY, 0)
}
func (s *FunctionFrameContext) ParameterList() IParameterListContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IParameterListContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IParameterListContext)
}
func (s *FunctionFrameContext) ARROW() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserARROW, 0)
}
func (s *FunctionFrameContext) AllStatement() []IStatementContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IStatementContext)(nil)).Elem())
var tst = make([]IStatementContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IStatementContext)
}
}
return tst
}
func (s *FunctionFrameContext) Statement(i int) IStatementContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IStatementContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IStatementContext)
}
func (s *FunctionFrameContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FunctionFrameContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *FunctionFrameContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFunctionFrame(s)
}
}
func (s *FunctionFrameContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFunctionFrame(s)
}
}
func (p *ScriptBlockParser) FunctionFrame() (localctx IFunctionFrameContext) {
localctx = NewFunctionFrameContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 14, ScriptBlockParserRULE_functionFrame)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(119)
p.Match(ScriptBlockParserOCURLY)
}
p.SetState(123)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserOPAREN {
{
p.SetState(120)
p.ParameterList()
}
{
p.SetState(121)
p.Match(ScriptBlockParserARROW)
}
}
{
p.SetState(125)
p.Match(ScriptBlockParserNEWLINES)
}
p.SetState(129)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
for ((_la-9)&-(0x1f+1)) == 0 && ((1<<uint((_la-9)))&((1<<(ScriptBlockParserNATIVE-9))|(1<<(ScriptBlockParserRAISE-9))|(1<<(ScriptBlockParserDELAY-9))|(1<<(ScriptBlockParserIDENTIFIER-9)))) != 0 {
{
p.SetState(126)
p.Statement()
}
p.SetState(131)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
}
{
p.SetState(132)
p.Match(ScriptBlockParserCCURLY)
}
return localctx
}
// IFunctionDefinitionContext is an interface to support dynamic dispatch.
type IFunctionDefinitionContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsFunctionDefinitionContext differentiates from other interfaces.
IsFunctionDefinitionContext()
}
type FunctionDefinitionContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyFunctionDefinitionContext() *FunctionDefinitionContext {
var p = new(FunctionDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_functionDefinition
return p
}
func (*FunctionDefinitionContext) IsFunctionDefinitionContext() {}
func NewFunctionDefinitionContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *FunctionDefinitionContext {
var p = new(FunctionDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_functionDefinition
return p
}
func (s *FunctionDefinitionContext) GetParser() antlr.Parser { return s.parser }
func (s *FunctionDefinitionContext) FUNCTION() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserFUNCTION, 0)
}
func (s *FunctionDefinitionContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *FunctionDefinitionContext) FunctionFrame() IFunctionFrameContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionFrameContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionFrameContext)
}
func (s *FunctionDefinitionContext) Documentation() IDocumentationContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDocumentationContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDocumentationContext)
}
func (s *FunctionDefinitionContext) Tag() ITagContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITagContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITagContext)
}
func (s *FunctionDefinitionContext) INTERNAL() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserINTERNAL, 0)
}
func (s *FunctionDefinitionContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FunctionDefinitionContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *FunctionDefinitionContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFunctionDefinition(s)
}
}
func (s *FunctionDefinitionContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFunctionDefinition(s)
}
}
func (p *ScriptBlockParser) FunctionDefinition() (localctx IFunctionDefinitionContext) {
localctx = NewFunctionDefinitionContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 16, ScriptBlockParserRULE_functionDefinition)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(135)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserDOC_START {
{
p.SetState(134)
p.Documentation()
}
}
p.SetState(138)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserPOUND {
{
p.SetState(137)
p.Tag()
}
}
p.SetState(141)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserINTERNAL {
{
p.SetState(140)
p.Match(ScriptBlockParserINTERNAL)
}
}
{
p.SetState(143)
p.Match(ScriptBlockParserFUNCTION)
}
{
p.SetState(144)
p.Match(ScriptBlockParserIDENTIFIER)
}
{
p.SetState(145)
p.FunctionFrame()
}
return localctx
}
// IFunctionDefinitionShortcutContext is an interface to support dynamic dispatch.
type IFunctionDefinitionShortcutContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsFunctionDefinitionShortcutContext differentiates from other interfaces.
IsFunctionDefinitionShortcutContext()
}
type FunctionDefinitionShortcutContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyFunctionDefinitionShortcutContext() *FunctionDefinitionShortcutContext {
var p = new(FunctionDefinitionShortcutContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_functionDefinitionShortcut
return p
}
func (*FunctionDefinitionShortcutContext) IsFunctionDefinitionShortcutContext() {}
func NewFunctionDefinitionShortcutContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *FunctionDefinitionShortcutContext {
var p = new(FunctionDefinitionShortcutContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_functionDefinitionShortcut
return p
}
func (s *FunctionDefinitionShortcutContext) GetParser() antlr.Parser { return s.parser }
func (s *FunctionDefinitionShortcutContext) FUNCTION() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserFUNCTION, 0)
}
func (s *FunctionDefinitionShortcutContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *FunctionDefinitionShortcutContext) EQUALS() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserEQUALS, 0)
}
func (s *FunctionDefinitionShortcutContext) FunctionCall() IFunctionCallContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionCallContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionCallContext)
}
func (s *FunctionDefinitionShortcutContext) Documentation() IDocumentationContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDocumentationContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDocumentationContext)
}
func (s *FunctionDefinitionShortcutContext) Tag() ITagContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITagContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITagContext)
}
func (s *FunctionDefinitionShortcutContext) INTERNAL() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserINTERNAL, 0)
}
func (s *FunctionDefinitionShortcutContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FunctionDefinitionShortcutContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *FunctionDefinitionShortcutContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFunctionDefinitionShortcut(s)
}
}
func (s *FunctionDefinitionShortcutContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFunctionDefinitionShortcut(s)
}
}
func (p *ScriptBlockParser) FunctionDefinitionShortcut() (localctx IFunctionDefinitionShortcutContext) {
localctx = NewFunctionDefinitionShortcutContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 18, ScriptBlockParserRULE_functionDefinitionShortcut)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(148)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserDOC_START {
{
p.SetState(147)
p.Documentation()
}
}
p.SetState(151)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserPOUND {
{
p.SetState(150)
p.Tag()
}
}
p.SetState(154)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserINTERNAL {
{
p.SetState(153)
p.Match(ScriptBlockParserINTERNAL)
}
}
{
p.SetState(156)
p.Match(ScriptBlockParserFUNCTION)
}
{
p.SetState(157)
p.Match(ScriptBlockParserIDENTIFIER)
}
{
p.SetState(158)
p.Match(ScriptBlockParserEQUALS)
}
{
p.SetState(159)
p.FunctionCall()
}
return localctx
}
// ITagContext is an interface to support dynamic dispatch.
type ITagContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsTagContext differentiates from other interfaces.
IsTagContext()
}
type TagContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyTagContext() *TagContext {
var p = new(TagContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_tag
return p
}
func (*TagContext) IsTagContext() {}
func NewTagContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TagContext {
var p = new(TagContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_tag
return p
}
func (s *TagContext) GetParser() antlr.Parser { return s.parser }
func (s *TagContext) POUND() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserPOUND, 0)
}
func (s *TagContext) AllIDENTIFIER() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserIDENTIFIER)
}
func (s *TagContext) IDENTIFIER(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, i)
}
func (s *TagContext) COLON() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCOLON, 0)
}
func (s *TagContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TagContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TagContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterTag(s)
}
}
func (s *TagContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitTag(s)
}
}
func (p *ScriptBlockParser) Tag() (localctx ITagContext) {
localctx = NewTagContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 20, ScriptBlockParserRULE_tag)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(161)
p.Match(ScriptBlockParserPOUND)
}
{
p.SetState(162)
p.Match(ScriptBlockParserIDENTIFIER)
}
{
p.SetState(163)
p.Match(ScriptBlockParserCOLON)
}
{
p.SetState(164)
p.Match(ScriptBlockParserIDENTIFIER)
}
return localctx
}
// ITemplateDefinitionContext is an interface to support dynamic dispatch.
type ITemplateDefinitionContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsTemplateDefinitionContext differentiates from other interfaces.
IsTemplateDefinitionContext()
}
type TemplateDefinitionContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyTemplateDefinitionContext() *TemplateDefinitionContext {
var p = new(TemplateDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_templateDefinition
return p
}
func (*TemplateDefinitionContext) IsTemplateDefinitionContext() {}
func NewTemplateDefinitionContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TemplateDefinitionContext {
var p = new(TemplateDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_templateDefinition
return p
}
func (s *TemplateDefinitionContext) GetParser() antlr.Parser { return s.parser }
func (s *TemplateDefinitionContext) TEMPLATE() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserTEMPLATE, 0)
}
func (s *TemplateDefinitionContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *TemplateDefinitionContext) FunctionFrame() IFunctionFrameContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionFrameContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionFrameContext)
}
func (s *TemplateDefinitionContext) Documentation() IDocumentationContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDocumentationContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDocumentationContext)
}
func (s *TemplateDefinitionContext) INTERNAL() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserINTERNAL, 0)
}
func (s *TemplateDefinitionContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TemplateDefinitionContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *TemplateDefinitionContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterTemplateDefinition(s)
}
}
func (s *TemplateDefinitionContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitTemplateDefinition(s)
}
}
func (p *ScriptBlockParser) TemplateDefinition() (localctx ITemplateDefinitionContext) {
localctx = NewTemplateDefinitionContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 22, ScriptBlockParserRULE_templateDefinition)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(167)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserDOC_START {
{
p.SetState(166)
p.Documentation()
}
}
p.SetState(170)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserINTERNAL {
{
p.SetState(169)
p.Match(ScriptBlockParserINTERNAL)
}
}
{
p.SetState(172)
p.Match(ScriptBlockParserTEMPLATE)
}
{
p.SetState(173)
p.Match(ScriptBlockParserIDENTIFIER)
}
{
p.SetState(174)
p.FunctionFrame()
}
return localctx
}
// IConstantDefinitionContext is an interface to support dynamic dispatch.
type IConstantDefinitionContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsConstantDefinitionContext differentiates from other interfaces.
IsConstantDefinitionContext()
}
type ConstantDefinitionContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyConstantDefinitionContext() *ConstantDefinitionContext {
var p = new(ConstantDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_constantDefinition
return p
}
func (*ConstantDefinitionContext) IsConstantDefinitionContext() {}
func NewConstantDefinitionContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ConstantDefinitionContext {
var p = new(ConstantDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_constantDefinition
return p
}
func (s *ConstantDefinitionContext) GetParser() antlr.Parser { return s.parser }
func (s *ConstantDefinitionContext) CONSTANT() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCONSTANT, 0)
}
func (s *ConstantDefinitionContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *ConstantDefinitionContext) EQUALS() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserEQUALS, 0)
}
func (s *ConstantDefinitionContext) Expression() IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *ConstantDefinitionContext) Documentation() IDocumentationContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDocumentationContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDocumentationContext)
}
func (s *ConstantDefinitionContext) INTERNAL() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserINTERNAL, 0)
}
func (s *ConstantDefinitionContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ConstantDefinitionContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ConstantDefinitionContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterConstantDefinition(s)
}
}
func (s *ConstantDefinitionContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitConstantDefinition(s)
}
}
func (p *ScriptBlockParser) ConstantDefinition() (localctx IConstantDefinitionContext) {
localctx = NewConstantDefinitionContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 24, ScriptBlockParserRULE_constantDefinition)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(177)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserDOC_START {
{
p.SetState(176)
p.Documentation()
}
}
p.SetState(180)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserINTERNAL {
{
p.SetState(179)
p.Match(ScriptBlockParserINTERNAL)
}
}
{
p.SetState(182)
p.Match(ScriptBlockParserCONSTANT)
}
{
p.SetState(183)
p.Match(ScriptBlockParserIDENTIFIER)
}
{
p.SetState(184)
p.Match(ScriptBlockParserEQUALS)
}
{
p.SetState(185)
p.expression(0)
}
return localctx
}
// IFormatterContext is an interface to support dynamic dispatch.
type IFormatterContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsFormatterContext differentiates from other interfaces.
IsFormatterContext()
}
type FormatterContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyFormatterContext() *FormatterContext {
var p = new(FormatterContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_formatter
return p
}
func (*FormatterContext) IsFormatterContext() {}
func NewFormatterContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *FormatterContext {
var p = new(FormatterContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_formatter
return p
}
func (s *FormatterContext) GetParser() antlr.Parser { return s.parser }
func (s *FormatterContext) LESS_THAN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserLESS_THAN, 0)
}
func (s *FormatterContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *FormatterContext) GREATER_THAN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserGREATER_THAN, 0)
}
func (s *FormatterContext) ArgumentList() IArgumentListContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IArgumentListContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IArgumentListContext)
}
func (s *FormatterContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FormatterContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *FormatterContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFormatter(s)
}
}
func (s *FormatterContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFormatter(s)
}
}
func (p *ScriptBlockParser) Formatter() (localctx IFormatterContext) {
localctx = NewFormatterContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 26, ScriptBlockParserRULE_formatter)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(187)
p.Match(ScriptBlockParserLESS_THAN)
}
{
p.SetState(188)
p.Match(ScriptBlockParserIDENTIFIER)
}
{
p.SetState(189)
p.Match(ScriptBlockParserGREATER_THAN)
}
{
p.SetState(190)
p.ArgumentList()
}
return localctx
}
// IImportLineContext is an interface to support dynamic dispatch.
type IImportLineContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsImportLineContext differentiates from other interfaces.
IsImportLineContext()
}
type ImportLineContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyImportLineContext() *ImportLineContext {
var p = new(ImportLineContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_importLine
return p
}
func (*ImportLineContext) IsImportLineContext() {}
func NewImportLineContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ImportLineContext {
var p = new(ImportLineContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_importLine
return p
}
func (s *ImportLineContext) GetParser() antlr.Parser { return s.parser }
func (s *ImportLineContext) IMPORT() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIMPORT, 0)
}
func (s *ImportLineContext) STRING() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserSTRING, 0)
}
func (s *ImportLineContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ImportLineContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *ImportLineContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterImportLine(s)
}
}
func (s *ImportLineContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitImportLine(s)
}
}
func (p *ScriptBlockParser) ImportLine() (localctx IImportLineContext) {
localctx = NewImportLineContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 28, ScriptBlockParserRULE_importLine)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(192)
p.Match(ScriptBlockParserIMPORT)
}
{
p.SetState(193)
p.Match(ScriptBlockParserSTRING)
}
return localctx
}
// ITopDefinitionContext is an interface to support dynamic dispatch.
type ITopDefinitionContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsTopDefinitionContext differentiates from other interfaces.
IsTopDefinitionContext()
}
type TopDefinitionContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyTopDefinitionContext() *TopDefinitionContext {
var p = new(TopDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_topDefinition
return p
}
func (*TopDefinitionContext) IsTopDefinitionContext() {}
func NewTopDefinitionContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *TopDefinitionContext {
var p = new(TopDefinitionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_topDefinition
return p
}
func (s *TopDefinitionContext) GetParser() antlr.Parser { return s.parser }
func (s *TopDefinitionContext) CopyFrom(ctx *TopDefinitionContext) {
s.BaseParserRuleContext.CopyFrom(ctx.BaseParserRuleContext)
}
func (s *TopDefinitionContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TopDefinitionContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
type FunctionDefinitionTopContext struct {
*TopDefinitionContext
}
func NewFunctionDefinitionTopContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *FunctionDefinitionTopContext {
var p = new(FunctionDefinitionTopContext)
p.TopDefinitionContext = NewEmptyTopDefinitionContext()
p.parser = parser
p.CopyFrom(ctx.(*TopDefinitionContext))
return p
}
func (s *FunctionDefinitionTopContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FunctionDefinitionTopContext) FunctionDefinition() IFunctionDefinitionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionDefinitionContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionDefinitionContext)
}
func (s *FunctionDefinitionTopContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *FunctionDefinitionTopContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFunctionDefinitionTop(s)
}
}
func (s *FunctionDefinitionTopContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFunctionDefinitionTop(s)
}
}
type FunctionShortcutTopContext struct {
*TopDefinitionContext
}
func NewFunctionShortcutTopContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *FunctionShortcutTopContext {
var p = new(FunctionShortcutTopContext)
p.TopDefinitionContext = NewEmptyTopDefinitionContext()
p.parser = parser
p.CopyFrom(ctx.(*TopDefinitionContext))
return p
}
func (s *FunctionShortcutTopContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FunctionShortcutTopContext) FunctionDefinitionShortcut() IFunctionDefinitionShortcutContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionDefinitionShortcutContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionDefinitionShortcutContext)
}
func (s *FunctionShortcutTopContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *FunctionShortcutTopContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFunctionShortcutTop(s)
}
}
func (s *FunctionShortcutTopContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFunctionShortcutTop(s)
}
}
type ConstantDefinitionTopContext struct {
*TopDefinitionContext
}
func NewConstantDefinitionTopContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *ConstantDefinitionTopContext {
var p = new(ConstantDefinitionTopContext)
p.TopDefinitionContext = NewEmptyTopDefinitionContext()
p.parser = parser
p.CopyFrom(ctx.(*TopDefinitionContext))
return p
}
func (s *ConstantDefinitionTopContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ConstantDefinitionTopContext) ConstantDefinition() IConstantDefinitionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IConstantDefinitionContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IConstantDefinitionContext)
}
func (s *ConstantDefinitionTopContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *ConstantDefinitionTopContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterConstantDefinitionTop(s)
}
}
func (s *ConstantDefinitionTopContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitConstantDefinitionTop(s)
}
}
type TemplateDefinitionTopContext struct {
*TopDefinitionContext
}
func NewTemplateDefinitionTopContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *TemplateDefinitionTopContext {
var p = new(TemplateDefinitionTopContext)
p.TopDefinitionContext = NewEmptyTopDefinitionContext()
p.parser = parser
p.CopyFrom(ctx.(*TopDefinitionContext))
return p
}
func (s *TemplateDefinitionTopContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *TemplateDefinitionTopContext) TemplateDefinition() ITemplateDefinitionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITemplateDefinitionContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITemplateDefinitionContext)
}
func (s *TemplateDefinitionTopContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *TemplateDefinitionTopContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterTemplateDefinitionTop(s)
}
}
func (s *TemplateDefinitionTopContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitTemplateDefinitionTop(s)
}
}
func (p *ScriptBlockParser) TopDefinition() (localctx ITopDefinitionContext) {
localctx = NewTopDefinitionContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 30, ScriptBlockParserRULE_topDefinition)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(207)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 23, p.GetParserRuleContext()) {
case 1:
localctx = NewConstantDefinitionTopContext(p, localctx)
p.EnterOuterAlt(localctx, 1)
{
p.SetState(195)
p.ConstantDefinition()
}
{
p.SetState(196)
p.Match(ScriptBlockParserNEWLINES)
}
case 2:
localctx = NewFunctionDefinitionTopContext(p, localctx)
p.EnterOuterAlt(localctx, 2)
{
p.SetState(198)
p.FunctionDefinition()
}
{
p.SetState(199)
p.Match(ScriptBlockParserNEWLINES)
}
case 3:
localctx = NewTemplateDefinitionTopContext(p, localctx)
p.EnterOuterAlt(localctx, 3)
{
p.SetState(201)
p.TemplateDefinition()
}
{
p.SetState(202)
p.Match(ScriptBlockParserNEWLINES)
}
case 4:
localctx = NewFunctionShortcutTopContext(p, localctx)
p.EnterOuterAlt(localctx, 4)
{
p.SetState(204)
p.FunctionDefinitionShortcut()
}
{
p.SetState(205)
p.Match(ScriptBlockParserNEWLINES)
}
}
return localctx
}
// IStatementContext is an interface to support dynamic dispatch.
type IStatementContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsStatementContext differentiates from other interfaces.
IsStatementContext()
}
type StatementContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyStatementContext() *StatementContext {
var p = new(StatementContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_statement
return p
}
func (*StatementContext) IsStatementContext() {}
func NewStatementContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StatementContext {
var p = new(StatementContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_statement
return p
}
func (s *StatementContext) GetParser() antlr.Parser { return s.parser }
func (s *StatementContext) CopyFrom(ctx *StatementContext) {
s.BaseParserRuleContext.CopyFrom(ctx.BaseParserRuleContext)
}
func (s *StatementContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *StatementContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
type RaiseStatementContext struct {
*StatementContext
}
func NewRaiseStatementContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *RaiseStatementContext {
var p = new(RaiseStatementContext)
p.StatementContext = NewEmptyStatementContext()
p.parser = parser
p.CopyFrom(ctx.(*StatementContext))
return p
}
func (s *RaiseStatementContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *RaiseStatementContext) Raise() IRaiseContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IRaiseContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IRaiseContext)
}
func (s *RaiseStatementContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *RaiseStatementContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterRaiseStatement(s)
}
}
func (s *RaiseStatementContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitRaiseStatement(s)
}
}
type FunctionCallStatementContext struct {
*StatementContext
}
func NewFunctionCallStatementContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *FunctionCallStatementContext {
var p = new(FunctionCallStatementContext)
p.StatementContext = NewEmptyStatementContext()
p.parser = parser
p.CopyFrom(ctx.(*StatementContext))
return p
}
func (s *FunctionCallStatementContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FunctionCallStatementContext) FunctionCall() IFunctionCallContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionCallContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionCallContext)
}
func (s *FunctionCallStatementContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *FunctionCallStatementContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFunctionCallStatement(s)
}
}
func (s *FunctionCallStatementContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFunctionCallStatement(s)
}
}
type DelayStructureStatementContext struct {
*StatementContext
}
func NewDelayStructureStatementContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *DelayStructureStatementContext {
var p = new(DelayStructureStatementContext)
p.StatementContext = NewEmptyStatementContext()
p.parser = parser
p.CopyFrom(ctx.(*StatementContext))
return p
}
func (s *DelayStructureStatementContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *DelayStructureStatementContext) DelayStructure() IDelayStructureContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IDelayStructureContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IDelayStructureContext)
}
func (s *DelayStructureStatementContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *DelayStructureStatementContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterDelayStructureStatement(s)
}
}
func (s *DelayStructureStatementContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitDelayStructureStatement(s)
}
}
type NativeCallStatementContext struct {
*StatementContext
}
func NewNativeCallStatementContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *NativeCallStatementContext {
var p = new(NativeCallStatementContext)
p.StatementContext = NewEmptyStatementContext()
p.parser = parser
p.CopyFrom(ctx.(*StatementContext))
return p
}
func (s *NativeCallStatementContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *NativeCallStatementContext) NativeCall() INativeCallContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*INativeCallContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(INativeCallContext)
}
func (s *NativeCallStatementContext) NEWLINES() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserNEWLINES, 0)
}
func (s *NativeCallStatementContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterNativeCallStatement(s)
}
}
func (s *NativeCallStatementContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitNativeCallStatement(s)
}
}
func (p *ScriptBlockParser) Statement() (localctx IStatementContext) {
localctx = NewStatementContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 32, ScriptBlockParserRULE_statement)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.SetState(221)
p.GetErrorHandler().Sync(p)
switch p.GetTokenStream().LA(1) {
case ScriptBlockParserIDENTIFIER:
localctx = NewFunctionCallStatementContext(p, localctx)
p.EnterOuterAlt(localctx, 1)
{
p.SetState(209)
p.FunctionCall()
}
{
p.SetState(210)
p.Match(ScriptBlockParserNEWLINES)
}
case ScriptBlockParserNATIVE:
localctx = NewNativeCallStatementContext(p, localctx)
p.EnterOuterAlt(localctx, 2)
{
p.SetState(212)
p.NativeCall()
}
{
p.SetState(213)
p.Match(ScriptBlockParserNEWLINES)
}
case ScriptBlockParserDELAY:
localctx = NewDelayStructureStatementContext(p, localctx)
p.EnterOuterAlt(localctx, 3)
{
p.SetState(215)
p.DelayStructure()
}
{
p.SetState(216)
p.Match(ScriptBlockParserNEWLINES)
}
case ScriptBlockParserRAISE:
localctx = NewRaiseStatementContext(p, localctx)
p.EnterOuterAlt(localctx, 4)
{
p.SetState(218)
p.Raise()
}
{
p.SetState(219)
p.Match(ScriptBlockParserNEWLINES)
}
default:
panic(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))
}
return localctx
}
// IDelayStructureContext is an interface to support dynamic dispatch.
type IDelayStructureContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsDelayStructureContext differentiates from other interfaces.
IsDelayStructureContext()
}
type DelayStructureContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyDelayStructureContext() *DelayStructureContext {
var p = new(DelayStructureContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_delayStructure
return p
}
func (*DelayStructureContext) IsDelayStructureContext() {}
func NewDelayStructureContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *DelayStructureContext {
var p = new(DelayStructureContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_delayStructure
return p
}
func (s *DelayStructureContext) GetParser() antlr.Parser { return s.parser }
func (s *DelayStructureContext) DELAY() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserDELAY, 0)
}
func (s *DelayStructureContext) StructureList() IStructureListContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IStructureListContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IStructureListContext)
}
func (s *DelayStructureContext) FunctionFrame() IFunctionFrameContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFunctionFrameContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFunctionFrameContext)
}
func (s *DelayStructureContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *DelayStructureContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *DelayStructureContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterDelayStructure(s)
}
}
func (s *DelayStructureContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitDelayStructure(s)
}
}
func (p *ScriptBlockParser) DelayStructure() (localctx IDelayStructureContext) {
localctx = NewDelayStructureContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 34, ScriptBlockParserRULE_delayStructure)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(223)
p.Match(ScriptBlockParserDELAY)
}
{
p.SetState(224)
p.StructureList()
}
{
p.SetState(225)
p.FunctionFrame()
}
return localctx
}
// IRaiseContext is an interface to support dynamic dispatch.
type IRaiseContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsRaiseContext differentiates from other interfaces.
IsRaiseContext()
}
type RaiseContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyRaiseContext() *RaiseContext {
var p = new(RaiseContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_raise
return p
}
func (*RaiseContext) IsRaiseContext() {}
func NewRaiseContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *RaiseContext {
var p = new(RaiseContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_raise
return p
}
func (s *RaiseContext) GetParser() antlr.Parser { return s.parser }
func (s *RaiseContext) RAISE() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserRAISE, 0)
}
func (s *RaiseContext) Tag() ITagContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*ITagContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(ITagContext)
}
func (s *RaiseContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *RaiseContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *RaiseContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterRaise(s)
}
}
func (s *RaiseContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitRaise(s)
}
}
func (p *ScriptBlockParser) Raise() (localctx IRaiseContext) {
localctx = NewRaiseContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 36, ScriptBlockParserRULE_raise)
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
{
p.SetState(227)
p.Match(ScriptBlockParserRAISE)
}
{
p.SetState(228)
p.Tag()
}
return localctx
}
// IExpressionContext is an interface to support dynamic dispatch.
type IExpressionContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsExpressionContext differentiates from other interfaces.
IsExpressionContext()
}
type ExpressionContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyExpressionContext() *ExpressionContext {
var p = new(ExpressionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_expression
return p
}
func (*ExpressionContext) IsExpressionContext() {}
func NewExpressionContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ExpressionContext {
var p = new(ExpressionContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_expression
return p
}
func (s *ExpressionContext) GetParser() antlr.Parser { return s.parser }
func (s *ExpressionContext) CopyFrom(ctx *ExpressionContext) {
s.BaseParserRuleContext.CopyFrom(ctx.BaseParserRuleContext)
}
func (s *ExpressionContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ExpressionContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
type StringExprContext struct {
*ExpressionContext
}
func NewStringExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *StringExprContext {
var p = new(StringExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *StringExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *StringExprContext) STRING() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserSTRING, 0)
}
func (s *StringExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterStringExpr(s)
}
}
func (s *StringExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitStringExpr(s)
}
}
type DivideExprContext struct {
*ExpressionContext
}
func NewDivideExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *DivideExprContext {
var p = new(DivideExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *DivideExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *DivideExprContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *DivideExprContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *DivideExprContext) DIVIDE() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserDIVIDE, 0)
}
func (s *DivideExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterDivideExpr(s)
}
}
func (s *DivideExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitDivideExpr(s)
}
}
type IntegerDivideExprContext struct {
*ExpressionContext
}
func NewIntegerDivideExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IntegerDivideExprContext {
var p = new(IntegerDivideExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *IntegerDivideExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *IntegerDivideExprContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *IntegerDivideExprContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *IntegerDivideExprContext) INTEGER_DIVIDE() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserINTEGER_DIVIDE, 0)
}
func (s *IntegerDivideExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterIntegerDivideExpr(s)
}
}
func (s *IntegerDivideExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitIntegerDivideExpr(s)
}
}
type SubtractExprContext struct {
*ExpressionContext
}
func NewSubtractExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *SubtractExprContext {
var p = new(SubtractExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *SubtractExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *SubtractExprContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *SubtractExprContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *SubtractExprContext) SUBTRACT() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserSUBTRACT, 0)
}
func (s *SubtractExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterSubtractExpr(s)
}
}
func (s *SubtractExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitSubtractExpr(s)
}
}
type PowerExprContext struct {
*ExpressionContext
}
func NewPowerExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *PowerExprContext {
var p = new(PowerExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *PowerExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *PowerExprContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *PowerExprContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *PowerExprContext) POWER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserPOWER, 0)
}
func (s *PowerExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterPowerExpr(s)
}
}
func (s *PowerExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitPowerExpr(s)
}
}
type AddExprContext struct {
*ExpressionContext
}
func NewAddExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *AddExprContext {
var p = new(AddExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *AddExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *AddExprContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *AddExprContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *AddExprContext) PLUS() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserPLUS, 0)
}
func (s *AddExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterAddExpr(s)
}
}
func (s *AddExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitAddExpr(s)
}
}
type NumberExprContext struct {
*ExpressionContext
}
func NewNumberExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *NumberExprContext {
var p = new(NumberExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *NumberExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *NumberExprContext) Number() INumberContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*INumberContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(INumberContext)
}
func (s *NumberExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterNumberExpr(s)
}
}
func (s *NumberExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitNumberExpr(s)
}
}
type MultiplyExprContext struct {
*ExpressionContext
}
func NewMultiplyExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *MultiplyExprContext {
var p = new(MultiplyExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *MultiplyExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *MultiplyExprContext) AllExpression() []IExpressionContext {
var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExpressionContext)(nil)).Elem())
var tst = make([]IExpressionContext, len(ts))
for i, t := range ts {
if t != nil {
tst[i] = t.(IExpressionContext)
}
}
return tst
}
func (s *MultiplyExprContext) Expression(i int) IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), i)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *MultiplyExprContext) MULTIPLY() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserMULTIPLY, 0)
}
func (s *MultiplyExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterMultiplyExpr(s)
}
}
func (s *MultiplyExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitMultiplyExpr(s)
}
}
type CallExprContext struct {
*ExpressionContext
}
func NewCallExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *CallExprContext {
var p = new(CallExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *CallExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *CallExprContext) RUN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserRUN, 0)
}
func (s *CallExprContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *CallExprContext) ArgumentList() IArgumentListContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IArgumentListContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IArgumentListContext)
}
func (s *CallExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterCallExpr(s)
}
}
func (s *CallExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitCallExpr(s)
}
}
type FormatterExprContext struct {
*ExpressionContext
}
func NewFormatterExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *FormatterExprContext {
var p = new(FormatterExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *FormatterExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *FormatterExprContext) Formatter() IFormatterContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IFormatterContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IFormatterContext)
}
func (s *FormatterExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterFormatterExpr(s)
}
}
func (s *FormatterExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitFormatterExpr(s)
}
}
type IdentifierExprContext struct {
*ExpressionContext
}
func NewIdentifierExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IdentifierExprContext {
var p = new(IdentifierExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *IdentifierExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *IdentifierExprContext) IDENTIFIER() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserIDENTIFIER, 0)
}
func (s *IdentifierExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterIdentifierExpr(s)
}
}
func (s *IdentifierExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitIdentifierExpr(s)
}
}
type ParenthExprContext struct {
*ExpressionContext
}
func NewParenthExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *ParenthExprContext {
var p = new(ParenthExprContext)
p.ExpressionContext = NewEmptyExpressionContext()
p.parser = parser
p.CopyFrom(ctx.(*ExpressionContext))
return p
}
func (s *ParenthExprContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *ParenthExprContext) OPAREN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserOPAREN, 0)
}
func (s *ParenthExprContext) Expression() IExpressionContext {
var t = s.GetTypedRuleContext(reflect.TypeOf((*IExpressionContext)(nil)).Elem(), 0)
if t == nil {
return nil
}
return t.(IExpressionContext)
}
func (s *ParenthExprContext) CPAREN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserCPAREN, 0)
}
func (s *ParenthExprContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterParenthExpr(s)
}
}
func (s *ParenthExprContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitParenthExpr(s)
}
}
func (p *ScriptBlockParser) Expression() (localctx IExpressionContext) {
return p.expression(0)
}
func (p *ScriptBlockParser) expression(_p int) (localctx IExpressionContext) {
var _parentctx antlr.ParserRuleContext = p.GetParserRuleContext()
_parentState := p.GetState()
localctx = NewExpressionContext(p, p.GetParserRuleContext(), _parentState)
var _prevctx IExpressionContext = localctx
var _ antlr.ParserRuleContext = _prevctx // TODO: To prevent unused variable warning.
_startState := 38
p.EnterRecursionRule(localctx, 38, ScriptBlockParserRULE_expression, _p)
defer func() {
p.UnrollRecursionContexts(_parentctx)
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
var _alt int
p.EnterOuterAlt(localctx, 1)
p.SetState(242)
p.GetErrorHandler().Sync(p)
switch p.GetTokenStream().LA(1) {
case ScriptBlockParserSIGN, ScriptBlockParserDIGITS:
localctx = NewNumberExprContext(p, localctx)
p.SetParserRuleContext(localctx)
_prevctx = localctx
{
p.SetState(231)
p.Number()
}
case ScriptBlockParserSTRING:
localctx = NewStringExprContext(p, localctx)
p.SetParserRuleContext(localctx)
_prevctx = localctx
{
p.SetState(232)
p.Match(ScriptBlockParserSTRING)
}
case ScriptBlockParserIDENTIFIER:
localctx = NewIdentifierExprContext(p, localctx)
p.SetParserRuleContext(localctx)
_prevctx = localctx
{
p.SetState(233)
p.Match(ScriptBlockParserIDENTIFIER)
}
case ScriptBlockParserOPAREN:
localctx = NewParenthExprContext(p, localctx)
p.SetParserRuleContext(localctx)
_prevctx = localctx
{
p.SetState(234)
p.Match(ScriptBlockParserOPAREN)
}
{
p.SetState(235)
p.expression(0)
}
{
p.SetState(236)
p.Match(ScriptBlockParserCPAREN)
}
case ScriptBlockParserLESS_THAN:
localctx = NewFormatterExprContext(p, localctx)
p.SetParserRuleContext(localctx)
_prevctx = localctx
{
p.SetState(238)
p.Formatter()
}
case ScriptBlockParserRUN:
localctx = NewCallExprContext(p, localctx)
p.SetParserRuleContext(localctx)
_prevctx = localctx
{
p.SetState(239)
p.Match(ScriptBlockParserRUN)
}
{
p.SetState(240)
p.Match(ScriptBlockParserIDENTIFIER)
}
{
p.SetState(241)
p.ArgumentList()
}
default:
panic(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))
}
p.GetParserRuleContext().SetStop(p.GetTokenStream().LT(-1))
p.SetState(264)
p.GetErrorHandler().Sync(p)
_alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 27, p.GetParserRuleContext())
for _alt != 2 && _alt != antlr.ATNInvalidAltNumber {
if _alt == 1 {
if p.GetParseListeners() != nil {
p.TriggerExitRuleEvent()
}
_prevctx = localctx
p.SetState(262)
p.GetErrorHandler().Sync(p)
switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 26, p.GetParserRuleContext()) {
case 1:
localctx = NewPowerExprContext(p, NewExpressionContext(p, _parentctx, _parentState))
p.PushNewRecursionContext(localctx, _startState, ScriptBlockParserRULE_expression)
p.SetState(244)
if !(p.Precpred(p.GetParserRuleContext(), 7)) {
panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 7)", ""))
}
{
p.SetState(245)
p.Match(ScriptBlockParserPOWER)
}
{
p.SetState(246)
p.expression(7)
}
case 2:
localctx = NewMultiplyExprContext(p, NewExpressionContext(p, _parentctx, _parentState))
p.PushNewRecursionContext(localctx, _startState, ScriptBlockParserRULE_expression)
p.SetState(247)
if !(p.Precpred(p.GetParserRuleContext(), 6)) {
panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 6)", ""))
}
{
p.SetState(248)
p.Match(ScriptBlockParserMULTIPLY)
}
{
p.SetState(249)
p.expression(7)
}
case 3:
localctx = NewDivideExprContext(p, NewExpressionContext(p, _parentctx, _parentState))
p.PushNewRecursionContext(localctx, _startState, ScriptBlockParserRULE_expression)
p.SetState(250)
if !(p.Precpred(p.GetParserRuleContext(), 5)) {
panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 5)", ""))
}
{
p.SetState(251)
p.Match(ScriptBlockParserDIVIDE)
}
{
p.SetState(252)
p.expression(6)
}
case 4:
localctx = NewIntegerDivideExprContext(p, NewExpressionContext(p, _parentctx, _parentState))
p.PushNewRecursionContext(localctx, _startState, ScriptBlockParserRULE_expression)
p.SetState(253)
if !(p.Precpred(p.GetParserRuleContext(), 4)) {
panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 4)", ""))
}
{
p.SetState(254)
p.Match(ScriptBlockParserINTEGER_DIVIDE)
}
{
p.SetState(255)
p.expression(5)
}
case 5:
localctx = NewAddExprContext(p, NewExpressionContext(p, _parentctx, _parentState))
p.PushNewRecursionContext(localctx, _startState, ScriptBlockParserRULE_expression)
p.SetState(256)
if !(p.Precpred(p.GetParserRuleContext(), 3)) {
panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 3)", ""))
}
{
p.SetState(257)
p.Match(ScriptBlockParserPLUS)
}
{
p.SetState(258)
p.expression(4)
}
case 6:
localctx = NewSubtractExprContext(p, NewExpressionContext(p, _parentctx, _parentState))
p.PushNewRecursionContext(localctx, _startState, ScriptBlockParserRULE_expression)
p.SetState(259)
if !(p.Precpred(p.GetParserRuleContext(), 2)) {
panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 2)", ""))
}
{
p.SetState(260)
p.Match(ScriptBlockParserSUBTRACT)
}
{
p.SetState(261)
p.expression(3)
}
}
}
p.SetState(266)
p.GetErrorHandler().Sync(p)
_alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 27, p.GetParserRuleContext())
}
return localctx
}
// INumberContext is an interface to support dynamic dispatch.
type INumberContext interface {
antlr.ParserRuleContext
// GetParser returns the parser.
GetParser() antlr.Parser
// IsNumberContext differentiates from other interfaces.
IsNumberContext()
}
type NumberContext struct {
*antlr.BaseParserRuleContext
parser antlr.Parser
}
func NewEmptyNumberContext() *NumberContext {
var p = new(NumberContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
p.RuleIndex = ScriptBlockParserRULE_number
return p
}
func (*NumberContext) IsNumberContext() {}
func NewNumberContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *NumberContext {
var p = new(NumberContext)
p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
p.parser = parser
p.RuleIndex = ScriptBlockParserRULE_number
return p
}
func (s *NumberContext) GetParser() antlr.Parser { return s.parser }
func (s *NumberContext) AllDIGITS() []antlr.TerminalNode {
return s.GetTokens(ScriptBlockParserDIGITS)
}
func (s *NumberContext) DIGITS(i int) antlr.TerminalNode {
return s.GetToken(ScriptBlockParserDIGITS, i)
}
func (s *NumberContext) SIGN() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserSIGN, 0)
}
func (s *NumberContext) DOT() antlr.TerminalNode {
return s.GetToken(ScriptBlockParserDOT, 0)
}
func (s *NumberContext) GetRuleContext() antlr.RuleContext {
return s
}
func (s *NumberContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
return antlr.TreesStringTree(s, ruleNames, recog)
}
func (s *NumberContext) EnterRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.EnterNumber(s)
}
}
func (s *NumberContext) ExitRule(listener antlr.ParseTreeListener) {
if listenerT, ok := listener.(ScriptBlockParserListener); ok {
listenerT.ExitNumber(s)
}
}
func (p *ScriptBlockParser) Number() (localctx INumberContext) {
localctx = NewNumberContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 40, ScriptBlockParserRULE_number)
var _la int
defer func() {
p.ExitRule()
}()
defer func() {
if err := recover(); err != nil {
if v, ok := err.(antlr.RecognitionException); ok {
localctx.SetException(v)
p.GetErrorHandler().ReportError(p, v)
p.GetErrorHandler().Recover(p, v)
} else {
panic(err)
}
}
}()
p.EnterOuterAlt(localctx, 1)
p.SetState(268)
p.GetErrorHandler().Sync(p)
_la = p.GetTokenStream().LA(1)
if _la == ScriptBlockParserSIGN {
{
p.SetState(267)
p.Match(ScriptBlockParserSIGN)
}
}
{
p.SetState(270)
p.Match(ScriptBlockParserDIGITS)
}
p.SetState(273)
p.GetErrorHandler().Sync(p)
if p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 29, p.GetParserRuleContext()) == 1 {
{
p.SetState(271)
p.Match(ScriptBlockParserDOT)
}
{
p.SetState(272)
p.Match(ScriptBlockParserDIGITS)
}
}
return localctx
}
func (p *ScriptBlockParser) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex int) bool {
switch ruleIndex {
case 19:
var t *ExpressionContext = nil
if localctx != nil {
t = localctx.(*ExpressionContext)
}
return p.Expression_Sempred(t, predIndex)
default:
panic("No predicate with index: " + fmt.Sprint(ruleIndex))
}
}
func (p *ScriptBlockParser) Expression_Sempred(localctx antlr.RuleContext, predIndex int) bool {
switch predIndex {
case 0:
return p.Precpred(p.GetParserRuleContext(), 7)
case 1:
return p.Precpred(p.GetParserRuleContext(), 6)
case 2:
return p.Precpred(p.GetParserRuleContext(), 5)
case 3:
return p.Precpred(p.GetParserRuleContext(), 4)
case 4:
return p.Precpred(p.GetParserRuleContext(), 3)
case 5:
return p.Precpred(p.GetParserRuleContext(), 2)
default:
panic("No predicate with index: " + fmt.Sprint(predIndex))
}
}
<file_sep>/compiler/back/evaluator/rawify_visitor.go
package evaluator
import (
"fmt"
"github.com/falcinspire/scriptblock/compiler/back/values"
)
type RawifyValueVisitor struct {
Result string
}
func NewRawifyValueVisitor() *RawifyValueVisitor {
return &RawifyValueVisitor{}
}
func (visitor *RawifyValueVisitor) VisitNumber(numberValue *values.NumberValue) {
visitor.Result = fmt.Sprintf("%.2f", numberValue.Value)
}
func (visitor *RawifyValueVisitor) VisitString(stringValue *values.StringValue) {
visitor.Result = stringValue.Value
}
func (visitor *RawifyValueVisitor) VisitFunction(functionValue *values.FunctionValue) {
visitor.Result = fmt.Sprintf("function %s:%s/%s", functionValue.Module, functionValue.Unit, functionValue.Name)
}
func (visitor *RawifyValueVisitor) VisitTemplate(templateValue *values.TemplateValue) {
panic(fmt.Errorf("Cannot reduce a template reference to a value"))
}
func (visitor *RawifyValueVisitor) VisitFunctor(functorValue *values.FunctorValue) {
panic(fmt.Errorf("Cannot reduce a closure reference to a value"))
}
<file_sep>/compiler/back/tags/doc.go
// Package tags writes tag configuration files to the output.
package tags
<file_sep>/compiler/back/evaluator/loop_inject.go
package evaluator
import (
"fmt"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/dumper"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/google/uuid"
)
type LoopInject struct {
InjectBody []string
}
func NewLoopInject() *LoopInject {
return &LoopInject{[]string{}}
}
func GenerateTickFunction(inject *LoopInject, unitLocation *location.UnitLocation, output string) (module, unit, name string) {
loopFunctionName := fmt.Sprintf("loop-%s", uuid.New().String())
loopFunctionBody := inject.InjectBody
dumper.DumpFunction(unitLocation.Module, unitLocation.Unit, loopFunctionName, loopFunctionBody, output)
return unitLocation.Module, unitLocation.Unit, loopFunctionName
}
func GenerateDelayLines(inject *LoopInject, delay int, functionCall *ast.FunctionCall, data *EvaluateData) (runCommand string) {
cloudID := uuid.New().String()
invokeValue := ReduceExpression(ast.NewCallExpression(functionCall.Callee, functionCall.Arguments, nil), data)
translateValue := RawifyValue(invokeValue)
testCloud := createRepeatCommand(cloudID, delay, translateValue)
inject.InjectBody = append(inject.InjectBody, testCloud)
summonCloud := createSummonTimerCommand(cloudID, delay)
return summonCloud
}
// createRepeatCommand generates the command needed to be looped for the delay to work
func createRepeatCommand(cloudID string, delay int, mcrunnable string) string {
return fmt.Sprintf("execute as @e[type=minecraft:area_effect_cloud,tag=%s,nbt={Age:%d}] run %s", cloudID, delay, mcrunnable)
}
// createSummonTimerCommand generates the command needed to summon the cloud
func createSummonTimerCommand(cloudID string, delay int) string {
return fmt.Sprintf("execute at @p run summon minecraft:area_effect_cloud ~ ~ ~ {Tags:[\"%s\"],Duration:%d}", cloudID, delay+1)
}
<file_sep>/compiler/ast/visitor_base.go
package ast
// BaseExpressionVisitor is a visitor for expressions that does nothing by default
type BaseExpressionVisitor struct{}
// VisitNumber is the double dispatch for number expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitNumber(expr *NumberExpression) {}
// VisitString is the double dispatch for string expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitString(expr *StringExpression) {}
// VisitAdd is the double dispatch for addition expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitAdd(expr *AddExpression) {}
// VisitSubtract is the double dispatch for subtraction expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitSubtract(expr *SubtractExpression) {}
// VisitMultiply is the double dispatch for multiply expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitMultiply(expr *MultiplyExpression) {}
// VisitDivide is the double dispatch for divide expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitDivide(expr *DivideExpression) {}
// VisitIntegerDivide is the double dispatch for integer divide expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitIntegerDivide(expr *IntegerDivideExpression) {}
// VisitPower is the double dispatch for power expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitPower(expr *PowerExpression) {}
// VisitFormatter is the double dispatch for formatter expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitFormatter(expr *FormatterExpression) {}
// VisitIdentifier is the double dispatch for identifier expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitIdentifier(expr *IdentifierExpression) {}
// VisitFunctor is the double dispatch for functor expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitFunctor(expr *FunctorExpression) {}
// VisitCall is the double dispatch for call expressions that does nothing by default
func (visitor *BaseExpressionVisitor) VisitCall(expr *CallExpression) {}
// BaseStatementVisitor is the visitor for statements that does nothing by default
type BaseStatementVisitor struct{}
// VisitFunctionCall is the double dispatch for function call statements that does nothing by default
func (visitor *BaseStatementVisitor) VisitFunctionCall(functionCall *FunctionCall) {}
// VisitNativeCall is the double dispatch for native call statements that does nothing by default
func (visitor *BaseStatementVisitor) VisitNativeCall(nativeCall *NativeCall) {}
// VisitDelay is the double dispatch for delay statements that does nothing by default
func (visitor *BaseStatementVisitor) VisitDelay(delay *DelayStatement) {}
// VisitRaise is the double dispatch for raise statements that does nothing by default
func (visitor *BaseStatementVisitor) VisitRaise(delay *RaiseStatement) {}
// BaseTopVisitor is the visitor for top definitions that does nothing by default
type BaseTopVisitor struct{}
// VisitConstantDefinition is the visitor for constant definitions that does nothing by default
func (visitor *BaseTopVisitor) VisitConstantDefinition(definition *ConstantDefinition) {}
// VisitFunctionDefinition is the visitor for function definitions that does nothing by default
func (visitor *BaseTopVisitor) VisitFunctionDefinition(definition *FunctionDefinition) {}
// VisitFunctionShortcutDefinition is the visitor for function shortcut definitions that does nothing by default
func (visitor *BaseTopVisitor) VisitFunctionShortcutDefinition(definition *FunctionShortcutDefinition) {
}
// VisitTemplateDefinition is the visitor for template definitions that does nothing by default
func (visitor *BaseTopVisitor) VisitTemplateDefinition(definition *TemplateDefinition) {}
<file_sep>/compiler/back/desugar/function_injector.go
package desugar
import (
"fmt"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/google/uuid"
)
type functionInjector struct {
unit *ast.Unit
location *location.UnitLocation
index int
}
func newFunctionInjector(unit *ast.Unit, location *location.UnitLocation, index int) *functionInjector {
return &functionInjector{unit, location, index}
}
func (injector *functionInjector) injectFunction(body []ast.Statement) (module, unit, name string) {
functionName := fmt.Sprintf("%s-%s", injector.location.Unit, uuid.New().String())
injector.unit.Definitions = append(injector.unit.Definitions, ast.NewFunctionDefinition(functionName, body, true, ast.Tag{}, "", nil))
return injector.location.Module, injector.location.Unit, functionName
}
func (injector *functionInjector) injectFunctor(parameters []string, captures []string, body []ast.Statement) (module, unit, name string) {
functorName := fmt.Sprintf("%s-%s", injector.location.Unit, uuid.New().String())
injector.unit.Definitions = append(injector.unit.Definitions, ast.NewTemplateDefinition(functorName, parameters, captures, body, true, "", nil))
return injector.location.Module, injector.location.Unit, functorName
}
func (injector *functionInjector) replaceFunction(name string, body []ast.Statement, internal bool, tag ast.Tag, docs string) {
function := ast.NewFunctionDefinition(name, body, internal, tag, docs, nil)
injector.unit.Definitions[injector.index] = function
}
<file_sep>/compiler/ast/unit.go
package ast
// Unit is any node that represents a unit
type Unit struct {
ImportLines []*ImportLine
Definitions []TopDefinition
}
// NewUnit is a constructor for Unit
func NewUnit(importLines []*ImportLine, definitions []TopDefinition) *Unit {
unit := new(Unit)
unit.ImportLines = importLines
unit.Definitions = definitions
return unit
}
// Accept runs the double dispatch for the visitor
func (unit *Unit) Accept(visitor UnitVisitor) {
visitor.VisitUnit(unit)
}
<file_sep>/compiler/back/evaluator/invoke_simple.go
package evaluator
import (
"github.com/falcinspire/scriptblock/compiler/back/values"
)
func InvokeValue(value values.Value, arguments []values.Value, data *EvaluateData) *InvokeResult {
visitor := NewInvokeValueVisitor(arguments, data)
value.Accept(visitor)
return visitor.Result
}
type InvokeResult struct {
FunctionModule string
FunctionUnit string
FunctionName string
Lines []string
}
func NewFunctionReferenceInvokeResult(module, unit, name string) *InvokeResult {
return &InvokeResult{module, unit, name, nil}
}
func NewLinesInvokeResult(lines []string) *InvokeResult {
return &InvokeResult{"", "", "", lines}
}
func IsFunctionReferenceInvokeResult(result *InvokeResult) bool {
return result.FunctionModule != ""
}
func IsLinesInvokeResult(result *InvokeResult) bool {
return result.Lines != nil
}
<file_sep>/compiler/front/pretty/resolved_visitor.go
package pretty
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
)
type ResolvedTopDefinitionVisitor struct {
*ast.BaseTopVisitor
Result ResolvedTopDefinition
}
func (visitor *ResolvedTopDefinitionVisitor) VisitConstantDefinition(definition *ast.ConstantDefinition) {
value := QuickVisitExpression(definition.Value, &ResolvedExpressionVisitor{nil, nil})
visitor.Result = &ResolvedConstantDefinition{"constant", definition.Name, definition.Internal, definition.Documentation, value}
}
func (visitor *ResolvedTopDefinitionVisitor) VisitFunctionDefinition(definition *ast.FunctionDefinition) {
body := QuickVisitBody(definition.Body)
visitor.Result = &ResolvedFunctionDefinition{"function", definition.Name, definition.Internal, definition.Documentation, body}
}
func (visitor *ResolvedTopDefinitionVisitor) VisitTemplateDefinition(definition *ast.TemplateDefinition) {
body := QuickVisitBody(definition.Body)
visitor.Result = &ResolvedTemplateDefinition{"template", definition.Name, definition.Internal, definition.Documentation, definition.Parameters, definition.Capture, body}
}
func QuickVisitExpressionList(expressionsAst []ast.Expression, visitor *ResolvedExpressionVisitor) []ResolvedExpression {
expressions := make([]ResolvedExpression, len(expressionsAst))
for i, expressionaST := range expressionsAst {
expressionaST.Accept(visitor)
expressions[i] = visitor.Result
}
return expressions
}
func QuickVisitExpression(expression ast.Expression, visitor *ResolvedExpressionVisitor) ResolvedExpression {
expression.Accept(visitor)
return visitor.Result
}
func QuickVisitBody(body []ast.Statement) []ResolvedStatement {
statements := make([]ResolvedStatement, len(body))
for i, statement := range body {
visitor := &ResolvedStatementVisitor{nil, nil}
statement.Accept(visitor)
statements[i] = visitor.Result
}
return statements
}
type ResolvedStatementVisitor struct {
*ast.BaseStatementVisitor
Result ResolvedStatement
}
func (visitor *ResolvedStatementVisitor) VisitFunctionCall(functionCall *ast.FunctionCall) {
expressionVisitor := &ResolvedExpressionVisitor{nil, nil}
callee := QuickVisitExpression(functionCall.Callee, expressionVisitor)
arguments := QuickVisitExpressionList(functionCall.Arguments, expressionVisitor)
var trailing *TrailingFunction
if functionCall.Trailing != nil {
trailing = &TrailingFunction{"trailing-funtion", functionCall.Trailing.Parameters, QuickVisitBody(functionCall.Trailing.Body)}
}
visitor.Result = &ResolvedFunctionCall{"function-call", callee, arguments, trailing}
}
func (visitor *ResolvedStatementVisitor) VisitNativeCall(nativeCall *ast.NativeCall) {
expressionVisitor := &ResolvedExpressionVisitor{nil, nil}
arguments := QuickVisitExpressionList(nativeCall.Arguments, expressionVisitor)
visitor.Result = &ResolvedNativeCall{"native-call", arguments}
}
type ResolvedExpressionVisitor struct {
*ast.BaseExpressionVisitor
Result ResolvedExpression
}
func (visitor *ResolvedExpressionVisitor) VisitIdentifier(call *ast.IdentifierExpression) {
address := QuickVisitAddress(call.Address)
visitor.Result = &ResolvedIdentifierExpression{"identifier", address}
}
func QuickVisitAddress(address *symbol.AddressBox) ResolvedAddress {
switch address.Type {
case symbol.UNIT:
data := address.Data.(*symbol.UnitAddress)
return &ResolvedUnitAddress{data.Module, data.Unit, data.Name}
case symbol.PARAMETER:
data := address.Data.(*symbol.ParameterAddress)
return &ResolvedParameterAddress{data.ClosureDepth, data.Name}
case symbol.CAPTURE:
data := address.Data.(*symbol.CaptureAddress)
return &ResolvedCaptureAddress{data.Name}
}
return nil
}
func (visitor *ResolvedExpressionVisitor) VisitAdd(add *ast.AddExpression) {
visitor.Result = &ResolvedOperatorExpression{"+", QuickVisitExpression(add.Left, visitor), QuickVisitExpression(add.Right, visitor)}
}
func (visitor *ResolvedExpressionVisitor) VisitSubtract(add *ast.SubtractExpression) {
visitor.Result = &ResolvedOperatorExpression{"-", QuickVisitExpression(add.Left, visitor), QuickVisitExpression(add.Right, visitor)}
}
func (visitor *ResolvedExpressionVisitor) VisitMultiply(add *ast.MultiplyExpression) {
visitor.Result = &ResolvedOperatorExpression{"*", QuickVisitExpression(add.Left, visitor), QuickVisitExpression(add.Right, visitor)}
}
func (visitor *ResolvedExpressionVisitor) VisitDivide(add *ast.DivideExpression) {
visitor.Result = &ResolvedOperatorExpression{"/", QuickVisitExpression(add.Left, visitor), QuickVisitExpression(add.Right, visitor)}
}
func (visitor *ResolvedExpressionVisitor) VisitIntegerDivide(add *ast.IntegerDivideExpression) {
visitor.Result = &ResolvedOperatorExpression{"//", QuickVisitExpression(add.Left, visitor), QuickVisitExpression(add.Right, visitor)}
}
func (visitor *ResolvedExpressionVisitor) VisitPower(add *ast.PowerExpression) {
visitor.Result = &ResolvedOperatorExpression{"^", QuickVisitExpression(add.Left, visitor), QuickVisitExpression(add.Right, visitor)}
}
func (visitor *ResolvedExpressionVisitor) VisitNumber(number *ast.NumberExpression) {
visitor.Result = &ResolvedNumberExpression{"number", number.Value}
}
func (visitor *ResolvedExpressionVisitor) VisitString(number *ast.StringExpression) {
visitor.Result = &ResolvedStringExpression{"string", number.Value}
}
<file_sep>/compiler/back/desugar/desugar_simple.go
package desugar
import (
"github.com/sirupsen/logrus"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
)
type functionFrame struct {
Parameters []string
Body []ast.Statement
}
// Unit removes the syntactic sugar from the tree, performing tree rewrites/injections as needed
func Unit(unit *ast.Unit, location *location.UnitLocation) {
for i, definition := range unit.Definitions {
definition.Accept(newDesugarTopDefinitionVisitor(newFunctionInjector(unit, location, i)))
}
}
func desugarFunctionFrame(frame *functionFrame, injector *functionInjector, depth int) *freeVariableSet {
freeVars := newFreeVariableSet()
for i, statement := range frame.Body {
statement.Accept(newDesugarStatementVisitor(injector, NewStatementRewriter(frame.Body, i), depth, freeVars))
}
return freeVars
}
func desugarExpressionFrame(expression ast.Expression) {
expressionVisitor := newDesugarExpressionVisitor(0, newFreeVariableSet())
expression.Accept(expressionVisitor)
}
type desugaredBody struct {
Module, Unit, Name string
PassCaptures []*ast.IdentifierExpression
}
func desugarTrailing(frame *functionFrame, injector *functionInjector, depth int) ast.Expression {
freeVariables := newFreeVariableSet()
toFunction := desugarBody(frame, injector, depth, freeVariables)
captures := toFunction.PassCaptures
moduleName := toFunction.Module
unitName := toFunction.Unit
functionName := toFunction.Name
callIdentifier := ast.NewIdentifierExpression(functionName, nil)
callIdentifier.Address = symbol.NewUnitAddressBox(moduleName, unitName, functionName)
var expression ast.Expression
if len(captures) > 0 {
expression = ast.NewFunctorExpression(callIdentifier, captures, nil)
} else {
expression = callIdentifier
}
return expression
}
func desugarBody(frame *functionFrame, injector *functionInjector, depth int, freeVariables *freeVariableSet) *desugaredBody {
childFreeVariables := desugarFunctionFrame(frame, injector, depth)
var module string
var unit string
var name string
var closes []string
var captures []*ast.IdentifierExpression
if len(ListFreeSet(childFreeVariables)) == 0 && len(frame.Parameters) == 0 {
closes = []string{}
captures = []*ast.IdentifierExpression{}
module, unit, name = injector.injectFunction(frame.Body)
logrus.WithFields(logrus.Fields{
"name": name,
"type": "function",
}).Info("injected")
} else if len(ListFreeSet(childFreeVariables)) == 0 && len(frame.Parameters) > 0 {
closes = []string{}
captures = []*ast.IdentifierExpression{}
module, unit, name = injector.injectFunctor(frame.Parameters, symbol.NoCloses(), frame.Body)
logrus.WithFields(logrus.Fields{
"name": name,
"type": "template",
}).Info("injected")
} else {
passChildFreesUp(freeVariables, childFreeVariables, depth)
closes = makeClosesSet(childFreeVariables)
captures = makeCaptureSet(childFreeVariables, depth)
module, unit, name = injector.injectFunctor(frame.Parameters, closes, frame.Body)
logrus.WithFields(logrus.Fields{
"name": name,
"type": "closure",
}).Info("injected")
}
return &desugaredBody{module, unit, name, captures}
}
func passChildFreesUp(parent, child *freeVariableSet, depth int) {
for _, enclosed := range ListFreeSet(child) {
if isFree(enclosed, depth) {
AddToFreeSet(enclosed, parent)
}
}
}
func makeClosesSet(child *freeVariableSet) []string {
closes := make([]string, len(ListFreeSet(child)))
for i, freeAddress := range ListFreeSet(child) {
closes[i] = freeAddress.Name
}
return closes
}
func makeCaptureSet(child *freeVariableSet, depth int) []*ast.IdentifierExpression {
captures := make([]*ast.IdentifierExpression, len(ListFreeSet(child)))
for i, enclosedVariable := range ListFreeSet(child) {
captures[i] = ast.NewIdentifierExpression(enclosedVariable.Name, nil)
captures[i].Address = symbol.NewAddressBox(symbol.PARAMETER, enclosedVariable)
}
return captures
}
func isFree(enclosedVariable *symbol.ParameterAddress, depth int) bool {
return enclosedVariable.ClosureDepth != depth
}
<file_sep>/compiler/ast/symbol/util.go
package symbol
func NoParameters() []string {
return []string{}
}
func NoCloses() []string {
return []string{}
}
<file_sep>/compiler/back/valuepass/pass_one_visitor.go
package valuepass
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/addressbook"
"github.com/falcinspire/scriptblock/compiler/back/evaluator"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/sirupsen/logrus"
)
type topOneValueVisitor struct {
*ast.BaseTopVisitor
data *evaluator.EvaluateData
}
func newOneValueVisitor(data *evaluator.EvaluateData) *topOneValueVisitor {
return &topOneValueVisitor{nil, data}
}
func (visitor *topOneValueVisitor) VisitFunctionDefinition(definition *ast.FunctionDefinition) {
logrus.WithFields(logrus.Fields{
"module": visitor.data.Location.Module,
"unit": visitor.data.Location.Unit,
"name": definition.Name,
}).Info("Evaluating function reference")
value := values.NewFunctionValue(visitor.data.Location.Module, visitor.data.Location.Unit, definition.Name)
var table values.ValueTable
if definition.Internal {
table = values.LookupValueTable(visitor.data.Location.Module, visitor.data.Location.Unit, visitor.data.ValueLibrary.Internal)
} else {
table = values.LookupValueTable(visitor.data.Location.Module, visitor.data.Location.Unit, visitor.data.ValueLibrary.Exported)
}
table[definition.Name] = value
}
func (visitor *topOneValueVisitor) VisitTemplateDefinition(definition *ast.TemplateDefinition) {
logrus.WithFields(logrus.Fields{
"module": visitor.data.Location.Module,
"unit": visitor.data.Location.Unit,
"name": definition.Name,
}).Info("Evaluating template reference")
value := values.NewTemplateValue(visitor.data.Location.Module, visitor.data.Location.Unit, definition.Name)
var table values.ValueTable
if definition.Internal {
table = values.LookupValueTable(visitor.data.Location.Module, visitor.data.Location.Unit, visitor.data.ValueLibrary.Internal)
} else {
table = values.LookupValueTable(visitor.data.Location.Module, visitor.data.Location.Unit, visitor.data.ValueLibrary.Exported)
}
table[definition.Name] = value
addressbook.InsertFunctorAddress(definition, visitor.data.Location.Module, visitor.data.Location.Unit, definition.Name, visitor.data.AddressBook)
}
type unitOneValueVisitor struct {
data *evaluator.EvaluateData
}
func newUnitOneValueVisitor(data *evaluator.EvaluateData) *unitOneValueVisitor {
return &unitOneValueVisitor{data}
}
func (visitor *unitOneValueVisitor) VisitUnit(unit *ast.Unit) {
for _, definition := range unit.Definitions {
definition.Accept(newOneValueVisitor(visitor.data))
}
}
<file_sep>/compiler/front/symbols/symboltable.go
package symbols
import "github.com/falcinspire/scriptblock/compiler/ast/symbol"
type SymbolTable map[string]*symbol.AddressBox
func NewSymbolTable() SymbolTable {
return make(SymbolTable)
}
type LocalSymbolTable map[string]*symbol.AddressBox
func NewLocalSymbolTable() LocalSymbolTable {
return make(LocalSymbolTable)
}
type LinkedSymbolTable struct {
linked []LocalSymbolTable
}
func NewLinkedSymbolTable() *LinkedSymbolTable {
return &LinkedSymbolTable{[]LocalSymbolTable{}}
}
func (this *LinkedSymbolTable) PeekTable() LocalSymbolTable {
return this.linked[len(this.linked)-1]
}
func (this *LinkedSymbolTable) GetTableAt(i int) LocalSymbolTable {
return this.linked[i]
}
func (this *LinkedSymbolTable) PushTable(table LocalSymbolTable) {
this.linked = append(this.linked, table)
}
func (this *LinkedSymbolTable) PopTable() {
this.linked = this.linked[0 : len(this.linked)-1]
}
func (this *LinkedSymbolTable) Length() int {
return len(this.linked)
}
<file_sep>/compiler/back/evaluator/reduce_visitor.go
package evaluator
import (
"fmt"
"math"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/dumper"
"github.com/falcinspire/scriptblock/compiler/back/nativefuncs"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/google/uuid"
)
type ReduceExpressionVisitor struct {
*ast.BaseExpressionVisitor
Result values.Value
nativeMap map[string]nativefuncs.NativeFunction
data *EvaluateData
}
func NewReduceExpressionVisitor(data *EvaluateData) *ReduceExpressionVisitor {
visitor := new(ReduceExpressionVisitor)
visitor.nativeMap = nativefuncs.CreateNativeMap()
visitor.data = data
return visitor
}
func (visitor *ReduceExpressionVisitor) QuickVisitExpression(expression ast.Expression) values.Value {
expression.Accept(visitor)
return visitor.Result
}
func (visitor *ReduceExpressionVisitor) QuickVisitArgumentList(argumentList []ast.Expression) []values.Value {
argumentValues := make([]values.Value, len(argumentList))
for i, argument := range argumentList {
argumentValues[i] = visitor.QuickVisitExpression(argument)
}
return argumentValues
}
func (visitor *ReduceExpressionVisitor) VisitNumber(number *ast.NumberExpression) {
visitor.Result = values.NewNumberValue(number.Value)
}
func (visitor *ReduceExpressionVisitor) VisitString(stringExpression *ast.StringExpression) {
visitor.Result = values.NewStringValue(stringExpression.Value)
}
func (visitor *ReduceExpressionVisitor) VisitIdentifier(identifier *ast.IdentifierExpression) {
visitor.Result = GetValueForAddress(identifier.Address, visitor.data)
}
func (visitor *ReduceExpressionVisitor) VisitFunctor(functor *ast.FunctorExpression) {
callee := visitor.QuickVisitExpression(functor.Callee).(*values.TemplateValue)
captureArgs := make([]values.Value, len(functor.Capture))
for i, capture := range functor.Capture {
captureArgs[i] = ReduceIdentifier(capture, visitor.data)
}
visitor.Result = values.NewFunctorValue(callee, captureArgs)
}
func (visitor *ReduceExpressionVisitor) VisitAdd(add *ast.AddExpression) {
left := visitor.QuickVisitExpression(add.Left).(*values.NumberValue)
right := visitor.QuickVisitExpression(add.Right).(*values.NumberValue)
visitor.Result = values.NewNumberValue(left.Value + right.Value)
}
func (visitor *ReduceExpressionVisitor) VisitSubtract(add *ast.SubtractExpression) {
left := visitor.QuickVisitExpression(add.Left).(*values.NumberValue)
right := visitor.QuickVisitExpression(add.Right).(*values.NumberValue)
visitor.Result = values.NewNumberValue(left.Value - right.Value)
}
func (visitor *ReduceExpressionVisitor) VisitMultiply(add *ast.MultiplyExpression) {
left := visitor.QuickVisitExpression(add.Left).(*values.NumberValue)
right := visitor.QuickVisitExpression(add.Right).(*values.NumberValue)
visitor.Result = values.NewNumberValue(left.Value * right.Value)
}
func (visitor *ReduceExpressionVisitor) VisitDivide(add *ast.DivideExpression) {
left := visitor.QuickVisitExpression(add.Left).(*values.NumberValue)
right := visitor.QuickVisitExpression(add.Right).(*values.NumberValue)
visitor.Result = values.NewNumberValue(left.Value / right.Value)
}
func (visitor *ReduceExpressionVisitor) VisitIntegerDivide(add *ast.IntegerDivideExpression) {
left := visitor.QuickVisitExpression(add.Left).(*values.NumberValue)
right := visitor.QuickVisitExpression(add.Right).(*values.NumberValue)
visitor.Result = values.NewNumberValue(float64(int(left.Value) / int(right.Value)))
}
func (visitor *ReduceExpressionVisitor) VisitPower(add *ast.PowerExpression) {
left := visitor.QuickVisitExpression(add.Left).(*values.NumberValue)
right := visitor.QuickVisitExpression(add.Right).(*values.NumberValue)
visitor.Result = values.NewNumberValue(math.Pow(left.Value, right.Value))
}
func (visitor *ReduceExpressionVisitor) VisitFormatter(formatter *ast.FormatterExpression) {
valueArray := visitor.QuickVisitArgumentList(formatter.Arguments)
stringResult := visitor.nativeMap[formatter.Format](visitor.data.ModulePath, valueArray)
visitor.Result = values.NewStringValue(stringResult)
}
func (visitor *ReduceExpressionVisitor) VisitCall(call *ast.CallExpression) {
callee := visitor.QuickVisitExpression(call.Identifier)
arguments := visitor.QuickVisitArgumentList(call.Arguments)
result := InvokeValue(callee, arguments, visitor.data)
if IsLinesInvokeResult(result) {
if len(result.Lines) == 1 {
//TODO is this the right value?
visitor.Result = values.NewStringValue(result.Lines[0])
} else {
generatedName := fmt.Sprintf("%s-%s", visitor.data.Location.Unit, uuid.New().String())
dumper.DumpFunction(visitor.data.Location.Module, visitor.data.Location.Unit, generatedName, result.Lines, visitor.data.Output)
visitor.Result = values.NewFunctionValue(visitor.data.Location.Module, visitor.data.Location.Unit, generatedName)
}
} else {
visitor.Result = values.NewFunctionValue(result.FunctionModule, result.FunctionUnit, result.FunctionName)
}
}
<file_sep>/compiler/maintool/toolunit.go
package maintool
import (
"github.com/falcinspire/scriptblock/compiler/back/addressbook"
"github.com/falcinspire/scriptblock/compiler/back/desugar"
"github.com/falcinspire/scriptblock/compiler/back/tags"
"github.com/falcinspire/scriptblock/compiler/back/valuepass"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/falcinspire/scriptblock/compiler/front/astbook"
"github.com/falcinspire/scriptblock/compiler/front/imports"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/front/resolver"
"github.com/falcinspire/scriptblock/compiler/front/symbolgen"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
)
func DoUnitFront(unitLocation *location.UnitLocation, astbooko astbook.AstBook, importbook imports.ImportBook, symbollibrary *symbols.SymbolLibrary) {
astree := astbook.LookupAst(unitLocation, astbooko)
symbolgen.SymbolsPass(astree, unitLocation, symbollibrary)
resolver.ResolvePass(astree, unitLocation, symbollibrary, importbook)
}
func DoUnitBack(unitLocation *location.UnitLocation, astbooko astbook.AstBook, valuelibrary *values.ValueLibrary, addressbook addressbook.AddressBook, theTags map[string]tags.LocationList, modulePath string, output string) {
astree := astbook.LookupAst(unitLocation, astbooko)
desugar.Unit(astree, unitLocation)
valuepass.ValuePass(astree, unitLocation, valuelibrary, addressbook, theTags, modulePath, output)
}
<file_sep>/cmd/scriptblock/main.go
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/falcinspire/scriptblock/compiler/maintool"
"github.com/falcinspire/scriptblock/home"
)
func main() {
modulePrefix := os.Args[1]
version := os.Args[2]
module := filepath.Join(modulePrefix, version)
_, exists := home.FindModuleInHome(module) // TODO remove redundancy
if !exists {
panic(fmt.Errorf("no module by name %s", module))
}
outputPath := home.MakeModuleOutput(module)
maintool.DoProject(module, outputPath)
}
<file_sep>/compiler/back/evaluator/invoke_visitor.go
package evaluator
import (
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/sirupsen/logrus"
"github.com/falcinspire/scriptblock/compiler/back/addressbook"
"github.com/falcinspire/scriptblock/compiler/back/values"
)
type InvokeValueVisitor struct {
*values.BaseValueVisitor
Result *InvokeResult
arguments []values.Value
data *EvaluateData
}
func NewInvokeValueVisitor(arguments []values.Value, data *EvaluateData) *InvokeValueVisitor {
return &InvokeValueVisitor{nil, nil, arguments, data}
}
func (visitor *InvokeValueVisitor) VisitFunction(functionValue *values.FunctionValue) {
logrus.WithFields(logrus.Fields{
"module": functionValue.Module,
"unit": functionValue.Unit,
"name": functionValue.Name,
}).Info("invoking function")
visitor.Result = NewFunctionReferenceInvokeResult(functionValue.Module, functionValue.Unit, functionValue.Name)
}
func (visitor *InvokeValueVisitor) VisitFunctor(functorValue *values.FunctorValue) {
logrus.WithFields(logrus.Fields{
"argslength": len(visitor.arguments),
"capturelength": len(functorValue.Capture),
"module": functorValue.Callee.Module,
"unit": functorValue.Callee.Unit,
"name": functorValue.Callee.Name,
}).Info("invoking functor")
templateReference := functorValue.Callee
theFunctor := addressbook.AddressTemplate(templateReference.Module, templateReference.Unit, templateReference.Name, visitor.data.AddressBook)
injectBody := TranslateFunctor(theFunctor, visitor.arguments, location.NewUnitLocation(templateReference.Module, templateReference.Unit), functorValue.Capture, visitor.data)
visitor.Result = NewLinesInvokeResult(injectBody)
}
func (visitor *InvokeValueVisitor) VisitTemplate(templateValue *values.TemplateValue) {
logrus.WithFields(logrus.Fields{
"module": templateValue.Module,
"unit": templateValue.Unit,
"name": templateValue.Name,
"argslength": len(visitor.arguments),
}).Info("invoking template")
theTemplate := addressbook.AddressTemplate(templateValue.Module, templateValue.Unit, templateValue.Name, visitor.data.AddressBook)
injectBody := TranslateFunctor(theTemplate, visitor.arguments, location.NewUnitLocation(templateValue.Module, templateValue.Unit), []values.Value{}, visitor.data) // TODO make this different location?
visitor.Result = NewLinesInvokeResult(injectBody)
}
<file_sep>/compiler/front/symbolgen/toplevel_visitor.go
package symbolgen
import (
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/ast/location"
"github.com/falcinspire/scriptblock/compiler/ast/symbol"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
)
type TopDefinitionVisitor struct {
*ast.BaseTopVisitor
unitAddress *location.UnitLocation
ExportedSymbols symbols.SymbolTable
InternalSymbols symbols.SymbolTable
}
func NewTopDefinitionVisitor(address *location.UnitLocation, exported, internal symbols.SymbolTable) *TopDefinitionVisitor {
return &TopDefinitionVisitor{nil, address, exported, internal}
}
func (visitor *TopDefinitionVisitor) VisitConstantDefinition(definition *ast.ConstantDefinition) {
address := symbol.NewUnitAddressBox(visitor.unitAddress.Module, visitor.unitAddress.Unit, definition.Name)
var symboltable symbols.SymbolTable
if definition.Internal {
symboltable = visitor.InternalSymbols
} else {
symboltable = visitor.ExportedSymbols
}
symboltable[definition.Name] = address
}
func (visitor *TopDefinitionVisitor) VisitFunctionDefinition(definition *ast.FunctionDefinition) {
address := symbol.NewUnitAddressBox(visitor.unitAddress.Module, visitor.unitAddress.Unit, definition.Name)
var symboltable symbols.SymbolTable
if definition.Internal {
symboltable = visitor.InternalSymbols
} else {
symboltable = visitor.ExportedSymbols
}
symboltable[definition.Name] = address
}
func (visitor *TopDefinitionVisitor) VisitTemplateDefinition(definition *ast.TemplateDefinition) {
address := symbol.NewUnitAddressBox(visitor.unitAddress.Module, visitor.unitAddress.Unit, definition.Name)
var symboltable symbols.SymbolTable
if definition.Internal {
symboltable = visitor.InternalSymbols
} else {
symboltable = visitor.ExportedSymbols
}
symboltable[definition.Name] = address
}
func (visitor *TopDefinitionVisitor) VisitFunctionShortcutDefinition(shortcut *ast.FunctionShortcutDefinition) {
address := symbol.NewUnitAddressBox(visitor.unitAddress.Module, visitor.unitAddress.Unit, shortcut.Name)
var symboltable symbols.SymbolTable
if shortcut.Internal {
symboltable = visitor.InternalSymbols
} else {
symboltable = visitor.ExportedSymbols
}
symboltable[shortcut.Name] = address
}
type UnitSymbolVisitor struct {
unitAddress *location.UnitLocation
Exported symbols.SymbolTable
Internal symbols.SymbolTable
}
func NewUnitSymbolVisitor(unitAddress *location.UnitLocation) *UnitSymbolVisitor {
visitor := new(UnitSymbolVisitor)
visitor.unitAddress = unitAddress
visitor.Exported = symbols.NewSymbolTable()
visitor.Internal = symbols.NewSymbolTable()
return visitor
}
func (visitor *UnitSymbolVisitor) VisitUnit(unit *ast.Unit) {
for _, definition := range unit.Definitions {
definitionVisitor := NewTopDefinitionVisitor(visitor.unitAddress, visitor.Exported, visitor.Internal)
definition.Accept(definitionVisitor)
}
}
<file_sep>/compiler/back/values/valuebook.go
package values
type ValueTable map[string]Value
func NewValueTable() ValueTable {
return make(ValueTable)
}
func LookupUnitValue(module string, unit string, function string, valuebook ValueTable) (value Value, exists bool) {
value, exists = valuebook[function]
return
}
type LocalValueTable struct {
Parameters map[string]Value
Captures map[string]Value
}
func NewLocalValueTable(parameters map[string]Value, captures map[string]Value) *LocalValueTable {
return &LocalValueTable{parameters, captures}
}
func LookupParameterValue(name string, local *LocalValueTable) (value Value, exists bool) {
value, exists = local.Parameters[name]
return
}
func LookupCaptureValue(name string, local *LocalValueTable) (value Value, exists bool) {
value, exists = local.Captures[name]
return
}
<file_sep>/compiler/back/evaluator/translate_visitor.go
package evaluator
import (
"fmt"
"strings"
"github.com/falcinspire/scriptblock/compiler/ast"
"github.com/falcinspire/scriptblock/compiler/back/values"
)
type TranslateStatementVisitor struct {
Lines []string
data *EvaluateData
}
func NewTranslateStatementVisitor(data *EvaluateData) *TranslateStatementVisitor {
return &TranslateStatementVisitor{[]string{}, data}
}
func (visitor *TranslateStatementVisitor) QuickVisitStatement(statement ast.Statement) []string {
statement.Accept(visitor)
return visitor.Lines
}
func (visitor *TranslateStatementVisitor) VisitFunctionCall(call *ast.FunctionCall) {
invoker := ReduceExpression(call.Callee, visitor.data)
arguments := ReduceArgumentList(call.Arguments, visitor.data)
result := InvokeValue(invoker, arguments, visitor.data)
if IsFunctionReferenceInvokeResult(result) {
visitor.Lines = []string{fmt.Sprintf("function %s:%s/%s", result.FunctionModule, result.FunctionUnit, result.FunctionName)}
} else {
visitor.Lines = result.Lines
}
}
func (visitor *TranslateStatementVisitor) VisitNativeCall(call *ast.NativeCall) {
arguments := ReduceArgumentList(call.Arguments, visitor.data)
stringArgs := make([]string, len(arguments))
for i, argument := range arguments {
stringArgs[i] = RawifyValue(argument)
}
visitor.Lines = []string{strings.Join(stringArgs, " ")}
}
func (visitor *TranslateStatementVisitor) VisitDelay(delay *ast.DelayStatement) {
tickDelay := int(ReduceExpression(delay.TickDelay, visitor.data).(*values.NumberValue).Value)
summonCloud := GenerateDelayLines(visitor.data.LoopInject, tickDelay, delay.FunctionCall, visitor.data)
visitor.Lines = []string{summonCloud}
}
func (visitor *TranslateStatementVisitor) VisitRaise(raise *ast.RaiseStatement) {
visitor.Lines = []string{fmt.Sprintf("function #%s:%s\n", raise.Tag.Namespace, raise.Tag.Identity)}
}
<file_sep>/compiler/front/parser/.antlr/ScriptBlockParser.java
// Generated from c:\Falcinspire\go\src\github.com\falcinspire\scriptblock\front\parser\ScriptBlockParser.g4 by ANTLR 4.7.1
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class ScriptBlockParser extends Parser {
static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
WS=1, COMMENT=2, DOC_START=3, DOC_END=4, DOC_LINE=5, NEWLINES=6, FUNCTION=7,
TEMPLATE=8, NATIVE=9, CONSTANT=10, RUN=11, DELAY=12, IMPORT=13, INTERNAL=14,
ARROW=15, OPAREN=16, CPAREN=17, OCURLY=18, CCURLY=19, OSQUARE=20, CSQUARE=21,
COMMA=22, EQUALS=23, SEMICOLON=24, COLON=25, POWER=26, MULTIPLY=27, DIVIDE=28,
INTEGER_DIVIDE=29, PLUS=30, SUBTRACT=31, DOT=32, GREATER_THAN=33, LESS_THAN=34,
POUND=35, IDENTIFIER=36, SIGN=37, DIGITS=38, STRING=39, RAISE=40;
public static final int
RULE_unit = 0, RULE_documentation = 1, RULE_parameterList = 2, RULE_argumentList = 3,
RULE_structureList = 4, RULE_nativeCall = 5, RULE_functionCall = 6, RULE_functionFrame = 7,
RULE_functionDefinition = 8, RULE_functionDefinitionShortcut = 9, RULE_tag = 10,
RULE_templateDefinition = 11, RULE_constantDefinition = 12, RULE_formatter = 13,
RULE_importLine = 14, RULE_topDefinition = 15, RULE_statement = 16, RULE_delayStructure = 17,
RULE_raise = 18, RULE_expression = 19, RULE_number = 20;
public static final String[] ruleNames = {
"unit", "documentation", "parameterList", "argumentList", "structureList",
"nativeCall", "functionCall", "functionFrame", "functionDefinition", "functionDefinitionShortcut",
"tag", "templateDefinition", "constantDefinition", "formatter", "importLine",
"topDefinition", "statement", "delayStructure", "raise", "expression",
"number"
};
private static final String[] _LITERAL_NAMES = {
null, null, null, "'/*'", "'*/'", null, null, "'func'", "'script'", "'command'",
"'const'", "'run'", "'delay'", "'import'", "'internal'", "'->'", "'('",
"')'", "'{'", "'}'", "'['", "']'", "','", "'='", "';'", "':'", "'^'",
"'*'", "'/'", "'//'", "'+'", "'-'", "'.'", "'>'", "'<'", "'#'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, "WS", "COMMENT", "DOC_START", "DOC_END", "DOC_LINE", "NEWLINES",
"FUNCTION", "TEMPLATE", "NATIVE", "CONSTANT", "RUN", "DELAY", "IMPORT",
"INTERNAL", "ARROW", "OPAREN", "CPAREN", "OCURLY", "CCURLY", "OSQUARE",
"CSQUARE", "COMMA", "EQUALS", "SEMICOLON", "COLON", "POWER", "MULTIPLY",
"DIVIDE", "INTEGER_DIVIDE", "PLUS", "SUBTRACT", "DOT", "GREATER_THAN",
"LESS_THAN", "POUND", "IDENTIFIER", "SIGN", "DIGITS", "STRING", "RAISE"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "ScriptBlockParser.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public ScriptBlockParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class UnitContext extends ParserRuleContext {
public TerminalNode EOF() { return getToken(ScriptBlockParser.EOF, 0); }
public List<ImportLineContext> importLine() {
return getRuleContexts(ImportLineContext.class);
}
public ImportLineContext importLine(int i) {
return getRuleContext(ImportLineContext.class,i);
}
public List<TerminalNode> NEWLINES() { return getTokens(ScriptBlockParser.NEWLINES); }
public TerminalNode NEWLINES(int i) {
return getToken(ScriptBlockParser.NEWLINES, i);
}
public List<TopDefinitionContext> topDefinition() {
return getRuleContexts(TopDefinitionContext.class);
}
public TopDefinitionContext topDefinition(int i) {
return getRuleContext(TopDefinitionContext.class,i);
}
public UnitContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_unit; }
}
public final UnitContext unit() throws RecognitionException {
UnitContext _localctx = new UnitContext(_ctx, getState());
enterRule(_localctx, 0, RULE_unit);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(47);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==IMPORT) {
{
{
setState(42);
importLine();
setState(43);
match(NEWLINES);
}
}
setState(49);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(53);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << DOC_START) | (1L << FUNCTION) | (1L << TEMPLATE) | (1L << CONSTANT) | (1L << INTERNAL) | (1L << POUND))) != 0)) {
{
{
setState(50);
topDefinition();
}
}
setState(55);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(56);
match(EOF);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class DocumentationContext extends ParserRuleContext {
public TerminalNode DOC_START() { return getToken(ScriptBlockParser.DOC_START, 0); }
public List<TerminalNode> NEWLINES() { return getTokens(ScriptBlockParser.NEWLINES); }
public TerminalNode NEWLINES(int i) {
return getToken(ScriptBlockParser.NEWLINES, i);
}
public TerminalNode DOC_END() { return getToken(ScriptBlockParser.DOC_END, 0); }
public List<TerminalNode> DOC_LINE() { return getTokens(ScriptBlockParser.DOC_LINE); }
public TerminalNode DOC_LINE(int i) {
return getToken(ScriptBlockParser.DOC_LINE, i);
}
public DocumentationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_documentation; }
}
public final DocumentationContext documentation() throws RecognitionException {
DocumentationContext _localctx = new DocumentationContext(_ctx, getState());
enterRule(_localctx, 2, RULE_documentation);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(58);
match(DOC_START);
setState(59);
match(NEWLINES);
setState(63);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==DOC_LINE) {
{
{
setState(60);
match(DOC_LINE);
}
}
setState(65);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(66);
match(DOC_END);
setState(67);
match(NEWLINES);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ParameterListContext extends ParserRuleContext {
public TerminalNode OPAREN() { return getToken(ScriptBlockParser.OPAREN, 0); }
public TerminalNode CPAREN() { return getToken(ScriptBlockParser.CPAREN, 0); }
public List<TerminalNode> IDENTIFIER() { return getTokens(ScriptBlockParser.IDENTIFIER); }
public TerminalNode IDENTIFIER(int i) {
return getToken(ScriptBlockParser.IDENTIFIER, i);
}
public List<TerminalNode> COMMA() { return getTokens(ScriptBlockParser.COMMA); }
public TerminalNode COMMA(int i) {
return getToken(ScriptBlockParser.COMMA, i);
}
public ParameterListContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_parameterList; }
}
public final ParameterListContext parameterList() throws RecognitionException {
ParameterListContext _localctx = new ParameterListContext(_ctx, getState());
enterRule(_localctx, 4, RULE_parameterList);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(69);
match(OPAREN);
setState(78);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==IDENTIFIER) {
{
setState(70);
match(IDENTIFIER);
setState(75);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==COMMA) {
{
{
setState(71);
match(COMMA);
setState(72);
match(IDENTIFIER);
}
}
setState(77);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
setState(80);
match(CPAREN);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ArgumentListContext extends ParserRuleContext {
public TerminalNode OPAREN() { return getToken(ScriptBlockParser.OPAREN, 0); }
public TerminalNode CPAREN() { return getToken(ScriptBlockParser.CPAREN, 0); }
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public List<TerminalNode> COMMA() { return getTokens(ScriptBlockParser.COMMA); }
public TerminalNode COMMA(int i) {
return getToken(ScriptBlockParser.COMMA, i);
}
public ArgumentListContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_argumentList; }
}
public final ArgumentListContext argumentList() throws RecognitionException {
ArgumentListContext _localctx = new ArgumentListContext(_ctx, getState());
enterRule(_localctx, 6, RULE_argumentList);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(82);
match(OPAREN);
setState(91);
_errHandler.sync(this);
_la = _input.LA(1);
if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << RUN) | (1L << OPAREN) | (1L << LESS_THAN) | (1L << IDENTIFIER) | (1L << SIGN) | (1L << DIGITS) | (1L << STRING))) != 0)) {
{
setState(83);
expression(0);
setState(88);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==COMMA) {
{
{
setState(84);
match(COMMA);
setState(85);
expression(0);
}
}
setState(90);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
setState(93);
match(CPAREN);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StructureListContext extends ParserRuleContext {
public TerminalNode OSQUARE() { return getToken(ScriptBlockParser.OSQUARE, 0); }
public TerminalNode CSQUARE() { return getToken(ScriptBlockParser.CSQUARE, 0); }
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public List<TerminalNode> COMMA() { return getTokens(ScriptBlockParser.COMMA); }
public TerminalNode COMMA(int i) {
return getToken(ScriptBlockParser.COMMA, i);
}
public StructureListContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_structureList; }
}
public final StructureListContext structureList() throws RecognitionException {
StructureListContext _localctx = new StructureListContext(_ctx, getState());
enterRule(_localctx, 8, RULE_structureList);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(95);
match(OSQUARE);
setState(104);
_errHandler.sync(this);
_la = _input.LA(1);
if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << RUN) | (1L << OPAREN) | (1L << LESS_THAN) | (1L << IDENTIFIER) | (1L << SIGN) | (1L << DIGITS) | (1L << STRING))) != 0)) {
{
setState(96);
expression(0);
setState(101);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==COMMA) {
{
{
setState(97);
match(COMMA);
setState(98);
expression(0);
}
}
setState(103);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
setState(106);
match(CSQUARE);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class NativeCallContext extends ParserRuleContext {
public TerminalNode NATIVE() { return getToken(ScriptBlockParser.NATIVE, 0); }
public ArgumentListContext argumentList() {
return getRuleContext(ArgumentListContext.class,0);
}
public NativeCallContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_nativeCall; }
}
public final NativeCallContext nativeCall() throws RecognitionException {
NativeCallContext _localctx = new NativeCallContext(_ctx, getState());
enterRule(_localctx, 10, RULE_nativeCall);
try {
enterOuterAlt(_localctx, 1);
{
setState(108);
match(NATIVE);
setState(109);
argumentList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FunctionCallContext extends ParserRuleContext {
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public FunctionFrameContext functionFrame() {
return getRuleContext(FunctionFrameContext.class,0);
}
public ArgumentListContext argumentList() {
return getRuleContext(ArgumentListContext.class,0);
}
public FunctionCallContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_functionCall; }
}
public final FunctionCallContext functionCall() throws RecognitionException {
FunctionCallContext _localctx = new FunctionCallContext(_ctx, getState());
enterRule(_localctx, 12, RULE_functionCall);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(111);
match(IDENTIFIER);
setState(117);
_errHandler.sync(this);
switch (_input.LA(1)) {
case OPAREN:
{
{
setState(112);
argumentList();
setState(114);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==OCURLY) {
{
setState(113);
functionFrame();
}
}
}
}
break;
case OCURLY:
{
setState(116);
functionFrame();
}
break;
default:
throw new NoViableAltException(this);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FunctionFrameContext extends ParserRuleContext {
public TerminalNode OCURLY() { return getToken(ScriptBlockParser.OCURLY, 0); }
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public TerminalNode CCURLY() { return getToken(ScriptBlockParser.CCURLY, 0); }
public ParameterListContext parameterList() {
return getRuleContext(ParameterListContext.class,0);
}
public TerminalNode ARROW() { return getToken(ScriptBlockParser.ARROW, 0); }
public List<StatementContext> statement() {
return getRuleContexts(StatementContext.class);
}
public StatementContext statement(int i) {
return getRuleContext(StatementContext.class,i);
}
public FunctionFrameContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_functionFrame; }
}
public final FunctionFrameContext functionFrame() throws RecognitionException {
FunctionFrameContext _localctx = new FunctionFrameContext(_ctx, getState());
enterRule(_localctx, 14, RULE_functionFrame);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(119);
match(OCURLY);
setState(123);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==OPAREN) {
{
setState(120);
parameterList();
setState(121);
match(ARROW);
}
}
setState(125);
match(NEWLINES);
setState(129);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << NATIVE) | (1L << DELAY) | (1L << IDENTIFIER) | (1L << RAISE))) != 0)) {
{
{
setState(126);
statement();
}
}
setState(131);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(132);
match(CCURLY);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FunctionDefinitionContext extends ParserRuleContext {
public TerminalNode FUNCTION() { return getToken(ScriptBlockParser.FUNCTION, 0); }
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public FunctionFrameContext functionFrame() {
return getRuleContext(FunctionFrameContext.class,0);
}
public DocumentationContext documentation() {
return getRuleContext(DocumentationContext.class,0);
}
public TagContext tag() {
return getRuleContext(TagContext.class,0);
}
public TerminalNode INTERNAL() { return getToken(ScriptBlockParser.INTERNAL, 0); }
public FunctionDefinitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_functionDefinition; }
}
public final FunctionDefinitionContext functionDefinition() throws RecognitionException {
FunctionDefinitionContext _localctx = new FunctionDefinitionContext(_ctx, getState());
enterRule(_localctx, 16, RULE_functionDefinition);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(135);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==DOC_START) {
{
setState(134);
documentation();
}
}
setState(138);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==POUND) {
{
setState(137);
tag();
}
}
setState(141);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==INTERNAL) {
{
setState(140);
match(INTERNAL);
}
}
setState(143);
match(FUNCTION);
setState(144);
match(IDENTIFIER);
setState(145);
functionFrame();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FunctionDefinitionShortcutContext extends ParserRuleContext {
public TerminalNode FUNCTION() { return getToken(ScriptBlockParser.FUNCTION, 0); }
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public TerminalNode EQUALS() { return getToken(ScriptBlockParser.EQUALS, 0); }
public FunctionCallContext functionCall() {
return getRuleContext(FunctionCallContext.class,0);
}
public DocumentationContext documentation() {
return getRuleContext(DocumentationContext.class,0);
}
public TagContext tag() {
return getRuleContext(TagContext.class,0);
}
public TerminalNode INTERNAL() { return getToken(ScriptBlockParser.INTERNAL, 0); }
public FunctionDefinitionShortcutContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_functionDefinitionShortcut; }
}
public final FunctionDefinitionShortcutContext functionDefinitionShortcut() throws RecognitionException {
FunctionDefinitionShortcutContext _localctx = new FunctionDefinitionShortcutContext(_ctx, getState());
enterRule(_localctx, 18, RULE_functionDefinitionShortcut);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(148);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==DOC_START) {
{
setState(147);
documentation();
}
}
setState(151);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==POUND) {
{
setState(150);
tag();
}
}
setState(154);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==INTERNAL) {
{
setState(153);
match(INTERNAL);
}
}
setState(156);
match(FUNCTION);
setState(157);
match(IDENTIFIER);
setState(158);
match(EQUALS);
setState(159);
functionCall();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TagContext extends ParserRuleContext {
public TerminalNode POUND() { return getToken(ScriptBlockParser.POUND, 0); }
public List<TerminalNode> IDENTIFIER() { return getTokens(ScriptBlockParser.IDENTIFIER); }
public TerminalNode IDENTIFIER(int i) {
return getToken(ScriptBlockParser.IDENTIFIER, i);
}
public TerminalNode COLON() { return getToken(ScriptBlockParser.COLON, 0); }
public TagContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_tag; }
}
public final TagContext tag() throws RecognitionException {
TagContext _localctx = new TagContext(_ctx, getState());
enterRule(_localctx, 20, RULE_tag);
try {
enterOuterAlt(_localctx, 1);
{
setState(161);
match(POUND);
setState(162);
match(IDENTIFIER);
setState(163);
match(COLON);
setState(164);
match(IDENTIFIER);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TemplateDefinitionContext extends ParserRuleContext {
public TerminalNode TEMPLATE() { return getToken(ScriptBlockParser.TEMPLATE, 0); }
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public FunctionFrameContext functionFrame() {
return getRuleContext(FunctionFrameContext.class,0);
}
public DocumentationContext documentation() {
return getRuleContext(DocumentationContext.class,0);
}
public TerminalNode INTERNAL() { return getToken(ScriptBlockParser.INTERNAL, 0); }
public TemplateDefinitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_templateDefinition; }
}
public final TemplateDefinitionContext templateDefinition() throws RecognitionException {
TemplateDefinitionContext _localctx = new TemplateDefinitionContext(_ctx, getState());
enterRule(_localctx, 22, RULE_templateDefinition);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(167);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==DOC_START) {
{
setState(166);
documentation();
}
}
setState(170);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==INTERNAL) {
{
setState(169);
match(INTERNAL);
}
}
setState(172);
match(TEMPLATE);
setState(173);
match(IDENTIFIER);
setState(174);
functionFrame();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ConstantDefinitionContext extends ParserRuleContext {
public TerminalNode CONSTANT() { return getToken(ScriptBlockParser.CONSTANT, 0); }
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public TerminalNode EQUALS() { return getToken(ScriptBlockParser.EQUALS, 0); }
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class,0);
}
public DocumentationContext documentation() {
return getRuleContext(DocumentationContext.class,0);
}
public TerminalNode INTERNAL() { return getToken(ScriptBlockParser.INTERNAL, 0); }
public ConstantDefinitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_constantDefinition; }
}
public final ConstantDefinitionContext constantDefinition() throws RecognitionException {
ConstantDefinitionContext _localctx = new ConstantDefinitionContext(_ctx, getState());
enterRule(_localctx, 24, RULE_constantDefinition);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(177);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==DOC_START) {
{
setState(176);
documentation();
}
}
setState(180);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==INTERNAL) {
{
setState(179);
match(INTERNAL);
}
}
setState(182);
match(CONSTANT);
setState(183);
match(IDENTIFIER);
setState(184);
match(EQUALS);
setState(185);
expression(0);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FormatterContext extends ParserRuleContext {
public TerminalNode LESS_THAN() { return getToken(ScriptBlockParser.LESS_THAN, 0); }
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public TerminalNode GREATER_THAN() { return getToken(ScriptBlockParser.GREATER_THAN, 0); }
public ArgumentListContext argumentList() {
return getRuleContext(ArgumentListContext.class,0);
}
public FormatterContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_formatter; }
}
public final FormatterContext formatter() throws RecognitionException {
FormatterContext _localctx = new FormatterContext(_ctx, getState());
enterRule(_localctx, 26, RULE_formatter);
try {
enterOuterAlt(_localctx, 1);
{
setState(187);
match(LESS_THAN);
setState(188);
match(IDENTIFIER);
setState(189);
match(GREATER_THAN);
setState(190);
argumentList();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ImportLineContext extends ParserRuleContext {
public TerminalNode IMPORT() { return getToken(ScriptBlockParser.IMPORT, 0); }
public List<TerminalNode> IDENTIFIER() { return getTokens(ScriptBlockParser.IDENTIFIER); }
public TerminalNode IDENTIFIER(int i) {
return getToken(ScriptBlockParser.IDENTIFIER, i);
}
public TerminalNode COLON() { return getToken(ScriptBlockParser.COLON, 0); }
public ImportLineContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_importLine; }
}
public final ImportLineContext importLine() throws RecognitionException {
ImportLineContext _localctx = new ImportLineContext(_ctx, getState());
enterRule(_localctx, 28, RULE_importLine);
try {
enterOuterAlt(_localctx, 1);
{
setState(192);
match(IMPORT);
setState(193);
match(IDENTIFIER);
setState(194);
match(COLON);
setState(195);
match(IDENTIFIER);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TopDefinitionContext extends ParserRuleContext {
public TopDefinitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_topDefinition; }
public TopDefinitionContext() { }
public void copyFrom(TopDefinitionContext ctx) {
super.copyFrom(ctx);
}
}
public static class FunctionDefinitionTopContext extends TopDefinitionContext {
public FunctionDefinitionContext functionDefinition() {
return getRuleContext(FunctionDefinitionContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public FunctionDefinitionTopContext(TopDefinitionContext ctx) { copyFrom(ctx); }
}
public static class FunctionShortcutTopContext extends TopDefinitionContext {
public FunctionDefinitionShortcutContext functionDefinitionShortcut() {
return getRuleContext(FunctionDefinitionShortcutContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public FunctionShortcutTopContext(TopDefinitionContext ctx) { copyFrom(ctx); }
}
public static class ConstantDefinitionTopContext extends TopDefinitionContext {
public ConstantDefinitionContext constantDefinition() {
return getRuleContext(ConstantDefinitionContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public ConstantDefinitionTopContext(TopDefinitionContext ctx) { copyFrom(ctx); }
}
public static class TemplateDefinitionTopContext extends TopDefinitionContext {
public TemplateDefinitionContext templateDefinition() {
return getRuleContext(TemplateDefinitionContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public TemplateDefinitionTopContext(TopDefinitionContext ctx) { copyFrom(ctx); }
}
public final TopDefinitionContext topDefinition() throws RecognitionException {
TopDefinitionContext _localctx = new TopDefinitionContext(_ctx, getState());
enterRule(_localctx, 30, RULE_topDefinition);
try {
setState(209);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,23,_ctx) ) {
case 1:
_localctx = new ConstantDefinitionTopContext(_localctx);
enterOuterAlt(_localctx, 1);
{
setState(197);
constantDefinition();
setState(198);
match(NEWLINES);
}
break;
case 2:
_localctx = new FunctionDefinitionTopContext(_localctx);
enterOuterAlt(_localctx, 2);
{
setState(200);
functionDefinition();
setState(201);
match(NEWLINES);
}
break;
case 3:
_localctx = new TemplateDefinitionTopContext(_localctx);
enterOuterAlt(_localctx, 3);
{
setState(203);
templateDefinition();
setState(204);
match(NEWLINES);
}
break;
case 4:
_localctx = new FunctionShortcutTopContext(_localctx);
enterOuterAlt(_localctx, 4);
{
setState(206);
functionDefinitionShortcut();
setState(207);
match(NEWLINES);
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StatementContext extends ParserRuleContext {
public StatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_statement; }
public StatementContext() { }
public void copyFrom(StatementContext ctx) {
super.copyFrom(ctx);
}
}
public static class RaiseStatementContext extends StatementContext {
public RaiseContext raise() {
return getRuleContext(RaiseContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public RaiseStatementContext(StatementContext ctx) { copyFrom(ctx); }
}
public static class FunctionCallStatementContext extends StatementContext {
public FunctionCallContext functionCall() {
return getRuleContext(FunctionCallContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public FunctionCallStatementContext(StatementContext ctx) { copyFrom(ctx); }
}
public static class DelayStructureStatementContext extends StatementContext {
public DelayStructureContext delayStructure() {
return getRuleContext(DelayStructureContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public DelayStructureStatementContext(StatementContext ctx) { copyFrom(ctx); }
}
public static class NativeCallStatementContext extends StatementContext {
public NativeCallContext nativeCall() {
return getRuleContext(NativeCallContext.class,0);
}
public TerminalNode NEWLINES() { return getToken(ScriptBlockParser.NEWLINES, 0); }
public NativeCallStatementContext(StatementContext ctx) { copyFrom(ctx); }
}
public final StatementContext statement() throws RecognitionException {
StatementContext _localctx = new StatementContext(_ctx, getState());
enterRule(_localctx, 32, RULE_statement);
try {
setState(223);
_errHandler.sync(this);
switch (_input.LA(1)) {
case IDENTIFIER:
_localctx = new FunctionCallStatementContext(_localctx);
enterOuterAlt(_localctx, 1);
{
{
setState(211);
functionCall();
setState(212);
match(NEWLINES);
}
}
break;
case NATIVE:
_localctx = new NativeCallStatementContext(_localctx);
enterOuterAlt(_localctx, 2);
{
{
setState(214);
nativeCall();
setState(215);
match(NEWLINES);
}
}
break;
case DELAY:
_localctx = new DelayStructureStatementContext(_localctx);
enterOuterAlt(_localctx, 3);
{
{
setState(217);
delayStructure();
setState(218);
match(NEWLINES);
}
}
break;
case RAISE:
_localctx = new RaiseStatementContext(_localctx);
enterOuterAlt(_localctx, 4);
{
{
setState(220);
raise();
setState(221);
match(NEWLINES);
}
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class DelayStructureContext extends ParserRuleContext {
public TerminalNode DELAY() { return getToken(ScriptBlockParser.DELAY, 0); }
public StructureListContext structureList() {
return getRuleContext(StructureListContext.class,0);
}
public FunctionFrameContext functionFrame() {
return getRuleContext(FunctionFrameContext.class,0);
}
public DelayStructureContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_delayStructure; }
}
public final DelayStructureContext delayStructure() throws RecognitionException {
DelayStructureContext _localctx = new DelayStructureContext(_ctx, getState());
enterRule(_localctx, 34, RULE_delayStructure);
try {
enterOuterAlt(_localctx, 1);
{
setState(225);
match(DELAY);
setState(226);
structureList();
setState(227);
functionFrame();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class RaiseContext extends ParserRuleContext {
public TerminalNode RAISE() { return getToken(ScriptBlockParser.RAISE, 0); }
public TagContext tag() {
return getRuleContext(TagContext.class,0);
}
public RaiseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_raise; }
}
public final RaiseContext raise() throws RecognitionException {
RaiseContext _localctx = new RaiseContext(_ctx, getState());
enterRule(_localctx, 36, RULE_raise);
try {
enterOuterAlt(_localctx, 1);
{
setState(229);
match(RAISE);
setState(230);
tag();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ExpressionContext extends ParserRuleContext {
public ExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_expression; }
public ExpressionContext() { }
public void copyFrom(ExpressionContext ctx) {
super.copyFrom(ctx);
}
}
public static class StringExprContext extends ExpressionContext {
public TerminalNode STRING() { return getToken(ScriptBlockParser.STRING, 0); }
public StringExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class DivideExprContext extends ExpressionContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TerminalNode DIVIDE() { return getToken(ScriptBlockParser.DIVIDE, 0); }
public DivideExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class IntegerDivideExprContext extends ExpressionContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TerminalNode INTEGER_DIVIDE() { return getToken(ScriptBlockParser.INTEGER_DIVIDE, 0); }
public IntegerDivideExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class SubtractExprContext extends ExpressionContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TerminalNode SUBTRACT() { return getToken(ScriptBlockParser.SUBTRACT, 0); }
public SubtractExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class PowerExprContext extends ExpressionContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TerminalNode POWER() { return getToken(ScriptBlockParser.POWER, 0); }
public PowerExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class AddExprContext extends ExpressionContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TerminalNode PLUS() { return getToken(ScriptBlockParser.PLUS, 0); }
public AddExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class NumberExprContext extends ExpressionContext {
public NumberContext number() {
return getRuleContext(NumberContext.class,0);
}
public NumberExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class MultiplyExprContext extends ExpressionContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TerminalNode MULTIPLY() { return getToken(ScriptBlockParser.MULTIPLY, 0); }
public MultiplyExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class CallExprContext extends ExpressionContext {
public TerminalNode RUN() { return getToken(ScriptBlockParser.RUN, 0); }
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public ArgumentListContext argumentList() {
return getRuleContext(ArgumentListContext.class,0);
}
public CallExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class FormatterExprContext extends ExpressionContext {
public FormatterContext formatter() {
return getRuleContext(FormatterContext.class,0);
}
public FormatterExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class IdentifierExprContext extends ExpressionContext {
public TerminalNode IDENTIFIER() { return getToken(ScriptBlockParser.IDENTIFIER, 0); }
public IdentifierExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public static class ParenthExprContext extends ExpressionContext {
public TerminalNode OPAREN() { return getToken(ScriptBlockParser.OPAREN, 0); }
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class,0);
}
public TerminalNode CPAREN() { return getToken(ScriptBlockParser.CPAREN, 0); }
public ParenthExprContext(ExpressionContext ctx) { copyFrom(ctx); }
}
public final ExpressionContext expression() throws RecognitionException {
return expression(0);
}
private ExpressionContext expression(int _p) throws RecognitionException {
ParserRuleContext _parentctx = _ctx;
int _parentState = getState();
ExpressionContext _localctx = new ExpressionContext(_ctx, _parentState);
ExpressionContext _prevctx = _localctx;
int _startState = 38;
enterRecursionRule(_localctx, 38, RULE_expression, _p);
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(244);
_errHandler.sync(this);
switch (_input.LA(1)) {
case SIGN:
case DIGITS:
{
_localctx = new NumberExprContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(233);
number();
}
break;
case STRING:
{
_localctx = new StringExprContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(234);
match(STRING);
}
break;
case IDENTIFIER:
{
_localctx = new IdentifierExprContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(235);
match(IDENTIFIER);
}
break;
case OPAREN:
{
_localctx = new ParenthExprContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(236);
match(OPAREN);
setState(237);
expression(0);
setState(238);
match(CPAREN);
}
break;
case LESS_THAN:
{
_localctx = new FormatterExprContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(240);
formatter();
}
break;
case RUN:
{
_localctx = new CallExprContext(_localctx);
_ctx = _localctx;
_prevctx = _localctx;
setState(241);
match(RUN);
setState(242);
match(IDENTIFIER);
setState(243);
argumentList();
}
break;
default:
throw new NoViableAltException(this);
}
_ctx.stop = _input.LT(-1);
setState(266);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,27,_ctx);
while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) {
if ( _alt==1 ) {
if ( _parseListeners!=null ) triggerExitRuleEvent();
_prevctx = _localctx;
{
setState(264);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,26,_ctx) ) {
case 1:
{
_localctx = new PowerExprContext(new ExpressionContext(_parentctx, _parentState));
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(246);
if (!(precpred(_ctx, 7))) throw new FailedPredicateException(this, "precpred(_ctx, 7)");
setState(247);
match(POWER);
setState(248);
expression(7);
}
break;
case 2:
{
_localctx = new MultiplyExprContext(new ExpressionContext(_parentctx, _parentState));
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(249);
if (!(precpred(_ctx, 6))) throw new FailedPredicateException(this, "precpred(_ctx, 6)");
setState(250);
match(MULTIPLY);
setState(251);
expression(7);
}
break;
case 3:
{
_localctx = new DivideExprContext(new ExpressionContext(_parentctx, _parentState));
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(252);
if (!(precpred(_ctx, 5))) throw new FailedPredicateException(this, "precpred(_ctx, 5)");
setState(253);
match(DIVIDE);
setState(254);
expression(6);
}
break;
case 4:
{
_localctx = new IntegerDivideExprContext(new ExpressionContext(_parentctx, _parentState));
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(255);
if (!(precpred(_ctx, 4))) throw new FailedPredicateException(this, "precpred(_ctx, 4)");
setState(256);
match(INTEGER_DIVIDE);
setState(257);
expression(5);
}
break;
case 5:
{
_localctx = new AddExprContext(new ExpressionContext(_parentctx, _parentState));
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(258);
if (!(precpred(_ctx, 3))) throw new FailedPredicateException(this, "precpred(_ctx, 3)");
setState(259);
match(PLUS);
setState(260);
expression(4);
}
break;
case 6:
{
_localctx = new SubtractExprContext(new ExpressionContext(_parentctx, _parentState));
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(261);
if (!(precpred(_ctx, 2))) throw new FailedPredicateException(this, "precpred(_ctx, 2)");
setState(262);
match(SUBTRACT);
setState(263);
expression(3);
}
break;
}
}
}
setState(268);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,27,_ctx);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
unrollRecursionContexts(_parentctx);
}
return _localctx;
}
public static class NumberContext extends ParserRuleContext {
public List<TerminalNode> DIGITS() { return getTokens(ScriptBlockParser.DIGITS); }
public TerminalNode DIGITS(int i) {
return getToken(ScriptBlockParser.DIGITS, i);
}
public TerminalNode SIGN() { return getToken(ScriptBlockParser.SIGN, 0); }
public TerminalNode DOT() { return getToken(ScriptBlockParser.DOT, 0); }
public NumberContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_number; }
}
public final NumberContext number() throws RecognitionException {
NumberContext _localctx = new NumberContext(_ctx, getState());
enterRule(_localctx, 40, RULE_number);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(270);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==SIGN) {
{
setState(269);
match(SIGN);
}
}
setState(272);
match(DIGITS);
setState(275);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,29,_ctx) ) {
case 1:
{
setState(273);
match(DOT);
setState(274);
match(DIGITS);
}
break;
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) {
switch (ruleIndex) {
case 19:
return expression_sempred((ExpressionContext)_localctx, predIndex);
}
return true;
}
private boolean expression_sempred(ExpressionContext _localctx, int predIndex) {
switch (predIndex) {
case 0:
return precpred(_ctx, 7);
case 1:
return precpred(_ctx, 6);
case 2:
return precpred(_ctx, 5);
case 3:
return precpred(_ctx, 4);
case 4:
return precpred(_ctx, 3);
case 5:
return precpred(_ctx, 2);
}
return true;
}
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3*\u0118\4\2\t\2\4"+
"\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+
"\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+
"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\3\2\3\2\3\2\7\2\60\n\2\f\2\16"+
"\2\63\13\2\3\2\7\2\66\n\2\f\2\16\29\13\2\3\2\3\2\3\3\3\3\3\3\7\3@\n\3"+
"\f\3\16\3C\13\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\7\4L\n\4\f\4\16\4O\13\4\5"+
"\4Q\n\4\3\4\3\4\3\5\3\5\3\5\3\5\7\5Y\n\5\f\5\16\5\\\13\5\5\5^\n\5\3\5"+
"\3\5\3\6\3\6\3\6\3\6\7\6f\n\6\f\6\16\6i\13\6\5\6k\n\6\3\6\3\6\3\7\3\7"+
"\3\7\3\b\3\b\3\b\5\bu\n\b\3\b\5\bx\n\b\3\t\3\t\3\t\3\t\5\t~\n\t\3\t\3"+
"\t\7\t\u0082\n\t\f\t\16\t\u0085\13\t\3\t\3\t\3\n\5\n\u008a\n\n\3\n\5\n"+
"\u008d\n\n\3\n\5\n\u0090\n\n\3\n\3\n\3\n\3\n\3\13\5\13\u0097\n\13\3\13"+
"\5\13\u009a\n\13\3\13\5\13\u009d\n\13\3\13\3\13\3\13\3\13\3\13\3\f\3\f"+
"\3\f\3\f\3\f\3\r\5\r\u00aa\n\r\3\r\5\r\u00ad\n\r\3\r\3\r\3\r\3\r\3\16"+
"\5\16\u00b4\n\16\3\16\5\16\u00b7\n\16\3\16\3\16\3\16\3\16\3\16\3\17\3"+
"\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3"+
"\21\3\21\3\21\3\21\3\21\3\21\3\21\5\21\u00d4\n\21\3\22\3\22\3\22\3\22"+
"\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\5\22\u00e2\n\22\3\23\3\23\3\23"+
"\3\23\3\24\3\24\3\24\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25"+
"\3\25\3\25\5\25\u00f7\n\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25"+
"\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\7\25\u010b\n\25\f\25\16"+
"\25\u010e\13\25\3\26\5\26\u0111\n\26\3\26\3\26\3\26\5\26\u0116\n\26\3"+
"\26\2\3(\27\2\4\6\b\n\f\16\20\22\24\26\30\32\34\36 \"$&(*\2\2\2\u012c"+
"\2\61\3\2\2\2\4<\3\2\2\2\6G\3\2\2\2\bT\3\2\2\2\na\3\2\2\2\fn\3\2\2\2\16"+
"q\3\2\2\2\20y\3\2\2\2\22\u0089\3\2\2\2\24\u0096\3\2\2\2\26\u00a3\3\2\2"+
"\2\30\u00a9\3\2\2\2\32\u00b3\3\2\2\2\34\u00bd\3\2\2\2\36\u00c2\3\2\2\2"+
" \u00d3\3\2\2\2\"\u00e1\3\2\2\2$\u00e3\3\2\2\2&\u00e7\3\2\2\2(\u00f6\3"+
"\2\2\2*\u0110\3\2\2\2,-\5\36\20\2-.\7\b\2\2.\60\3\2\2\2/,\3\2\2\2\60\63"+
"\3\2\2\2\61/\3\2\2\2\61\62\3\2\2\2\62\67\3\2\2\2\63\61\3\2\2\2\64\66\5"+
" \21\2\65\64\3\2\2\2\669\3\2\2\2\67\65\3\2\2\2\678\3\2\2\28:\3\2\2\29"+
"\67\3\2\2\2:;\7\2\2\3;\3\3\2\2\2<=\7\5\2\2=A\7\b\2\2>@\7\7\2\2?>\3\2\2"+
"\2@C\3\2\2\2A?\3\2\2\2AB\3\2\2\2BD\3\2\2\2CA\3\2\2\2DE\7\6\2\2EF\7\b\2"+
"\2F\5\3\2\2\2GP\7\22\2\2HM\7&\2\2IJ\7\30\2\2JL\7&\2\2KI\3\2\2\2LO\3\2"+
"\2\2MK\3\2\2\2MN\3\2\2\2NQ\3\2\2\2OM\3\2\2\2PH\3\2\2\2PQ\3\2\2\2QR\3\2"+
"\2\2RS\7\23\2\2S\7\3\2\2\2T]\7\22\2\2UZ\5(\25\2VW\7\30\2\2WY\5(\25\2X"+
"V\3\2\2\2Y\\\3\2\2\2ZX\3\2\2\2Z[\3\2\2\2[^\3\2\2\2\\Z\3\2\2\2]U\3\2\2"+
"\2]^\3\2\2\2^_\3\2\2\2_`\7\23\2\2`\t\3\2\2\2aj\7\26\2\2bg\5(\25\2cd\7"+
"\30\2\2df\5(\25\2ec\3\2\2\2fi\3\2\2\2ge\3\2\2\2gh\3\2\2\2hk\3\2\2\2ig"+
"\3\2\2\2jb\3\2\2\2jk\3\2\2\2kl\3\2\2\2lm\7\27\2\2m\13\3\2\2\2no\7\13\2"+
"\2op\5\b\5\2p\r\3\2\2\2qw\7&\2\2rt\5\b\5\2su\5\20\t\2ts\3\2\2\2tu\3\2"+
"\2\2ux\3\2\2\2vx\5\20\t\2wr\3\2\2\2wv\3\2\2\2x\17\3\2\2\2y}\7\24\2\2z"+
"{\5\6\4\2{|\7\21\2\2|~\3\2\2\2}z\3\2\2\2}~\3\2\2\2~\177\3\2\2\2\177\u0083"+
"\7\b\2\2\u0080\u0082\5\"\22\2\u0081\u0080\3\2\2\2\u0082\u0085\3\2\2\2"+
"\u0083\u0081\3\2\2\2\u0083\u0084\3\2\2\2\u0084\u0086\3\2\2\2\u0085\u0083"+
"\3\2\2\2\u0086\u0087\7\25\2\2\u0087\21\3\2\2\2\u0088\u008a\5\4\3\2\u0089"+
"\u0088\3\2\2\2\u0089\u008a\3\2\2\2\u008a\u008c\3\2\2\2\u008b\u008d\5\26"+
"\f\2\u008c\u008b\3\2\2\2\u008c\u008d\3\2\2\2\u008d\u008f\3\2\2\2\u008e"+
"\u0090\7\20\2\2\u008f\u008e\3\2\2\2\u008f\u0090\3\2\2\2\u0090\u0091\3"+
"\2\2\2\u0091\u0092\7\t\2\2\u0092\u0093\7&\2\2\u0093\u0094\5\20\t\2\u0094"+
"\23\3\2\2\2\u0095\u0097\5\4\3\2\u0096\u0095\3\2\2\2\u0096\u0097\3\2\2"+
"\2\u0097\u0099\3\2\2\2\u0098\u009a\5\26\f\2\u0099\u0098\3\2\2\2\u0099"+
"\u009a\3\2\2\2\u009a\u009c\3\2\2\2\u009b\u009d\7\20\2\2\u009c\u009b\3"+
"\2\2\2\u009c\u009d\3\2\2\2\u009d\u009e\3\2\2\2\u009e\u009f\7\t\2\2\u009f"+
"\u00a0\7&\2\2\u00a0\u00a1\7\31\2\2\u00a1\u00a2\5\16\b\2\u00a2\25\3\2\2"+
"\2\u00a3\u00a4\7%\2\2\u00a4\u00a5\7&\2\2\u00a5\u00a6\7\33\2\2\u00a6\u00a7"+
"\7&\2\2\u00a7\27\3\2\2\2\u00a8\u00aa\5\4\3\2\u00a9\u00a8\3\2\2\2\u00a9"+
"\u00aa\3\2\2\2\u00aa\u00ac\3\2\2\2\u00ab\u00ad\7\20\2\2\u00ac\u00ab\3"+
"\2\2\2\u00ac\u00ad\3\2\2\2\u00ad\u00ae\3\2\2\2\u00ae\u00af\7\n\2\2\u00af"+
"\u00b0\7&\2\2\u00b0\u00b1\5\20\t\2\u00b1\31\3\2\2\2\u00b2\u00b4\5\4\3"+
"\2\u00b3\u00b2\3\2\2\2\u00b3\u00b4\3\2\2\2\u00b4\u00b6\3\2\2\2\u00b5\u00b7"+
"\7\20\2\2\u00b6\u00b5\3\2\2\2\u00b6\u00b7\3\2\2\2\u00b7\u00b8\3\2\2\2"+
"\u00b8\u00b9\7\f\2\2\u00b9\u00ba\7&\2\2\u00ba\u00bb\7\31\2\2\u00bb\u00bc"+
"\5(\25\2\u00bc\33\3\2\2\2\u00bd\u00be\7$\2\2\u00be\u00bf\7&\2\2\u00bf"+
"\u00c0\7#\2\2\u00c0\u00c1\5\b\5\2\u00c1\35\3\2\2\2\u00c2\u00c3\7\17\2"+
"\2\u00c3\u00c4\7&\2\2\u00c4\u00c5\7\33\2\2\u00c5\u00c6\7&\2\2\u00c6\37"+
"\3\2\2\2\u00c7\u00c8\5\32\16\2\u00c8\u00c9\7\b\2\2\u00c9\u00d4\3\2\2\2"+
"\u00ca\u00cb\5\22\n\2\u00cb\u00cc\7\b\2\2\u00cc\u00d4\3\2\2\2\u00cd\u00ce"+
"\5\30\r\2\u00ce\u00cf\7\b\2\2\u00cf\u00d4\3\2\2\2\u00d0\u00d1\5\24\13"+
"\2\u00d1\u00d2\7\b\2\2\u00d2\u00d4\3\2\2\2\u00d3\u00c7\3\2\2\2\u00d3\u00ca"+
"\3\2\2\2\u00d3\u00cd\3\2\2\2\u00d3\u00d0\3\2\2\2\u00d4!\3\2\2\2\u00d5"+
"\u00d6\5\16\b\2\u00d6\u00d7\7\b\2\2\u00d7\u00e2\3\2\2\2\u00d8\u00d9\5"+
"\f\7\2\u00d9\u00da\7\b\2\2\u00da\u00e2\3\2\2\2\u00db\u00dc\5$\23\2\u00dc"+
"\u00dd\7\b\2\2\u00dd\u00e2\3\2\2\2\u00de\u00df\5&\24\2\u00df\u00e0\7\b"+
"\2\2\u00e0\u00e2\3\2\2\2\u00e1\u00d5\3\2\2\2\u00e1\u00d8\3\2\2\2\u00e1"+
"\u00db\3\2\2\2\u00e1\u00de\3\2\2\2\u00e2#\3\2\2\2\u00e3\u00e4\7\16\2\2"+
"\u00e4\u00e5\5\n\6\2\u00e5\u00e6\5\20\t\2\u00e6%\3\2\2\2\u00e7\u00e8\7"+
"*\2\2\u00e8\u00e9\5\26\f\2\u00e9\'\3\2\2\2\u00ea\u00eb\b\25\1\2\u00eb"+
"\u00f7\5*\26\2\u00ec\u00f7\7)\2\2\u00ed\u00f7\7&\2\2\u00ee\u00ef\7\22"+
"\2\2\u00ef\u00f0\5(\25\2\u00f0\u00f1\7\23\2\2\u00f1\u00f7\3\2\2\2\u00f2"+
"\u00f7\5\34\17\2\u00f3\u00f4\7\r\2\2\u00f4\u00f5\7&\2\2\u00f5\u00f7\5"+
"\b\5\2\u00f6\u00ea\3\2\2\2\u00f6\u00ec\3\2\2\2\u00f6\u00ed\3\2\2\2\u00f6"+
"\u00ee\3\2\2\2\u00f6\u00f2\3\2\2\2\u00f6\u00f3\3\2\2\2\u00f7\u010c\3\2"+
"\2\2\u00f8\u00f9\f\t\2\2\u00f9\u00fa\7\34\2\2\u00fa\u010b\5(\25\t\u00fb"+
"\u00fc\f\b\2\2\u00fc\u00fd\7\35\2\2\u00fd\u010b\5(\25\t\u00fe\u00ff\f"+
"\7\2\2\u00ff\u0100\7\36\2\2\u0100\u010b\5(\25\b\u0101\u0102\f\6\2\2\u0102"+
"\u0103\7\37\2\2\u0103\u010b\5(\25\7\u0104\u0105\f\5\2\2\u0105\u0106\7"+
" \2\2\u0106\u010b\5(\25\6\u0107\u0108\f\4\2\2\u0108\u0109\7!\2\2\u0109"+
"\u010b\5(\25\5\u010a\u00f8\3\2\2\2\u010a\u00fb\3\2\2\2\u010a\u00fe\3\2"+
"\2\2\u010a\u0101\3\2\2\2\u010a\u0104\3\2\2\2\u010a\u0107\3\2\2\2\u010b"+
"\u010e\3\2\2\2\u010c\u010a\3\2\2\2\u010c\u010d\3\2\2\2\u010d)\3\2\2\2"+
"\u010e\u010c\3\2\2\2\u010f\u0111\7\'\2\2\u0110\u010f\3\2\2\2\u0110\u0111"+
"\3\2\2\2\u0111\u0112\3\2\2\2\u0112\u0115\7(\2\2\u0113\u0114\7\"\2\2\u0114"+
"\u0116\7(\2\2\u0115\u0113\3\2\2\2\u0115\u0116\3\2\2\2\u0116+\3\2\2\2 "+
"\61\67AMPZ]gjtw}\u0083\u0089\u008c\u008f\u0096\u0099\u009c\u00a9\u00ac"+
"\u00b3\u00b6\u00d3\u00e1\u00f6\u010a\u010c\u0110\u0115";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}<file_sep>/compiler/front/pretty/printresolved.go
package pretty
import (
"encoding/json"
"fmt"
"github.com/falcinspire/scriptblock/compiler/ast"
)
func PrintResolved(unit *ast.Unit) {
imports := make([]*ResolvedImport, len(unit.ImportLines))
for i, importLine := range unit.ImportLines {
imports[i] = &ResolvedImport{Module: importLine.Module, Unit: importLine.Unit}
}
definitions := make([]ResolvedTopDefinition, len(unit.Definitions))
for i, definition := range unit.Definitions {
visitor := &ResolvedTopDefinitionVisitor{nil, nil}
definition.Accept(visitor)
definitions[i] = visitor.Result
}
jsonData, _ := json.Marshal(&ResolvedUnit{imports, definitions})
fmt.Println(string(jsonData))
}
<file_sep>/compiler/maintool/toolproject.go
package maintool
import (
"fmt"
"path/filepath"
"github.com/falcinspire/scriptblock/compiler/front/astbook"
"github.com/falcinspire/scriptblock/compiler/back/addressbook"
"github.com/falcinspire/scriptblock/compiler/back/values"
"github.com/falcinspire/scriptblock/compiler/front/imports"
"github.com/falcinspire/scriptblock/compiler/front/symbols"
"github.com/sirupsen/logrus"
"github.com/falcinspire/scriptblock/compiler/dependency"
"github.com/falcinspire/scriptblock/environment"
"github.com/falcinspire/scriptblock/home"
)
func DoProject(sourceModuleQualified string, output string) {
scriptblockHome := environment.GetHomeSourcePath()
order := makeModuleDependencyOrder(sourceModuleQualified, scriptblockHome)
astbooko := astbook.NewAstBook()
importbooko := imports.NewImportBook()
symbollibrary := symbols.NewSymbolLibrary()
valuelibrary := values.NewValueLibrary()
addressbooko := addressbook.NewAddressBook()
logrus.WithFields(logrus.Fields{
"order": order,
}).Info("module dependency order")
for _, moduleQualified := range order {
DoModule(moduleQualified, scriptblockHome, output, astbooko, importbooko, symbollibrary, valuelibrary, addressbooko)
}
}
//TODO test multiple modules
func makeModuleDependencyOrder(moduleQualified string, scriptblockHome string) []string {
graph := dependency.NewDependencyGraph()
moduleToID := make(map[string]int)
idToModule := make(map[int]string)
addModuleDependencies(moduleQualified, scriptblockHome, graph, moduleToID, idToModule)
orderID, circular := dependency.MakeDependencyOrder(graph)
if circular {
panic(fmt.Errorf("circular module dependency"))
}
order := make([]string, len(graph.Nodes))
for index, i := range orderID {
order[index] = idToModule[i]
}
return order
}
func addModuleDependencies(moduleQualified string, scriptblockHome string, graph *dependency.DependencyGraph, moduleToID map[string]int, idToModule map[int]string) int {
modulePath := filepath.Join(scriptblockHome, moduleQualified)
id, exists := moduleToID[moduleQualified]
if exists {
return id
}
id = dependency.AddVertex(graph)
idToModule[id] = moduleQualified
config := home.ReadModuleFile(filepath.Join(modulePath, "module.yaml"))
for _, depends := range config.Dependencies {
dependsID := addModuleDependencies(filepath.Join(depends.Location, depends.Version), scriptblockHome, graph, moduleToID, idToModule)
dependency.AddDependency(id, dependsID, graph)
}
return id
}
<file_sep>/compiler/back/values/values.go
package values
import (
"fmt"
)
type Value interface {
Accept(visitor ValueVisitor)
}
type NumberValue struct {
Value float64
}
func NewNumberValue(value float64) *NumberValue {
box := new(NumberValue)
box.Value = value
return box
}
func (this *NumberValue) Accept(visitor ValueVisitor) {
visitor.VisitNumber(this)
}
func (this *NumberValue) String() string {
return fmt.Sprintf("%.2f", this.Value)
}
type StringValue struct {
Value string
}
func NewStringValue(value string) *StringValue {
stringValue := new(StringValue)
stringValue.Value = value
return stringValue
}
func (this *StringValue) Accept(visitor ValueVisitor) {
visitor.VisitString(this)
}
func (value *StringValue) String() string {
return value.Value
}
type FunctionValue struct {
Module string
Unit string
Name string
}
func NewFunctionValue(module string, unit string, name string) *FunctionValue {
return &FunctionValue{module, unit, name}
}
func (this *FunctionValue) Accept(visitor ValueVisitor) {
visitor.VisitFunction(this)
}
type TemplateValue struct {
Module string
Unit string
Name string
}
func NewTemplateValue(module string, unit string, name string) *TemplateValue {
return &TemplateValue{module, unit, name}
}
func (this *TemplateValue) Accept(visitor ValueVisitor) {
visitor.VisitTemplate(this)
}
type FunctorValue struct {
Callee *TemplateValue
Capture []Value
}
func NewFunctorValue(callee *TemplateValue, capture []Value) *FunctorValue {
return &FunctorValue{callee, capture}
}
func (this *FunctorValue) Accept(visitor ValueVisitor) {
visitor.VisitFunctor(this)
}
| 7e5f7e5e42cd24a3c7d5c1f9c6c8fe471b2a14c9 | [
"Text",
"Java",
"Go",
"Markdown"
] | 93 | Go | Falcinspire/ScriptBlock | 25c89f07f60880b8161459a2d06e7fa4e21153aa | 0662ab91752fbd612c58e552db60c0584c1520dc |
refs/heads/master | <repo_name>Hamrounmh/gestion_des_services_des_enseignants<file_sep>/src/Controller/HomeController.php
<?php
namespace App\Controller;
use App\Entity\Inscription;
use App\Repository\InscriptionRepository;
use App\Repository\UniteRepository;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class HomeController extends AbstractController {
private $repository;
private $uniteRepository;
private $inscriptionRepository;
public function __construct(UserRepository $repository,UniteRepository $uniteRepository,InscriptionRepository $inscriptionRepository)
{
$this->repository=$repository;
$this->uniteRepository=$uniteRepository;
$this->inscriptionRepository=$inscriptionRepository;
}
public function choisir($id)
{
$user=$this->repository->findUserByID($id);
$unities=$this->uniteRepository->findAll();
return $this->render('Choisir.html.twig',[
'user' => $user,
'unities' =>$unities
]);
}
public function index($id): Response
{
$user=$this->repository->findUserByID($id);
if($user->getAdmin()==0){
return $this->render('Admin.html.twig',[
'id'=>$id,
'user' => $user
]);
}
return $this->render('home.html.twig',[
'id' =>$id,
'user' => $user
]);
}
public function valider($id,Request $request):Response
{
$user=$this->repository->findUserByID($id);
$nomUnite =$request->get('nomUnite');
$nbh=$request->get('nbh');
$type=$request->get('type');
$nbh=intval($nbh);
$type=strval($type);
$id=intval($id);
$inscription= new Inscription();
$inscription
->setNbh($nbh)
->setNomUnite($nomUnite)
->setType($type)
->setIdUser($id)
->setIdUnite($id)
->setValide('NO')
->setNomUser($user->getLogin());
$em=$this->getDoctrine()->getManager();
$em->persist($inscription);
$em->flush();
if($user->getAdmin()==0){
return $this->render('Admin.html.twig',[
'id'=>$id,
'user' => $user
]);
}
return $this->render('home.html.twig',[
'id'=> $id,
'user' => $user
]);
}
public function choix($id):Response
{
$inscription =$this->inscriptionRepository->findInscriptionById($id);
$user=$this->repository->findUserByID($id);
return $this->render('Choix.html.twig',[
'user' => $user,
'inscription' => $inscription
]);
}
}<file_sep>/src/Controller/AdminController.php
<?php
/**
* Created by IntelliJ IDEA.
* User: bboydhaouse
* Date: 08/03/19
* Time: 04:42 م
*/
namespace App\Controller;
use App\Entity\Unite;
use App\Entity\User;
use App\Form\UniteType;
use App\Repository\InscriptionRepository;
use App\Repository\UniteRepository;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class AdminController extends AbstractController {
private $repository;
private $uniteRepository;
private $inscriptionRepository;
public function __construct(UserRepository $repository,UniteRepository $uniteRepository,InscriptionRepository $inscriptionRepository)
{
$this->repository=$repository;
$this->uniteRepository=$uniteRepository;
$this->inscriptionRepository=$inscriptionRepository;
}
public function demande($id)
{
$user=$this->repository->findUserByID($id);
$inscription=$this->inscriptionRepository->findValide('NO');
return $this->render('Valider.html.twig',[
'id'=>$id,
'user' => $user,
'inscription'=>$inscription
]);
}
public function index($id): Response
{
$user=$this->repository->findUserByID($id);
if($user->getAdmin()==0){
return $this->render('Admin.html.twig',[
'id'=>$id,
'user' => $user
]);
}
return $this->render('home.html.twig',[
'id'=> $id,
'user' => $user
]);
}
public function validate($id,$idInc): Response
{
$selected= $this->inscriptionRepository->findInscriptionByIdINC($idInc);
$user=$this->repository->findUserByID($id);
$em=$this->getDoctrine()->getManager();
$em->remove($selected);
$selected->setValide('YES');
$em->persist($selected);
$em->flush();
$inscription=$this->inscriptionRepository->findValide('NO');
return $this->render('Valider.html.twig',[
'id'=>$id,
'user' => $user,
'inscription'=>$inscription
]);
}
public function editUnite($id):Response
{
$user=$this->repository->findUserByID($id);
return $this->render('AjoutUnite.html.twig',[
'user' => $user]);
}
public function editUser($id):Response
{
$user=$this->repository->findUserByID($id);
return $this->render('AjoutUser.html.twig',[
'user' => $user]);
}
public function validerUnite($id, Request $request):Response
{
$user=$this->repository->findUserByID($id);
$nom =$request->get('nom');
$nbh=$request->get('nbh');
$type=$request->get('type');
$nbh=intval($nbh);
$nom=strval($nom);
$type=strval($type);
$id=intval($id);
$unite=new Unite();
$unite
->setName($nom)
->setLimiteHeurs($nbh)
->setType($type);
$em=$this->getDoctrine()->getManager();
$em->persist($unite);
$em->flush();
return $this->render('Admin.html.twig',[
'user' => $user]);
}
public function validerUser($id,Request $request):Response
{
$user=$this->repository->findUserByID($id);
$login =$request->get('login');
$nbh=$request->get('nbh');
$function=$request->get('function');
$admin=$request->get('admin');
$password=$request->get('password');
$nbh=intval($nbh);
$admin=intval($admin);
$password=strval($password);
$login=strval($login);
$function=strval($function);
$user1=new User();
$user1
->setAdmin($admin)
->setFunction($function)
->setHourTime($nbh)
->setLogin($login)
->setPassword($password);
$em=$this->getDoctrine()->getManager();
$em->persist($user1);
$em->flush();
return $this->render('Admin.html.twig',[
'user' => $user]);
}
}<file_sep>/src/Controller/ConnexionController.php
<?php
/**
* Created by IntelliJ IDEA.
* User: bboydhaouse
* Date: 08/03/19
* Time: 08:54 ص
*/
namespace App\Controller;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ConnexionController extends AbstractController
{
private $repository;
public function __construct(UserRepository $repository)
{
$this->repository=$repository;
}
public function index():Response
{
$message="welcome !";
return $this->render('Connexion.html.twig',[
'message'=>$message
]);
}
public function Connexion(Request $request):Response
{
$password =$request->get('<PASSWORD>');
$login=$request->get('login');
$user=$this->repository->findUser($login,$password);
if($user == null){
$message="password incorrect";
return $this->render('Connexion.html.twig',[
'message'=>$message
]);
}elseif($user->getAdmin()==0){
return $this->render('Admin.html.twig',[
'user'=>$user
]);
}else{
return $this->render('home.html.twig',[
'user' => $user,
'id'=>$user->getId()
]);
}
}
} | 3e3362af865dd91c5fba00b49c47160cf6e7ba8f | [
"PHP"
] | 3 | PHP | Hamrounmh/gestion_des_services_des_enseignants | e9c2427304227bb190f6f5ec73abe55c618d3a26 | 8213dc1a0c5c82f875db37231e37723abe147dc5 |
refs/heads/master | <repo_name>nacika-ins/hyper_ex<file_sep>/src/lib.rs
extern crate cookie;
extern crate hyper;
extern crate url;
pub mod http;
pub use http::Client;
pub use http::encode_uri_component;
<file_sep>/README.md
# hyper-ex
Add the cookie-sync function to hyper
## WARNING!!
This crate please use for development and verification.
Security risk many of the Cookie, this crate does not guarantee the safety of the security.
## Usage
It will `git clone` in any directory.
```bash
git clone https://github.com/nacika-ins/hyper_ex.git /path/to/hyper_ex
```
Add this to your `Cargo.toml`:
```toml
[dependencies.hyper_ex]
path = "/path/to/hyper_ex"
```
## Example
### Get request
```rust
extern crate hyper_ex;
use hyper_ex::Client;
fn main() {
let mut client = Client::new();
client.change_useragent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"
.to_owned());
let body = client.get_body("http://google.com").unwrap();
println!("{}", body);
}
```
### Post request
```rust
extern crate hyper_ex;
use hyper_ex::Client;
fn main() {
let mut client = Client::new();
client.change_useragent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"
.to_owned());
let body = client.post_body("http://google.com", "data").unwrap();
println!("{}", body);
}
```<file_sep>/Cargo.toml
[package]
name = "hyper_ex"
version = "0.1.0"
authors = ["nacika <<EMAIL>>"]
[dependencies]
hyper = "0.6.15"
cookie = "^0.1"
url = { git = "https://github.com/servo/rust-url" }
<file_sep>/examples/post.rs
extern crate hyper_ex;
use hyper_ex::Client;
fn main() {
let mut client = Client::new();
client.change_useragent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"
.to_owned());
let body = client.post_body("http://google.com", "data").unwrap();
println!("{}", body);
}
<file_sep>/src/http.rs
use std::io::Read;
use hyper;
use hyper::header::Cookie;
use hyper::header::Headers;
use cookie::Cookie as CookiePair;
use hyper::header::SetCookie;
use hyper::header::UserAgent;
use hyper::error::Error;
use hyper::client::RedirectPolicy;
use url::Url;
use url::percent_encoding::utf8_percent_encode;
use url::percent_encoding::FORM_URLENCODED_ENCODE_SET;
use hyper::status::StatusCode;
pub fn encode_uri_component(text: &str) -> String {
utf8_percent_encode(&text, FORM_URLENCODED_ENCODE_SET)
}
pub struct Client {
client: hyper::Client,
headers: Headers,
}
impl<'a> Client {
fn cookie_sync<'b>(&'b mut self, response_headers: &'b mut Headers, domain: &str) {
let set_cookies = response_headers.iter()
.filter_map(|header| {
if header.is::<SetCookie>() {
header.value::<SetCookie>()
} else {
None
}
})
.next();
let new_cookies = match set_cookies {
Some(v) => {
let mut new_cookies: Vec<CookiePair> = vec![];
let cookies = &self.headers
.iter()
.filter_map(|header| {
if header.is::<Cookie>() {
header.value::<Cookie>()
} else {
None
}
})
.next()
.unwrap();
for cookie in v.iter() {
let mut cp = cookie.clone() as CookiePair;
if cp.domain.is_none() {
cp.domain = Some(domain.to_string().clone());
}
new_cookies.push(cp);
}
for cookie in cookies.iter() {
let name = cookie.name.to_owned();
let old_cookie = v.iter().find(|&r| r.name.to_owned() == name);
match old_cookie {
Some(_) => (),
None => new_cookies.push(cookie.clone() as CookiePair),
}
}
new_cookies
}
None => {
let mut new_cookies: Vec<CookiePair> = vec![];
let cookies = &self.headers
.iter()
.filter_map(|header| {
if header.is::<Cookie>() {
header.value::<Cookie>()
} else {
None
}
})
.next()
.unwrap();
for cookie in cookies.iter() {
new_cookies.push(cookie.clone() as CookiePair)
}
new_cookies
}
};
self.headers.set(Cookie(new_cookies));
}
pub fn set_header<'b>(&'b mut self, name: &str, value: &str) {
self.headers.set_raw(name.to_owned().clone(),
vec![value.to_owned().clone().into_bytes()]);
}
pub fn new() -> Client {
let mut headers = Headers::new();
let useragent = "hyper-ex".to_owned();
headers.set(UserAgent(useragent));
headers.set(Cookie(vec![]));
let mut client = Client {
client: hyper::Client::new(),
headers: headers,
};
client.client.set_redirect_policy(RedirectPolicy::FollowNone);
client
}
pub fn change_useragent<'b>(&'b mut self, useragent: String) {
self.headers.set(UserAgent(useragent));
}
pub fn get_body<'b>(&'b mut self, url: &'b str) -> Result<String, Error> {
let orig_url = Url::parse(url).unwrap();
let domain = orig_url.domain().unwrap();
let res = self.client
.get(url)
.headers(self.headers.clone())
.send();
let mut body = String::new();
match res {
Ok(mut v) => {
self.cookie_sync(&mut v.headers, domain.clone());
v.read_to_string(&mut body).unwrap();
if v.status == StatusCode::MovedPermanently || v.status == StatusCode::Found {
let location = String::from_utf8(v.headers
.get_raw("Location")
.unwrap()
.to_owned()
.pop()
.unwrap())
.unwrap();
body = self.get_body(&location).unwrap();
}
Ok(body)
}
Err(e) => Err(e),
}
}
pub fn post_body<'b>(&'b mut self,
url: &'b str,
request_body: &'b str)
-> Result<String, Error> {
let orig_url = Url::parse(url).unwrap();
let domain = orig_url.domain().unwrap();
let res = self.client
.post(url)
.body(&request_body.to_owned())
.headers(self.headers.clone())
.send();
let mut body = String::new();
match res {
Ok(mut v) => {
self.cookie_sync(&mut v.headers, domain.clone());
v.read_to_string(&mut body).unwrap();
if v.status == StatusCode::MovedPermanently || v.status == StatusCode::Found {
let location = String::from_utf8(v.headers
.get_raw("Location")
.unwrap()
.to_owned()
.pop()
.unwrap())
.unwrap();
body = self.post_body(&location, request_body).unwrap();
}
Ok(body)
}
Err(e) => Err(e),
}
}
pub fn delete<'b>(&'b mut self, url: &'b str) -> Result<String, Error> {
let orig_url = Url::parse(url).unwrap();
let domain = orig_url.domain().unwrap();
let res = self.client
.delete(url)
.headers(self.headers.clone())
.send();
let mut body = String::new();
match res {
Ok(mut v) => {
self.cookie_sync(&mut v.headers, domain.clone());
v.read_to_string(&mut body).unwrap();
Ok(body)
}
Err(e) => Err(e),
}
}
pub fn get_cookies(&self) -> Vec<CookiePair> {
let cookies = self.headers
.iter()
.filter_map(|header| {
if header.is::<Cookie>() {
header.value::<Cookie>()
} else {
None
}
})
.next()
.unwrap();
let clone_cookies: Vec<CookiePair> = cookies.iter().cloned().collect();
clone_cookies
}
pub fn set_cookie<'b>(&'b mut self,
name: String,
value: String,
domain: String,
path: String) {
let mut headers = Headers::new();
let mut cookie = CookiePair::new(name.to_owned(), value.to_owned());
cookie.path = Some(path.to_owned());
cookie.domain = Some(domain.to_owned());
headers.set(SetCookie(vec![cookie]));
self.cookie_sync(&mut headers, &domain);
}
}
#[test]
fn test_client() {
let mut client = Client::new();
client.change_useragent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"
.to_owned());
let body = client.get_body("http://google.com").unwrap();
println!("{}", body);
let body = client.post_body("http://google.com", "data").unwrap();
println!("{}", body);
}
| b47e2a41d07d97693b73fd8e19ad530b977aa9c1 | [
"Markdown",
"Rust",
"TOML"
] | 5 | Rust | nacika-ins/hyper_ex | d784bfbbeaccdfd9c72b75c298d585490cc5bc65 | e6e4bd55122dd2b6cce6f02ee355db7cdec9eb4c |
refs/heads/master | <repo_name>keerthi2222/Numberbased-sums<file_sep>/Fibonacci21.java
package numbersums;
public class Fibonacci21
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i;
System.out.println(" "+n1+" "+n2);
for(i=1;i<10;i++)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
<file_sep>/Sumofdigits5.java
package numbersums;
public class Sumofdigits5
{
public static void main(String args[])
{
int n,d,sum=0;
n=123451;
while(n>0)
{
d=n%10;
sum=sum+d;
n=n/10;
}
System.out.println("Sum of digits of the integer:"+sum);
}
}
<file_sep>/Sumofnaturalnum1.java
package numbersums;
public class Sumofnaturalnum1
{
public static void main(String args[])
{
int n=24;
int sum=0;
sum=n*(n+1)/2;
System.out.println(sum);
}
}
<file_sep>/Palindrome7.java
package numbersums;
public class Palindrome7
{
public static void main(String args[])
{
int n,d,sum=0;
n=12121;
int temp=n;
while(n>0)
{
d=n%10;
sum=sum*10+d;
n=n/10;
}
if(sum==temp)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}
<file_sep>/Disariumnumber.java
package numbersums;
public class Disariumnumber
{
public static void main(String args[])
{
int n=175,sum=0,d,temp;
int count=0;
temp=n;
while(n!=0)
{
count++;
n=n/10;
}
n=temp;
while(n>0)
{
d=n%10;
sum=sum+(int)Math.pow(d,count);
n=n/10;
count--;
}
if(sum==temp)
System.out.println(temp+" is a disarium number");
else
System.out.println(temp+" is not a disarium number");
}
}
| 0d106a823c978afeb03df45c10a103c444d11adc | [
"Java"
] | 5 | Java | keerthi2222/Numberbased-sums | 437081c5a184c720f7ff638dfd1693b7f797cbaf | 67136448dac754870cdaa7ce55d084346c8a84f9 |
refs/heads/master | <file_sep>
function count(input){
if(arguments.length != 1){
throw "provide a single arguemnt";
}
onesNzerosArray = input.split("");
if (onesNzerosArray.length != 10){
throw "invalid argument provide a 10 digit string"
}
let result = 0;
for (let i = 0; i < onesNzerosArray.length; i++){
if(onesNzerosArray[i] != 1 && onesNzerosArray[i] != 0){
throw "Invalid arguemnt, all digits of input must get 1s or 0s";
}
if(i ==4 && onesNzerosArray[i] == 1){
result += 50;
}
if(i ==5 && onesNzerosArray[i] == 1){
result += 5;
}
if(i ==3 && onesNzerosArray[i] == 1){
result += 10;
}
if(i ==6 && onesNzerosArray[i] == 1){
result += 1;
}
}
/*
0 - left pinky
1 - left ring
2 - left middle
3 - left index
4 - left thumb
5 - right thumb
6 - right index
7 - right middle
8 - right ring
9 - right pinky
*/
for (let left = 2, right = 7; right < 10; right ++, left --){
if(onesNzerosArray[left] ==1 ){
if(onesNzerosArray[left + 1 ] == 0 ){
throw "invalid number";
}
else {
result += 10;
}
}
if(onesNzerosArray[right] ==1){
if(onesNzerosArray[right - 1 ] ==0){
throw "invalid number";
}
else {
result += 1;
}
}
}
return result;
}
console.log(count("0000110000"));
| 58252b1499c00bc44fbd30808f9566273d81b793 | [
"JavaScript"
] | 1 | JavaScript | cap9090/counting | bfb55fed3bce1ef1cdfcb75bade6595fa7c30db0 | 61e1b4e2dc2b75521046ee79d976fa13532b0cb1 |
refs/heads/master | <repo_name>riyaarora65/CrudKoaApp<file_sep>/crudOperations.js
const koa = require("koa");
const Router = require("koa-router");
const Logger = require("koa-logger");
// const mongo = require('koa-mongo');
const BodyParser = require("koa-bodyparser");
const MongoClient = require('mongodb').MongoClient;
const app = new koa ();
const router = new Router();
const url = 'mongodb://localhost:27017';
let db;
app.use(Logger());
app.use(BodyParser()); //parses the json and url encoded data
MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if(err)
return console.log(err);
db = client.db("demodb")
app.db = db;
console.log('Connected to db');
});
// app.use(mongo({
// host: 'localhost',
// port: 27017,
// db: 'demodb'
// }));
//ctx is the Koa context that encapsulates the request and response objects into a single object
const fetchAllRecords = async (ctx) => {
try{
ctx.body = await ctx.app.db.collection("people").find().toArray();
}
catch(err)
{
ctx.status = err.status || 500;
ctx.body = err.message;
}
}
const createRecord = async (ctx) => {
try{
ctx.body = await ctx.app.db.collection("people").insertOne(ctx.request.body);
}
catch(err)
{
ctx.status = err.status || 500;
ctx.body = err.message;
}
}
const fetchRecord = async (ctx) => {
try{
ctx.body = await ctx.app.db.collection("people").findOne({"_id": mongo.ObjectId(ctx.params.id)})
}
catch(err)
{
ctx.status = err.status || 500;
ctx.body = err.message;
}
}
const updateRecord = async (ctx) => {
let documentQuery = {"_id": mongo.ObjectId(ctx.params.id)};
let valuesToUpdate = ctx.request.body;
try {
ctx.body = await ctx.app.db.collection("people").updateOne(documentQuery, {$set: valuesToUpdate});
}
catch(err)
{
ctx.status = err.status || 500;
ctx.body = err.message;
}
}
const deleteRecord = async (ctx) => {
let documentQuery = {"_id": mongo.ObjectId(ctx.params.id)};
try {
ctx.body = await ctx.app.db.collection("people").deleteOne(documentQuery);
}
catch(err)
{
ctx.status = err.status || 500;
ctx.body = err.message;
}
}
//Read
router.get("/people", fetchAllRecords);
//Create
router.post("/people", createRecord);
//Get by ID
router.get("/people/:id", fetchRecord);
//Update
router.put("/people/:id", updateRecord);
//Delete
router.delete("/people/:id", deleteRecord);
//returns seperate middleware for responding to options requests. This also handles 405 error Method Not Allowed and 501 Not Implemented
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('Server running on port 3000');
});
<file_sep>/index.js
const koa = require('koa');
const json = require('koa-json');
const KoaRouter = require('koa-router');
const path = require('path');
const render = require('koa-ejs');
const app = new koa();
const router = new KoaRouter();
app.use(json());
render(app, {
root: path.join(__dirname, 'views'), //view root directory
layout: 'layout', // global layout file
viewExt: 'html', // view file extension
cache: false, //cache compiled templates
debug: false
});
// ctx is the koa context that encapsulates node's request and response objects into a single object
// which provides methods for writing web app
const home = async (ctx) => {
await ctx.render('index', {
title: 'template params for title'
});
}
router.get('/', home);
router.get('/demo', ctx => (ctx.body = 'Using Router!!'))
// app.use(async ctx => (ctx.body = {msg: 'Hello World'}));
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
console.log('Website is live!') | 4e2572feab7afa71d8eef77e50e88aad2b5ea507 | [
"JavaScript"
] | 2 | JavaScript | riyaarora65/CrudKoaApp | aa4064bfd6523e01420a53652d5a7d64aeb1e937 | 3a18fd02e2bf3f491a157772a823c3df83540e78 |
refs/heads/master | <file_sep>package com.company;
public class Elem {
public String name;
public String typeOfConnection;
public Elem(String name){
this.name = name;
}
}
<file_sep>package com.company;
import java.util.HashMap;
import java.util.Map;
public class NodeStruct {
String name;
Map<String, String> atrs = new HashMap<String, String>();
public NodeStruct() {
name = "-";
}
public NodeStruct(String name) {
this.name = name;
}
public void addAtr(String key, String value) {
atrs.put(key, value);
}
public Map<String, String> getAtrs(){
return atrs;
}
public void clear() {
name = "-";
atrs.clear();
}
}
<file_sep>package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
String endSymb = "1";
//List<Elem> allElems = new ArrayList<Elem>();
//Map<String, Elem> allElems = new HashMap<String, Elem>();
//Graph graph = new Graph();
GraphMatrSmej myGraph = new GraphMatrSmej(10);
Scanner in = new Scanner(System.in);
while (endSymb != "0") {
System.out.println("0 - Выход; 1 - Ввод узла; 2 - Ввод связи; 3 - Вывод графа");
System.out.println("4 - Удалить узел; 5 - Удалить связь; 6 - Добавить атриьут;");
endSymb = in.nextLine();
switch (endSymb) {
case "0":
System.out.println("Выход");
endSymb = "0";
break;
case "1":
System.out.println("Введи имя нового понятия");
String curName = in.nextLine();
myGraph.addVertex(curName);
break;
case "2":
try {
System.out.println("Введите по типу: 'Понятие1' 'Понятие2' 'Связь'");
String elem1 = in.next();
String elem2 = in.next();
String connection = in.next();
in.nextLine();
myGraph.addNode(elem1, elem2, connection);
} catch (Exception e) {
System.out.println("Err: При создании связи");
endSymb = "0";
}
break;
case "3":
myGraph.printAll();
break;
case "4":
System.out.println("Введи имя Понятия для удаления");
String curNameToDel = in.nextLine();
myGraph.delVertex(curNameToDel);
break;
case "5":
System.out.println("Введи имя Связи для удаления");
curNameToDel = in.nextLine();
myGraph.delVertex(curNameToDel);
break;
case "6":
System.out.println("Введите по типу: 'Понятие1' 'Понятие2' 'Атрибут' 'Значение'");
String elem1 = in.next();
String elem2 = in.next();
String atr1 = in.next();
String atr2 = in.next();
in.nextLine();
myGraph.addAtr(elem1, elem2, atr1, atr2);
break;
default:
System.out.println("Ошибка ввода");
}
}
in.close();
}
}
| 5b492efa75d7bfc9f4cf8cfffec666a692320807 | [
"Java"
] | 3 | Java | KozinOleg97/Lab_2_AI | 73034b6ac790749bccbe3e9769400c6c4afe2ef6 | c07c2bed3520adc47077e0b5994ec804c3aa3a99 |
refs/heads/master | <file_sep>all:
g++ -g -std=c++11 Interpreter.cpp Parser.cpp run.cpp UserFunction.cpp -o Interpreter
test:
g++ -g -std=c++11 Interpreter.cpp Parser.cpp tests.cpp UserFunction.cpp -o tests
clean:
rm -f *.out *.exe
rm -r *.dSYM
<file_sep>#include "Interpreter.h"
int main() {
Interpreter interpreter;
while(true) {
std::string line;
cin >> line;
// std::cout << "Result" << "\n";
double val = interpreter.computeInfix(line);
std::cout << "Result: "<< val << "\n";
}
return 0;
}
<file_sep><h4>The following was a homework project</h4>
We had to build a JavaScript Interpreter based on the specified details.
------------------------------------------------------------------------
<span class="c14"></span>
<span class="c2 c5"><h4>The Interpreter</h4></span>
<span class="c14">CSE 250 Data Structures in C++ - Fall 2015</span>
------------------------------------------------------------------------
<span class="c2 c6"></span>
<span></span>
<span></span>
<span>In this homework you will write an interpreter for the web
programming language JavaScript. Writing a full interpreter for the
language would be a monumental task, so we will implement a small subset
of the languages features with many simplifying assumptions. For more
information about the language </span><span
class="c0">[here](https://www.google.com/url?q=http://www.w3schools.com/js/default.asp&sa=D&usg=AFQjCNEzs0TdJQBNNYypgptwqW69VwJtrg)</span><span> is
an excellent JavaScript tutorial. It’s not required to understand
JavaScript (beside very basic syntax) to complete this assignment,
though the tutorial contains editors where you can run code in a browser
and compare the output with that of your interpreter which may prove
useful.</span>
<span></span>
<span>The following language features will be interpreted in this
homework:</span>
<span></span>
- <span>Tracking variables (numbers only)</span>
- <span>Printing to a document using “document.write”</span>
- <span>Computing infix expressions including parentheses</span>
- <span>Track and call user-defined functions</span>
- <span>Interpret if and else statements</span>
<span></span>
<span>The following is a list of simplifying assumptions for this
assignment. These are not restrictions of JavaScript itself, but we will
not violate these while testing during grading. The intent is to limit
the amount of tedious string parsing involved in this assignment so you
can spend more time on the data structures and logic of the project.
This list might grow as questions arise:</span>
<span></span>
- <span>Functions only use local variables that are defined within the
function or appear in the parameter list</span>
- <span>Variable names and function names cannot begin with a
keyword</span>
- <span>All variables will be numbers which can be stored as C++
doubles</span>
- <span>document.write will always be called with a single variable or
a single string</span>
- <span>No direct negative values (can have “0-5” not “-5”) </span>
- <span>Return is always a single variable (can have “return x” but no
“return 1”)</span>
- <span>No function calls in infix or if statements. All function
calls will be on a line of its own, with or without an assignment
(“var y = myFunction(x)”). </span>
- <span>No immediately nested functions (can’t have
“function1(function2(five))”)</span>
- <span>Only number variables for function calls (can’t have
“function(5)” )</span>
- <span>All JavaScript code can be assumed to be well-formed (no
testing with syntax errors)</span>
- <span>The opening ‘{‘ is always on the same line as the function,
if, or else that it opens</span>
- <span>Can assume } is on a line by itself except for if
statements</span>
- <span>When a } closes an if statement it is either “}”, “} else if
{“ or “} else {“</span>
- <span>Comparisons are only \> and \< (no ||, &&, ==)</span>
- <span>Comparisons always compare exactly 2 variables</span>
<span></span>
<span>Some string parsing code is provided in the </span><span
class="c7">Parser</span><span> class. While you don’t need to understand
everything in </span><span class="c8">Parser.cpp</span><span>, you
should read </span><span class="c8">Parser.h</span><span> to know how to
use the provided functions. It’s not required that you use any of these
functions, though they can significantly reduce the amount of string
parsing you’ll need to implement. Beyond this, there is much freedom in
how you implement the interpreter. This will be a fairly large program
and you will need to make several design decisions while coding. There
are a few suggestions in the code to help you get started, though you
can go in different direction if you’d like. </span>
<span></span>
<span>The provided Makefile compiles your code into an executable names
</span><span class="c8">Interpreter</span><span>. The usage of this
executable is “</span><span class="c8">./Interpreter \<inputFile.js\>
\<outputFile\></span><span>”</span><span>.</span>
<span></span>
<span>Relevant code can be found in the course repository: </span><span
class="c0">[https://bitbucket.org/hartloff/cse250-fall2015/src/1439472551c0/homework/Interpreter/?at=master](https://www.google.com/url?q=https://bitbucket.org/hartloff/cse250-fall2015/src/1439472551c0/homework/Interpreter/?at%3Dmaster&sa=D&usg=AFQjCNHt4DR5WL3yBdbFHypFdgWU9bhjJA)</span><span> </span>
<span></span>
<span></span>
------------------------------------------------------------------------
<span></span>
<span></span>
<span class="c2 c14"><strong><em>Part 1</em></strong></span>
<span></span>
<span>Your interpreter must have the following functionality:</span>
<span></span>
- <span>Declare number variables using the “var” keyword</span>
- <span>Assign values to variables using infix notation to
compute +,-,\*,/ on numbers with or without parenthesis</span>
- <span>Output strings and numbers to an output file using
“document.write”</span>
<span></span>
<span></span>
<span class="c2 c14"><strong><em>Part 2</em></strong></span>
<span></span>
<span>Your interpreter must have the functionality from part 1 as well
as the following:</span>
<span></span>
- <span>Interpret and call user-defined functions using the “function”
keyword</span>
- <span>Handle nested function calls</span>
<span></span>
<span></span>
<span class="c2 c14"><strong><em>Part 3</em></strong></span>
<span></span>
<span>Your interpreter must have the functionality from parts 1 and 2 as
well as the following:</span>
<span></span>
- <span>The “if” statement with “else” and “else if”</span>
- <span>Handle nested if/else blocks</span>
<span></span>
<span></span>
<span class="c2 c6">Submission</span>
<span></span>
<span>Submit </span><span class="c8">Interpreter.cpp, Interpreter.h,
UserFunction.cpp, </span><span>and</span><span
class="c8"> UserFunction.h</span><span>. You can define more
classes and functions as long as they are contained in these 4 files. Do
not edit </span><span class="c8">Makefile, Parser.cpp, Parser.h,
run.cpp, </span><span>or</span><span class="c8"> run.h.</span>
<file_sep>#include "Interpreter.h"
void Interpreter::interpretScript(ifstream& inputFile, ofstream& outputFile, int lineNumber) {
string lineFromFile;
theStack.push_back(new std::map<string, double>);
// int lineNumber = 0;
set_io(inputFile,outputFile);
while (getline(*_inputFile, lineFromFile))
{
lineNumber++;
LINE_TYPE lineType = getLineType(lineFromFile); // Check Parser.h for the different line types
// cout << "line " << lineNumber << " is type: " << lineType << endl;
// Use your interpreter to execute each line
switch (lineType) {
case BLANK_LINE:
break;
case DEFINE_VAR:
defineVariable(lineFromFile);
break;
case USER_DEFINED:
handleUserDefined(lineFromFile);
break;
case DOC_WRITE:
writeToOutput(lineFromFile,*_outputFile);
break;
case FUNCTION_DEF:
defineFunction(lineFromFile,*_inputFile);
break;
case RETURN:
break;
case END_BLOCK:
break;
case IF:
handleControlFlow(lineFromFile, *_inputFile);
break;
case ELSE:
break;
case ELSE_IF:
break;
}
}
// write the result from the return statement of the program into the output file
// outputFile << "output of the document.write lines";
}
double Interpreter::interpretLines(std::vector<std::string> lines) {
// theStack.push_back(&varList);
for (std::vector<std::string>::iterator it = lines.begin(); it < lines.end(); it++){
std::string lineFromFile = *it;
std::cout << *it << "\n";
LINE_TYPE lineType = getLineType(lineFromFile);
// cout << "line " << lineNumber << " is type: " << lineType << endl;
switch (lineType) {
case BLANK_LINE:
break;
case DEFINE_VAR:
defineVariable(lineFromFile);
break;
case USER_DEFINED:
handleUserDefined(lineFromFile);
break;
case DOC_WRITE:
writeToOutput(lineFromFile,*_outputFile);
break;
case FUNCTION_DEF:
break;
case RETURN:
{
getNextSymbol(lineFromFile);
double ret = computeInfix(lineFromFile);
theStack.pop_back();
return ret;
}
case END_BLOCK:
break;
case IF:
{
std::vector<std::string> vec(it+1,lines.end());
handleControlFlow(lineFromFile, vec);
break;
}
case ELSE:
break;
case ELSE_IF:
break;
}
}
return NAN;
}
void Interpreter::set_io(ifstream& inputFile, ofstream& outputFile) {
_inputFile = &inputFile;
_outputFile= &outputFile;
}
//NOTE Done
void Interpreter::defineVariable(string line , bool defined) {
// std::cout << line << "\n";
if (!defined)
{
getNextSymbol(line);
}
line.erase(std::remove(line.begin(),line.end(),' '),line.end());
std::cout << line << "\n";
// std::vector<string>& v = tokenize(line,",");
std::vector<std::string> v;
v.push_back(line);
// std::cout << v[0] << ' ' << v[1] << "\n";
for (std::vector<string>::iterator it = v.begin(); it < v.end(); it++) {
if (it->back() == '=') {
std::cerr << "Invalid syntax" << std::endl;
exit(1);
}
// cout << *it;
std::vector<string> vect = tokenize(*it , "=");
// std::cout << vect[1] <<' '<< /*vect[1] <<*/ "\n";
if (vect.size() == 1 && !defined) {
theStack.back()->insert(std::pair<std::string,double>(vect[0],NAN));
} else if (vect.size() == 1 && defined)
{
std::cerr << "Invalid syntax" << "\n";
exit(1);
} else {
(*theStack.back())[vect[0]] = computeInfix(vect[1]);
// std::cout << vect[0] << "=" << vect[1] << "\n";
// theStack.back()->insert(pair<std::string,double>(vect[0],computeInfix(vect[1])));
}
// std::cout << vect[0] << ' ' << computeInfix(vect[1]) << "\n";
}
}
//NOTE Done
void Interpreter::writeToOutput(string line , ofstream& output) {
getNextSymbol(line);
string outputLine = "";
double outputNum;
if (getNextSymbol(line) == "(")
{
if (line[0] == '\"')
{
getNextSymbol(line);
int x = line.find_first_of("\"");
outputLine = line.substr(0,x);
line.erase(0,x+1);
if(getNextSymbol(line) != ")")
{
std::cerr << "Bad syntax" << "\n";
exit(1);
}
output << outputLine;
return;
} else {
int x = line.find_last_of(")");
outputNum = computeInfix(line.substr(0,x));
output << outputNum;
return;
}
}
}
//NOTE Done
void Interpreter::handleUserDefined(string line) {
std::string lineCopy = line;
switch (isUserDefined(getNextSymbol(lineCopy)))
{
case 1:
defineVariable(line,true);
break;
case 2:
int openParen = line.find_first_of("(");
int closeParen = line.find_last_of(")");
string parameterList = line.substr(openParen+1,closeParen-openParen-1);
call(functionMap[getNextSymbol(line)],parameterList);
break;
}
}
//NOTE Done
void Interpreter::defineFunction(std::string header , ifstream& inputFile) {
getNextSymbol(header);
string name = getNextSymbol(header);
int openParen = header.find_first_of("(");
int closeParen = header.find_last_of(")");
string parameterList = header.substr(openParen+1,closeParen-openParen-1);
std::cout << parameterList << "\n";
std::vector<string> lines;
std::stack<string> brackets;
std::string lineFromFile;
brackets.push("{");
LINE_TYPE lineType;
while(getline(inputFile,lineFromFile) && getLineType(lineFromFile) != END_BLOCK && !brackets.empty()) {
lineType = getLineType(lineFromFile);
if (lineType == END_BLOCK)
{
brackets.pop();
continue;
}
lines.push_back(lineFromFile);
}
std::vector<std::string> vec = tokenize(parameterList,",");
UserFunction* func = new UserFunction(name,vec,lines);
functionMap.insert(std::pair<std::string,UserFunction* >(name,func));
}
//TODO Handle control statements
void Interpreter::handleControlFlow(std::string header, ifstream& inputFile) {
std::stack<std::string> brackets;
std::vector<std::string> definition;
std::string condition = header;
bool evaluated = false;
bool evalCondition = evaluateCondition(condition);
brackets.push("{");
std::string line;
while (!brackets.empty() && getline(inputFile, line) )
{
// std::cout << evaluated << ' ';
LINE_TYPE lineType = getLineType(line);
if (lineType == END_BLOCK)
{
brackets.pop();
continue;
} else if (lineType == IF) {
brackets.push("{");
} else if (lineType == ELSE_IF || lineType == ELSE) {
brackets.pop();
if (brackets.empty())
{
if (lineType == ELSE_IF)
{
evaluated = evalCondition;
evalCondition = evaluateCondition(line);
} else if (lineType == ELSE) {
evaluated = evalCondition;
evalCondition = true;
}
continue;
}
brackets.push("{");
}
if (evalCondition == true && evaluated == false)
{
definition.push_back(line);
}
}
interpretLines(definition);
return;
}
void Interpreter::handleControlFlow(std::string header, std::vector<std::string> lines) {
std::stack<std::string> brackets;
std::vector<std::string> definition;
std::string condition = header;
bool evaluated = false;
bool evalCondition = evaluateCondition(condition);
brackets.push("{");
std::string line;
for (std::vector<std::string>::iterator it = lines.begin(); it < lines.end() && !brackets.empty(); it++){
// std::cout << evaluated << ' ';
LINE_TYPE lineType = getLineType(line);
if (lineType == END_BLOCK)
{
brackets.pop();
continue;
} else if (lineType == IF) {
brackets.push("{");
} else if (lineType == ELSE_IF || lineType == ELSE) {
brackets.pop();
if (brackets.empty())
{
if (lineType == ELSE_IF)
{
evaluated = evalCondition;
evalCondition = evaluateCondition(line);
} else if (lineType == ELSE) {
evaluated = evalCondition;
evalCondition = true;
}
continue;
}
brackets.push("{");
}
if (evalCondition == true && evaluated == false)
{
std::cout << condition << "---->" << evalCondition << "," << evaluated << "\n";
definition.push_back(line);
}
}
interpretLines(definition);
}
//NOTE Done
double Interpreter::call(UserFunction* f,std::string args) {
std::vector<std::string> argStrings = tokenize(args,",");
std::vector<std::string> paramaterNames = f->getParameterList();
if (argStrings.size() != paramaterNames.size())
{
std::cerr << "Invalig number of arguments" << "\n";
exit(1);
}
std::map<std::string, double> localVariables;
for (int i = 0; i < argStrings.size(); ++i)
{
localVariables.insert(pair<std::string,double>(paramaterNames[i],computeInfix(argStrings[i])));
}
theStack.push_back(&localVariables);
std::vector<std::string> lines = f->getFunctionDefinition();
return interpretLines(lines);
}
//NOTE Done
double Interpreter::computeInfix(string rhs) {
stack<double> operandStack;
stack<string> operatorStack;
// std::cout << "[START]" << "\n";
string line = rhs;
string symbol = getNextSymbol(line);
// std::cout << "[CHECK]" << "\n";
// std::cout << symbol << '\n';
// std::cout << " XXXXXX " << "\n";
if (isUserDefined(symbol) == 2)
{
int openParen = rhs.find_first_of("(");
int closeParen = rhs.find_last_of(")");
string args = rhs.substr(openParen+1,closeParen-openParen-1);
return call(functionMap[symbol], args);
}
while(symbol != ""){
// std::cout << "1";
if(isNumber(symbol)) {
operandStack.push(stod(symbol));
} else if (isOperator(symbol)) {
while(!operatorStack.empty() && opPrecedence(operatorStack.top()) >= opPrecedence(symbol))
{
double y = operandStack.top();
operandStack.pop();
double x = operandStack.top();
operandStack.pop();
operandStack.push(evaluateOperation(x,y,operatorStack.top()));
operatorStack.pop();
}
operatorStack.push(symbol);
} else if (symbol == "("){
operatorStack.push(symbol);
} else if (symbol == ")"){
while (operatorStack.top() != "(")
{
if (operatorStack.empty())
{
std::cerr << "Not a well formed expression" << "\n";
exit(1);
}
double y = operandStack.top();
operandStack.pop();
double x = operandStack.top();
operandStack.pop();
operandStack.push(evaluateOperation(x,y,operatorStack.top()));
operatorStack.pop();
}
operatorStack.pop();
} else if (isUserDefined(symbol) == 1){
operandStack.push(evaluateVariable(symbol));
}
symbol = getNextSymbol(line);
}
// std::cout << "\n" << "2" << "\n";
// std::cout << "Top : " << operandStack.top() << "\n";
while(!operatorStack.empty()) {
// std::cout << "3" ;
if (operatorStack.top() == "(")
{
std::cerr << "Not a well formed expression" << "\n";
exit(1);
}
double y = operandStack.top();
operandStack.pop();
double x = operandStack.top();
operandStack.pop();
operandStack.push(evaluateOperation(x,y,operatorStack.top()));
operatorStack.pop();
}
// std::cout << " XXXXXX " << "\n";
std::cout << " <===================== "<<operandStack.top() << "\n";
return operandStack.top();
}
bool Interpreter::isOperator(string sym) {
// char sym = symbol.c_str()[0];
return (sym == "+" || sym == "-" || sym == "*" || sym == "/");
}
int Interpreter::opPrecedence(string symbol) {
char sym = symbol.c_str()[0];
switch (sym)
{
case '*':
return 3;
break;
case '/':
return 3;
break;
case '+':
return 2;
break;
case '-':
return 2;
break;
default:
return 0;
break;
}
}
int Interpreter::isUserDefined(string symbol) {
for(std::vector<std::map<std::string, double>* >::iterator it = theStack.begin();it < theStack.end();it++){
if ((*it)->count(symbol) > 0) return 1;
}
if (functionMap.count(symbol) > 0) return 2;
return 0;
}
double Interpreter::evaluateVariable(string symbol) {
for(std::vector<std::map<std::string, double>* >::iterator it = theStack.begin();it < theStack.end();it++){
int count = (*it)->count(symbol);
if (count > 0) {
std::map<std::string, double>::iterator point = (*it)->find(symbol);
// std::cout << "In stack: " << point->first << ' ' << point->second << "\n";
if (std::isnan(point->second) == false)
{
return point->second;
}
}
}
std::cerr << "Use of uninitialized variable or improper values: " << symbol << "\n";
std::cout << "Stack Trace:" << "\n";
for(std::vector< std::map<std::string, double> * >::iterator vectIter = theStack.begin(); vectIter < theStack.end(); vectIter++) {
for(std::map<std::string, double>::iterator mapIter = (*vectIter)->begin();mapIter != (*vectIter)->end(); mapIter++){
std::cout << mapIter->first << ' '<< mapIter->second << "\n";
}
}
exit(1);
}
double Interpreter::evaluateOperation(double x,double y, std::string symbol) {
char op = symbol.c_str()[0];
// std::cout << "(x,y) = " << x << y << "\n";
switch (op)
{
case '*':
return x * y;
break;
case '/':
return x/y;
break;
case '+':
return x+y;
break;
case '-':
return x-y;
break;
default:
std::cerr << "Invalid expression" << "\n";
exit(1);
break;
}
}
bool Interpreter::evaluateCondition(std::string header) {
int openParen = header.find_first_of("(");
int closeParen = header.find_last_of(")");
std::string condition = header.substr(openParen+1, closeParen-openParen-1);
std::string op;
std::vector<std::string> operands;
operands = tokenize(condition, "<");
op = "<";
if (operands.size() == 1)
{
operands = tokenize(condition, ">");
op = ">";
}
// std::cout << header << "----->";
bool ret = false;
double x = computeInfix(operands[0]);
double y = computeInfix(operands[1]);
if (op == ">")
{
ret = x > y;
} else if (op == "<") {
ret = x < y;
}
std::cout << x << op << y << "----->" << ret << "\n";
return ret;
}
<file_sep>#ifndef UNTITLED_INTERPRETER_H
#define UNTITLED_INTERPRETER_H
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <utility>
#include "UserFunction.h"
#include "Parser.h"
using namespace std;
class Interpreter {
private:
vector< map<string, double> * > theStack;
map<string, UserFunction* > functionMap; // a map of user defined functions
// stack to remember nesting of if blocks
// stack<Invocation *> invocationPile;
ifstream* _inputFile;
ofstream* _outputFile;
void set_io(ifstream& , ofstream&);
void defineVariable(string,bool defined = false);
void writeToOutput(string,ofstream&);
void handleUserDefined(string);
void defineFunction(std::string,ifstream&);
void handleControlFlow(std::string, ifstream&);
void handleControlFlow(std::string, std::vector<std::string>);
bool isOperator(string);
int opPrecedence(string);
int isUserDefined(string);
double evaluateVariable(string);
double evaluateOperation(double , double , std::string);
bool evaluateCondition(std::string);
public:
Interpreter():_inputFile(NULL),_outputFile(NULL){};
void interpretScript(ifstream&, ofstream&, int lineNumber = 0);
double interpretLines(std::vector<string>);
double computeInfix(string); // separate function for computing infix notation
double call(UserFunction*,std::string);
};
#endif //UNTITLED_INTERPRETER_H
<file_sep>#include "UserFunction.h"
// UserFunction::UserFunction(string& name, std::vector<std::string>& parameters, std::vector<string>& lines) : _name(name), _functionDefinition(lines){
// for (std::vector<std::string>::iterator it = parameters.begin(); it < parameters.end(); it++) {
// _parameterList.push_back(std::pair<std::string,double>(*it,NAN));
// }
// }
// double UserFunction::call(std::vector<double> arguments) {
// if (_parameterList.size() != arguments.size())
// {
// std::cerr << "Invalid number of arguments" << "\n";
// exit(1);
// }
//
// std::map<std::string, double> variables;
//
// for (int i = 0; i < arguments.size(); ++i)
// {
// _parameterList[i].second = arguments[i];
// variables.insert(_parameterList[i]);
// }
// return
// }
UserFunction::UserFunction (const std::string& name,const std::vector<std::string>& parameters, const std::vector<std::string>& lines) : _name(name),_parameterList(parameters),_functionDefinition(lines) {}
std::string UserFunction::getName(){return _name;};
std::vector<std::string> UserFunction::getParameterList(){return _parameterList;};
std::vector<std::string> UserFunction::getFunctionDefinition(){return _functionDefinition;}
<file_sep>#ifndef CSE250_FALL2015_USERFUNCTION_H
#define CSE250_FALL2015_USERFUNCTION_H
#include <vector>
#include <string>
#include <map>
#include <cmath>
#include <utility>
using namespace std;
// This class is not required, but might be helpful in writing your interpreter
class UserFunction {
private:
std::string _name;
std::vector<std::string> _parameterList;
std::vector<string> _functionDefinition;
public:
UserFunction(const string&,const std::vector<string>&,const std::vector<string>&);
// double call(vector<double>);
std::string getName();
std::vector<std::string> getParameterList();
std::vector<std::string> getFunctionDefinition();
};
#endif //CSE250_FALL2015_USERFUNCTION_H
| 2cb8f342e127109738c84d79179d17bd17136953 | [
"Markdown",
"Makefile",
"C++"
] | 7 | Makefile | anandbalakrishnan/Interpreter | 9f0d2e91d98c355b63398ccba9e4ef81b0e43154 | 5f3789af3e0f647bc860d6a004cc8fdbe7178b69 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
private AndroidJavaObject jo;
// Use this for initialization
void Start () {
AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
jo = jc.GetStatic<AndroidJavaObject> ("currentActivity");
}
public void showscreen(){
jo.Call ("onRTSPVRLibClicked");
}
// Update is called once per frame
void Update () {
}
}
<file_sep>This is the unity part for VR
| 375defaa9fa01a9a44521dbad168fb964b4896f3 | [
"Markdown",
"C#"
] | 2 | C# | gengwb/VR_VLC_Unity | ef26519446bd650fd19fcadd233611e5f0183eba | 5ba1cbd7534d893658093817f5a0d8e2705a25b8 |
refs/heads/master | <repo_name>akandt/classes-lab<file_sep>/main.js
const productArray = [
{
brand: 'Superior',
item: 'DRT-3500',
quantity: 11
},
{
brand: 'Empire',
item: 'Boulevard',
quantity: 7
},
{
brand: 'Montigo',
item: 'Delray',
quantity: 5
},
{
brand: 'Napoleon',
item: 'Vector',
quantity: 3
},
];
class WoodlandDirect {
constructor(warehouse) {
this.inventory = warehouse;
}
// Get List of Hearths in Inventory
getInventory() {
console.log('Fireplace inventory:', this.inventory);
}
// Find item
getItem(item){
let hasItem = false;
for (let i = 0; i < this.inventory.length; i++) {
if (this.inventory[i].item === item && this.inventory[i].quantity > 0){
hasItem = true;
}
}
if (hasItem){
console.log('We have it in stock');
} else {
console.log(`We're out of that item`);
}
}
// Add Hearth to Inventory
addHearthToInventory(brand, item) {
this.inventory.push({ brand, item });
}
// Remove Hearth from Inventory
removeHearthFromInventory(item) {
for (let i = 0; i < this.inventory.length; i++) {
if (this.inventory[i].item === item) {
this.inventory.splice(i, 1);
}
}
console.log("This is the new hearth list", this.inventory);
}
// Edit Hearth in Inventory
editHearth(item, newQuantity) {
for (let i = 0; i < this.inventory.length; i++) {
if (this.inventory[i].item === item) {
this.inventory[i].quantity = newQuantity;
}
console.log("This is the new quantity", this.inventory[i].quantity);
}
}
}
const cuiStore = new WoodlandDirect(productArray);
cuiStore.editHearth('Delray', 30); | af9e3d8b15557e03db095d69e79869a93a52e103 | [
"JavaScript"
] | 1 | JavaScript | akandt/classes-lab | 063a4ded99c922cbe2a3bf08053f6d5923e7312f | 44847a9aed4e86bf9b0ed232e6ae30d9ba97e594 |
refs/heads/master | <file_sep>#include <Arduino.h>
#include <FastLED.h>
#define LED_COUNT 1
#define DATA_PIN 8
#define DELAY_TIME 1000
CRGB leds[LED_COUNT];
void setup() {
delay( 3000 ); // power-up safety delay
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, LED_COUNT);
FastLED.setBrightness(10);
}
void loop() {
leds[0] = CRGB::LightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MediumSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DimGrey;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DarkSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::AliceBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::SeaGreen;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::SpringGreen;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MidnightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::SteelBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::PapayaWhip;
FastLED.show();
delay(random(50, 800));
leds[0] = CRGB::LightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MediumSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DimGrey;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DarkSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::AliceBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::SpringGreen;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Blue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MidnightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::SteelBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::PapayaWhip;
FastLED.show();
delay(random(50, 800));
leds[0] = CRGB::LightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MediumSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DimGrey;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DarkSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::AliceBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MediumBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Blue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MidnightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::SteelBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::PapayaWhip;
FastLED.show();
delay(random(50, 800));
leds[0] = CRGB::LightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MediumSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DimGrey;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::DarkSlateBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::AliceBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MediumBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Aquamarine;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::Blue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::MidnightBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::SteelBlue;
FastLED.show();
delay(random(40, 110));
leds[0] = CRGB::PapayaWhip;
FastLED.show();
delay(random(50, 800));
leds[0] = CRGB::MediumSlateBlue;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::Violet;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::SeaGreen;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::Aqua;
FastLED.show();
delay(random(100, 200));
leds[0] = CRGB::FireBrick;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::SpringGreen;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::Honeydew;
FastLED.show();
delay(random(100, 200));
leds[0] = CRGB::Aqua;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::HotPink;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::SpringGreen;
FastLED.show();
delay(random(90, 110));
leds[0] = CRGB::CornflowerBlue;
FastLED.show();
delay(random(500, 1800));
leds[0] = CRGB::PapayaWhip;
FastLED.show();
delay(random(50, 500));
}
// FAVORITE COLORS: PapayaWhip(White), MediumSlateBlue, Aqua, CornflowerBlue, FireBrick, HotPink, Honeydew, SeaGreen, Violet, SpringGreen
// **************** FAVORITE COLOR SPARKLE PROGRAM
// leds[0] = CRGB::MediumSlateBlue;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::Violet;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::SeaGreen;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::Aqua;
// FastLED.show();
// delay(random(100, 200));
//
// leds[0] = CRGB::FireBrick;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::SpringGreen;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::Honeydew;
// FastLED.show();
// delay(random(100, 200));
//
// leds[0] = CRGB::Aqua;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::HotPink;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::SpringGreen;
// FastLED.show();
// delay(random(90, 110));
//
// leds[0] = CRGB::CornflowerBlue;
// FastLED.show();
// delay(random(500, 1800));
//
// leds[0] = CRGB::PapayaWhip;
// FastLED.show();
// delay(random(50, 500));
// ***************** BLUE SPARKLE/FIREWORK PROGRAM
// leds[0] = CRGB::LightBlue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::MediumSlateBlue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::DimGrey;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::DarkSlateBlue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::AliceBlue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::Aquamarine;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::MediumBlue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::Aquamarine;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::Blue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::MidnightBlue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::SteelBlue;
// FastLED.show();
// delay(random(40, 110));
//
// leds[0] = CRGB::PapayaWhip;
// FastLED.show();
// delay(random(50, 800));
| 940ca39ce21e4aefe595f55e7d927146ee7b1bb3 | [
"C++"
] | 1 | C++ | that-jill/cyborg | 3c0822c85494510ffd66efe3a6ba7a46ea6d9e06 | d1999137549c353580b33e525e52910a73fc12f0 |
refs/heads/master | <file_sep>let btn=document.querySelector('.btn-send');
let s=document.querySelector('.appen');
let f=document.querySelector('.form');
btn.addEventListener('click',function(){
let d=document.createElement('div');
let t=document.createElement('button');
t.innerHTML="Complete";
t.classList.add('rahmabtn');
let t1=document.createElement('button');
t1.innerHTML="Delete";
t1.classList.add('rahmabtn1')
d.append(t);
d.append(t1);
// if(f.value!="")
// let val= document.createElement('p');
// console.log(val);
let ss= (f.value);
// let pop= (val.innerHTML=ss);
d.append(ss);
s.append(d);
t.addEventListener('click',function(){
t.innerHTML="Undo";
d.style.textDecoration="line-through";
})
// }
t1.addEventListener('click',function(){
d.remove();
})
}) | 95a8f966b1b15571deab527e092fbd9b42ff8ec9 | [
"JavaScript"
] | 1 | JavaScript | FriouiRahma/To-do-app | 727acaa2d4afd22f321ce0f90f86f7512518f1e7 | d284bd6843f6881512ec1ec3dbf47d2adf167630 |
refs/heads/master | <repo_name>bhadreshkumarghevariya/AndroidApps<file_sep>/Practical_List/Practical1/App1/app/src/main/java/com/example/app1/MainActivity.java
package com.example.app1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView txtUniAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
controlInitialization();
//String address= getString(R.string.txtUniversityAddress);
//txtUniAddress.setText(address);
}
private void controlInitialization()
{
txtUniAddress = findViewById(R.id.txtUniAddress);
}
}<file_sep>/Practical_List/Practical3/App1/app/src/main/java/com/example/app1/MainActivity2.java
package com.example.app1;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity {
TextView txtName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
controlInitialization();
String sname = getIntent().getStringExtra("studentName");
Toast.makeText(getApplicationContext(),sname,Toast.LENGTH_LONG).show();
txtName.setText(sname);
}
private void controlInitialization() {
txtName = findViewById(R.id.txtName);
}
}<file_sep>/Practical_List/Practical3/App3/app/src/main/java/com/example/app3/MainActivity.java
package com.example.app3;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioGroup rbGrpCourses;
RadioButton rbBSCIT,rbMSCIT,rbINTMSCIT,rbBCA;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
controlInitialization();
onButtonClick();
}
private void controlInitialization()
{
rbGrpCourses = findViewById(R.id.rbGrpCourses);
rbBCA = findViewById(R.id.rbBCA);
rbMSCIT = findViewById(R.id.rbMSCIT);
rbBSCIT = findViewById(R.id.rbBSCIT);
rbINTMSCIT = findViewById(R.id.rbINTMSCIT);
}
private void onButtonClick()
{
rbGrpCourses.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId)
{
case R.id.rbBCA:
Toast.makeText(getApplicationContext(),"You selected "+rbBCA.getText().toString(),Toast.LENGTH_LONG).show();
break;
case R.id.rbBSCIT:
Toast.makeText(getApplicationContext(),"You selected "+rbBSCIT.getText().toString(),Toast.LENGTH_LONG).show();
break;
case R.id.rbMSCIT:
Toast.makeText(getApplicationContext(),"You selected "+rbMSCIT.getText().toString(),Toast.LENGTH_LONG).show();
break;
case R.id.rbINTMSCIT:
Toast.makeText(getApplicationContext(),"You selected "+rbINTMSCIT.getText().toString(),Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(),"Nothing Happen",Toast.LENGTH_LONG).show();
}
}
});
}
}<file_sep>/Practice/App2/app/src/main/java/com/example/app2/MainActivity.java
package com.example.app2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText edtTxtName,edtTxtEmail,edtTxtBirthDate,edtTxtPassword,edtTxtAddress,edtTxtWebsite;
TextView txtShowData;
Button btnStoreData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
controlInitialization();
}
private void controlInitialization()
{
edtTxtName = findViewById(R.id.edtTxtName);
edtTxtEmail = findViewById(R.id.edtTxtEmail);
edtTxtBirthDate = findViewById(R.id.edtTxtBirthDate);
edtTxtPassword = findViewById(R.id.edtTxtPassword);
edtTxtAddress = findViewById(R.id.edtTxtAddress);
edtTxtWebsite = findViewById(R.id.edtTxtWebsite);
txtShowData = findViewById(R.id.txtShowData);
btnStoreData = findViewById(R.id.btnStoreData);
}
public void storeData(View view)
{
String data = "Name :"+edtTxtName.getText().toString() +"\n Email Address :"+edtTxtEmail.getText().toString()+"\n Birth Date :"+edtTxtBirthDate.getText().toString()+"\n Password :"+edtTxtPassword.getText().toString()+"\n Address :"+edtTxtAddress.getText().toString()+"\n WebSite :"+edtTxtWebsite.getText().toString();
txtShowData.setText(data);
Toast t1 = Toast.makeText(getApplicationContext(),data,Toast.LENGTH_LONG);
t1.show();
}
} | b2086538cc81871527e608076325f49b2ae4b9e8 | [
"Java"
] | 4 | Java | bhadreshkumarghevariya/AndroidApps | c4a8d54719ad746ccf35781ccafdefd0cef0508e | b98dd289771660e1cf79a80303261b601cf34169 |
refs/heads/master | <file_sep># Pandemic-Simulation
This program was inspired by the 2020 coronavirus, and I created it to act as a helpful visualization for how isolation is extremely important in preventing the spread of a disease.
<file_sep>"""
Program: Coronavirus Simulation
Author: <NAME>
Date: March 18, 2020
I created this program in light of the coronavirus epidemic. I was inspired by
the vast confusion people had surrounding the need for isolation. I felt that by
creating this program, it could better teach people about why isolation is so
important in preventing the spread of a virus. Plans on expanding in the future
could involve creating a special member of the People class (compromised person)
to show the effectiveness of herd immunity on protecting a member of the
population who can't be relied on recovering from a disease on their own. I can
also expand the program to collect data from different iterations at different
values of infected and isolation to then graph in Matlab to better depict the
effect of isolation.
"""
import sys
import pygame
from pygame.locals import *
from random import randint
import time
# Game Settings
print("Please enter an isolation constant (0-100):")
isolation = float(input())
print("Please enter an starting infected population (0-100):")
infected = int(input())
mortality = 2
recovery = 15
pygame.init()
pygame.display.set_caption("Coronavirus Infection Simulation")
size = width, height = 1300, 650
speed = [25, 0]
black = 0, 0, 0
day_counter = 0
count = 0
# Creating People object
class Person:
"""A single person in the game. Has attributes of being sick, isolated, and
alive. Meant to interact with another member of its population to create
the simulation."""
def __init__(self, isolated, sick):
self.alive = True
self.isolated = isolated
self.sick = sick
if self.isolated:
self.speed = [0, 0]
else:
self.speed = [randint(-100, 100) * 0.25, randint(-100, 100) * 0.25]
if sick:
self.image = pygame.image.load("red box.jpg")
else:
self.image = pygame.image.load("white box.png")
self.ps = self.image.get_rect()
self.left = randint(1, 51)
self.top = randint(1, 25)
def new_day(self):
"""The change from day to day for a sick person.
They can either recover or die
If dead then they have no more impact on the population"""
if self.sick:
change = randint(1, 100)
if change <= mortality:
self.isolated = True
self.speed = [0, 0]
self.alive = False
self.sick = False
self.image = pygame.image.load("green square.png")
elif change <= recovery:
self.sick = False
self.image = pygame.image.load("white box.png")
def contact(self, other):
"""The event that two people come in contact with each other.
Handles the case where the infection spreads
Also handles the change in direction as they part ways
Isolated people dont come into contact so people pass through them"""
if self.ps.colliderect(other.ps) and not self.isolated \
and not other.isolated:
self.speed[0], self.speed[1] = \
self.speed[0] * -1, self.speed[1] * -1
other.speed[0], other.speed[1] = \
other.speed[0] * -1, other.speed[1] * -1
if self.sick and not other.sick:
other.sick = True
other.image = pygame.image.load("red box.jpg")
elif not self.sick and other.sick:
self.sick = True
self.image = pygame.image.load("red box.jpg")
def sim_continue(pop):
"""Tells the simulation if there is any point in continuing.
End of simulation defined as the event when the whole population is either
dead or completely recovered."""
all_dead = all(not people.alive for people in pop)
all_healed = all(not people.sick for people in pop)
return not(all_dead or all_healed)
def statistics(pop):
"""Informs the user of population statistics following the extermination of
either the population or the virus"""
alive = 0
dead = 0
for people in pop:
if people.alive:
alive += 1
else:
dead += 1
return alive, dead
screen = pygame.display.set_mode(size)
population = []
# Creating the population
for i in range(100):
is_isolated = False
is_infected = False
temp = randint(1, 100)
if temp <= isolation:
is_isolated = True
if temp <= infected:
is_infected = True
new_person = Person(is_isolated, is_infected)
new_person.ps = \
new_person.ps.move(new_person.left * 25, new_person.top * 25)
population.append(new_person)
# Creating the Simulation
while sim_continue(population):
count += 1
if count == 3:
day_counter += 1
count = 0
time.sleep(0.09)
# Exit Key (right arrow)
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_RIGHT:
sys.exit()
screen.fill(black)
for person in population:
person.ps = person.ps.move(person.speed)
if person.ps.left < 0 or person.ps.right > width:
person.speed[0] = person.speed[0] * -1
if person.ps.top < 0 or person.ps.bottom > height:
person.speed[1] = person.speed[1] * -1
for friend in population:
if person is friend:
pass
else:
person.contact(friend)
if count == 0:
person.new_day()
screen.blit(person.image, person.ps)
pygame.display.flip()
print("Days til completion: ", day_counter)
stats = statistics(population)
print("Alive: ", stats[0])
print("Dead: ", stats[1])
| e733e9b9f753a51778fc416c04c6f973ae5177b1 | [
"Markdown",
"Python"
] | 2 | Markdown | nathan-verghis/Pandemic-Simulation | a870532da3eda2920bae43c26d59053d8e9492d5 | 5f727105d8919ccd0fc7856cf0678c89f5316ed1 |
refs/heads/master | <repo_name>mdelacre/W-ANOVA<file_sep>/Functions/Analyses on power.R
# Codes for subcategories
# Hom vs. sdSD vs. SDsd
##### Hom = homoscedasticity
##### sdSD = the last group has the biggest sd
##### SDsd = the last group has the smallest sd
# bal vs. nN vs. Nn
##### bal = equal n across groups
##### nN = the last group has the biggest sample size
##### Nn = the last group has the smallest sample size
RECAP=NULL
summary=function(K,alpha){
files_path="G:/Welch's W ANOVA/ANOVA's Welch/Outputs of simulations/statistics_power and type 1 error rate/Power/"
setwd(files_path)
allfiles=list.files(files_path)
if (K==2){
Files=allfiles[grepl("k= 2",allfiles)==TRUE]
if(alpha==0.05){
files=Files[grepl("alpha= 0.05",Files)==TRUE]
} else if (alpha==0.01){
files=Files[grepl("alpha= 0.01",Files)==TRUE]
} else if (alpha==0.1){
files=Files[grepl("alpha= 0.1",Files)==TRUE]}
} else if (K==3){
Files=allfiles[grepl("k= 3",allfiles)==TRUE]
if(alpha==0.05){
files=Files[grepl("alpha= 0.05",Files)==TRUE]
} else if (alpha==0.01){
files=Files[grepl("alpha= 0.01",Files)==TRUE]
} else if (alpha==0.1){
files=Files[grepl("alpha= 0.1",Files)==TRUE]}
}
for (i in 1:length(files)){
File=read.table(files[i],sep=";",dec=".")
# Computing [O-E]/E in order to check consistency between observed and expected power (for F, F* and W tests)
OE_deviation_F=(as.numeric(File[,4])-as.numeric(File[,7]))/as.numeric(File[,7])
OE_deviation_W=(as.numeric(File[,5])-as.numeric(File[,8]))/as.numeric(File[,8])
OE_deviation_BF=(as.numeric(File[,6])-as.numeric(File[,9]))/as.numeric(File[,9])
File[,10]=OE_deviation_F
File[,11]=OE_deviation_W
File[,12]=OE_deviation_BF
# Subdivise datasets into 9 categories
# Depending on sd-ratio, sample sizes ratio,
# On the fact that there is a positive, negative or no correlation between n and sd
# And on the fact that the last group (where mean = 1) has biggest sd/sample size that other groups (where mean = 0) or not
# see codes line 5:14 for subcategories)
# Conditions id
id_Hom_bal=c(6,22,38,54,70)
id_Hom_nN=c(10,14,26,30,42,46,58,62,74,78)
id_Hom_Nn=c(2,18,34,50,66)
id_sdSD_bal=c(7,8,23,24,39,40,55,56,71,72)
id_SDsd_bal=c(5,21,37,53,69)
id_sdSD_nN=c(11,12,15,16,27,28,31,32,43,44,47,48,59,60,63,64,75,76,79,80)
id_SDsd_Nn=c(1,17,33,49,65)
id_SDsd_nN=c(9,13,25,29,41,45,57,61,73,77)
id_sdSD_Nn=c(3,4,19,20,35,36,51,52,67,68)
Hom_bal=apply(File[id_Hom_bal,c(4:6,10:12)],2,mean)
Hom_nN=apply(File[id_Hom_nN,c(4:6,10:12)],2,mean)
Hom_Nn=apply(File[id_Hom_Nn,c(4:6,10:12)],2,mean)
sdSD_bal=apply(File[id_sdSD_bal,c(4:6,10:12)],2,mean)
SDsd_bal=apply(File[id_SDsd_bal,c(4:6,10:12)],2,mean)
sdSD_nN=apply(File[id_sdSD_nN,c(4:6,10:12)],2,mean)
SDsd_Nn=apply(File[id_SDsd_Nn,c(4:6,10:12)],2,mean)
SDsd_nN=apply(File[id_SDsd_nN,c(4:6,10:12)],2,mean)
sdSD_Nn=apply(File[id_sdSD_Nn,c(4:6,10:12)],2,mean)
subcateg=list(Hom_bal=Hom_bal,Hom_nN=Hom_nN,Hom_Nn=Hom_Nn,sdSD_bal=sdSD_bal,SDsd_bal=SDsd_bal,sdSD_nN=sdSD_nN,sdSD_Nn=sdSD_Nn,SDsd_nN=SDsd_nN,SDsd_Nn=SDsd_Nn)
# Print results
power_results=data.frame(matrix(0, ncol = 9, nrow = 9))
colnames(power_results)=c("Distribution","K","subcategory","power_F","power_W","power_BF","consistency_F","consistency_W","consistency_BF")
power_results[,1]=File[1,1] # Distributions of simulations
power_results[,2]=File[1,2] # Number of groups
for (j in 1:length(subcateg)){
power_results[j,3]=ls(subcateg)[j]
power_results[j,4:9]=round(subcateg[[j]],3)
}
RECAP[[i]]=power_results
}
write.table(RECAP,paste0("power RECAP, K=",K,"and alpha=",alpha,".txt"))
return(RECAP)
}
RECAP_K2_alpha.01=summary(K=2,alpha=.01)
RECAP_K2_alpha.05=summary(K=2,alpha=.05)
RECAP_K2_alpha.1=summary(K=2,alpha=.1)
RECAP_K3_alpha.01=summary(K=3,alpha=.01)
RECAP_K3_alpha.05=summary(K=3,alpha=.05)
RECAP_K3_alpha.1=summary(K=3,alpha=.1)
############################## Graphics ##############################
# Legend
par(mfrow=c(1,1),oma = c(0, 0, 0, 0))
plot(1:3,RECAP[[1]][1,4:6],bty="n",xaxt="n",,yaxt="n",ylim=c(.62,.67),main="",ylab="",xlab="",pch=19,type="o")
legend("center", legend=c("Chi-square and normal Left-skewed","Chi-square and normal Righ-skewed","Double exponential","Mixed normal","Normal","Normal Right-skewed and Normal Left-skewed","Normal right-skewed"),
lty=1:7,pch=1:7,cex=1.1)
graphs=function(K,alpha){
if (K==2){
if(alpha==.01){RECAP=RECAP_K2_alpha.01
} else if (alpha==.05){RECAP=RECAP_K2_alpha.05
} else if (alpha==.1){RECAP=RECAP_K2_alpha.1}
} else if (K==3){
if(alpha==.01){RECAP=RECAP_K3_alpha.01
} else if (alpha==.05){RECAP=RECAP_K3_alpha.05
} else if (alpha==.1){RECAP=RECAP_K3_alpha.1}
}
subcategory=sapply(RECAP, '[[', 3)[,1]
index=c("a","b","c","d","e","f","g","h","i")
for (S in 1:length(subcategory)){
par(xpd=FALSE,mar=c(3,4,4,1))
pow=NULL
for (j in 1:length(RECAP)){
pow=c(pow,RECAP[[j]][S,4:6])
pow=unlist(pow)
}
MIN_Y=min(unlist(pow))-min(unlist(pow))%%.1
if(MIN_Y>=.7){
YMIN=.7
YMAX=1} else{
YMIN=MIN_Y
YMAX=YMIN+.3
}
setwd("C:/Users/Administrateur/Desktop/Plots W-test")
png(file=paste0("Fig2",index[S],", K=",K,", alpha=",alpha,".png"),width=2000,height=1700, units = "px", res = 300)
par(mfrow=c(1,2),oma = c(0, 0, 3, 0))
plot(1:3,NULL,bty="n",ylim=c(YMIN,YMAX),xaxt="n",main="Power",cex.main=1.2,xlab="",ylab="averaged power",pch=19,type="o",col="white")
axis(side=1,1:3,c("F-test","W-test","F*-test"))
for (j in 1:length(RECAP)){
lines(1:3,RECAP[[j]][S,4:6],bty="n",xaxt="n",pch=j,type="o",lty=j)}
plot(10:11,NULL,bty="n",ylim=c(-1,3),xaxt="n",main="Consistency",cex.main=1.2,xlab="",ylab="averaged consistency",pch=19,type="o")
axis(side=1,1:3,c("F-test","W-test","F*-test"))
for (j in 1:length(RECAP)){
lines(1:3,RECAP[[j]][S,7:9],bty="n",xaxt="n",pch=j,type="o",lty=j)
}
abline(h=0,lty=2,lwd=2,col="red")
dev.off()
}
}
graphs(K=2,alpha=.01)
graphs(K=2,alpha=.05)
graphs(K=2,alpha=.1)
graphs(K=3,alpha=.01)
graphs(K=3,alpha=.05)
graphs(K=3,alpha=.1)
getwd()<file_sep>/Functions/Type 1 error rate of generated random datasets.R
##########################################################
#### COMPUTING ALPHA ####
##########################################################
library(stringr)
typeIerrorrate=function(alpha){
# Defining all subsections containing RDS files
Mainfolder="G:/Welch's W ANOVA/ANOVA's Welch/Outputs of simulations/Data files/All simulations/Without effect/"
subfolder1=list.files(Mainfolder)
subfolder2=list.files(paste0(Mainfolder,subfolder1[1]))
subfolders=expand.grid(subfolder1,subfolder2)
subsection=paste0(subfolders[,1],"/",subfolders[,2])
for (j in 1:length(subsection)){
target_section=paste0(Mainfolder,subsection[j])
setwd(target_section)
files=list.files()# listing all files in the subsection
# organize files in the desired order
k=length(as.numeric(str_extract_all(files[1], "[0-9]+")[[1]]))/3
filenames_n=matrix(0,length(files),k)
for (a in 1:length(files)){
filenames_n[a,]=as.numeric(str_extract_all(files[a], "[0-9]+")[[1]])[1:k]
}
sorting=filenames_n[order(filenames_n[,1],filenames_n[,ncol(filenames_n)]),]
ordre=NULL
for (b in 1:(length(files)/4)){
liste=files[grep(paste0(sorting[(4*b),(k-1)],",",sorting[(4*b),k],"]"),files)]
ordre=c(ordre,liste)
}
files=ordre
# Computing elements of power for each file
results=data.frame(matrix(0,length(files),6)) # How many conditions?
colnames(results)=c("Distributions","Nb_groups","Condition","F_alpha","W_alpha","BF_alpha")
for (i in 1:length(files)){
A=readRDS(files[i])
# Extract informations about the condition in the name file
Distributions=sub("Distr=", "\\",gsub("\\..*","",gsub(",n=", ".", files[i])))
filenames_numbers=as.numeric(str_extract_all(files[i], "[0-9]+")[[1]])
k=length(filenames_numbers)/3 # because all file names contain 3k numbers
Condition=i
# Compute the observed power of each condition (= proportion of pvalues under alpha, for each test)
alpha_F = sum(A[,1]<alpha)/length(A[,1]) # proportion of pvalues under alpha, for the F-test
alpha_W = sum(A[,2]<alpha)/length(A[,2]) # proportion of pvalues under alpha, for the W-test
alpha_BF = sum(A[,3]<alpha)/length(A[,3])# proportion of pvalues under alpha, for the F*-test
results[i,]=c(Distributions, k, Condition,alpha_F,alpha_W,alpha_BF)
rm(A)
}
setwd("G:/Welch's W ANOVA/ANOVA's Welch/Outputs of simulations/statistics_power and type 1 error rate/alpha/")
write.table(results,paste0(results[1,1]," when k= ",results[1,2]," and alpha= ",alpha,".txt"),sep=";",dec=",")
rm(results)
}
}
typeIerrorrate(alpha=.01)
typeIerrorrate(alpha=.05)
typeIerrorrate(alpha=.10)<file_sep>/Functions/Analyses on type I error rate.R
# Codes for subcategories
# Hom vs. sdSD vs. SDsd
##### Hom = homoscedasticity
##### sdSD = the last group has the biggest sd
##### SDsd = the last group has the smallest sd
# bal vs. nN vs. Nn
##### bal = equal n across groups
##### nN = the last group has the biggest sample size
##### Nn = the last group has the smallest sample size
RECAP=NULL
summary=function(K,alpha){
files_path="G:/Welch's W ANOVA/ANOVA's Welch/Outputs of simulations/statistics_power and type 1 error rate/alpha/"
setwd(files_path)
allfiles=list.files(files_path)
if (K==2){
Files=allfiles[grepl("k= 2",allfiles)==TRUE]
if(alpha==0.05){
files=Files[grepl("alpha= 0.05",Files)==TRUE]
} else if (alpha==0.01){
files=Files[grepl("alpha= 0.01",Files)==TRUE]
} else if (alpha==0.1){
files=Files[grepl("alpha= 0.1",Files)==TRUE]}
} else if (K==3){
Files=allfiles[grepl("k= 3",allfiles)==TRUE]
if(alpha==0.05){
files=Files[grepl("alpha= 0.05",Files)==TRUE]
} else if (alpha==0.01){
files=Files[grepl("alpha= 0.01",Files)==TRUE]
} else if (alpha==0.1){
files=Files[grepl("alpha= 0.1",Files)==TRUE]}
} else if (K==4){
Files=allfiles[grepl("k= 4",allfiles)==TRUE]
if(alpha==0.05){
files=Files[grepl("alpha= 0.05",Files)==TRUE]
} else if (alpha==0.01){
files=Files[grepl("alpha= 0.01",Files)==TRUE]
} else if (alpha==0.1){
files=Files[grepl("alpha= 0.1",Files)==TRUE]}
} else if (K==5){
Files=allfiles[grepl("k= 5",allfiles)==TRUE]
if(alpha==0.05){
files=Files[grepl("alpha= 0.05",Files)==TRUE]
} else if (alpha==0.01){
files=Files[grepl("alpha= 0.01",Files)==TRUE]
} else if (alpha==0.1){
files=Files[grepl("alpha= 0.1",Files)==TRUE]}
}
for (i in 1:length(files)){
File=read.table(files[i],sep=";",dec=".")
# Subdivise datasets into 9 categories
# Depending on sd-ratio, sample sizes ratio,
# On the fact that there is a positive, negative or no correlation between n and sd
# And on the fact that the last group (where mean = 1) has biggest sd/sample size that other groups (where mean = 0) or not
# see codes line 5:14 for subcategories)
# Conditions id
id_Hom_bal=c(6,22,38,54,70) #
id_Hom_unbal=c(10,14,26,30,42,46,58,62,74,78,2,18,34,50,66)
id_Het_bal=c(7,8,23,24,39,40,55,56,71,72,5,21,37,53,69)
id_Het_positivecor=c(11,12,15,16,27,28,31,32,43,44,47,48,59,60,63,64,75,76,79,80,1,17,33,49,65)
id_Het_negativecor=c(9,13,25,29,41,45,57,61,73,77,3,4,19,20,35,36,51,52,67,68)
Hom_bal=apply(File[id_Hom_bal,c(4:6)],2,mean)
Hom_unbal=apply(File[id_Hom_unbal,c(4:6)],2,mean)
Het_bal=apply(File[id_Het_bal,c(4:6)],2,mean)
Het_positivecor=apply(File[id_Het_positivecor,c(4:6)],2,mean)
Het_negativecor=apply(File[id_Het_negativecor,c(4:6)],2,mean)
subcateg=list(Het_bal=Het_bal,Het_negativecor=Het_negativecor,Het_positivecor=Het_positivecor,Hom_bal=Hom_bal,Hom_unbal=Hom_unbal)
Hom_bal_sd=apply(File[id_Hom_bal,c(4:6)],2,sd)
Hom_unbal_sd=apply(File[id_Hom_unbal,c(4:6)],2,sd)
Het_bal_sd=apply(File[id_Het_bal,c(4:6)],2,sd)
Het_positivecor_sd=apply(File[id_Het_positivecor,c(4:6)],2,sd)
Het_negativecor_sd=apply(File[id_Het_negativecor,c(4:6)],2,sd)
subcateg_sd=list(Het_bal_sd=Het_bal_sd,Het_negativecor_sd=Het_negativecor_sd,Het_positivecor_sd=Het_positivecor_sd,Hom_bal_sd=Hom_bal_sd,Hom_unbal_sd=Hom_unbal_sd)
# Print results
alpha_results=data.frame(matrix(0, ncol = 9, nrow = length(subcateg)))
colnames(alpha_results)=c("Distribution","K","subcategory","alpha_F","alpha_W","alpha_BF","stderror_F","stderror_W","stderror_BF")
alpha_results[,1]=File[1,1] # Distributions of simulations
alpha_results[,2]=File[1,2] # Number of groups
for (j in 1:length(subcateg)){
alpha_results[j,3]=ls(subcateg,sorted=TRUE)[j]
alpha_results[j,4:6]=round(subcateg[[j]],3)
alpha_results[j,7:9]=round(subcateg_sd[[j]],3)
}
RECAP[[i]]=alpha_results
}
return(RECAP)
cat(capture.output(print(RECAP), file=paste0("alpha RECAP, K=",K,".txt")))
}
RECAP_K2_alpha.01=summary(K=2,alpha=.01)
RECAP_K2_alpha.05=summary(K=2,alpha=.05)
RECAP_K2_alpha.10=summary(K=2,alpha=.1)
RECAP_K3_alpha.01=summary(K=3,alpha=.01)
RECAP_K3_alpha.05=summary(K=3,alpha=.05)
RECAP_K3_alpha.10=summary(K=3,alpha=.1)
RECAP_K4_alpha.01=summary(K=4,alpha=.01)
RECAP_K4_alpha.05=summary(K=4,alpha=.05)
RECAP_K4_alpha.10=summary(K=4,alpha=.1)
RECAP_K5_alpha.01=summary(K=5,alpha=.01)
RECAP_K5_alpha.05=summary(K=5,alpha=.05)
RECAP_K5_alpha.10=summary(K=5,alpha=.1)
############################## Graphics ##############################
# Legend
plot(1:3,RECAP[[1]][1,4:6],bty="n",xaxt="n",yaxt="n",ylim=c(.62,.67),main="",xlab="",ylab="",pch=19,type="o")
legend("center", legend=c("Chi-square and normal Left-skewed","Chi-square and normal Righ-skewed","Double exponential","Mixed normal","Normal","Normal Right-skewed and Normal Left-skewed","Normal right-skewed"),
lty=1:7,pch=1:7,cex=1.1)
graphs=function(K,yliminf,ylimsup,alpha){
if (K==2){
if(alpha==.01){RECAP=RECAP_K2_alpha.01
} else if (alpha==.05){RECAP=RECAP_K2_alpha.05
} else if (alpha==.1){RECAP=RECAP_K2_alpha.10}
} else if (K==3){
if(alpha==.01){RECAP=RECAP_K3_alpha.01
} else if (alpha==.05){RECAP=RECAP_K3_alpha.05
} else if (alpha==.1){RECAP=RECAP_K3_alpha.10}
} else if (K==4){
if(alpha==.01){RECAP=RECAP_K4_alpha.01
} else if (alpha==.05){RECAP=RECAP_K4_alpha.05
} else if (alpha==.1){RECAP=RECAP_K4_alpha.10}
} else if (K==5){
if(alpha==.01){RECAP=RECAP_K5_alpha.01
} else if (alpha==.05){RECAP=RECAP_K5_alpha.05
} else if (alpha==.1){RECAP=RECAP_K5_alpha.10}
}
subcategory=sapply(RECAP, '[[', 3)[,1]
index=c("C","E","D","A","B")
for (S in 1:length(subcategory)){
setwd("C:/Users/Administrateur/Desktop/Plots W-test")
png(file=paste0("Fig1",index[S],", K=",K,", alpha=",alpha,".png"),width=2000,height=1700, units = "px", res = 300)
par(xpd=FALSE,mar=c(3,4,4,1))
plot(1:3,NULL,bty="n",ylim=c(yliminf,ylimsup),xaxt="n",xlab="",ylab="averaged Type I error rate",pch=7,type="o")
axis(side=1,1:3,c("F-test","W-test","F*-test"))
for (j in 1:length(RECAP)){
lines(1:3,RECAP[[j]][S,4:6],bty="n",xaxt="n",main="Averaged alpha of 3 tests when n and sd are equal across groups",pch=j,type="o",lty=j)}
abline(h=alpha,lty=2,lwd=2,col="red")
rect(.5,.5*alpha,3.5,1.5*alpha, col= rgb(0, 0, 0, alpha=.05),border=NA)
rect(.5,.9*alpha,3.5,1.1*alpha, col= rgb(0, 0, 0, alpha=.25),border=NA)
dev.off()
}
}
getwd()
graphs(K=3,.02,.12,alpha=.05)
(K,yliminf,ylimsup,alpha)
graphs(K=4,.02,.15,alpha=.05)
graphs(K=5,.02,.15,alpha=.05)
<file_sep>/README.md
# W-ANOVA
1) All simulations were performed using the script "generate nSim random datasets, performing 3 tests on each dataset, extracting p-values and storing them in a file.R"
For 7 distributions, 80 conditions were tested (varying as a function of sd, sd-ratio, sample sizes and sample sizes ratio).
For each condition, 1.000.000 random datasets were generated, three test were performed on each datasets, and p-values were extracted and stored in .rds files
2) Observed and expected power were computed for each test (F, F* and W) and for each condition, using the script "Observed and expected power for generated sample datasets.R"
==> See "Power.xlsx" for raw observed and expected power.
3) Thanks to te function "Analyses on power.R", the three tests (F, F* and W) were compared in terms of:
- raw power
- consistency between observed and expected power ([O-E]/E)
4) The Type I error rate were computed for each test (F,F* and W) and for each condition, using the script "Type 1 error rate of generated random datasets.R"
==> See "Type I error rate.xlsx"
3) Thanks to te function "Analyses on type I error rate.R", the three tests (F, F* and W) were compared in terms of type I error rate.
<file_sep>/Functions/Observed and expected power for generated sample datasets.R
library(stringr)
power=function(alpha){
# Defining all subsections containing RDS files
Mainfolder="G:/Welch's W ANOVA/ANOVA's Welch/Outputs of simulations/Data files/All simulations/With effect/"
subfolder1=list.files(Mainfolder)
subfolder2=list.files(paste0(Mainfolder,subfolder1[1]))
subfolders=expand.grid(subfolder1,subfolder2)
subsection=paste0(subfolders[,1],"/",subfolders[,2])
for (j in 1:length(subsection)){
target_section=paste0(Mainfolder,subsection[j])
setwd(target_section)
files=list.files()# listing all files in the subsection
# organize files in the desired order
k=length(as.numeric(str_extract_all(files[1], "[0-9]+")[[1]]))/3
filenames_n=matrix(0,length(files),k)
for (a in 1:length(files)){
filenames_n[a,]=as.numeric(str_extract_all(files[a], "[0-9]+")[[1]])[1:k]
}
sorting=filenames_n[order(filenames_n[,1],filenames_n[,ncol(filenames_n)]),]
ordre=NULL
for (b in 1:(length(files)/4)){
liste=files[grep(paste0(sorting[(4*b),(k-1)],",",sorting[(4*b),k],"]"),files)]
ordre=c(ordre,liste)
}
files=ordre
# Computing elements of power for each file
results=data.frame(matrix(0,length(files),9))
colnames(results)=c("Distributions","Nb_groups","Condition","F_power","W_power","BF_power","F_power_expected","W_power_expected","BF_power_expected")
for (i in 1:length(files)){
A=readRDS(files[i])
# Extract informations about the condition in the name file
Distributions=sub("Distr=", "\\",gsub("\\..*","",gsub(",n=", ".", files[i])))
filenames_numbers=as.numeric(str_extract_all(files[i], "[0-9]+")[[1]])
k=length(filenames_numbers)/3 # because all file names contain 3k numbers
Condition=i
colnames(results)=c("Distributions","Nb_groups","Condition","F_power","W_power","BF_power","F_power_expected","W_power_expected","BF_power_expected")
# Compute the observed power of each condition (= proportion of pvalues under alpha, for each test)
power_F = sum(A[,1]<alpha)/length(A[,1]) # proportion of pvalues under alpha, for the F-test
power_W = sum(A[,2]<alpha)/length(A[,2]) # proportion of pvalues under alpha, for the W-test
power_BF = sum(A[,3]<alpha)/length(A[,3])# proportion of pvalues under alpha, for the F*-test
# Compute the expected power
# All input parameters are specified in the file names
# always in the same order: All n, All means, All sds
# in other words, file names always contain 3*k numbers
n=filenames_numbers[1:k]
m=filenames_numbers[(k+1):(2*k)]
sd=filenames_numbers[(2*k+1):(3*k)]
sd_pooled<-sqrt(sum((n-1)*sd^2)/(sum(n)-k)) #pooled standard deviation
sd_BF<-sqrt(sum((1-n/sum(n))*sd^2)) #sd of B-F
mu <- sum(n*m)/sum(n)
mean_SS <- sum(n*(m-mu)^2)
mean_sd <- sqrt(sum(n*(m-mu)^2)/sum(n))
f <- mean_sd/sd_pooled
#Expected power for ANOVA
df1 <- k - 1
df2_anova <- sum(n) - k
crit_f <- qf(1 - alpha, df1, df2_anova)
ncp_anova <- mean_SS/(sd_pooled^2) #ncp_anova <- f^2 * sum(n)
power_F_theo <- pf(crit_f, df1, df2_anova, ncp = ncp_anova, lower.tail = FALSE)
#Expected power for Welch's ANOVA
df1 <- k - 1
w_j <- n/sd^2
mu <- sum((w_j*m)/sum(w_j))
df2_welch <- (k^2-1)/(3*sum((1-w_j/sum(w_j))^2/(n-1)))
crit_w <- qf(1 - alpha, df1, df2_welch)
ncp_w <- sum(w_j*(m-mu)^2)
power_W_theo <- pf(crit_w, df1, df2_welch, ncp = ncp_w, lower.tail = FALSE)
#Expected power for Brown-Forsythe's test of comparison of means
df1 <- k - 1
df2_BF <- 1/sum((((1-n/sum(n))*sd^2)/sum((1-n/sum(n))*sd^2))^2/(n-1))
crit_BF <- qf(1 - alpha, df1, df2_BF)
ncp_BF <- mean_SS/(sd_BF^2)*(k-1)
power_BF_theo <- pf(crit_BF, df1, df2_BF, ncp = ncp_BF, lower.tail = FALSE)
results[i,]=c(Distributions, k, Condition,power_F,power_W,power_BF,power_F_theo,power_W_theo,power_BF_theo)
#rm(list=setdiff(ls(), list("Mainfolder","subsection","results","files")))
rm(A)
}
setwd("G:/Welch's W ANOVA/ANOVA's Welch/Outputs of simulations/statistics_power and type 1 error rate")
write.table(results,paste0(results[1,1]," when k= ",results[1,2]," and alpha= ",alpha,".txt"),sep=";",dec=",")
rm(results)
}
}
power(alpha=.05)
power(alpha=.01)
power(alpha=.10) | f146f8f6444905c72d0b071824ab61da3ff24e41 | [
"Markdown",
"R"
] | 5 | R | mdelacre/W-ANOVA | 68d09a36ac866b191eaec08b08304d838974a124 | 063bae73e99980af5bbc099b6aac4f5d06349a67 |
refs/heads/master | <repo_name>BoKyoungHan/Draw_CDF<file_sep>/drawCDF.py
import matplotlib.pyplot as plt
import numpy as np
import csv
import array
import sys
import os
from scipy import stats
MS_SCALE = 1
MS_COEFF = 1000
'''if sys.argv[1].isdigit() == False:
print("Usage: python drawCDF.py [YTICK_LIMIT] [File] ... ")
print("[YTICK_LIMIT] format should be digit [0, 1]")
sys.exit()'''
YTICK_LIMIT = float(sys.argv[1])
'''if len(sys.argv) < 2:
print("Usage: python drawCDF.py [baseline] [target]")
print("You need at least one input file")
sys.exit()'''
'''if len(sys.argv) >= 4:
print("Usage: python drawCDF.py [baseline] [target]")
sys.exit()'''
fig, ax = plt.subplots(1, 1)
fig.suptitle(sys.argv[2])
max_latency = 0
min_latency = 0
for i in range(3, len(sys.argv)):
fr = open(sys.argv[i], 'r')
cdf_data = {}
print(sys.argv[i])
total_num = 0
while True:
rline = fr.readline()
if not rline: break;
item = rline.split(',')
latency = int(item[0]) # response time
if MS_SCALE:
latency = int(latency / MS_COEFF)
if latency in cdf_data:
cdf_data[latency] += 1
else:
cdf_data[latency] = 1
total_num += 1
if max_latency < max(cdf_data.keys()):
max_latency = max(cdf_data.keys())
if min_latency > min(cdf_data.keys()):
min_latency = min(cdf_data.keys())
cdf_data = dict(sorted(cdf_data.items()))
x = []
y = []
cumulated_num = 0
for key, value in cdf_data.items():
cumulated_num += value
probability = cumulated_num / float(total_num)
#print(probability)
if probability > YTICK_LIMIT:
y.append(probability)
x.append(key)
#print(min(cdf_data.keys()))
#print(max(cdf_data.keys()))
plt.plot(x, y, label = sys.argv[i].replace('.csv', ''))
#plt.xlim([min_latency, max_latency])
#plt.xticks([min_latency, (min_latency + max_latency) / 2, max_latency])
#plt.axis('square')
if MS_SCALE:
plt.xlabe:('Erase Latency [ms]')
else:
plt.xlabel('Erase Latency [μs]')
plt.ylabel('Cumulative Distribution')
plt.xlabel('User Write Latency [ms]')
plt.tick_params(axis = 'y', length = 0.01)
plt.legend(loc = 'lower right')
plt.grid(True, axis = 'y', linestyle='--')
plt.savefig(sys.argv[2] + '.' + sys.argv[1] + '.png')
<file_sep>/README.md
# Draw_CDF
Draw and save CDF graph in file in python
| 954495014cf67a8a1f385a9cb16012fc31c76eb2 | [
"Markdown",
"Python"
] | 2 | Python | BoKyoungHan/Draw_CDF | 6dd9444b56c86415278120acafa4ebb2bfc286e0 | e3b3034c3e672a455904df3184ea61071457d0a0 |
refs/heads/master | <repo_name>bjornhjelle/solr-puppet<file_sep>/provisioning/README.txt
puppet module install bashtoni/timezone --modulepath modules
Notice: Preparing to install into /home/bjorn/prosjekter/evita/solr/provisioning/modules ...
Notice: Downloading from https://forge.puppetlabs.com ...
Notice: Installing -- do not interrupt ...
/home/bjorn/prosjekter/evita/solr/provisioning/modules
└── bashtoni-timezone (v0.1.2)
<file_sep>/provisioning/modules/solr/templates/solr_startup.erb
#!/bin/sh
##############################################################################
# chkconfig: 345 90 10
# description: Solr
##############################################################################
# This is the startup script for Solr , running under linuxes
# with chkconfig support.
#
##############################################################################
##############################################################################
# Change these to match your environment. In particular, change SOLR_HOME
# and SOLR_RUNASUSER
JETTY_PORT=8983
JETTY_STOP_PORT=8884
JETTY_STOP_KEY="34t6adfsgertt435po34"
SOLR_NAME=solr
SOLR_HOME=<%=@home_dir%>/solr_home
SOLR_SERVER_DIR=<%=@home_dir%>/solr/example
SOLR_INSTANCE_DIR=<%=@home_dir%>/solr
SOLR_RUNASUSER=<%=@user%>
##############################################################################
##############################################################################
# It should normally not be necessary to change below this line
##############################################################################
THIS=$0
JAVA_OPTS="-DSTOP.PORT=${JETTY_STOP_PORT} -DSTOP.KEY=${JETTY_STOP_KEY} -Djetty.port=${JETTY_PORT} -Xmx2048m -XX:MaxPermSize=128m -Dsolr.solr.home=${SOLR_HOME} -Dsolr.install.dir=${SOLR_INSTANCE_DIR}"
CMD="java ${JAVA_OPTS} -jar start.jar"
if [ $(whoami) == root ]; then
echo Switching from root to $SOLR_RUNASUSER: su $SOLR_RUNASUSER -c "${THIS} $*"
su $SOLR_RUNASUSER -c "${THIS} $*"
exit
fi
if [ $(whoami) != $SOLR_RUNASUSER ]; then
echo You are currently logged in as user $(whoami).
echo This script must be run as either '${SOLR_RUNASUSER}' or 'root'.
exit
fi
start() {
echo "Starting ${SOLR_NAME}"
ps -ef | grep "\-Djetty.port=${JETTY_PORT}" | grep -v grep
if [ "$?" = "0" ]; then
echo "${SOLR_NAME} is already running"
exit 1
else
(cd $SOLR_SERVER_DIR ; $CMD >logs/$SOLR_NAME-stdout.log 2>logs/$SOLR_NAME-stderr.log &)
fi
}
stop() {
echo "Stopping ${SOLR_NAME}"
(cd $SOLR_SERVER_DIR ; $CMD --stop)
}
status() {
echo "Searching for ${SOLR_NAME}"
ps -ef | grep "\-Djetty.port=${JETTY_PORT}" | grep -v grep
if [ "$?" = "0" ]; then
echo "${SOLR_NAME} is running"
else
echo "${SOLR_NAME} is not running"
exit 1
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep 5
start
;;
status)
status
;;
*)
echo "Usage: $0 (start|stop|restart|status)"
exit 2
esac
exit $?
<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# All Vagrant configuration is done here. The most common configuration
# options are documented and commented below. For a complete reference,
# please see the online documentation at vagrantup.com.
#config.vm.synced_folder ".", "/project", :owner => "vagrant", :group => "vagrant", :mount_options => ['dmode=777,fmode=777']
# "." mounted on /vagrant by default
config.vm.network :forwarded_port, guest: 8983, host: 8983, auto_correct: true
config.vm.network :forwarded_port, guest: 5000, host: 5000, auto_correct: true
config.vm.network :private_network, ip: "192.168.33.20"
config.ssh.forward_agent = true
config.vm.box = "fedora20"
config.vm.box_url = "https://dl.dropboxusercontent.com/u/15733306/vagrant/fedora-20-netinst-2014_01_05-minimal-puppet-guestadditions.box"
config.vm.provider :virtualbox do |vb|
vb.name = "solr"
vb.customize ["modifyvm", :id, "--memory", "2024"]
end
config.vm.provision :puppet, :module_path => "provisioning/modules", run: "always" do |puppet|
puppet.hiera_config_path = "provisioning/hiera.yaml"
puppet.manifests_path = "provisioning/manifests"
puppet.manifest_file = "development.pp"
# puppet.options = "--verbose --debug"
end
end
<file_sep>/README.md
# Solr, install with puppet #
Scripts to install Solr 4.10.3 using puppet. Two ways to install are implemented:
1. in a Linux VM (Fedora 20)
2. on a Linux machine (tested on Fedora 20)
Solr is installed with Solr home, log-directory and index-directory outside of the Solr-distribution to make it easy to change to another release of Solr. Script for start on boot is provided.
## Getting started ##
Before installing in a VM you must have installed:
* Ruby
* Vagrant
* VirtualBox
To install on a Linux machine you must have installed:
* Ruby
* Puppet
Then clone the repository:
git clone https://github.com/bjornhjelle/solr-puppet.git
## Solr in a VM ##
To install Solr in a VM
cd solr-puppet
vagrant up
### Start Solr ###
Log in to the VM and start Solr
vagrant ssh
solr start
This uses the script that comes with the Solr distribution to start/stop Solr. Read more [here](https://cwiki.apache.org/confluence/display/solr/Running+Solr).
The Solr admin interface can now be reached using URL: <http://localhost:8983/solr>
### To add content ###
On the host machine:
cd sampledocs
./post.sh solr.xml
And verify that the document was indexed:
<http://localhost:8983/solr/collection1/select?q=*%3A*&wt=json&indent=true>
Or use the full set of example docs available in the VM:
vagrant ssh
cd solr/example/exampledocs
./post.sh hd.xml
### File locations ###
* Indexes will be stored in `/home/vagrant/indexes`
* Log files will be stored in `/home/vagrant/logs`
* Solr home is the directory `/home/vagrant/solr_home` (based on the example home i the distribution: `example/solr`)
## Solr on a Linux machine ##
To install, first add the linux user to run solr, set a password, and log in as `solr`:
useradd solr
passwd solr
su - solr
Then clone and apply puppet manifest:
git clone https://github.com/bjornhjelle/solr-puppet.git config
sudo puppet apply --modulepath config/provisioning/modules config/provisioning/manifests/server.pp
Solr should now have been started with Solr home set to config/solr_home where the collection1 core is configured.
### Start and stop Solr ###
Logged in as `solr`, Solr can be started and stopped with the `solr` script as described [here](https://cwiki.apache.org/confluence/display/solr/Running+Solr). But Solr has now been configured to start on boot and can be stopped/restarted/started as a service:
sudo service solr stop|start|restart
TODO: fix this so systemd also works:
Solr can be stopped/restarted/started with `systemctl`:
sudo systemctl stop|start|restart solr
## Port numbers ##
Jetty port numbers for stopping and starting are set in the startup scripts that are provisioned by puppet to /etc/init.d/solr.
| 9972e4edbcf3c28446d9566c2564377be17bc070 | [
"Markdown",
"Text",
"Ruby",
"Shell"
] | 4 | Text | bjornhjelle/solr-puppet | 5df4f7bfa3c388b55ee2eac7cf96961fad11c61c | ffc1c92fed7705b7e690c761897e47ca6a0200d2 |
refs/heads/master | <file_sep>def plus_two(num)
num += 2
return num
end | 6e00a81e6635bd133cd3e3ed044115122ec61113 | [
"Ruby"
] | 1 | Ruby | CaptainBaghdad/debugging-with-pry-prework | 77d85dc410c1bf90e56b652d002177e70955ee12 | 31487eff534f255321531986493808fe231ffd9b |
refs/heads/master | <file_sep>
<?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
require 'config.php';
@$cat=$_GET['cat'];
@$cat3=$_GET['cat3'];
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Brand</title>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/noticons.css">
<link rel="stylesheet" href="css/editor.min.css">
<link rel="stylesheet" href="css/wpcom.css">
<link rel="stylesheet" href="css/buttons.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/hovercard.css">
<link rel="stylesheet" href="css/services.css">
<link rel="stylesheet" href="css/style3.css">
<link rel="stylesheet" href="css/font-awesome.css">
<link rel="stylesheet" href="css/color.css">
<link rel="stylesheet" href="css/accordionmenu.css" type="text/css" media="screen" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="./jquery.tabletoCSV.js" type="text/javascript" charset="utf-8"></script>
<script src="css/wpgroho.js" type="text/javascript" charset="utf-8"></script>
<script src="css/loader0.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<!-- Navigation -->
<div id="wpadminbar" class="ltr">
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
<ul id="wp-admin-bar-root-default" class="ab-top-menu">
<li id="wp-admin-bar-blog" class="menupop my-sites"><a class="ab-item" aria-haspopup="true" href="index">Brand</a> </li>
</ul>
<ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu">
<li id="wp-admin-bar-my-account" class="menupop with-avatar no-grav"><a href="logout.php?logout" class="ab-item" aria-haspopup="true"><img alt="" src="upload/pr.png" class="avatar avatar-32" height="32" width="32"></a> </li>
<li id="wp-admin-bar-ab-new-post"><a class="ab-item" href="createpost"></a> </li> </ul>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8">
<?php
$sql1 = "SELECT * FROM post order by postid DESC LIMIT $start_from, $per_page ";
$result2 = $conn->query($sql1);
if ($result2->num_rows > 0){?>
<h1 class="page-header">
Users Post
</h1>
<?php while($row2 = $result2->fetch_assoc()) {
$userid11 = $row2["userid"];
$sql1001 = "SELECT * FROM user where userid='$userid11' ";
$result2001 = $conn->query($sql1001);
$row2001 = $result2001->fetch_assoc();?>
<!-- First Blog Post -->
<h2>
<?php echo $row2["title"]?> <small>by <?php echo $row2001["username"]?></small></h2>
<p><span class="glyphicon glyphicon-time"></span> Posted on <?php echo $row2["created"]?></p>
<img src="<?php echo $row2['path'] ?>" class="img-responsive">
<?php echo "<p>" .$row2["body"]. "</p>";
?>
<a class="btn btn-sm btn-primary" href="post.php?postid=<?php echo $row2['postid']?>">Read More <span class="glyphicon glyphicon-chevron-right"></span></a>
<hr>
<?php
}
} else {
echo "0 results";}
$query = 'SELECT * FROM post';
$result34 = mysqli_query($conn, $query);
if ($result34->num_rows > 0 && $result34->num_rows > 5){$total_records = mysqli_num_rows($result34);
$total_pages = ceil($total_records / $per_page);
if($page==1){
echo "<ul class='pager'><li class='previous'> </li> ";
$i=1; $i<=$total_pages; $i++;
echo " <li class='next'><a href='index?page=".$i."'>".'Older →'."</a> </li></ul> ";
}
elseif($page==$total_pages)
{$i=1; $i<=$total_pages; $i++;
$i2=$page-1;
echo " <ul class='pager'> <li class='previous'><a href='index?page=".$i2."'>".'← Newer'."</a> </li> ";
echo "<li class='previous'> </li></ul> ";
}
else {
$i=1; $i<=$total_pages; $i++;
$i1=$page+1;
$i2=$page-1;
echo "<ul class='pager'> <li class='previous'><a href='index?page=".$i2."'>".'← Newer'."</a> </li> ";
echo " <li class='next'><a href='index?page=".$i1."'>".'Older →'."</a> </li></ul> ";
}}
else{
}?>
</div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-4">
<hr>
<?php if(empty($_SESSION['userid']))
{
?><div class="well">
<center> <h2>Register to post with us</h2></center>
<center> <a class="btn btn-danger" href="signup">Register</a> </center>
<center><a href="login">Log in</a><span> if you're already a brand member. </span></center>
<!-- /.input-group -->
</div>
<?php } ?>
<!-- Blog Categories Well -->
<div id="wrapper-200a">
<?php
$sql145 = "SELECT * FROM category";
$result245 = $conn->query($sql145);
if ($result245->num_rows > 0){
while($row245 = $result245->fetch_assoc()) { ?> <ul> <li class="block">
<input type="checkbox" name="item" id="<?php echo $row245['cat_id'];
?> " />
<label for="<?php echo $row245['cat_id'];
?> "><i aria-hidden="true" class="icon-users"></i> <?php echo $row245['category'];
?> <span><?php
$cat_id23=$row245['cat_id'];$sql145232 = "SELECT * FROM post where cat_id=$cat_id23";
$result245232 = $conn->query($sql145232);$count123=$result245232->num_rows;
$sql14523 = "SELECT * FROM subcategory where cat_id=$cat_id23";
$result24523 = $conn->query($sql14523); echo $count123;
?></span></label>
<?php
if ($result24523->num_rows > 0){
while($row24523 = $result24523->fetch_assoc()) { ?>
<ul class="options">
<li><a href="" target="_blank"><i aria-hidden="true" class="icon-eye"></i> <?php echo $row24523['subcategory'];?><span><?php
$subcat_id23=$row24523['subcat_id'];
$sql199 = "SELECT * FROM post where subcat_id=$subcat_id23";
$result199 = $conn->query($sql199);
$count1234=$result199->num_rows;
echo $count1234;
?></span>
</a></li></ul><?php }}?>
</li></ul>
<?php }}?>
</div>
<!-- Side Widget Well -->
</div> </div></div>
<!-- /.row -->
<hr>
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li> <a class="navbar-brand" style="
padding-top: 6px;
font-size: 12px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
<file_sep><?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
$userid = $_SESSION['userid'];
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
if(isset($_SESSION['userid'])=="")
{
session_destroy();
unset($_SESSION['user']);
header("Location: login");
}
elseif ($r['admin']==0 ) {
session_destroy();
unset($_SESSION['user']);
header("Location: login");
}
else
{
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
require 'config.php';
@$cat=$_GET['cat'];
@$cat3=$_GET['cat3'];
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>BRAND</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/noticons.css">
<link rel="stylesheet" href="css/editor.min.css">
<link rel="stylesheet" href="css/wpcom.css">
<link rel="stylesheet" href="css/buttons.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/hovercard.css">
<link rel="stylesheet" href="css/services.css">
<link rel="stylesheet" href="css/style3.css">
<link rel="stylesheet" href="accordionmenu.css" type="text/css" media="screen" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="./jquery.tabletoCSV.js" type="text/javascript" charset="utf-8"></script>
<script src="css/wpgroho.js" type="text/javascript" charset="utf-8"></script>
<script src="css/loader0.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function(){
$("#export").click(function(){
$("#export_table").tableToCSV();
});
});
</script>
</head>
<body>
<div id="wpadminbar" class="ltr">
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
<ul id="wp-admin-bar-root-default" class="ab-top-menu">
<li id="wp-admin-bar-blog" class="menupop my-sites"><a class="ab-item" aria-haspopup="true" href="index">Brand</a> </li>
</ul>
<ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu">
<li id="wp-admin-bar-my-account" class="menupop with-avatar no-grav"><a href="logout.php?logout" class="ab-item" aria-haspopup="true"><img alt="" src="https://2.gravatar.com/avatar/eda4e5db5db0ede52414c9ca5c31d1fa?s=32&d=mm&r=G" class="avatar avatar-32" height="32" width="32"></a> </li>
<li id="wp-admin-bar-ab-new-post"><a class="ab-item" href="createpost"></a> </li> </ul>
</div>
</div>
<br>
<div id="adminmenuwrap" style="
top: 2px;
">
<ul id="adminmenu">
<li class="wp-not-current-submenu menu-top menu-icon-comments" id="menu-comments">
<a href="admin" class="wp-not-current-submenu menu-top menu-icon-comments"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-dashboard"><br></div><div class="wp-menu-name">Dashboard </div></a></li>
<li class="wp-first-item wp-has-submenu wp-has-current-submenu wp-menu-open menu-top menu-top-first menu-icon-dashboard" id="menu-dashboard">
<a href="admin" class="wp-first-item wp-has-submenu wp-has-current-submenu wp-menu-open menu-top menu-top-first menu-icon-dashboard" aria-haspopup="false"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-post"><br></div><div class="wp-menu-name">Posts</div></a>
</li>
<li class="wp-not-current-submenu menu-top menu-icon-comments" id="menu-comments">
<a href="adcom" class="wp-not-current-submenu menu-top menu-icon-comments"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-comments"><br></div><div class="wp-menu-name">Comments </div></a></li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-users" id="menu-users">
<a href="aduser" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-users" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-users"><br></div><div class="wp-menu-name">Users</div></a>
</li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-links" id="menu-links">
<a href="adcat" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-links" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-links"><br></div><div class="wp-menu-name">Categories</div></a>
</li>
</ul>
</div>
<div class="container" style="
margin-left: 170px;
margin-top: 22px;
margin-right: 15px;
">
<h1><?php
$sql1 = "SELECT * FROM post order by postid DESC LIMIT $start_from, $per_page ";
$result2 = $conn->query($sql1);
$sql1356 = "SELECT * FROM post ";
$result2356 = $conn->query($sql1356);$count789=$result2356->num_rows;
?>
Posts<small>(<?php echo $count789;?>)</small> <a href="createpost"><button class = "btn btn-sm " >Add New</button> </a> <button class="btn btn-sm " id="export" data-export="export">Export</button>
</h1>
<?php if ($result2->num_rows > 0){
echo "<table id='export_table' style= ' table-layout: fixed;border-radius:10px;background-color: #ECEFF1; color: #01579B; width:100%; '><tr height='50px' ><th style='width:15%;padding-right:40px;' >Title</th><th style='width:30%;padding-right:40px;' >Body</th><th style='width:30%;padding-right:40px;'>Image path</th><th style='width:15%;padding-right:40px;'>Author</th><th style='width:15%;padding-right:40px;' >Category</th><th style='width:20%;padding-right:40px;' >Sub-Category</th><th style='width:15%;padding-right:40px;' >Date</th></tr>";
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$userid12345=$row2["userid"];
$sql09 = "SELECT * FROM user where userid=$userid12345";
$result09 = $conn->query($sql09);
$row09 = $result09->fetch_assoc();
$cat_id12=$row2["cat_id"];
$sql091 = "SELECT * FROM category where cat_id=$cat_id12";
$result091 = $conn->query($sql091);
$row091 = $result091->fetch_assoc();
if($row2['cat_id']==0)
{
$category567='Uncategorized';
}
else
{
$category567=$row091["category"];
}
$sql091123 = "SELECT * FROM subcategory where cat_id=$cat_id12";
$result091123 = $conn->query($sql091123);
$row091123 = $result091123->fetch_assoc();
if($row2['subcat_id']==0)
{
$subcategory567='Uncategorized';
}
else
{
$subcategory567=$row091123["subcategory"];
}
echo "<tr height='70px'><td style='width:15%;padding-right:40px;' >" . $row2["title"]. "</td><td style='width:30%;padding-right:40px;word-wrap:break-word;' >" .$row2["body"]." </td><td style='width:30%;padding-right:40px; word-wrap:break-word;' >" . $row2["path"]. " </td><td style='width:15%;padding-right:40px;' >" . $row09["username"]. " </td><td style='width:15%;padding-right:40px;' >" . $category567. " </td><td style='width:20%;padding-right:40px;' >" . $subcategory567. " </td><td style='width:15%;padding-right:40px;' >" . $row2["created"]. " </td></tr>";
}
echo "</table>";
}
else {
echo "0 results";}
$query = "SELECT * FROM post ";
$result34 = mysqli_query($conn, $query);
if ($result34->num_rows > 0 && $result34->num_rows > 5){$total_records = mysqli_num_rows($result34);
$total_pages = ceil($total_records / $per_page);
if($page==1){
echo "<ul class='pager'><li class='previous'> </li> ";
$i=1; $i<=$total_pages; $i++;
echo " <li class='next'><a href='adpost?page=".$i."'>".'Older →'."</a> </li></ul> ";
}
elseif($page==$total_pages)
{$i=1; $i<=$total_pages; $i++;
$i2=$page-1;
echo " <ul class='pager'> <li class='previous'><a href='adpost?page=".$i2."'>".'← Newer'."</a> </li> ";
echo "<li class='previous'> </li></ul> ";
}
else {
$i=1; $i<=$total_pages; $i++;
$i1=$page+1;
$i2=$page-1;
echo "<ul class='pager'> <li class='previous'><a href='adpost?page=".$i2."'>".'← Newer'."</a> </li> ";
echo " <li class='next'><a href='adpost?page=".$i1."'>".'Older →'."</a> </li></ul> ";
}}
else{
}?>
</div>
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li><a class="navbar-brand" style="
padding-top: 6px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<script src="js/bootstrap.min.js"></script>
</body>
</html><?php }?><file_sep><?php
session_start();
if(empty($_GET['postid'])) {
header("Location: login.php");
}
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$postid = $_GET['postid'];
$conn=mysqli_connect("localhost","root","","new");
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
if(isset($_POST['submit']))
{
$body= $_POST['body'];
$postid = $_GET['postid'];
$cat_id = $_GET['cat_id'];
$subcat_id = $_GET['subcat_id'];
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('captacha doesnt match ')
window.location.href='post.php?postid=$postid';
</SCRIPT>");}
else
{
$sql="INSERT into comment (body,postid,createdat,userid,cat_id,subcat_id) value('$body','$postid',now(),'$userid','$cat_id','$subcat_id')";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('thanks for posting comment')
window.location.href='post.php?postid=$postid';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='index.php';
</SCRIPT>");}
}
}
if(isset($_POST['submit1']))
{
$body= $_POST['body'];
$postid = $_GET['postid'];
$cat_id = $_GET['cat_id'];
$subcat_id = $_GET['subcat_id'];
$sql="INSERT into comment (body,postid,createdat,userid,cat_id,subcat_id) value('$body','$postid',now(),'$userid','$cat_id','$subcat_id')";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('thanks for posting comment')
window.location.href='post.php?postid=$postid';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='index.php';
</SCRIPT>");}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Brand Post</title>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/noticons.css">
<link rel="stylesheet" href="css/editor.min.css">
<link rel="stylesheet" href="css/wpcom.css">
<link rel="stylesheet" href="css/buttons.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/hovercard.css">
<link rel="stylesheet" href="css/services.css">
<link rel="stylesheet" href="css/style3.css">
<link rel="stylesheet" href="css/font-awesome.css">
<link rel="stylesheet" href="css/color.css">
<link rel="stylesheet" href="css/accordionmenu.css" type="text/css" media="screen" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="./jquery.tabletoCSV.js" type="text/javascript" charset="utf-8"></script>
<script src="css/wpgroho.js" type="text/javascript" charset="utf-8"></script>
<script src="css/loader0.js" type="text/javascript" charset="utf-8"></script>
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<!-- Navigation -->
<div id="wpadminbar" class="ltr">
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
<ul id="wp-admin-bar-root-default" class="ab-top-menu">
<li id="wp-admin-bar-blog" class="menupop my-sites"><a class="ab-item" aria-haspopup="true" href="index">Brand</a> </li>
</ul>
<ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu">
<li id="wp-admin-bar-my-account" class="menupop with-avatar no-grav"><a href="logout.php?logout" class="ab-item" aria-haspopup="true"><img alt="" src="upload/pr.png" class="avatar avatar-32" height="32" width="32"></a> </li>
<li id="wp-admin-bar-ab-new-post"><a class="ab-item" href="createpost"></a> </li> </ul>
</div>
</div>
<br>
<!-- Page Content -->
<div class="container">
<?php
$sql1 = "SELECT * FROM post where postid='$postid' ";
?>
<div class="row">
<?php
$result2 = $conn->query($sql1);
$row2 = $result2->fetch_assoc();
$cat_id1 = $row2["cat_id"];
$subcat_id1 = $row2["subcat_id"];
$userid111 = $row2["userid"];
$sql10011 = "SELECT * FROM user where userid='$userid111' ";
$result20011 = $conn->query($sql10011);
$row20011 = $result20011->fetch_assoc();?>
<!-- Blog Post Content Column -->
<div class="col-lg-8">
<!-- Blog Post -->
<!-- Title -->
<?php echo "<h1 >".$row2["title"]."</h1>" ;?>
<!-- Author -->
<p class="lead">
by <a href="#"><?php echo $row20011["username"]?></a>
</p>
<hr>
<!-- Date/Time -->
<p><span class="glyphicon glyphicon-time"></span> Posted on <?php echo $row2["created"] ?></p>
<hr>
<!-- Preview Image -->
<img src="<?php echo $row2['path'] ?>" class="img-responsive">
<hr>
<!-- Post Content -->
<p class="lead"><?php echo $row2["body"]?></p>
<hr>
<!-- Blog Comments -->
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<form method="POST" name="contact_form"
action="?postid=<?php echo $postid ?>&cat_id=<?php echo $cat_id1?>&subcat_id=<?php echo $subcat_id1?>">
<div class="form-group">
<textarea required name="body" class="form-control" rows="3"></textarea>
</div>
<?php if(!empty($_SESSION['userid'])) {?>
<button type="submit" value="Submit1" name='submit1' class="btn btn-primary">Submit</button>
<?php } else { ?>
<label >prove you're not a robot:</label> <br>
<p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='comment'>Enter the code above here :</label>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<button type="submit" value="Submit" name='submit'class="btn btn-primary">Submit</button> <br>
<?php } ?>
</form>
</div>
<hr>
<!-- Posted Comments -->
<!-- Comment -->
<?php
$sql1000 = "SELECT * FROM comment where postid='$postid' ";
$result2000 = $conn->query($sql1000);
if ($result2000->num_rows > 0){?>
<div class="row">
<?php while($row2000 = $result2000->fetch_assoc()){?>
<div class="media"><?php
$userid11 = $row2000["userid"];
$sql1001 = "SELECT * FROM user where userid='$userid11' ";
$result2001 = $conn->query($sql1001);
$row2001 = $result2001->fetch_assoc();
?>
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $row2001["username"]?>
<small> <?php echo $row2000["createdat"]?></small>
</h4>
<?php echo $row2000["body"]?>
</div>
</div><?php }?>
</div><?php }?><hr></div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-4">
<br>
<!-- Blog Search Well -->
<div id="wrapper-200a">
<?php
$sql145 = "SELECT * FROM category";
$result245 = $conn->query($sql145);
if ($result245->num_rows > 0){
while($row245 = $result245->fetch_assoc()) { ?> <ul> <li class="block">
<input type="checkbox" name="item" id="<?php echo $row245['cat_id'];
?> " />
<label for="<?php echo $row245['cat_id'];
?> "><i aria-hidden="true" class="icon-users"></i> <?php echo $row245['category'];
?> <span><?php
$cat_id23=$row245['cat_id'];$sql145232 = "SELECT * FROM post where cat_id=$cat_id23";
$result245232 = $conn->query($sql145232);$count123=$result245232->num_rows;
$sql14523 = "SELECT * FROM subcategory where cat_id=$cat_id23";
$result24523 = $conn->query($sql14523); echo $count123;
?></span></label>
<?php
if ($result24523->num_rows > 0){
while($row24523 = $result24523->fetch_assoc()) { ?>
<ul class="options">
<li><a href="" target="_blank"><i aria-hidden="true" class="icon-eye"></i> <?php echo $row24523['subcategory'];?><span><?php
$subcat_id23=$row24523['subcat_id'];
$sql199 = "SELECT * FROM post where subcat_id=$subcat_id23";
$result199 = $conn->query($sql199);
$count1234=$result199->num_rows;
echo $count1234;
?></span>
</a></li></ul><?php }}?>
</li></ul>
<?php }}?>
</div>
</div>
</div>
</div>
<!-- /.container -->
<hr>
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li> <a class="navbar-brand" style="
padding-top: 6px;
font-size: 12px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>
<file_sep>
<?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
if(isset($_SESSION['userid'])!="")
{
header("Location: index");
}
if(isset($_POST['insert']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
$lastname = mysqli_real_escape_string($conn, $_POST['lastname']);
$password = md5(mysqli_real_escape_string($conn,$_POST['password']));
$cpassword = md5(mysqli_real_escape_string($conn,$_POST['cpassword']));
if($password===$cpassword)
{
$sql = "INSERT INTO user (email,username,firstname, lastname,password,created) VALUES('$email','$username','$firstname','$lastname','$password',now())";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('successfully registered')
window.location.href='login.php?';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='signup.php';
</SCRIPT>");}
}
else
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('your password doesnt match')
window.location.href='signup.php';
</SCRIPT>");}
}
?><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="wp-toolbar" lang="en"><!--<![endif]--><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Brand Posts</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" id="all-css-6" href="css/style.css" type="text/css" media="all">
<link rel="stylesheet" id="all-css-6" href="css/bootstrap.css" type="text/css" media="all">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css"/>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$('#defaultForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
firstname: {
message: 'The firstname is not valid',
validators: {
notEmpty: {
message: 'Required'
},
stringLength: {
min: 2,
max: 15,
message: 'Firstname should be 2-15 length'
},
regexp: {
regexp: /^[a-z]*$/i,
message: 'The username can only consist of alphabets'
}
}
},
lastname: {
message: 'The lastname is not valid',
validators: {
notEmpty: {
message: 'Required'
},
stringLength: {
min: 2,
max: 15,
message: 'Lastname should be 2-15 length'
},
regexp: {
regexp: /^[a-z]*$/i,
message: 'The lastname can only consist of alphabets'
}
}
},
username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'Required'
},
stringLength: {
min: 2,
max: 15,
message: 'Username should be 2-15 length'
},
regexp: {
regexp: /^\w+$/,
message: 'The username can only consist of alphabetical, number'
},
different: {
field: 'password',
message: 'The username and password can\'t be the same as each other'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Required'
},
regexp: {
regexp: /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|in|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i,
message: 'Input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'Required'
},
stringLength: {
min: 6,
max:15,
message: 'Password should be 6-15 length '
},
regexp: {
regexp: /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/,
message: 'The password must contain at least one number,one lowercase letter,one uppercase letter'
},
different: {
field: 'username',
message: 'The password can\'t be the same as username'
}
}
},
cpassword: {
validators: {
notEmpty: {
message: 'Required'
},
identical: {
field: 'password',
message: 'Passwords Do Not Match!'
},
different: {
field: 'username',
message: 'The password can\'t be the same as username'
}
}
},
}
});
});
</script>
</head>
<body class="wp-admin wp-core-ui js mp6 admin-color-mp6 legacy-color-fresh edit-php auto-fold admin-bar post-type-post branch-4-4 version-4-4-1 admin-color-fresh locale-en multisite customize-support svg">
<div id="wpwrap">
<div id="wpcontent">
<div id="wpadminbar" class="ltr">
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
<div id="wpadminbar" class="ltr">
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
<ul id="wp-admin-bar-root-default" class="ab-top-menu">
<li id="wp-admin-bar-blog" class="menupop my-sites"><a class="ab-item" aria-haspopup="true" href="index">Brand</a> </li>
</ul> <ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu">
<li id="wp-admin-bar-my-account" class="menupop with-avatar no-grav"><a href="login" class="btn btn-sm btn-primary" >Have an account? Log in</a> </li>
</ul>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div></div><!-- wpcontent -->
<div class="wrapper"><?PHP
if(!empty($_SESSION['success_msg'])){ ?><br>
<div class="alert alert-danger" style="
position: absolute; left: 495px;
right: 495px;
top: 48px;
">
<?php echo $_SESSION['success_msg']; ?></div>
<?php unset($_SESSION['success_msg']); } ?>
<?php
include_once('dbconfig.php'); ?>
<div style="
position: absolute;
right: 0px;
width: 950px;">
<div style=" color: #141823;
font-family: 'Freight Sans Bold', 'lucida grande',tahoma,verdana,arial,sans-serif;
font-size: 40px;
font-weight: normal;
white-space: nowrap;">Sign Up</div>
<div style="color: #4e5665;
font-family: 'Freight Sans', 'lucida grande',tahoma,verdana,arial,sans-serif;
font-size: 22px;
font-weight: normal;
line-height: 28px;"
>It's free and always will be.</div><br>
<form class="form-horizontal" method="post" action="" id="defaultForm" method="post" >
<div class="form-group">
<div class="col-xs-3">
<input type="text" class="form-control" name="firstname" placeholder="First name"/>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="lastname" placeholder="Last name"/>
</div></div>
<div class="form-group">
<div class="col-lg-5">
<input type="text" class="form-control" name="username" placeholder="User name" required/>
</div>
</div>
<div class="form-group">
<div class="col-lg-5">
<input type="text" class="form-control" name="email" placeholder="Email"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-5">
<input style="
margin-bottom: 0px;
" type="<PASSWORD>" class="form-control" name="password" placeholder="<PASSWORD>"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-5">
<input style="
margin-bottom: 0px;"type="password" class="form-control" name="cpassword" placeholder="<PASSWORD> password"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-9 col-lg-offset-3" style="
position: absolute;
right: 100px;
">
<input type="submit" name="insert" class="btn btn-sm btn-primary">
</div>
</div>
</form></div></div>
<br class="clear">
<script type="text/javascript" src="js/wp.js"></script>
</body></html>
<file_sep>
<?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
if(isset($_SESSION['userid'])!="")
{
header("Location: index.php");
}
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
require 'config.php';
@$cat=$_GET['cat'];
@$cat3=$_GET['cat3'];
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
if(isset($_POST['submit']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
$lastname = mysqli_real_escape_string($conn, $_POST['lastname']);
$password = md5(mysqli_real_escape_string($conn,$_POST['password']));
$cpassword = md5(mysqli_real_escape_string($conn,$_POST['cpassword']));
if($password===$cpassword)
{
$sql = "INSERT INTO user (email,username,firstname, lastname,password,created) VALUES('$email','$username','$firstname','$lastname','$password',now())";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('successfully registered')
window.location.href='login.php?';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='signup.php';
</SCRIPT>");}
}
else
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('your password doesnt match')
window.location.href='signup.php';
</SCRIPT>");}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Brand - signup</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/blog-home.css" rel="stylesheet">
<script type="text/javascript">
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#7FA74D";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
} </script>
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">BRAND</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
</ul>
</div>
</div>
</nav>
<hr>
<hr>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-md-8">
<form class = "form-signin" role = "form" action = "" method = "post">
<center> <h2 class = "form-signin-heading"> Register to post with Us</h2></center>
<center> <input type = "email" class = "form-control"
name = "email" placeholder = "email" style="width: 30%;"
required autofocus></br></center>
<center> <input type = "text" class = "form-control"
name = "username" placeholder = "username " style="width: 30%;"
required ></br></center>
<center> <input type = "text" class = "form-control"
name = "firstname" placeholder = "firstname " style="width: 30%;"
required ></br></center>
<center> <input type = "text" class = "form-control"
name = "lastname" placeholder = "lastname " style="width: 30%;"
required ></br></center>
<center> <input type = "<PASSWORD>" class = "form-control" id="pass1"
name = "password" placeholder = "<PASSWORD>" style="width: 30%;" required></br></center>
<center> <input type = "password" class = "form-control" style="width: 30%;" id="pass2"
name = "cpassword" placeholder = "confirm password" onkeyup="checkPass(); return false;" required >
<center> <span id="confirmMessage" class="confirmMessage"></span></br></center>
<center> <button class = "btn btn-primary " type = "submit"
name = "submit">sign up</button></center>
</form>
</div>
<div class="col-md-4">
<div class="well">
<CENTER><p >
Already registered
</p> </CENTER><CENTER> <a href="login" class = "btn btn-sm btn-primary " >Login</a> </CENTER>
</div>
<!-- Blog Categories Well -->
<!-- Side Widget Well -->
<div class="well">
<h4>About Us</h4>
<p>DEVELOPERS MODEL</p>
</div>
</div>
</div> </div>
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li> <a class="navbar-brand" style="
padding-top: 6px;
font-size: 12px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
<file_sep><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<?php
$conn=mysqli_connect("localhost","root","","new");
$s12 = "SELECT * FROM category ";
$re12=mysqli_query($conn,$s12);
while($row12 = $re12->fetch_assoc())
{
$che=$row12['cat_id'];
echo '<input type="checkbox" id="'.$che.'"/>';?><script>
$('#<?php echo $che;?>').click(function() {
$("#hi").toggle(this.checked);
});
</script><?php }?>
<div id="hi" style="display:none">Age is something</div></body></html><file_sep><?php
$conn=mysqli_connect("localhost","root","","new");
$postid = mysqli_real_escape_string($conn,$_GET['postid']);
$sql="DELETE from post WHERE postid = $postid" ;
$sql1="DELETE from comment WHERE postid = $postid" ;
if ($conn->query($sql) === TRUE AND $conn->query($sql1) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('successfully deleted')
window.location.href='adpost.php';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='adpost.php';
</SCRIPT>");}
?>
<file_sep><?php
$userid = $_SESSION['userid'];
$conn=mysqli_connect("localhost","root","","new");
$catlabel = mysqli_real_escape_string($conn,$_POST['catlabel']);
$sublabel = mysqli_real_escape_string($conn, $_POST['sublabel']);
if ($_POST['submit']) {
$sql10 = "SELECT * FROM category where category= '$catlabel'";
$res10=mysqli_query($conn,$sql10);
$reee=mysqli_fetch_array($res10,MYSQLI_ASSOC);
$q=$reee["cat_id"];
$sql="INSERT into subcategory (cat_id,subcategory,createdat,userid) value('$q','$sublabel',now(),$userid)";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('subcategory successfully created')
window.location.href='adcat.php';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='admin.php';
</SCRIPT>");}
}
?>
<file_sep><?php
$conn=mysqli_connect("localhost","root","","new");
$subcat_id = mysqli_real_escape_string($conn,$_GET['subcat_id']);
$sql1="DELETE from subcategory WHERE subcat_id = $subcat_id" ;
$sql2="DELETE from post WHERE subcat_id = $subcat_id" ;
$sql3="DELETE from comment WHERE subcat_id = $subcat_id" ;
if ( $conn->query($sql1) === TRUE AND $conn->query($sql2) === TRUE AND $conn->query($sql3) === TRUE ) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('successfully deleted')
window.location.href='adcat.php';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='adcat.php';
</SCRIPT>");}
?><file_sep>
<?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
if(isset($_SESSION['userid'])!="")
{
header("Location: index");
}
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
require 'config.php';
@$cat=$_GET['cat'];
@$cat3=$_GET['cat3'];
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
if(isset($_POST['submit']))
{
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5(mysqli_real_escape_string($conn,$_POST['password']));
$sql = "SELECT * FROM user WHERE username='$username'";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_array($query, MYSQLI_ASSOC);
if ($result['password'] === $password)
{
if($result['admin']==1)
{
$_SESSION['userid'] = $result['userid'];
header("Location:admin");
}
elseif($result['admin']==0)
{
$_SESSION['userid'] = $result['userid'];
header("Location: profile");
}
}
else
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('wrong details')
window.location.href='login';
</SCRIPT>");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Brand - Login</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/blog-home.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index">BRAND</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
</div>
</div>
</nav>
<hr>
<hr>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-md-8">
<form class = "form-signin" role = "form" action = "" method = "post">
<CENTER> <h2 class = "form-signin-heading">Member Login </h2></CENTER>
<CENTER> <input type = "text" class = "form-control" style="width: 30%;"
name = "username" placeholder = "username "
required autofocus></CENTER><BR>
<CENTER> <input type = "password" class = "form-control"style="width: 30%;"
name = "password" placeholder = "password" required></CENTER><BR>
<CENTER> <button class = "btn btn-sm btn-primary " type = "submit"
name = "submit">Login</button></CENTER>
</form></div>
<div class="col-md-4">
<div class="well">
<CENTER><p >
One Account for everything in Brand
</p> </CENTER><CENTER> <a href="signup" class = "btn btn-sm btn-primary " >Create account</a> </CENTER>
</div>
<!-- Blog Categories Well -->
<!-- Side Widget Well -->
<div class="well">
<h4>About Us</h4>
<p>DEVELOPERS MODEL</p>
</div>
</div>
</div> </div>
<!-- /.row -->
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li> <a class="navbar-brand" style="
padding-top: 6px;
font-size: 12px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
<file_sep><?php
$conn=mysqli_connect("localhost","root","","new");
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$query = "SELECT * FROM student LIMIT $start_from, $per_page";
$result = mysqli_query ($conn, $query);
?><!DOCTYPE html><html>
<head>
<title>PHP Pagination</title>
</head><body>
<table align=”center” border=”2″ cellpadding=”3″>
<tr><th>Name</th><th>Phone</th><th>Country</th></tr>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr align=”center”>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['number']; ?></td>
<td><?php echo $row['country']; ?></td>
</tr>
<?php
};
?>
</table>
<div>
<?php
$query = 'select * from student';
$result = mysqli_query($conn, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<center><a href='pagination.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='pagination.php?page=".$i."''>".$i."</a> ";
};
echo "<a href='pagination.php?page=$total_pages'>".'Last Page'."</a></center> ";
?>
</div>
</body>
</html><file_sep><?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
$userid = $_SESSION['userid'];
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
if(isset($_SESSION['userid'])=="")
{
session_destroy();
unset($_SESSION['user']);
header("Location: login");
}
elseif ($r['admin']==0 ) {
session_destroy();
unset($_SESSION['user']);
header("Location: login");
}
else
{
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
require 'config.php';
@$cat=$_GET['cat'];
@$cat3=$_GET['cat3'];
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>BRAND</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/noticons.css">
<link rel="stylesheet" href="css/editor.min.css">
<link rel="stylesheet" href="css/wpcom.css">
<link rel="stylesheet" href="css/buttons.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/hovercard.css">
<link rel="stylesheet" href="css/services.css">
<link rel="stylesheet" href="css/style3.css">
<link rel="stylesheet" href="accordionmenu.css" type="text/css" media="screen" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="./jquery.tabletoCSV.js" type="text/javascript" charset="utf-8"></script>
<script src="css/wpgroho.js" type="text/javascript" charset="utf-8"></script>
<script src="css/loader0.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function(){
$("#export").click(function(){
$("#export_table").tableToCSV();
});
});
</script>
</head>
<body>
<div id="wpadminbar" class="ltr">
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
<ul id="wp-admin-bar-root-default" class="ab-top-menu">
<li id="wp-admin-bar-blog" class="menupop my-sites"><a class="ab-item" aria-haspopup="true" href="index">Brand</a> </li>
</ul>
<ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu">
<li id="wp-admin-bar-my-account" class="menupop with-avatar no-grav"><a href="logout.php?logout" class="ab-item" aria-haspopup="true"><img alt="" src="https://2.gravatar.com/avatar/eda4e5db5db0ede52414c9ca5c31d1fa?s=32&d=mm&r=G" class="avatar avatar-32" height="32" width="32"></a> </li>
<li id="wp-admin-bar-ab-new-post"><a class="ab-item" href="createpost"></a> </li> </ul>
</div>
</div>
<br>
<div id="adminmenuwrap" style="
top: 2px;
">
<ul id="adminmenu">
<li class="wp-first-item wp-has-submenu wp-has-current-submenu wp-menu-open menu-top menu-top-first menu-icon-dashboard" id="menu-dashboard">
<a href="admin" class="wp-first-item wp-has-submenu wp-has-current-submenu wp-menu-open menu-top menu-top-first menu-icon-dashboard" aria-haspopup="false"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-dashboard"><br></div><div class="wp-menu-name">Dashboard</div></a>
</li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-post open-if-no-js menu-top-first" id="menu-posts">
<a href="adpost" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-post open-if-no-js menu-top-first" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-post"><br></div><div class="wp-menu-name">Posts</div></a>
</li>
<li class="wp-not-current-submenu menu-top menu-icon-comments" id="menu-comments">
<a href="adcom" class="wp-not-current-submenu menu-top menu-icon-comments"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-comments"><br></div><div class="wp-menu-name">Comments </div></a></li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-users" id="menu-users">
<a href="aduser" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-users" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-users"><br></div><div class="wp-menu-name">Users</div></a>
</li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-links" id="menu-links">
<a href="adcat" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-links" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-links"><br></div><div class="wp-menu-name">Categories</div></a>
</li>
</ul>
</div>
<div class='container' style="
margin-left: 170px;
margin-top: 22px;
margin-right: 15px;
">
<?php
$sqlROW = "SELECT * FROM post";
$resultROW=mysqli_query($conn,$sqlROW);
$row_cntROW = $resultROW->num_rows;
?>
<div class="row">
<div class="col-lg-6">
<div class="well">
<h1 class="page-header">USER POSTS<BR>
<small><?php echo $row_cntROW ?> Posts found</small>
</h1>
<a class="btn btn-primary" href="adpost.php">View <span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
<?php
$sql72 = "SELECT * FROM comment ";
$result72=mysqli_query($conn,$sql72);
$row_cnt72 = $result72->num_rows;
?>
<div class="col-lg-6">
<div class="well">
<h1 class="page-header">USER COMMENTS<BR>
<small><?php echo $row_cnt72 ?> comments found</small>
</h1> <a class="btn btn-primary" href="adcom.php">View <span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div> </div>
</div>
<div class='container' style="
margin-left: 170px;
margin-top: 22px;
margin-right: 15px;
">
<div class="row">
<div class="col-lg-6">
<div class="well">
<?php
$sql5 = "SELECT * FROM user where admin=0 AND userid!=0 ";
$result7=mysqli_query($conn,$sql5);
$row_cnt = $result7->num_rows;?>
<h1 class="page-header">LIST OF USERS<BR>
<small><?php echo $row_cnt ?> Users found</small>
</h1> <a class="btn btn-primary" href="aduser.php">View <span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
<div class="col-lg-6">
<div class="well">
<h1 class="page-header">CREATE CATEGORY<BR>
<small>SUB CATEGORY</small>
</h1> <a class="btn btn-primary" href="adcat.php">Create<span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
</div>
</div>
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li><a class="navbar-brand" style="
padding-top: 6px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<script src="js/bootstrap.min.js"></script>
</body>
</html><?php }?><file_sep><?php
session_start();
include_once('dbConfig.php');
if(isset($_POST['bulk_delete_submit'])){
$idArr = $_POST['checked_id'];
foreach($idArr as $comid){
mysqli_query($conn,"DELETE FROM comment WHERE comid=".$comid);
}
$_SESSION['success_msg'] = 'Comments have been deleted successfully.';
header("Location:adcom");
}
?><file_sep><?php
if(isset($_POST['insert']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
$lastname = mysqli_real_escape_string($conn, $_POST['lastname']);
$password = md5(mysqli_real_escape_string($conn,$_POST['password']));
$cpassword = md5(mysqli_real_escape_string($conn,$_POST['cpassword']));
if($password===$cpassword)
{
$sql = "INSERT INTO user (email,username,firstname, lastname,password,created) VALUES('$email','$username','$firstname','$lastname','$password',now())";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('successfully registered')
window.location.href='login.php?';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='signup.php';
</SCRIPT>");}
}
}
?><file_sep><?php
$userid = $_SESSION['userid'];
$conn=mysqli_connect("localhost","root","","new");
if(isset($_POST['submit']))
{
$categorylabel = mysqli_real_escape_string($conn, $_POST['categorylabel']);
$sql = "INSERT INTO category (category,createdat,userid) VALUES('$categorylabel',now(),$userid)";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('category created successfully')
window.location.href='adcat.php';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='admin.php';
</SCRIPT>");}
}
?><file_sep><?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
if(isset($_SESSION['userid'])=="")
{
session_destroy();
unset($_SESSION['user']);
header("Location: login.php");
}
elseif(!empty($_SESSION['userid']))
{
$userid = $_SESSION['userid'];
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
$r10=mysqli_fetch_array($re,MYSQLI_ASSOC);
require 'config.php';
@$cat=$_GET['cat'];
@$cat3=$_GET['cat3'];
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);?>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Brand</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/blog-home.css" rel="stylesheet">
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='createpost.php?cat=' + val ;
}
function reload3(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
var val2=form.subcat.options[form.subcat.options.selectedIndex].value;
self.location='createpost.php?cat=' + val + '&cat3=' + val2 ;
}
</script>
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">BRAND</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<?php if(!empty($_SESSION['userid']))
{
?>
<li >
<a href="profile.php?userid=<?php echo $userid?>" ><span class="glyphicon glyphicon-user"></span> profile</a>
</li>
<li>
<a href="logout.php?logout"><span class="glyphicon glyphicon-log-in"></span> <?php echo $r10['username'];?>, logout</a>
</li>
<?php } else { ?>
<li >
<a href="signup.php" ><span class="glyphicon glyphicon-user"></span> Create blog</a>
</li>
<li >
<a href="login.php" ><span class="glyphicon glyphicon-log-in"></span> Login</a>
</li>
<?php } ?>
</ul>
</div>
</div>
</nav>
<hr>
<hr>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-md-8">
<?php
$re=mysqli_query($conn,$s);
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);?>
<br>
<div id='new'>
<h1 class="page-header">Create Ur Own Posts</h1>
<?Php
$quer2="SELECT DISTINCT category,cat_id FROM category order by category";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT subcategory,subcat_id FROM subcategory where cat_id=$cat order by subcategory";
}else{$quer="SELECT DISTINCT subcategory,subcat_id FROM subcategory order by subcategory"; }
if(isset($cat3) and strlen($cat3) > 0){
$quer3="SELECT DISTINCT subcat2 FROM subcategory2 where subcat_id=$cat3 order by subcat2";
}else{$quer3="SELECT DISTINCT subcat2 FROM subcategory2 order by subcat2"; }
?>
<form method="post" enctype="multipart/form-data" action='upload.php?userid=<?php echo $userid?>&cat_id=<?php echo $cat?>&subcat_id=<?php echo $cat3?>'>
<?php
echo "CATEGORY: <select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['cat_id']==@$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}?>
<?php
echo "</select><BR><BR>";
echo "SUB-CATEGORY: <select name='subcat' onchange=\"reload3(this.form)\"><option value=''>Select one</option>";
foreach ($dbo->query($quer) as $noticia) {
if($noticia['subcat_id']==@$cat3){echo "<option selected value='$noticia[subcat_id]'>$noticia[subcategory]</option>"."<BR>";}
else{echo "<option value='$noticia[subcat_id]'>$noticia[subcategory]</option>";}
}?>
<?PHP
echo "</select><BR><BR>";
?>
TITLE:
<input type='text' name="title"><BR><BR>
BODY:
<textarea name="body"rows="4" cols="50" required>
</textarea><BR><BR>
<input type='file' name='image' required><BR><BR>
<button class = "btn " type="submit" value="submit" name="submit" />POST</button>
</form>
</div></div>
<div class="col-md-4">
<div class="well">
<center> <h3>Categories</h3></center>
<div style="margin-left: -29px;" >
<?php
$sql901 = "SELECT * FROM category";
$result901 = $conn->query($sql901);
$rows901 = $result901->num_rows; // Find total rows returned by database
if($rows901 > 0) {
$cols901 = 2; // Define number of columns
$counter901 = 1; // Counter used to identify if we need to start or end a row
$nbsp901 = $cols901 - ($rows901 % $cols901); // Calculate the number of blank columns
echo '<table width="78%" align="center" >';
while ($rows901= $result901->fetch_array()) {
if(($counter901 % $cols901) == 1) { // Check if it's new row
echo '<tr>';
}
echo '<td><h4 style="margin-left: 29px;"><a href="catpage.php?cat_id='.$rows901['cat_id'].'">'.$rows901['category'].'</a></h4></td>';
if(($counter901 % $cols901) == 0) { // If it's last column in each row then counter remainder will be zero
echo '</tr>';
}
$counter901++; // Increase the counter
}
$result901->free();
if($nbsp901 > 0) { // Add unused column in last row
for ($i901 = 0; $i901 < $nbsp901; $i901++) {
echo '<td> </td>';
}
echo '</tr>';
}
echo '</table>';
}
?></div></div>
<div class="well" >
<center> <h4>Sub Categories</h4></center>
<div style="margin-left: 23px;">
<?php
$sql90 = "SELECT * FROM subcategory";
$result90 = $conn->query($sql90);
$rows90 = $result90->num_rows; // Find total rows returned by database
if($rows90 > 0) {
$cols = 4; // Define number of columns
$counter = 1; // Counter used to identify if we need to start or end a row
$nbsp = $cols - ($rows90 % $cols); // Calculate the number of blank columns
echo '<table width="100%" align="center" >';
while ($row90= $result90->fetch_array()) {
if(($counter % $cols) == 1) { // Check if it's new row
echo '<tr>';
}
echo '<td><h5><a href="subcatpage.php?subcat_id='.$row90['subcat_id'].'">'.$row90['subcategory'].'</a></h5></td>';
if(($counter % $cols) == 0) { // If it's last column in each row then counter remainder will be zero
echo '</tr>';
}
$counter++; // Increase the counter
}
$result90->free();
if($nbsp > 0) { // Add unused column in last row
for ($i = 0; $i < $nbsp; $i++) {
echo '<td> </td>';
}
echo '</tr>';
}
echo '</table>';
}
?></div>
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>About Us</h4>
<p>DEVELOPERS MODEL</p>
</div>
</div>
</div> </div>
<hr>
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li> <a class="navbar-brand" style="
padding-top: 6px;
font-size: 12px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html><?php }?><file_sep><?php
session_start();
$conn=mysqli_connect("localhost","root","","new");
$userid = $_SESSION['userid'];
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
if(isset($_SESSION['userid'])=="")
{
session_destroy();
unset($_SESSION['user']);
header("Location: login");
}
elseif ($r['admin']==0 ) {
session_destroy();
unset($_SESSION['user']);
header("Location: login");
}
else
{
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
require 'config.php';
@$cat=$_GET['cat'];
@$cat3=$_GET['cat3'];
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en" style="
BACKGROUND-COLOR: #FFFFFF;
">
<head>
<title>BRAND</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/noticons.css">
<link rel="stylesheet" href="css/editor.min.css">
<link rel="stylesheet" href="css/wpcom.css">
<link rel="stylesheet" href="css/buttons.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/hovercard.css">
<link rel="stylesheet" href="css/services.css">
<link rel="stylesheet" href="css/style3.css">
<link rel="stylesheet" href="accordionmenu.css" type="text/css" media="screen" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="./jquery.tabletoCSV.js" type="text/javascript" charset="utf-8"></script>
<script src="css/wpgroho.js" type="text/javascript" charset="utf-8"></script>
<script src="css/loader0.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function(){
$("#export").click(function(){
$("#export_table").tableToCSV();
});
});
</script>
</head>
<body>
<div id="wpadminbar" class="ltr">
<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
<ul id="wp-admin-bar-root-default" class="ab-top-menu">
<li id="wp-admin-bar-blog" class="menupop my-sites"><a class="ab-item" aria-haspopup="true" href="index">Brand</a> </li>
</ul>
<ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu">
<li id="wp-admin-bar-my-account" class="menupop with-avatar no-grav"><a href="logout.php?logout" class="ab-item" aria-haspopup="true"><img alt="" src="https://2.gravatar.com/avatar/eda4e5db5db0ede52414c9ca5c31d1fa?s=32&d=mm&r=G" class="avatar avatar-32" height="32" width="32"></a> </li>
<li id="wp-admin-bar-ab-new-post"><a class="ab-item" href="createpost"></a> </li> </ul>
</div>
</div>
<br>
<div id="adminmenuwrap" style="
top: 2px;
">
<ul id="adminmenu">
<li class="wp-not-current-submenu menu-top menu-icon-comments" id="menu-comments">
<a href="admin" class="wp-not-current-submenu menu-top menu-icon-comments"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-dashboard"><br></div><div class="wp-menu-name">Dashboard </div></a></li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-post open-if-no-js menu-top-first" id="menu-posts">
<a href="adpost" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-post open-if-no-js menu-top-first" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-post"><br></div><div class="wp-menu-name">Posts</div></a>
</li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-users" id="menu-users">
<a href="adcom" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-users" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-comments"><br></div><div class="wp-menu-name">Comments</div></a>
</li>
<li class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-links" id="menu-links">
<a href="aduser" class="wp-has-submenu wp-not-current-submenu menu-top menu-icon-links" aria-haspopup="true"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-users"><br></div><div class="wp-menu-name">Users</div></a>
</li>
</li><li class="wp-first-item wp-has-submenu wp-has-current-submenu wp-menu-open menu-top menu-top-first menu-icon-dashboard" id="menu-dashboard">
<a href="adcat" class="wp-first-item wp-has-submenu wp-has-current-submenu wp-menu-open menu-top menu-top-first menu-icon-dashboard" aria-haspopup="false"><div class="wp-menu-arrow"><div></div></div><div class="wp-menu-image dashicons-before dashicons-admin-links"><br></div><div class="wp-menu-name">Categories</div></a>
</li>
</ul>
</div>
<div class="container" style="
margin-left: 170px;
margin-top: 22px;
margin-right: 15px;
">
<div class='row'>
<div class='col-lg-3'>
<div class='well'>
<h3 class="page-header">Category</h3>
<form action="crecat.php" method="post" >
name<input type="text" name="categorylabel" required><br><br>
<button class = "btn " type="submit" value="submit" name="submit" />Create</button>
</form></div>
<div class="well"><h3 class="page-header">Sub-category</h3>
<?php $sql10 = "SELECT * FROM category ";
$res10=mysqli_query($conn,$sql10);
?>
<form action="subcat.php" method="post" enctype="multipart/form-data">
category
<?php
echo "<select name='catlabel'>";
while ($reee=mysqli_fetch_array($res10,MYSQLI_ASSOC)) {
echo '<option value="' . $reee[category] . '">'.$reee[category].'</option>';;
}
echo "</select>";?>
<br>sub category<input type="text" name="sublabel" required><br>
<br>
<button class = "btn " type="submit" value="submit" name="submit" />Create</button>
</form>
</div>
</div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-lg-9">
<div class='well'> <center> <h4> Categories</h4></center>
<hr>
<div style="margin-left: 230px;">
<?php
$sql1 = "SELECT * FROM category";
$result2 = $conn->query($sql1);
if ($result2->num_rows > 0){
while($row2 = $result2->fetch_assoc()) { ?>
<div class="row">
<div class="col-sm-3">
<h3> <a href="catpage.php?cat_id=<?php echo $row2['cat_id']?>" ><?php echo $row2['category'] ?></a><h3>
</div>
<div class="col-sm-5" style="padding-top: 20px;">
<a class="btn btn-sm btn-primary" href="catpage.php?cat_id=<?php echo $row2['cat_id']?>">View</a>
<a class="btn btn-sm btn-danger" href="delcat.php?cat_id=<?php echo $row2['cat_id']?>">Delete</a>
</div>
</div>
<hr> <?php
}
} else {
echo "0 results";}
?>
</div>
</div></div></div></div>
<div class="container" style="
margin-left: 170px;
margin-top: 22px;
margin-right: 15px;
">
<div class='row'>
<div class="well">
<center> <h4>Sub Categories</h4></center>
<div style="margin-left: 50px;">
<?php
$sql90 = "SELECT * FROM subcategory";
$result90 = $conn->query($sql90);
$rows90 = $result90->num_rows; // Find total rows returned by database
if($rows90 > 0) {
$cols = 4; // Define number of columns
$counter = 1; // Counter used to identify if we need to start or end a row
$nbsp = $cols - ($rows90 % $cols); // Calculate the number of blank columns
echo '<table width="100%" align="center" >';
while ($row90= $result90->fetch_array()) {
if(($counter % $cols) == 1) { // Check if it's new row
echo '<tr>';
}?>
<?php
echo '<td>
<div style="
align: center;" "><h2><a href="subcatpage.php?subcat_id='.$row90['subcat_id'].'">'.$row90['subcategory'].'</a></h2></div> <div >
<a class="btn btn-sm btn-primary" href="subcatpage.php?subcat_id='. $row90['subcat_id'].'">View</a>
<a class="btn btn-sm btn-danger" href="delsubcat.php?subcat_id='. $row90['subcat_id'].'">Delete</a>
</td>';?>
<?php
if(($counter % $cols) == 0) {?>
<?php
// If it's last column in each row then counter remainder will be zero
echo '</tr>';
}
$counter++; // Increase the counter
}
$result90->free();
if($nbsp > 0) { // Add unused column in last row
for ($i = 0; $i < $nbsp; $i++) {
echo '<td> </td>';
}
echo '</tr>';
}
echo '</table>';
}
?></div>
</div>
</div></div>
<hr>
<!-- Side Widget Well -->
<!-- /.row -->
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12" style="
height: 30px;
">
<ul class="nav navbar-nav navbar-right">
<li> <a class="navbar-brand" style="
padding-top: 6px;
font-size: 12px;
"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<script src="js/bootstrap.min.js"></script>
</body>
</html><?php }?><file_sep><?php
session_start();
if(empty($_GET['postid'])) {
header("Location: login.php");
}
if(!empty($_SESSION['userid'])) {
$userid = $_SESSION['userid'];}
else
{
$userid='0';
}
$postid = $_GET['postid'];
$conn=mysqli_connect("localhost","root","","new");
$s = "SELECT * FROM user where userid='$userid' ";
$re=mysqli_query($conn,$s);
$r=mysqli_fetch_array($re,MYSQLI_ASSOC);
if(isset($_POST['submit']))
{
$body= $_POST['body'];
$postid = $_GET['postid'];
$cat_id = $_GET['cat_id'];
$subcat_id = $_GET['subcat_id'];
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('captacha doesnt match ')
window.location.href='post.php?postid=$postid';
</SCRIPT>");}
else
{
$sql="INSERT into comment (body,postid,createdat,userid,cat_id,subcat_id) value('$body','$postid',now(),'$userid','$cat_id','$subcat_id')";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('thanks for posting comment')
window.location.href='post.php?postid=$postid';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='index.php';
</SCRIPT>");}
}
}
if(isset($_POST['submit1']))
{
$body= $_POST['body'];
$postid = $_GET['postid'];
$cat_id = $_GET['cat_id'];
$subcat_id = $_GET['subcat_id'];
$sql="INSERT into comment (body,postid,createdat,userid,cat_id,subcat_id) value('$body','$postid',now(),'$userid','$cat_id','$subcat_id')";
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('thanks for posting comment')
window.location.href='post.php?postid=$postid';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='index.php';
</SCRIPT>");}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Blog Post - Start Bootstrap Template</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/blog-post.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">BRAND</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active"><a href="index.php">Home</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<?php if(!empty($_SESSION['userid'])) {?>
<li>
<a href="logout.php?logout"><span class="glyphicon glyphicon-log-in"></span> <?php echo $r['username'];?>, logout</a>
</li>
<?php } else { ?>
<li >
<a href="signup.php" ><span class="glyphicon glyphicon-user"></span> Create blog</a>
</li>
<li >
<a href="login.php" ><span class="glyphicon glyphicon-log-in"></span> Login</a>
</li>
<?php } ?>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<?php
$sql1 = "SELECT * FROM post where postid='$postid' ";
?>
<div class="row">
<?php
$result2 = $conn->query($sql1);
$row2 = $result2->fetch_assoc();
$cat_id1 = $row2["cat_id"];
$subcat_id1 = $row2["subcat_id"];
$userid111 = $row2["userid"];
$sql10011 = "SELECT * FROM user where userid='$userid111' ";
$result20011 = $conn->query($sql10011);
$row20011 = $result20011->fetch_assoc();?>
<!-- Blog Post Content Column -->
<div class="col-lg-8">
<!-- Blog Post -->
<!-- Title -->
<?php echo "<h1 >".$row2["title"]."</h1>" ;?>
<!-- Author -->
<p class="lead">
by <a href="#"><?php echo $row20011["username"]?></a>
</p>
<hr>
<!-- Date/Time -->
<p><span class="glyphicon glyphicon-time"></span> Posted on <?php echo $row2["created"] ?></p>
<hr>
<!-- Preview Image -->
<img src="<?php echo $row2['path'] ?>" class="img-responsive">
<hr>
<!-- Post Content -->
<p class="lead"><?php echo $row2["body"]?></p>
<hr>
<!-- Blog Comments -->
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<form method="POST" name="contact_form"
action="?postid=<?php echo $postid ?>&cat_id=<?php echo $cat_id1?>&subcat_id=<?php echo $subcat_id1?>">
<div class="form-group">
<textarea required name="body" class="form-control" rows="3"></textarea>
</div>
<?php if(!empty($_SESSION['userid'])) {?>
<button type="submit" value="Submit1" name='submit1' class="btn btn-primary">Submit</button>
<?php } else { ?>
<label >prove you're not a robot:</label> <br>
<p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='comment'>Enter the code above here :</label>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<button type="submit" value="Submit" name='submit'class="btn btn-primary">Submit</button> <br>
<?php } ?>
</form>
</div>
<hr>
<!-- Posted Comments -->
<!-- Comment -->
<?php
$sql1000 = "SELECT * FROM comment where postid='$postid' ";
$result2000 = $conn->query($sql1000);
if ($result2000->num_rows > 0){?>
<div class="row">
<?php while($row2000 = $result2000->fetch_assoc()){?>
<div class="media"><?php
$userid11 = $row2000["userid"];
$sql1001 = "SELECT * FROM user where userid='$userid11' ";
$result2001 = $conn->query($sql1001);
$row2001 = $result2001->fetch_assoc();
?>
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $row2001["username"]?>
<small> <?php echo $row2000["createdat"]?></small>
</h4>
<?php echo $row2000["body"]?>
</div>
</div><?php }?>
</div><?php }?></div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-4">
<!-- Blog Search Well -->
<!-- Blog Categories Well -->
<div class="well">
<center> <h3>Categories</h3></center>
<div style="margin-left: -29px;" >
<?php
$sql901 = "SELECT * FROM category";
$result901 = $conn->query($sql901);
$rows901 = $result901->num_rows; // Find total rows returned by database
if($rows901 > 0) {
$cols901 = 2; // Define number of columns
$counter901 = 1; // Counter used to identify if we need to start or end a row
$nbsp901 = $cols901 - ($rows901 % $cols901); // Calculate the number of blank columns
echo '<table width="78%" align="center" >';
while ($rows901= $result901->fetch_array()) {
if(($counter901 % $cols901) == 1) { // Check if it's new row
echo '<tr>';
}
echo '<td><h4 style="margin-left: 29px;"><a href="catpage.php?cat_id='.$rows901['cat_id'].'">'.$rows901['category'].'</a></h4></td>';
if(($counter901 % $cols901) == 0) { // If it's last column in each row then counter remainder will be zero
echo '</tr>';
}
$counter901++; // Increase the counter
}
$result901->free();
if($nbsp901 > 0) { // Add unused column in last row
for ($i901 = 0; $i901 < $nbsp901; $i901++) {
echo '<td> </td>';
}
echo '</tr>';
}
echo '</table>';
}
?></div></div>
<div class="well" >
<center> <h4>Sub Categories</h4></center>
<div style="margin-left: 23px;">
<?php
$sql90 = "SELECT * FROM subcategory";
$result90 = $conn->query($sql90);
$rows90 = $result90->num_rows; // Find total rows returned by database
if($rows90 > 0) {
$cols = 4; // Define number of columns
$counter = 1; // Counter used to identify if we need to start or end a row
$nbsp = $cols - ($rows90 % $cols); // Calculate the number of blank columns
echo '<table width="100%" align="center" >';
while ($row90= $result90->fetch_array()) {
if(($counter % $cols) == 1) { // Check if it's new row
echo '<tr>';
}
echo '<td><h5><a href="subcatpage.php?subcat_id='.$row90['subcat_id'].'">'.$row90['subcategory'].'</a></h5></td>';
if(($counter % $cols) == 0) { // If it's last column in each row then counter remainder will be zero
echo '</tr>';
}
$counter++; // Increase the counter
}
$result90->free();
if($nbsp > 0) { // Add unused column in last row
for ($i = 0; $i < $nbsp; $i++) {
echo '<td> </td>';
}
echo '</tr>';
}
echo '</table>';
}
?></div>
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>ABOUT US</h4>
<p>Developers model</p>
</div>
</div>
</div>
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<hr>
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container-fluid">
<div class="col-lg-12">
<ul class="nav navbar-nav navbar-right">
<li><a class="navbar-brand"> ©2016 Brand.in </a></li>
</ul></div>
</div>
</nav>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>
<file_sep><?php
$conn=mysqli_connect("localhost","root","","new");
$cat_id = mysqli_real_escape_string($conn,$_GET['cat_id']);
$sql="DELETE from category WHERE cat_id = $cat_id" ;
$sql1="DELETE from subcategory WHERE cat_id = $cat_id" ;
$sql2="DELETE from post WHERE cat_id = $cat_id" ;
$sql3="DELETE from comment WHERE cat_id = $cat_id" ;
if ($conn->query($sql) === TRUE AND $conn->query($sql1) === TRUE AND $conn->query($sql2) === TRUE AND $conn->query($sql3) === TRUE ) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('successfully deleted')
window.location.href='adcat.php';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='adcat.php';
</SCRIPT>");}
?><file_sep>CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Deactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `users` (`id`, `first_name`, `last_name`, `email`, `phone`, `created`, `modified`, `status`) VALUES
(NULL, 'Nitya', 'Maity', '<EMAIL>', '123456', '2015-04-17 00:00:00', '2015-04-17 00:00:00', 1),
(NULL, 'Codex', 'World', '<EMAIL>', '123456', '2015-04-17 00:00:00', '2015-04-17 00:00:00', 1),
(NULL, 'Raj', 'Ans', '<EMAIL>', '123456', '2015-04-17 00:00:00', '2015-04-17 00:00:00', 1),
(NULL, 'John', 'Thomas', '<EMAIL>', '123456', '2015-04-17 00:00:00', '2015-04-17 00:00:00', 1),
(NULL, 'Kate', 'Bell', '<EMAIL>', '123456', '2015-04-17 00:00:00', '2015-04-17 00:00:00', 1);<file_sep><?php
$conn=mysqli_connect("localhost","root","","new");
$comid = mysqli_real_escape_string($conn,$_GET['comid']);
$sql="DELETE from comment WHERE comid = $comid" ;
if ($conn->query($sql) === TRUE) {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('successfully deleted')
window.location.href='adcom.php';
</SCRIPT>");}
else {
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('connection error')
window.location.href='adcom.php';
</SCRIPT>");}
?>
<file_sep><?php
set_time_limit(0);
require 'PHPMailer-master/PHPMailerAutoload.php';
$user_name=$_POST['user_name'];
$user_email=$_POST['user_email'];
$user_message=$_POST['user_message'];
$final_message=$user_name.'/'.$user_email.'/'.$user_message;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
$mail->Host =$mail->Host = gethostbyname('sg2plcpnl0101.prod.sin2.secureserver.net
');
$mail->Port = 465; // or 465
$mail->IsHTML(true);
$mail->Username = '<EMAIL>';
$mail->Password = '<PASSWORD>';
$mail->SetFrom('<EMAIL>');
$mail->Subject = 'FeedBack';
$mail->Body = $final_message;
$mail->AddAddress('<EMAIL>');
if(!$mail->Send()) {
echo '<pre>';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?> | 84445f9504d9827c52082b46e188b98f7560b116 | [
"SQL",
"PHP"
] | 22 | PHP | mavi257/first | d04270505c961eec314fa9da9e2d12610a5e9809 | 9daca6a1df91242732acc27df2cdf34f6f1284f4 |
refs/heads/master | <repo_name>PavlMais/LogicForms<file_sep>/clientapp/src/rete/components/Question.js
import Rete from "rete";
import VueQuestion from './Question.vue';
import SelectControl from '../controls/SelectControl.js';
export default class QuestionComponent extends Rete.Component {
constructor() {
super("Question");
this.data.component = VueQuestion;
}
builder(node) {
//node.addOutput(new Rete.Output('num', 'Next question', node.data.d_socket));
//node.addInput(new Rete.Input('num2', 'test', node.data.d_socket));
node.addControl(new SelectControl('ke', false));
}
worker(node, inputs, outputs) {
//console.log('working');
//outputs['num'] = node.data.num;
}
}<file_sep>/Entities/DBContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LogicForms.Entities
{
public class ApplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Form> Forms { get; set; }
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
{
}
public ApplicationContext()
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public override int SaveChanges()
{
ChangeTracker.DetectChanges();
return base.SaveChanges();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
}
}
<file_sep>/clientapp/src/rete/controls/TextControl.js
import Rete from "rete";
var VueTextControl = {
props: ['readonly', 'emitter', 'ikey', 'getData', 'putData'],
template: `
<div class="input-group input-group-sm">
<input type="text" class="form-control" :readonly="readonly" placeholder="Question" :value="value" @input="change($event)" @dblclick.stop="">
</div>
`,
data() {
return {
value: "",
}
},
methods: {
change(e) {
this.value = e.target.value;
this.update();
},
update() {
//if (this.ikey)
// this.putData(this.ikey, this.value)
this.putData('title', this.value)
this.emitter.trigger('process');
}
},
mounted() {
this.value = this.getData(this.ikey);
}
}
export default class TextControl extends Rete.Control {
constructor(emitter, key, readonly) {
super(key);
this.data.render = 'vue';
this.component = VueTextControl;
this.props = { emitter, ikey: key, readonly };
}
setValue(val) {
this.vueContext.value = val;
}
}
<file_sep>/clientapp/src/rete/controls/ListControl.js
import Rete from "rete";
import ModifyList from '../../components/modif_list.vue'
var VueListControl = {
props: ['readonly', 'emitter', 'ikey', 'getData', 'putData', 'onItemAdded', 'onItemRemoved', 'node'],
components: {
ModifyList
},
template: `<ModifyList @itemAdded="itemAdded" @itemRemoved="itemRemoved"></ModifyList>`,
data() {
return {
items: [],
}
},
itemAdd: null,
methods: {
update() {
if (this.ikey)
this.putData(this.ikey, this.items)
this.emitter.trigger('process');
},
itemAdded(new_item) {
this.items.push(new_item);
this.update();
this.onItemAdded(this.node, new_item)
},
itemRemoved(del_item_id) {
var item = this.items.find(x => x.id === del_item_id);
this.items.splice(this.items.indexOf(item), 1);
this.update();
this.onItemRemoved(this.node, del_item_id)
}
},
mounted() {
this.items = this.getData(this.ikey) || [];
}
}
export default class ListControl extends Rete.Control {
constructor(emitter, key, readonly, onItemAdded, onItemRemoved, node) {
super(key);
this.data.render = 'vue';
this.component = VueListControl;
node.data.choise_items = []
this.props = { emitter, ikey: key, readonly, onItemAdded, onItemRemoved, 'node': node };
}
setValue(val) {
this.vueContext.items = val;
}
}<file_sep>/clientapp/src/rete/nodes/infoblock_node.js
import Rete from "rete";
import { NodeTypes } from '../../config';
import NodeTemplate from './node_template.vue';
import TextControl from '../controls/TextControl.js'
export default class InfoBlockNode extends Rete.Component {
constructor() {
super("Info block");
this.data.component = NodeTemplate;
this.type = NodeTypes.INFO_BLOCK;
}
builder(node) {
node.data.type = this.type;
node.addOutput(new Rete.Output('num', 'Next question', node.data.m_socket));
node.addInput(new Rete.Input('num2', 'test', node.data.m_socket, true));
node.addControl(new TextControl(this.editor, 'key', false))
}
}<file_sep>/clientapp/src/rete/nodes/text_question_node.js
import Rete from "rete";
import { NodeTypes } from '../../config';
import NodeTemplate from './node_template.vue';
import TextControl from '../controls/TextControl.js'
import SelectControl from '../controls/SelectControl.js'
import TextConditionsControl from '../controls/TextConditions.js'
export default class TextQuestionNode extends Rete.Component {
constructor() {
super("Text question");
this.data.component = NodeTemplate;
this.type = NodeTypes.QUESTION_TEXT;
}
builder(node) {
node.data.type = this.type;
node.addOutput(new Rete.Output('num', 'Next question', node.data.m_socket));
node.addInput(new Rete.Input('num2', 'test', node.data.m_socket, true));
node.addControl(new TextControl(this.editor, 'key', false))
node.addControl(new SelectControl(this.editor, 'fd', false, ['Text', 'Number', 'Phone', 'Email']))
node.addControl(new TextConditionsControl(this.editor, 'fdfd', false,'num'))
}
}<file_sep>/clientapp/src/rete/nodes/end_node.js
import Rete from "rete";
import { NodeTypes } from '../../config.js';
import NodeTemplate from './node_template.vue';
export default class EndNode extends Rete.Component {
constructor() {
super("End node");
this.data.component = NodeTemplate;
this.type = NodeTypes.END;
}
builder(node) {
node.data.type = this.type;
node.addInput(new Rete.Input('num2', 'test', node.data.m_socket, true));
}
}<file_sep>/clientapp/src/rete/nodes/choise_question_node.js
import Rete from "rete";
import { NodeTypes } from '../../config';
import NodeTemplate from './node_template.vue';
import TextControl from '../controls/TextControl.js'
import ListControl from '../controls/ListControl.js'
export default class ChoiseQuestionNode extends Rete.Component {
constructor() {
super("Choise question");
this.data.component = NodeTemplate;
this.type = NodeTypes.QUESTION_CHOISE;
}
onChoiseAdded(node, new_item) {
new_item.output = new Rete.Output(new_item.id, 'output', node.data.m_socket)
node.addOutput(new_item.output)
node.data.choise_items.push(new_item)
node.update();
}
onChoiseRemoved(node, del_item_id) {
var item = node.data.choise_items.find(x => x.id === del_item_id);
node.removeOutput(item.output);
node.data.choise_items.splice(node.data.choise_items.indexOf(item), 1);
node.update();
}
builder(node) {
node.data.type = this.type;
node.addOutput(new Rete.Output('num', 'Next question', node.data.m_socket));
node.addInput(new Rete.Input('num2', 'test', node.data.m_socket, true));
node.addControl(new TextControl(this.editor, 'kedfsy', false))
node.addControl(new ListControl(this.editor, 'key', false, this.onChoiseAdded, this.onChoiseRemoved, node))
}
}<file_sep>/clientapp/src/rete/controls/TextConditions.js
import Rete from "rete";
import SelectVue from '../../common/select.vue'
import { BitwiseOp, StrConditions, NumCondition} from '../../config.js'
var VueSubCondition = {
props: ["condition", 'for_type'],
components: { SelectVue },
template: `
<div>
<div class="input-group input-group-sm">
<SelectVue :items="select_items" :value="condition.type_cond" @changed="condition_changed"></SelectVue>
<div class="input-group-append">
<button class="btn btn-light" @click="remove" type="button">Del</button>
</div>
</div>
<div class="input-group input-group-sm">
<input v-if="is_range" :value="condition.from" type="for_type" class="form-control" style="width:0px;" placeholder="From">
<input v-if="is_range" :value="condition.to" type="for_type" class="form-control" style="width:0px;" placeholder="To">
<input v-if="!is_range" :value="condition.value" type="for_type" class="form-control" style="width:0px;" :placeholder="placeholder">
</div>
</div>
`,
data() {
let placeholder = null;
return {
is_range: this.condition.type_cond == NumCondition.BETWEEN,
select_items: null,
placeholder
}
},
methods: {
condition_changed(type) {
this.is_range = type === NumCondition.BETWEEN
},
remove() {
this.$emit('remove', this.condition)
}
},
watch: {
for_type: {
immediate: true,
handler(new_type) {
switch (new_type) {
case 'number':
this.placeholder = 'Number'
this.select_items = NumCondition
break;
case 'string':
this.placeholder = 'String'
this.select_items = StrConditions
break;
default:
}
}
}
}
}
var VueNumCondition = {
props: ["condition", 'for_type'],
components: { VueSubCondition, SelectVue},
template: `
<div class="border p-1 rounded">
<div v-for="(item, index) of conditions" :key="index">
<SelectVue v-if="item.type == 'bitwise'" :items="select_items" :value="item.value" btn="X"></SelectVue>
<VueSubCondition v-else :condition="item" @remove="remove_condition" :id="index" :for_type="for_type"></VueSubCondition>
</div>
<button type="button" @click="add_bitwise_operator" class="btn btn-outline-light btn-block btn-sm">Add and/or</button>
</div>
`,
data() {
return {
conditions: [
{
type: 'condition',
type_cond: NumCondition.EQUAL,
value: null,
},
],
select_items: BitwiseOp,
}
},
methods: {
add_bitwise_operator() {
this.conditions.push({
type: 'bitwise',
value: BitwiseOp.AND
})
this.conditions.push({
type: 'condition',
type_cond: NumCondition.EQUAL,
value: null
})
},
remove_condition(condition) {
console.log('press')
console.log(condition)
let index = this.conditions.indexOf(condition)
this.conditions.splice(index, 1);
this.conditions.splice(index - 1, 1);
if (this.conditions.length == 0) {
this.$emit('remove')
}
}
}
}
var VueTextCondition = {
props: ["condition"],
template: `
<div class="border p-1">
<div class="input-group input-group-sm ">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" v-model="condition.title" aria-label="Checkbox for following text input">Not</input>
</div>
</div>
<select class="custom-select custom-select-sm">
<option value="queal">Equal to</option>
<option value="value">Include</option>
<option value="value">Exclude</option>
<option value="value">More</option>
</select>
</div>
<div class="input-group input-group-sm">
<input type="text" class="form-control" placeholder="String" aria-label="Small" aria-describedby="inputGroup-sizing-sm">
</div>
<button type="button" @click="add_bitwise_operator" class="btn btn-outline-light btn-block btn-sm">Add and/or</button>
</div>
`,
data() {
return {
bitwise_operators: []
}
},
methods: {
add_bitwise_operator() {
this.bitwise_operators.push({})
},
}
}
var VueTCControl = {
props: ['readonly', 'emitter', 'ikey', 'getData', 'putData', 'for_type'],
template: `
<div>
<div v-if="for_type == 'string'">
<VueTextCondition v-for="(condition, index) in conditions" :key="index" :condition="condition"></VueTextCondition>
</div>
<div v-else-if="for_type == 'num'">
<VueNumCondition :for_type="for_type" v-for="(condition, index) in conditions" :key="index" @remove="remove_cond" :condition="condition"></VueNumCondition>
</div>
<button type="button" @click="add_condition" class="btn btn-outline-light btn-block btn-sm">Add condition</button>
</div>
`,
components: {
VueTextCondition,
VueNumCondition
},
data() {
return {
value: "",
conditions: []
}
},
methods: {
add_condition() {
console.log(this.for_type)
this.conditions.push({})
this.$emit('condition_added')
},
remove_cond(condition) {
this.conditions.remove(condition);
},
change(e) {
this.value = e.target.value;
this.update();
},
update() {
this.putData('title', this.value)
this.emitter.trigger('process');
}
},
mounted() {
this.value = this.getData(this.ikey);
}
}
export default class TextConditionsControl extends Rete.Control {
constructor(emitter, key, readonly, for_type) {
super(key);
this.data.render = 'vue';
this.component = VueTCControl;
this.props = { emitter, ikey: key, readonly, for_type };
}
setValue(val) {
this.vueContext.value = val;
}
}
<file_sep>/clientapp/src/plugins/axios.js
import ax from 'axios'
// insert all your axios logic here
export const axios = ax
export default {
install(Vue) {
Vue.prototype.$axios = ax
}
}
export const api = ax.create({
baseURL: 'http://localhost:5001/api/',
timeout: 3000
});<file_sep>/clientapp/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/home.vue'
import Login from '../views/login.vue'
import CreateForm from '../views/create_form.vue'
import NotFound from '../views/404.vue';
import Form from '../views/form.vue';
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/login',
name: 'login',
component: Login,
},
{
path: '/create-form',
name: 'create-form',
component: CreateForm,
},
{
path: '/f-*',
name: 'form',
component: Form
},
{
path: '*',
name: 'not-found',
component: NotFound
}
]
})<file_sep>/clientapp/src/rete/controls/SelectControl.js
import Rete from "rete";
import SelectVue from '../../common/select.vue'
var VueSelectControl = {
props: ['readonly', 'ikey', 'getData', 'putData', 'items', 'emitter'],
components: { SelectVue },
template: `
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Type</label>
</div>
<SelectVue :items="items" v-model="selected" @change="change"></SelectVue>
</div>
`,
data() {
return {
value: '',
selected: ''
}
},
methods: {
change(value) {
this.value = value;
this.update();
},
update() {
if (this.ikey)
this.putData(this.ikey, this.value)
this.emitter.trigger('process');
}
},
mounted() {
this.value = this.getData(this.ikey) || this.items[0];
}
}
export default class SelectControl extends Rete.Control {
constructor(emitter, key, readonly, items) {
super(key);
this.data.render = 'vue';
this.component = VueSelectControl;
this.props = {emitter, ikey: key, readonly, items};
}
setValue(val) {
this.vueContext.value = val;
}
}
| f76c8252bdfe66a9ef564d7cabd0badaf763b437 | [
"JavaScript",
"C#"
] | 12 | JavaScript | PavlMais/LogicForms | 108bab036f76baa62d49a6b0ad121a3a95d4dcc6 | bf395127e84025ce17b5396ca17b2aaf85dca574 |
refs/heads/master | <file_sep>#include <stdio.h>
char prompt(void);
float calc_manager(void);
float calc_hourly(void);
float calc_commission(void);
float calc_pieceworker(void);
int main(void){
int total_emps = 0;
int manager_emps = 0;
int hourly_emps = 0;
int commission_emps = 0;
int piece_emps= 0;
float total_wages = 0;
float manager_wages = 0;
float hourly_wages = 0;
float commission_wages = 0;
float piece_wages = 0;
float temp_wage = 0;
char emp_type;
int finish = 0;
while (!finish) {
emp_type = prompt();
switch(emp_type) {
case '1':
temp_wage = calc_manager();
manager_wages += temp_wage;
total_wages += temp_wage;
manager_emps++;
total_emps++;
break;
case '2':
temp_wage = calc_hourly();
hourly_wages += temp_wage;
total_wages += temp_wage;
hourly_emps++;
total_emps++;
break;
case '3':
temp_wage = calc_commission();
commission_wages += temp_wage;
total_wages += temp_wage;
commission_emps++;
total_emps++;
break;
case '4':
temp_wage = calc_pieceworker();
piece_wages += temp_wage;
total_wages += temp_wage;
piece_emps++;
total_emps++;
break;
case 'Z':
printf("You entered too many characters. Please only enter '1' for manager, '2' for hourly, '3' for commission, '4' for pieceworker, or 'Q' to quit and see totals.\n");
break;
case 'Q':
finish = 1;
break;
default:
printf("Unrecognised paycode '%c'. Please only enter '1' for manager, '2' for hourly, '3' for commission, '4' for pieceworker, or 'Q' to quit and see totals.\n", emp_type);
break;
} // end switch
} // end while
printf("Manager: Employees: %d Total wages: $%.2f\nHourly: Employees: %d Total wages: $%.2f\nCommission: Employees: %d Total wages: $%.2f\nPieceworker: Employees: %d Total wages: $%.2f\nNet Total: Employees: %d Total wages: $%.2f\n", manager_emps, manager_wages, hourly_emps, hourly_wages, commission_emps, commission_wages, piece_emps, piece_wages, total_emps, total_wages);
} // end main
char prompt(void) {
char paycode[100];
printf("Enter employee paycode (1,2,3,4,Q): ");
scanf(" %s", &paycode[0]);
if (paycode[1] != '\0'){
return 'Z';
}
getchar();
return paycode[0];
}
float calc_manager(void){
float wage;
int valid = 0;
while (!valid){
printf("Enter weekly salary for manager: ");
valid = scanf("%f", &wage);
getchar();
}
printf("Manager salary of $%.2f\n", wage);
return wage;
}
float calc_hourly(void){
int hours = 0;
int overtime_hours = 0;
float fixed_rate = 0;
float overtime_rate = 0;
float fixed_total = 0;
float overtime_total = 0;
float total = 0;
int valid = 0;
while (!valid) {
printf("Enter the hourly wage for the employee: ");
valid = scanf("%f", &fixed_rate);
getchar();
}
valid = 0;
while (!valid){
printf("Enter hours worked for hourly employee: ");
valid = scanf("%d", &hours);
getchar();
}
if (hours<=40) {
fixed_total = hours * fixed_rate;
total = fixed_total;
} else {
fixed_total = (40 * fixed_rate);
overtime_rate = 1.5 * fixed_rate;
overtime_hours = hours - 40;
overtime_total = overtime_rate * overtime_hours;
total = fixed_total + overtime_total;
}
printf("Wages are $%.2f ($%.2f regular and $%.2f overtime)\n", total, fixed_total, overtime_total);
return total;
}
float calc_commission(void){
float base = 250;
float val_A = 0;
float val_B = 0;
float val_C = 0;
float rate_A = .057;
float rate_B = .064;
float rate_C = .072;
float wage_A = 0;
float wage_B = 0;
float wage_C = 0;
float comm_total = 0;
float total = 0;
int valid = 0;
while(!valid) {
printf("Enter the sales value of Item A: ");
valid = scanf("%f", &val_A);
getchar();
}
valid = 0;
while(!valid) {
printf("Enter the sales value of Item B: ");
valid = scanf("%f", &val_B);
getchar();
}
valid = 0;
while(!valid) {
printf("Enter the sales value of Item C: ");
valid = scanf("%f", &val_C);
getchar();
}
wage_A = val_A * rate_A;
wage_B = val_B * rate_B;
wage_C = val_C * rate_C;
comm_total = wage_A + wage_B + wage_C;
total = base + comm_total;
printf("Commission wage is $%.2f ($%.2f base + $%.2f commissions ($%.2f item A, $%.2f item B, $%.2f item C))\n", total, base, comm_total, wage_A, wage_B, wage_C );
return total;
}
float calc_pieceworker(void){
float rate_item1 = 22.50;
float rate_item2 = 24.50;
float rate_item3 = 26.00;
int amt_item1 = 0;
int amt_item2 = 0;
int amt_item3 = 0;
float pay_item1 = 0;
float pay_item2 = 0;
float pay_item3 = 0;
float total = 0;
int valid = 0;
while (!valid){
printf("Enter the number produced of item 1: ");
valid = scanf("%d", &amt_item1);
getchar();
}
valid = 0;
while (!valid){
printf("Enter the number produced of item 2: ");
valid = scanf("%d", &amt_item2);
getchar();
}
valid = 0;
while (!valid){
printf("Enter the number produced of item 3: ");
valid = scanf("%d", &amt_item3);
getchar();
}
pay_item1 = amt_item1 * rate_item1;
pay_item2 = amt_item2 * rate_item2;
pay_item3 = amt_item3 * rate_item3;
total = pay_item1 + pay_item2 + pay_item3;
printf("Pieceworker wage: $%.2f (items 1 $%.2f, items 2 $%.2f, items 3 $%.2f)\n", total, pay_item1, pay_item2, pay_item3);
return total;
}
| d44ffe3a22c0c74a17af84c002521ba4ce822a7b | [
"C"
] | 1 | C | krisbebb/HIT365-Assignment1 | eba95a9d2a956426c2017dbbb8e89bdc4dd0f6f9 | 06ce3cbf1fbbba6a296424746c721259d4772881 |
refs/heads/master | <repo_name>vsabbella/pythonsetup<file_sep>/request.py
import requests
from box import Box
response = requests.get("https://api.exchangeratesapi.io/latest?symbols=USD")
b = Box(response.json())
print("1 euro is", b.rates.USD, "dollars.")<file_sep>/pythonsetup.md
1. Package manger pip
2. Creating virtual environments
1. install virtual virtual environment tool : sudo python -m pip install virtualenv
2. Create a virtual environment: virtualenv rates
3. Create a virtual environment with python3 interpreter: virtualenv -p python3 rates_py3
4. source rates_py3/bin/activate or . rates_py3/bin/activate - . indicates the system to retrieve shell scripts from the folder mentioned
5. Use pip with python as best practise.
6. List the packages - python -m pip list
7. Install a package : Install requests :python -m pip install request.
8. Show where a package is installed : python -m pip show requests
9. Install box package: python -m pip install python-box
10. Export dependendent packages to a file : python -m pip freeze > requirements.txt
11. Import all dependent packages : python -m pip install -r requirements.txt
3. Clone a package from git
1. git clone https://github.com/pallets/flask
2. Editable install package for debugging/development: python -m pip install -e flask<file_sep>/managing-python-packages-virtual-environments/03/demos/m3_venv/requirements.txt
certifi==2018.11.29
chardet==3.0.4
idna==2.8
python-box==3.2.3
requests==2.21.0
urllib3==1.24.1
<file_sep>/requirements.txt
certifi==2020.6.20
chardet==3.0.4
idna==2.10
python-box==5.1.1
requests==2.24.0
urllib3==1.25.10
| 8eb080376c6983aa7c23cd8965ff985b3ff0a59f | [
"Markdown",
"Python",
"Text"
] | 4 | Python | vsabbella/pythonsetup | 7729adc2e251ceceb4696defe0c956a420133e10 | 6bb8a209985f4fe6a3778e8772b19e7b2d6d7c79 |
refs/heads/master | <repo_name>devramkumardnagarajan/willtop<file_sep>/README.md
# willtop
<file_sep>/js/main.js
function main() {
! function() {
"use strict";
function f() {
b.hasClass("show-nav") ? Modernizr.csstransforms ? (b.removeClass("show-nav"), d.removeClass("show-nav")) : (b.removeClass("show-nav"), d.removeClass("show-nav"), b.animate({
right: "-=300"
}, 500), d.animate({
right: "-=300"
}, 500)) : Modernizr.csstransforms ? (b.addClass("show-nav"), d.addClass("show-nav")) : (b.addClass("show-nav"), d.addClass("show-nav"), b.css("right", "0px"), d.css("right", "330px"))
}
function g() {
e.toggleClass("fa-times"), e.toggleClass("fa-bars")
}
function h() {
$(window).scrollTop() >= 100 ? $(".lp-our-numbers").removeClass("active") : $(".lp-our-numbers").addClass("active")
}
$("a.page-scroll").click(function() {
if (location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname) {
var a = $(this.hash);
if (a = a.length ? a : $("[name=" + this.hash.slice(1) + "]"), a.length) return $("html,body").animate({
scrollTop: a.offset().top - 40
}, 900), !1
}
}), $(window).bind("scroll", function() {
$(window).height();
console.log("hi");
$(window).scrollTop() >= 100 ? $(".navbar-default").addClass("on") : $(".navbar-default").removeClass("on")
}), /*$("body").scrollspy({
target: ".navbar-default",
offset: 80
}),*/ jQuery(window).scroll(function() {
jQuery(window).scrollTop() >= 150 ? (jQuery(".navbar-default").css({
background: "#18171D"
}), jQuery(".navbar-default img.logo").css({
"margin-top": "-30px",
"margin-bottom": "15px"
}), jQuery(".nav-bar").css({
"margin-top": "6px"
})) : (jQuery(".navbar-default").css({
background: "transparent"
}), jQuery(".navbar-default img.logo").css({
"margin-top": "-30px",
"margin-bottom": "25px"
}))
});
var b = ($("#site-wrapper"), $(".menu")),
d = ($(".menu ul li a"), $(".nav-toggle")),
e = $(".nav-toggle span");
$(function() {
d.on("click", function(a) {
a.stopPropagation(), a.preventDefault(), f(), g()
}), $(document).keyup(function(a) {
27 == a.keyCode && b.hasClass("show-nav") && (Modernizr.csstransforms ? (b.removeClass("show-nav"), d.removeClass("show-nav"), g()) : (b.removeClass("show-nav"), d.removeClass("show-nav"), b.css("right", "-300px"), d.css("right", "30px"), g()))
})
}), $(window).load(function () {
if ($(".lp-our-numbers").length != undefined) {
$(".lp-our-numbers").addClass("active")
}
}), $(window).scroll(function() {
h()
}), $(function() {
$(".lp-scroll-down").click(function() {
if (location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname) {
var a = $(this.hash);
if (a = a.length ? a : $("[name=" + this.hash.slice(1) + "]"), a.length) return $("html,body").animate({
scrollTop: a.offset().top - 90
}, 1e3), !1
}
})
}), jQuery(document).ready(function(a) {
function l() {
m(a(".cd-headline.letters").find("img, b")), n(a(".cd-headline"))
}
function m(b) {
b.each(function() {
var b = a(this),
c = b.text().split(""),
d = b.hasClass("is-visible");
for (i in c) b.parents(".rotate-2").length > 0 && (c[i] = "<em>" + c[i] + "</em>"), c[i] = d ? '<i class="in">' + c[i] + "</i>" : "<i>" + c[i] + "</i>";
var e = c.join("");
b.html(e).css("opacity", 1)
})
}
function n(e) {
var f = b;
e.each(function() {
var b = a(this);
if (b.hasClass("loading-bar")) f = c, setTimeout(function() {
b.find(".cd-words-wrapper").addClass("is-loading")
}, d);
else if (b.hasClass("clip")) {
var e = b.find(".cd-words-wrapper"),
g = e.width() + 10;
e.css("width", g)
} else if (!b.hasClass("type")) {
var h = b.find(".cd-words-wrapper img, .cd-words-wrapper b"),
i = 0;
h.each(function() {
var b = a(this).width();
b > i && (i = b)
}), b.find(".cd-words-wrapper").css("width", i)
}
setTimeout(function() {
o(b.find(".is-visible").eq(0))
}, f)
})
}
function o(a) {
var i = s(a);
if (a.parents(".cd-headline").hasClass("type")) {
var k = a.parent(".cd-words-wrapper");
k.addClass("selected").removeClass("waiting"), setTimeout(function() {
k.removeClass("selected"), a.removeClass("is-visible").addClass("is-hidden").children("i").removeClass("in").addClass("out")
}, g), setTimeout(function() {
p(i, f)
}, h)
} else if (a.parents(".cd-headline").hasClass("letters")) {
var l = a.children("i").length >= i.children("i").length;
q(a.find("i").eq(0), a, l, e), r(i.find("i").eq(0), i, l, e)
} else a.parents(".cd-headline").hasClass("clip") ? a.parents(".cd-words-wrapper").animate({
width: "2px"
}, j, function() {
u(a, i), p(i)
}) : a.parents(".cd-headline").hasClass("loading-bar") ? (a.parents(".cd-words-wrapper").removeClass("is-loading"), u(a, i), setTimeout(function() {
o(i)
}, c), setTimeout(function() {
a.parents(".cd-words-wrapper").addClass("is-loading")
}, d)) : (u(a, i), setTimeout(function() {
o(i)
}, b))
}
function p(a, b) {
a.parents(".cd-headline").hasClass("type") ? (r(a.find("i").eq(0), a, !1, b), a.addClass("is-visible").removeClass("is-hidden")) : a.parents(".cd-headline").hasClass("clip") && a.parents(".cd-words-wrapper").animate({
width: a.width() + 10
}, j, function() {
setTimeout(function() {
o(a)
}, k)
})
}
function q(c, d, e, f) {
if (c.removeClass("in").addClass("out"), c.is(":last-child") ? e && setTimeout(function() {
o(s(d))
}, b) : setTimeout(function() {
q(c.next(), d, e, f)
}, f), c.is(":last-child") && a("html").hasClass("no-csstransitions")) {
var g = s(d);
u(d, g)
}
}
function r(a, c, d, e) {
a.addClass("in").removeClass("out"), a.is(":last-child") ? (c.parents(".cd-headline").hasClass("type") && setTimeout(function() {
c.parents(".cd-words-wrapper").addClass("waiting")
}, 200), d || setTimeout(function() {
o(c)
}, b)) : setTimeout(function() {
r(a.next(), c, d, e)
}, e)
}
function s(a) {
return a.is(":last-child") ? a.parent().children().eq(0) : a.next()
}
function u(a, b) {
a.removeClass("is-visible").addClass("is-hidden"), b.removeClass("is-hidden").addClass("is-visible")
}
var b = 2500,
c = 3800,
d = c - 3e3,
e = 50,
f = 150,
g = 500,
h = g + 800,
j = 600,
k = 1500;
l()
}),
function() {
function a(a) {
classie.add(a.target.parentNode, "input--filled")
}
function b(a) {
"" === a.target.value.trim() && classie.remove(a.target.parentNode, "input--filled")
}
String.prototype.trim || function() {
var a = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(a, "")
}
}(), [].slice.call(document.querySelectorAll("input.input__field, textarea.input__field")).forEach(function(c) {
"" !== c.value.trim() && classie.add(c.parentNode, "input--filled"), c.addEventListener("focus", a), c.addEventListener("blur", b)
})
}(), $(".tip").each(function() {
$(this).tooltip({
placement: "top",
html: !0,
title: $("#" + $(this).data("tip")).html()
})
}), $(".tip").click(function(a) {
a.preventDefault()
}), $(function() {
$("#map1").show(), $(".changesrc").click(function() {
$(".map-container").hide();
var a = $(this).attr("value");
$("#map" + a).show()
})
})
}(), $(document).ready(function() {
$.apScrollTop({
onInit: function(a) {}
}), $.apScrollTop().on("apstInit", function(a) {}), $.apScrollTop().on("apstToggle", function(a, b) {}), $.apScrollTop().on("apstCssClassesUpdated", function(a) {}), $.apScrollTop().on("apstPositionUpdated", function(a) {}), $.apScrollTop().on("apstEnabled", function(a) {}), $.apScrollTop().on("apstDisabled", function(a) {}), $.apScrollTop().on("apstBeforeScrollTo", function(a, b) {}), $.apScrollTop().on("apstScrolledTo", function(a, b) {}), $.apScrollTop().on("apstDestroy", function(a, b) {})
}), $("#option-enabled").on("change", function() {
var a = $(this).is(":checked");
$.apScrollTop("option", "enabled", a)
}), $("#option-visibility-trigger").on("change", function() {
var a = $(this).val();
"custom-function" == a ? $.apScrollTop("option", "visibilityTrigger", function(a) {
return a > $("#image-for-custom-function").offset().top
}) : $.apScrollTop("option", "visibilityTrigger", parseInt(a))
}), $("#option-visibility-fade-speed").on("change", function() {
var a = parseInt($(this).val());
$.apScrollTop("option", "visibilityFadeSpeed", a)
}), $("#option-scroll-speed").on("change", function() {
var a = parseInt($(this).val());
$.apScrollTop("option", "scrollSpeed", a)
}), $("#option-position").on("change", function() {
var a = $(this).val();
$.apScrollTop("option", "position", a)
}),
function() {
var a = document.querySelectorAll(".parallax");
window.onscroll = function() {
[].slice.call(a).forEach(function(a, c) {
var d = window.pageYOffset,
e = "0 " + .6 * d + "px";
a.style.backgroundPosition = e
})
}
}(), $(window).load(function() {
window.matchMedia("(min-width: 992px)").matches && $(".lp-health-our_nmbers").addClass("active")
}), $(window).scroll(function() {
var a = $(this).scrollTop();
var d, e, b = $(".lp-information_ih");
void 0 !== b && void 0 !== b.offset() && (d = b.offset().top), (e = a - d + 400) >= 100 && $(".lp-inline_block-ih li").addClass("active")
}), $(".screen-navigations a").click(function(a) {
a.preventDefault();
"prev" == $(this).attr("data-slide") ? ($(".image-slider").slick("slickPrev"), $(".lp_mobile_screens").slick("slickPrev")) : ($(".image-slider").slick("slickNext"), $(".lp_mobile_screens").slick("slickNext"))
});
var a = $(".slt-testimonial_box .image-slider").find(".slick-active").index(),
b = $(".slt-testimonial_box .image-slider").find("li.slick-slide").not(".slick-cloned").length - 1;
$(".slt-testimonial_box .image-slider").on("afterChange", function() {
$(this).find(".slick-active").index()
}), $("#next").click(function() {
$("#prev").removeClass("inactive"), $("#prev").addClass("active"), a++, a == b ? ($("#next").removeClass("active"), $("#next").addClass("inactive")) : $("#next").removeClass("inactive")
}), $("#prev").click(function() {
$("#next").removeClass("inactive"), $("#next").addClass("active"), a--, 0 == a ? ($("#prev").removeClass("active"), $("#prev").addClass("inactive")) : $("#prev").removeClass("inactive")
}), $(window).load(function() {
});
}
$(function() {
$(document).mouseup(function(a) {
container = $("nav.menu"), container.is(a.target) || 0 !== container.has(a.target).length || container.hasClass("show-nav") && (container.removeClass("show-nav"), container.find(".nav-toggle").removeClass("show-nav"))
})
}), $(document).ready(function() {
/*$(".lp_mobile_screens").slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: !1,
swipe: !1,
infinite: !1,
asNavFor: ".image-slider"
}), $(".image-slider").slick({
slidesToShow: 1,
slidesToScroll: 1,
autoplay: !1,
swipe: !1,
infinite: !1,
arrows: !1,
variableWidth: !1,
focusOnSelect: !0,
asNavFor: ".lp_mobile_screens"
}), $("#surgeon-slider").slick({
slidesToShow: 1,
slidesToScroll: 1,
autoplay: !0,
autoplaySpeed: 2e3
}), setTimeout(function() {
$(".lp_count-numbers .slt-count_up").counterUp({
delay: 10,
time: 1200
}, 1200)
})
$('.awards-slick-slider').slick({
dots: false,
slidesToShow: 3,
slidesToScroll: 1,
arrows: false,
autoplay: true,
autoplaySpeed: 2000,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
infinite: true,
arrows: false,
dots: false
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});*/
}), main();<file_sep>/sendMail.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$service = $_POST['service'];
$message = $_POST['message'];
$to = '<EMAIL>';
$subject = $service.'service request';
$message = 'Hi, <br/> name:'.$name.'<br/>email:'.$email.'<br/>mobile:'.$mobile.'<br/>service:'.$service.'<br/>query:'.$message.'';
$headers = 'From: <EMAIL>' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=utf-8';
if(mail($to, $subject, $message, $headers))
echo "Email sent";
else
echo "Email sending failed";
?> | 47bbdb221429c051d5a90d0fc15fbde154ef47ec | [
"Markdown",
"JavaScript",
"PHP"
] | 3 | Markdown | devramkumardnagarajan/willtop | c67b8dbff8661e1f364d4dc95fa15a3bdbb2d3c3 | 730fcd9986818a8490e64ed5bcf9ae2eab26b383 |
refs/heads/main | <file_sep>package entities.pet.subEntities;
import lombok.*;
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Category {
private String name;
private Integer id;
}<file_sep>package steps;
import entities.pet.Pet;
import framework.ShopRequest;
import framework.ShopResponse;
import io.cucumber.java.en.Given;
import io.restassured.http.Method;
public class CommonSteps extends BaseSteps {
@Given("Is configured PetShop application on address {string}")
public void isConfiguredPetShopApplicationOnAddress(String baseAddress) {
shopRequest.setAddress(baseAddress);
}
@Given("on server {string} exist entity on endpoint {string} with id {int}")
public void onServerExistPetWithId(String word, String endpoint, int petId) {
ShopResponse response = new ShopRequest().setRequestType(Method.GET)
.setEndpoint(endpoint)
.addEntityId(petId)
.send();
if (word.trim().toLowerCase().equals("not")) {
if (response.getResponseCode() == 200) {
new ShopRequest().setRequestType(Method.DELETE)
.setEndpoint(endpoint)
.addEntityId(petId)
.send();
}
} else if (word.trim().toLowerCase().equals("")) {
if (response.getResponseCode() == 404) {
Pet pet = new Pet();
pet.setId(1);
new ShopRequest().setRequestType(Method.POST)
.setBody(pet.toString())
.setEndpoint(endpoint)
.addEntityId(petId)
.send();
}
}
}
}
<file_sep>package steps;
import framework.ShopRequest;
import framework.ShopResponse;
public abstract class BaseSteps {
protected ShopResponse shopResponse;
protected ShopRequest shopRequest = new ShopRequest();
}
<file_sep>package framework;
import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class ShopRequest {
private Method requestType;
private String endpointAddress;
private RequestSpecification requestSpecification = RestAssured.given();
public ShopRequest setAddress(String address) {
RestAssured.baseURI = address;
return this;
}
public ShopRequest setRequestType(Method type) {
requestType = type;
return this;
}
public ShopRequest setBody(String body) {
requestSpecification = requestSpecification.body(body);
return this;
}
public ShopRequest setEndpoint(String endpoint){
endpointAddress = endpoint;
return this;
}
public ShopRequest addEntityId(int id){
if (!endpointAddress.endsWith("/")){
endpointAddress = endpointAddress.concat("/");
}
endpointAddress = endpointAddress.concat(Integer.toString(id));
return this;
}
public ShopResponse send() {
Response response;
switch (requestType) {
case GET:
response = requestSpecification.get(endpointAddress);
break;
case DELETE:
response = requestSpecification.delete(endpointAddress);
break;
case POST:
response = requestSpecification.post(endpointAddress);
break;
default:
throw new NotImplementedException();
}
requestSpecification = null;
return new ShopResponse(response);
}
}
<file_sep># SimpleApiTestAutomationFramework
##API server:
https://petstore.swagger.io
##Reports located in:
SimpleApiTestAutomationFramework/target/site/serenity/index.html
##How to run:
mvn clean verify | d09689caf24ba1ead8693326bfe460a228342bb3 | [
"Markdown",
"Java"
] | 5 | Java | Wilu84/BackendTest | cb28bea9d2b59213fa58d0cb00139821f42e4d94 | 18b0588e127590a3cc9aab5aedb20f62187bee92 |
refs/heads/master | <repo_name>DylanLacey/sauce<file_sep>/spec/features/miso_spec.rb
require 'spec_helper'
describe "Wikipedia's Miso Page", :sauce => true do
it "Should mention a favorite type of Miso" do
visit "http://en.wikipedia.org/"
STDERR.puts "## Visited Wikipedia"
fill_in 'search', :with => "Miso"
STDERR.puts "## Filled in form"
click_button "searchButton"
STDERR.puts "## Clicked button"
page.should have_content "Akamiso"
STDERR.puts "## Page had content"
end
end
<file_sep>/Gemfile
source 'http://rubygems.org'
gem 'rails', '3.0.12'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
gem 'rspec-rails', '~> 2.12'
gem 'sauce', '~> 3.0.2'
gem 'sauce-connect'
gem 'capybara', '~> 2.0.3'
gem 'parallel_tests'
<file_sep>/spec/sauce_helper.rb
# You should edit this file with the browsers you wish to use
# For options, check out http://saucelabs.com/docs/platforms
require "sauce"
require "sauce/capybara"
Sauce.config do |config|
config[:browsers] = [
["Linux", "Chrome", nil],
["Linux", "Firefox", "20"]
]
end
| b786a283e9206b70c04f613f5047159f4a6ae490 | [
"Ruby"
] | 3 | Ruby | DylanLacey/sauce | c93c7e8db14d52f9b19a49d4a6d88a829a7b108a | aa7775bc6b209023e2ad371126e453187ac913e4 |
refs/heads/master | <file_sep>#we embed and image and xx.4gl in the script and pass also a custom imagepath
all: xx xx.bat
xx: xx.4gl
rm -f xx
../fglscriptify next.png icons/smiley.png xx.per xx.4gl
xx.bat: xx.4gl
rm -f xx.bat
../fglscriptify -o xx.bat next.png icons/smiley.png xx.per xx.4gl
clean:
rm -f xx xx.bat
<file_sep>#!/bin/bash
#!/bin/bash
DIR=`dirname "$0"`
#echo "DIR='$DIR'"
pushd "$DIR" >/dev/null
BINDIR=`pwd`
#echo "BINDIR='$BINDIR'"
popd > /dev/null
export _CATFILE="$BINDIR/`basename $0`"
export _CALLING_SCRIPT=`basename $0`
#echo "me:$_CATFILE"
firstcheck=`mktemp`
fglrun -V > $firstcheck
if [ $? -ne 0 ]
then
rm -f $firstcheck
echo "ERROR: no fglrun in the path"
exit 1
fi
ver=`cat $firstcheck | sed -n '/Genero virtual machine/q;p'`
major=`echo $ver | sed -n 's/^.* \([0-9]*\)\.\([0-9]*\).*$/\1/p'`
rm -f $firstcheck
if [ $major -lt 3 ]
then
echo "ERROR:fglrun version should be >= 3.0 ,current:$ver"
exit 1
fi
replace_dot(){
# replace dot with underscore
local dir=`dirname $1`
local base=`basename $1`
#genero doesn't like dots in the filename
base=`echo $base | sed -e 's/\./_/g'`
echo "$dir/$base"
}
# compute a unique temp filename and a unique directory
# without dots in the name
while true
do
_tmpfile=`mktemp`
_tmpdir_extractor=`dirname $_tmpfile`
rm -f $_tmpfile
_tmpfile=`replace_dot $_tmpfile`
_TMPDIR=`mktemp -d`
rm -rf $_TMPDIR
export _TMPDIR=`replace_dot $_TMPDIR`
if [ ! -e $_tmpfile ] && [ ! -e $_TMPDIR ]
then
break
fi
done
#echo "_tmpfile:$_tmpfile,_tmpdir_extractor:$_tmpdir_extractor,_TMPDIR:$_TMPDIR"
#we insert catsource.4gl on the next lines
cat >$_tmpfile.4gl <<EOF
--note: some 4gl constructs in this file are there to surround the pitfalls
--of echo'ing this file with the windows echo command to a temp 4gl file
--percent signs are avoided as well as or signs, thats why we avoid
--the sfmt operator and the cat operator and mixing quotes with double quotes
OPTIONS SHORT CIRCUIT
IMPORT util
IMPORT os
DEFINE tmpdir,fname,full,lastmodule STRING
DEFINE m_bat INT
DEFINE singlequote,doublequote,backslash,percent,dollar STRING
DEFINE m_binTypeArr,m_resTypeArr,m_imgarr,m_resarr DYNAMIC ARRAY OF STRING
MAIN
DEFINE line,err,catfile STRING
DEFINE ch,chw base.Channel
DEFINE sb base.StringBuffer
DEFINE write,writebin INT
LET singlequote=ASCII(39)
LET doublequote=ASCII(34)
LET backslash=ASCII(92) --we must not use the literal here
LET percent=ASCII(37)
LET dollar=ASCII(36)
LET m_binTypeArr[m_binTypeArr.getLength()+1]='png'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='jpg'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='bmp'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='gif'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='tiff'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='wav'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='mp3'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='aiff'
LET m_binTypeArr[m_binTypeArr.getLength()+1]='mpg'
LET m_resTypeArr[m_resTypeArr.getLength()+1]='per'
LET m_resTypeArr[m_resTypeArr.getLength()+1]='4st'
LET m_resTypeArr[m_resTypeArr.getLength()+1]='4tb'
LET m_resTypeArr[m_resTypeArr.getLength()+1]='4tm'
LET m_resTypeArr[m_resTypeArr.getLength()+1]='4sm'
LET m_resTypeArr[m_resTypeArr.getLength()+1]='iem'
LET sb=base.StringBuffer.create()
LET catfile=fgl_getenv("_CATFILE") --set by calling script
LET tmpdir=fgl_getenv("_TMPDIR") --set by calling script
LET m_bat=fgl_getenv("_IS_BAT_FILE") IS NOT NULL
IF catfile IS NULL OR tmpdir IS NULL THEN
CALL myerr("_CATFILE or _TMPDIR not set")
END IF
IF catfile IS NULL THEN
LET catfile=arg_val(1)
LET tmpdir=arg_val(2)
END IF
IF NOT m_bat THEN --windows fullPath is clumsy
LET tmpdir=os.Path.fullPath(tmpdir)
END IF
LET ch=base.Channel.create()
LET chw=base.Channel.create()
IF NOT os.Path.exists(tmpdir) THEN
IF NOT os.Path.mkdir(tmpdir) THEN
LET err="Can't mkdir :",tmpdir
CALL myerr(err)
END IF
END IF
CALL ch.openFile(catfile,"r")
WHILE (line:=ch.readLine()) IS NOT NULL
CASE
WHEN m_bat AND line.getIndexOf("rem __CAT_EOF_BEGIN__:",1)==1
LET fname=line.subString(23,line.getLength())
GOTO mark1
WHEN (NOT m_bat) AND line.getIndexOf("#__CAT_EOF_BEGIN__:",1)==1
LET fname=line.subString(20,line.getLength())
LABEL mark1:
LET full=os.Path.join(tmpdir,fname)
CALL checkSubdirs()
IF isBinary(fname) THEN
LET writebin=TRUE
CALL addDir(m_imgarr,os.Path.dirName(fname))
CALL sb.clear()
ELSE
IF isResource(fname) THEN
CALL addDir(m_resarr,os.Path.dirName(fname))
END IF
LET write=TRUE
CALL chw.openFile(full,"w")
END IF
WHEN ((NOT m_bat) AND line=="#__CAT_EOF_END__") OR
(m_bat AND line=="rem __CAT_EOF_END__")
IF writebin THEN
LET writebin=FALSE
CALL util.Strings.base64Decode(sb.toString(),full)
ELSE
LET write=FALSE
CALL chw.close()
CALL eventuallyCompileFile()
END IF
WHEN writebin
CALL sb.append(line.subString(IIF(m_bat,5,2),line.getLength()))
WHEN write
CALL chw.writeLine(line.subString(IIF(m_bat,5,2),line.getLength()))
END CASE
END WHILE
CALL ch.close()
CALL runLastModule()
END MAIN
FUNCTION addDir(arr,dirname)
DEFINE arr DYNAMIC ARRAY OF STRING
DEFINE dirname STRING
DEFINE i INT
FOR i=1 TO arr.getLength()
IF arr[i]=dirname THEN
RETURN --already contained
END IF
END FOR
LET arr[arr.getLength()+1]=dirname
END FUNCTION
FUNCTION setPathFor(arr,envName,cmd)
DEFINE arr DYNAMIC ARRAY OF STRING
DEFINE envName,tmp STRING
DEFINE cmd STRING
DEFINE i INT
IF arr.getLength()>0 THEN
LET tmp=envName,"="
LET cmd=cmd,IIF(m_bat,"set ",""),tmp
IF fgl_getenv(envName) IS NOT NULL THEN
IF m_bat THEN
LET cmd=percent,envName,percent,";"
ELSE
LET cmd=dollar,envName,":"
END IF
END IF
FOR i=1 TO arr.getLength()
IF i>1 THEN
LET cmd=cmd,IIF(m_bat,";",":")
END IF
LET cmd=cmd,quotePath(os.Path.join(tmpdir,arr[i]))
END FOR
LET cmd=cmd,IIF(m_bat,"&&"," ")
END IF
RETURN cmd
END FUNCTION
FUNCTION runLastModule() --we must get argument quoting right
DEFINE i INT
DEFINE arg,cmd,cmdsave,image2font STRING
IF lastmodule IS NULL THEN RETURN END IF
LET cmd=setPathFor(m_resarr,"FGLRESOURCEPATH",cmd)
LET image2font=os.Path.join(os.Path.join(fgl_getenv("FGLDIR"),"lib"),"image2font.txt")
LET cmdsave=cmd
LET cmd=setPathFor(m_imgarr,"FGLIMAGEPATH",cmd)
IF cmd!=cmdsave AND os.Path.exists(image2font) THEN
IF m_bat THEN
LET cmd=cmd.subString(1,cmd.getLength()-2),";",quotePath(image2font),"&&"
ELSE
LET cmd=cmd.subString(1,cmd.getLength()-1),":",quotePath(image2font)," "
END IF
END IF
LET cmd=cmd,"fglrun ",os.Path.join(tmpdir,lastmodule)
FOR i=1 TO num_args()
LET arg=arg_val(i)
CASE
WHEN m_bat AND arg.getIndexOf(' ',1)==0 AND
arg.getIndexOf(doublequote,1)==0
LET cmd=cmd,' ',arg --we don't need quotes
WHEN m_bat OR arg.getIndexOf(singlequote,1)!=0
--we must use double quotes on windows
LET cmd=cmd,' ',doublequote,quoteDouble(arg),doublequote
OTHERWISE
--sh: you can't quote single quotes inside single quotes
--everything else does not need to be quoted
LET cmd=cmd,' ',singlequote,arg,singlequote
END CASE
END FOR
--DISPLAY "cmd:",cmd
CALL myrun(cmd)
END FUNCTION
FUNCTION quotePath(p)
DEFINE p STRING
--TODO: quote space with backlash space
--IF NOT m_bat AND p.getIndexOf(" ",1)!=0
--RETURN quoteSpace(p)
--END IF
RETURN p
END FUNCTION
FUNCTION myerr(err)
DEFINE err STRING
DISPLAY "ERROR:",err
EXIT PROGRAM 1
END FUNCTION
FUNCTION eventuallyCompileFile()
DEFINE cmd STRING
CASE
WHEN os.Path.extension(fname)=="4gl"
LET cmd="cd ",tmpdir," && fglcomp -M ",fname
CALL myrun(cmd)
--DISPLAY "dirname:",fname,",basename:",os.Path.baseName(fname)
LET lastmodule=os.Path.baseName(fname)
--cut extension
LET lastmodule=lastmodule.subString(1,lastmodule.getLength()-4)
--DISPLAY "lastmodule=",lastmodule
WHEN os.Path.extension(fname)=="per"
LET cmd="cd ",tmpdir," && fglform -M ",fname
CALL myrun(cmd)
--other (resource) files are just copied
END CASE
END FUNCTION
FUNCTION myrun(cmd)
DEFINE cmd STRING, code INT
--DISPLAY "myrun:",cmd
RUN cmd RETURNING code
IF code THEN
EXIT PROGRAM 1
END IF
END FUNCTION
FUNCTION checkSubdirs()
DEFINE i,found INT
DEFINE dir,err STRING
DEFINE dirs DYNAMIC ARRAY OF STRING
LET dir=os.Path.fullPath(os.Path.dirName(full))
WHILE TRUE
CASE
WHEN dir IS NULL
EXIT WHILE
WHEN dir==tmpdir
LET found=true
EXIT WHILE
OTHERWISE
CALL dirs.insertElement(1)
LET dirs[1]=dir
END CASE
LET dir=os.Path.fullPath(os.Path.dirName(dir))
END WHILE
IF NOT found THEN
--we can't use sfmt because of .bat echo pitfalls
LET err=singlequote,fname,singlequote,' does point outside'
CALL myerr(err)
END IF
FOR i=1 TO dirs.getLength()
LET dir=dirs[i]
IF NOT os.Path.exists(dir) THEN
IF NOT os.Path.mkdir(dir) THEN
LET err="Can't create directory:",dir
CALL myerr(err)
END IF
END IF
END FOR
END FUNCTION
FUNCTION quoteDouble(s)
DEFINE s STRING
DEFINE c STRING
DEFINE i INT
DEFINE sb base.StringBuffer
LET sb=base.StringBuffer.create()
FOR i=1 TO s.getLength()
LET c=s.getCharAt(i)
CASE
WHEN c==doublequote
CALL sb.append(backslash)
WHEN (NOT m_bat) AND c==backslash
CALL sb.append(backslash)
END CASE
CALL sb.append(c)
END FOR
RETURN sb.toString()
END FUNCTION
FUNCTION isInArray(arr,fname)
DEFINE arr DYNAMIC ARRAY OF STRING
DEFINE fname,ext STRING
DEFINE i INT
LET ext=os.Path.extension(fname)
FOR i=1 TO arr.getLength()
IF arr[i]==ext THEN
RETURN TRUE
END IF
END FOR
RETURN FALSE
END FUNCTION
FUNCTION isBinary(fname)
DEFINE fname STRING
RETURN isInArray(m_binTypeArr,fname)
END FUNCTION
FUNCTION isResource(fname)
DEFINE fname STRING
RETURN isInArray(m_resTypeArr,fname)
END FUNCTION
EOF
#now compile and run catsource from the temp location
pushd `pwd` > /dev/null
cd $_tmpdir_extractor
mybase=`basename $_tmpfile`
fglcomp -M $mybase.4gl
if [ $? -ne 0 ]
then
exit 1
fi
rm -f $mybase.4gl
popd > /dev/null
fglrun $_tmpfile.42m "$@"
mycode=$?
rm -f $_tmpfile.42m
rm -rf $_TMPDIR
exit $mycode
#__CAT_EOF_BEGIN__:catsource.bat
#@echo off
#setlocal EnableExtensions
#
#rem get unique file name
#:loop
#set randbase=gen~%RANDOM%
#set extractor="%tmp%\%randbase%.4gl"
#set extractor42m="%tmp%\%randbase%.42m"
#rem important: without quotes
#set _TMPDIR=%tmp%\%randbase%_d
#set _IS_BAT_FILE=TRUE
#if exist %extractor% goto :loop
#if exist %extractor42m% goto :loop
#if exist %_TMPDIR% goto :loop
#rem echo tmp=%tmp%
#
#set tmpdrive=%tmp:~0,2%
#set _CATFILE=%~dpnx0
#rem We use a small line extractor program in 4gl to a temp file
#rem the bat only solutions at
#rem https://stackoverflow.com/questions/7954719/how-can-a-batch-script-do-the-equivalent-of-cat-eof
#rem are too slow for bigger programs, so 4gl rules !
#
#echo # Extractor coming from catsource.bat > %extractor%
#rem HERE_COMES_CATSOURCE
#set mydir=%cd%
#set mydrive=%~d0
#%tmpdrive%
#cd %tmp%
#fglcomp -M %randbase%
#if ERRORLEVEL 1 exit /b
#del %extractor%
#rem extract the 4gl code behind us to another 4GL file
#%mydrive%
#cd %mydir%
#fglrun %extractor42m% %1 %2 %3 %4 %5
#if ERRORLEVEL 1 exit /b
#del %extractor42m%
#exit /b
#__CAT_EOF_END__
#__CAT_EOF_BEGIN__:catsource.sh
##!/bin/bash
#DIR=`dirname "$0"`
##echo "DIR='$DIR'"
#pushd "$DIR" >/dev/null
#BINDIR=`pwd`
##echo "BINDIR='$BINDIR'"
#popd > /dev/null
#export _CATFILE="$BINDIR/`basename $0`"
#export _CALLING_SCRIPT=`basename $0`
##echo "me:$_CATFILE"
#firstcheck=`mktemp`
#fglrun -V > $firstcheck
#if [ $? -ne 0 ]
#then
# rm -f $firstcheck
# echo "ERROR: no fglrun in the path"
# exit 1
#fi
#ver=`cat $firstcheck | sed -n '/Genero virtual machine/q;p'`
#major=`echo $ver | sed -n 's/^.* \([0-9]*\)\.\([0-9]*\).*$/\1/p'`
#rm -f $firstcheck
#if [ $major -lt 3 ]
#then
# echo "ERROR:fglrun version should be >= 3.0 ,current:$ver"
# exit 1
#fi
#
#replace_dot(){
## replace dot with underscore
# local dir=`dirname $1`
# local base=`basename $1`
##genero doesn't like dots in the filename
# base=`echo $base | sed -e 's/\./_/g'`
# echo "$dir/$base"
#}
#
## compute a unique temp filename and a unique directory
## without dots in the name
#while true
#do
# _tmpfile=`mktemp`
# _tmpdir_extractor=`dirname $_tmpfile`
# rm -f $_tmpfile
# _tmpfile=`replace_dot $_tmpfile`
#
# _TMPDIR=`mktemp -d`
# rm -rf $_TMPDIR
# export _TMPDIR=`replace_dot $_TMPDIR`
#
# if [ ! -e $_tmpfile ] && [ ! -e $_TMPDIR ]
# then
# break
# fi
#done
##echo "_tmpfile:$_tmpfile,_tmpdir_extractor:$_tmpdir_extractor,_TMPDIR:$_TMPDIR"
#
##we insert catsource.4gl on the next lines
#cat >$_tmpfile.4gl <<EOF
##HERE_COMES_CATSOURCE
#EOF
#
##now compile and run catsource from the temp location
#pushd `pwd` > /dev/null
#cd $_tmpdir_extractor
#mybase=`basename $_tmpfile`
#fglcomp -M $mybase.4gl
#if [ $? -ne 0 ]
#then
# exit 1
#fi
#rm -f $mybase.4gl
#popd > /dev/null
#fglrun $_tmpfile.42m "$@"
#mycode=$?
#rm -f $_tmpfile.42m
#rm -rf $_TMPDIR
#exit $mycode
#__CAT_EOF_END__
#__CAT_EOF_BEGIN__:catsource.4gl
#--note: some 4gl constructs in this file are there to surround the pitfalls
#--of echo'ing this file with the windows echo command to a temp 4gl file
#--percent signs are avoided as well as or signs, thats why we avoid
#--the sfmt operator and the cat operator and mixing quotes with double quotes
#OPTIONS SHORT CIRCUIT
#IMPORT util
#IMPORT os
#DEFINE tmpdir,fname,full,lastmodule STRING
#DEFINE m_bat INT
#DEFINE singlequote,doublequote,backslash,percent,dollar STRING
#DEFINE m_binTypeArr,m_resTypeArr,m_imgarr,m_resarr DYNAMIC ARRAY OF STRING
#MAIN
# DEFINE line,err,catfile STRING
# DEFINE ch,chw base.Channel
# DEFINE sb base.StringBuffer
# DEFINE write,writebin INT
# LET singlequote=ASCII(39)
# LET doublequote=ASCII(34)
# LET backslash=ASCII(92) --we must not use the literal here
# LET percent=ASCII(37)
# LET dollar=ASCII(36)
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='png'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='jpg'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='bmp'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='gif'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='tiff'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='wav'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='mp3'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='aiff'
# LET m_binTypeArr[m_binTypeArr.getLength()+1]='mpg'
#
# LET m_resTypeArr[m_resTypeArr.getLength()+1]='per'
# LET m_resTypeArr[m_resTypeArr.getLength()+1]='4st'
# LET m_resTypeArr[m_resTypeArr.getLength()+1]='4tb'
# LET m_resTypeArr[m_resTypeArr.getLength()+1]='4tm'
# LET m_resTypeArr[m_resTypeArr.getLength()+1]='4sm'
# LET m_resTypeArr[m_resTypeArr.getLength()+1]='iem'
# LET sb=base.StringBuffer.create()
# LET catfile=fgl_getenv("_CATFILE") --set by calling script
# LET tmpdir=fgl_getenv("_TMPDIR") --set by calling script
# LET m_bat=fgl_getenv("_IS_BAT_FILE") IS NOT NULL
# IF catfile IS NULL OR tmpdir IS NULL THEN
# CALL myerr("_CATFILE or _TMPDIR not set")
# END IF
# IF catfile IS NULL THEN
# LET catfile=arg_val(1)
# LET tmpdir=arg_val(2)
# END IF
# IF NOT m_bat THEN --windows fullPath is clumsy
# LET tmpdir=os.Path.fullPath(tmpdir)
# END IF
# LET ch=base.Channel.create()
# LET chw=base.Channel.create()
# IF NOT os.Path.exists(tmpdir) THEN
# IF NOT os.Path.mkdir(tmpdir) THEN
# LET err="Can't mkdir :",tmpdir
# CALL myerr(err)
# END IF
# END IF
# CALL ch.openFile(catfile,"r")
# WHILE (line:=ch.readLine()) IS NOT NULL
# CASE
# WHEN m_bat AND line.getIndexOf("rem __CAT_EOF_BEGIN__:",1)==1
# LET fname=line.subString(23,line.getLength())
# GOTO mark1
# WHEN (NOT m_bat) AND line.getIndexOf("#__CAT_EOF_BEGIN__:",1)==1
# LET fname=line.subString(20,line.getLength())
# LABEL mark1:
# LET full=os.Path.join(tmpdir,fname)
# CALL checkSubdirs()
# IF isBinary(fname) THEN
# LET writebin=TRUE
# CALL addDir(m_imgarr,os.Path.dirName(fname))
# CALL sb.clear()
# ELSE
# IF isResource(fname) THEN
# CALL addDir(m_resarr,os.Path.dirName(fname))
# END IF
# LET write=TRUE
# CALL chw.openFile(full,"w")
# END IF
# WHEN ((NOT m_bat) AND line=="#__CAT_EOF_END__") OR
# (m_bat AND line=="rem __CAT_EOF_END__")
# IF writebin THEN
# LET writebin=FALSE
# CALL util.Strings.base64Decode(sb.toString(),full)
# ELSE
# LET write=FALSE
# CALL chw.close()
# CALL eventuallyCompileFile()
# END IF
# WHEN writebin
# CALL sb.append(line.subString(IIF(m_bat,5,2),line.getLength()))
# WHEN write
# CALL chw.writeLine(line.subString(IIF(m_bat,5,2),line.getLength()))
# END CASE
# END WHILE
# CALL ch.close()
# CALL runLastModule()
#END MAIN
#
#FUNCTION addDir(arr,dirname)
# DEFINE arr DYNAMIC ARRAY OF STRING
# DEFINE dirname STRING
# DEFINE i INT
# FOR i=1 TO arr.getLength()
# IF arr[i]=dirname THEN
# RETURN --already contained
# END IF
# END FOR
# LET arr[arr.getLength()+1]=dirname
#END FUNCTION
#
#FUNCTION setPathFor(arr,envName,cmd)
# DEFINE arr DYNAMIC ARRAY OF STRING
# DEFINE envName,tmp STRING
# DEFINE cmd STRING
# DEFINE i INT
# IF arr.getLength()>0 THEN
# LET tmp=envName,"="
# LET cmd=cmd,IIF(m_bat,"set ",""),tmp
# IF fgl_getenv(envName) IS NOT NULL THEN
# IF m_bat THEN
# LET cmd=percent,envName,percent,";"
# ELSE
# LET cmd=dollar,envName,":"
# END IF
# END IF
# FOR i=1 TO arr.getLength()
# IF i>1 THEN
# LET cmd=cmd,IIF(m_bat,";",":")
# END IF
# LET cmd=cmd,quotePath(os.Path.join(tmpdir,arr[i]))
# END FOR
# LET cmd=cmd,IIF(m_bat,"&&"," ")
# END IF
# RETURN cmd
#END FUNCTION
#
#FUNCTION runLastModule() --we must get argument quoting right
# DEFINE i INT
# DEFINE arg,cmd,cmdsave,image2font STRING
# IF lastmodule IS NULL THEN RETURN END IF
# LET cmd=setPathFor(m_resarr,"FGLRESOURCEPATH",cmd)
# LET image2font=os.Path.join(os.Path.join(fgl_getenv("FGLDIR"),"lib"),"image2font.txt")
# LET cmdsave=cmd
# LET cmd=setPathFor(m_imgarr,"FGLIMAGEPATH",cmd)
# IF cmd!=cmdsave AND os.Path.exists(image2font) THEN
# IF m_bat THEN
# LET cmd=cmd.subString(1,cmd.getLength()-2),";",quotePath(image2font),"&&"
# ELSE
# LET cmd=cmd.subString(1,cmd.getLength()-1),":",quotePath(image2font)," "
# END IF
# END IF
# LET cmd=cmd,"fglrun ",os.Path.join(tmpdir,lastmodule)
# FOR i=1 TO num_args()
# LET arg=arg_val(i)
# CASE
# WHEN m_bat AND arg.getIndexOf(' ',1)==0 AND
# arg.getIndexOf(doublequote,1)==0
# LET cmd=cmd,' ',arg --we don't need quotes
# WHEN m_bat OR arg.getIndexOf(singlequote,1)!=0
# --we must use double quotes on windows
# LET cmd=cmd,' ',doublequote,quoteDouble(arg),doublequote
# OTHERWISE
# --sh: you can't quote single quotes inside single quotes
# --everything else does not need to be quoted
# LET cmd=cmd,' ',singlequote,arg,singlequote
# END CASE
# END FOR
# --DISPLAY "cmd:",cmd
# CALL myrun(cmd)
#END FUNCTION
#
#FUNCTION quotePath(p)
# DEFINE p STRING
# --TODO: quote space with backlash space
# --IF NOT m_bat AND p.getIndexOf(" ",1)!=0
# --RETURN quoteSpace(p)
# --END IF
# RETURN p
#END FUNCTION
#
#FUNCTION myerr(err)
# DEFINE err STRING
# DISPLAY "ERROR:",err
# EXIT PROGRAM 1
#END FUNCTION
#
#FUNCTION eventuallyCompileFile()
# DEFINE cmd STRING
# CASE
# WHEN os.Path.extension(fname)=="4gl"
# LET cmd="cd ",tmpdir," && fglcomp -M ",fname
# CALL myrun(cmd)
# --DISPLAY "dirname:",fname,",basename:",os.Path.baseName(fname)
# LET lastmodule=os.Path.baseName(fname)
# --cut extension
# LET lastmodule=lastmodule.subString(1,lastmodule.getLength()-4)
# --DISPLAY "lastmodule=",lastmodule
# WHEN os.Path.extension(fname)=="per"
# LET cmd="cd ",tmpdir," && fglform -M ",fname
# CALL myrun(cmd)
# --other (resource) files are just copied
# END CASE
#END FUNCTION
#
#FUNCTION myrun(cmd)
# DEFINE cmd STRING, code INT
# --DISPLAY "myrun:",cmd
# RUN cmd RETURNING code
# IF code THEN
# EXIT PROGRAM 1
# END IF
#END FUNCTION
#
#FUNCTION checkSubdirs()
# DEFINE i,found INT
# DEFINE dir,err STRING
# DEFINE dirs DYNAMIC ARRAY OF STRING
# LET dir=os.Path.fullPath(os.Path.dirName(full))
# WHILE TRUE
# CASE
# WHEN dir IS NULL
# EXIT WHILE
# WHEN dir==tmpdir
# LET found=true
# EXIT WHILE
# OTHERWISE
# CALL dirs.insertElement(1)
# LET dirs[1]=dir
# END CASE
# LET dir=os.Path.fullPath(os.Path.dirName(dir))
# END WHILE
# IF NOT found THEN
# --we can't use sfmt because of .bat echo pitfalls
# LET err=singlequote,fname,singlequote,' does point outside'
# CALL myerr(err)
# END IF
# FOR i=1 TO dirs.getLength()
# LET dir=dirs[i]
# IF NOT os.Path.exists(dir) THEN
# IF NOT os.Path.mkdir(dir) THEN
# LET err="Can't create directory:",dir
# CALL myerr(err)
# END IF
# END IF
# END FOR
#END FUNCTION
#
#FUNCTION quoteDouble(s)
# DEFINE s STRING
# DEFINE c STRING
# DEFINE i INT
# DEFINE sb base.StringBuffer
# LET sb=base.StringBuffer.create()
# FOR i=1 TO s.getLength()
# LET c=s.getCharAt(i)
# CASE
# WHEN c==doublequote
# CALL sb.append(backslash)
# WHEN (NOT m_bat) AND c==backslash
# CALL sb.append(backslash)
# END CASE
# CALL sb.append(c)
# END FOR
# RETURN sb.toString()
#END FUNCTION
#
#FUNCTION isInArray(arr,fname)
# DEFINE arr DYNAMIC ARRAY OF STRING
# DEFINE fname,ext STRING
# DEFINE i INT
# LET ext=os.Path.extension(fname)
# FOR i=1 TO arr.getLength()
# IF arr[i]==ext THEN
# RETURN TRUE
# END IF
# END FOR
# RETURN FALSE
#END FUNCTION
#
#FUNCTION isBinary(fname)
# DEFINE fname STRING
# RETURN isInArray(m_binTypeArr,fname)
#END FUNCTION
#
#FUNCTION isResource(fname)
# DEFINE fname STRING
# RETURN isInArray(m_resTypeArr,fname)
#END FUNCTION
#
#__CAT_EOF_END__
#__CAT_EOF_BEGIN__:fglscriptify.4gl
#IMPORT os
#IMPORT util
#DEFINE m_chw base.Channel
#DEFINE m_outfile,m_lastsource STRING
#--DEFINE m_minversion STRING
#DEFINE m_optarr,m_sourcearr,m_binarr DYNAMIC ARRAY OF STRING
#DEFINE m_bat,m_verbose INT
#DEFINE m_envarr DYNAMIC ARRAY OF RECORD
# name STRING,
# value STRING
#END RECORD
#CONSTANT m_binfiles='["png","jpg","bmp","gif","tiff","wav","mp3","aiff","mpg"]'
#MAIN
# CONSTANT R_READ=4
# CONSTANT R_EXECUTE=1
# DEFINE catsource STRING
# DEFINE ch base.Channel
# DEFINE line STRING
# DEFINE i,dummy INT
# CALL parseArgs()
# IF m_lastsource IS NULL THEN
# CALL myerr("No 4gl source has been added")
# END IF
# CALL util.JSON.parse(m_binfiles,m_binarr)
# IF m_outfile IS NULL THEN
# LET m_outfile=os.Path.baseName(m_lastsource)
# --subtract .4gl
# LET m_outfile=m_outfile.subString(1,m_outfile.getLength()-4)
# ELSE
# IF os.Path.extension(m_outfile)=="bat" THEN
# LET m_bat=TRUE
# END IF
# END IF
# IF m_verbose THEN
# DISPLAY "outfile:",m_outfile
# DISPLAY "sources:",util.JSON.stringify(m_sourcearr)
# END IF
# LET ch=base.Channel.create()
# LET m_chw=base.Channel.create()
# LET catsource="catsource"
# IF m_bat THEN
# LET catsource=catsource,".bat"
# ELSE
# LET catsource=catsource,".sh"
# END IF
# LET catsource=os.Path.join(os.Path.dirName(arg_val(0)),catsource)
# CALL ch.openFile(catsource,"r")
# CALL m_chw.openFile(m_outfile,"w")
# IF m_bat THEN
# CALL m_chw.writeLine("@echo off")
# ELSE
# CALL m_chw.writeLine("#!/bin/bash")
# END IF
# FOR i=1 TO m_envarr.getLength()
# IF m_bat THEN
# CALL m_chw.writeLine(sfmt("set %1=%2",m_envarr[i].name,m_envarr[i].value))
# ELSE
# CALL m_chw.writeLine(sfmt("export %1=%2",m_envarr[i].name,m_envarr[i].value))
# END IF
# END FOR
# WHILE (line:=ch.readLine()) IS NOT NULL
# CASE
# WHEN (m_bat AND line=="rem HERE_COMES_CATSOURCE") OR
# ((NOT m_bat) AND line=="#HERE_COMES_CATSOURCE")
# CALL insert_extractor()
# OTHERWISE
# CALL m_chw.writeLine(line)
# END CASE
# END WHILE
# CALL ch.close()
# FOR i=1 TO m_sourcearr.getLength()
# CALL appendSource(m_sourcearr[i])
# END FOR
# -- rights are -r-xr--r--
# CALL os.Path.chRwx(m_outfile, ((R_READ+R_EXECUTE)*64) + (R_READ*8) + R_READ ) RETURNING dummy
#END MAIN
#
#FUNCTION parseArgs()
# DEFINE i,len INT
# DEFINE arg,space,flagX,pre,post STRING
# FOR i=0 TO num_args()
# LET arg=arg_val(i)
# LET len=arg.getLength()
#
#&define GETOPT(aopt,shortopt,longopt,desc,isFlag) \
# CASE \
# WHEN i==0 \
# IF LENGTH(longopt)>=10 THEN \
# LET space="\t" \
# ELSE \
# LET space="\t\t" \
# END IF \
# IF isFlag THEN \
# LET flagX = " yes " LET pre="(" LET post=")"\
# ELSE \
# LET flagX = " no " LET pre="<" LET post=">"\
# END IF \
# LET m_optarr[m_optarr.getLength()+1]=flagX,shortopt," ",longopt,space," ",pre,desc,post \
# WHEN (arg==shortopt OR arg==longopt) AND (NOT isFlag) \
# LET i=i+1 \
# LET aopt=arg_val(i) \
# CONTINUE FOR \
# WHEN (arg==shortopt OR arg==longopt) AND isFlag \
# LET aopt=TRUE \
# CONTINUE FOR \
# END CASE
#
# GETOPT(m_outfile,"-o","--outfile","created script file",FALSE)
# --GETOPT(m_minversion,"-m","--minversion","minimum fglcomp version",FALSE)
# GETOPT(m_verbose,"-v","--verbose","prints some traces",TRUE)
# IF i==0 THEN CONTINUE FOR END IF
# -- process result_file according to system path
# IF (arg=="-e" OR arg=="--env") THEN
# LET i=i+1
# CALL addRuntimeEnv(arg_val(i))
# CONTINUE FOR
# END IF
# IF arg.getCharAt(1) = '-' THEN
# DISPLAY SFMT("Option %1 is unknown.", arg)
# CALL help()
# END IF
# CALL addToSources(arg)
# END FOR
# IF num_args()=0 THEN
# CALL help()
# END IF
#END FUNCTION
#
#FUNCTION addRuntimeEnv(arg)
# DEFINE arg STRING
# DEFINE idx,new INT
# LET idx=arg.getIndexOf("=",1)
# IF idx==0 THEN
# RETURN
# END IF
# LET new=m_envarr.getLength()+1
# LET m_envarr[new].name=arg.subString(1,idx-1)
# LET m_envarr[new].value=arg.subString(idx+1,arg.getLength())
#END FUNCTION
#
#FUNCTION addToSources(fname)
# DEFINE fname STRING
# IF NOT os.Path.exists(fname) THEN
# CALL myerr(sfmt("Can't find '%1'",fname))
# END IF
# IF os.Path.isDirectory(fname) THEN
# CALL myerr(sfmt("'%1' is a directory, can only add regular files",fname))
# END IF
# CALL checkIsInPath(fname)
# LET m_sourcearr[m_sourcearr.getLength()+1]=fname
# IF os.Path.extension(fname)=="4gl" THEN
# LET m_lastsource=fname
# END IF
#END FUNCTION
#
#--we allow only file names which are inside our current dir
#--(and sub dirs)
#FUNCTION checkIsInPath(fname)
# DEFINE fname STRING
# DEFINE fullpwd,dir STRING
# DEFINE found INT
# LET fullpwd=os.Path.fullPath(os.Path.pwd())
# LET dir=os.Path.fullPath(os.Path.dirName(fname))
# WHILE dir IS NOT NULL
# IF dir==fullpwd THEN
# LET found=TRUE
# EXIT WHILE
# END IF
# LET dir=os.Path.fullPath(os.Path.dirName(dir))
# END WHILE
# IF NOT found THEN
# CALL myerr(sfmt("'%1' is not inside our current directories subtree",fname))
# END IF
#END FUNCTION
#
#
#FUNCTION help()
# DEFINE i INT
# DEFINE progname STRING
# LET progname=fgl_getenv("_CALLING_SCRIPT")
# IF progname IS NULL THEN
# LET progname="fglscriptify"
# END IF
# DISPLAY "usage: ",progname," ?option? ... ?file? <4glmain>"
# DISPLAY "Possible options:"
# DISPLAY " Flag short long\t\t Value or Description"
# DISPLAY " no -e --env\t\t <ENV>=<value>"
# FOR i=1 TO m_optarr.getLength()
# DISPLAY " ",m_optarr[i]
# END FOR
# EXIT PROGRAM 1
#END FUNCTION
#
#FUNCTION insert_extractor()
# DEFINE ch base.Channel
# DEFINE line,whitesp,catsource4gl STRING
# CONSTANT perc="%"
# LET ch=base.Channel.create()
# LET catsource4gl=os.Path.join(os.Path.dirName(arg_val(0)),"catsource.4gl")
# CALL ch.openFile(catsource4gl,"r")
# WHILE (line:=ch.readLine()) IS NOT NULL
# IF m_bat THEN
# LET whitesp=line CLIPPED
# IF whitesp.getLength()==0 THEN --echo with spaces produces ECHO off
# LET line="--"
# END IF
# CALL m_chw.writeLine(sfmt("echo %1 >> %2extractor%3",line,perc,perc))
# ELSE
# CALL m_chw.writeLine(line)
# END IF
# END WHILE
# CALL ch.close()
#END FUNCTION
#
#FUNCTION appendSource(fname)
# DEFINE fname,ext STRING
# DEFINE ch base.Channel
# DEFINE pre,line STRING
# LET ch=base.Channel.create()
# CALL ch.openFile(fname,"r")
# IF m_bat THEN
# LET pre="rem "
# ELSE
# LET pre="#"
# END IF
# CALL m_chw.writeLine(sfmt("%1__CAT_EOF_BEGIN__:%2",pre,fname))
# LET ext=os.Path.extension(fname)
# IF isBinary(fname) THEN
# CALL writeBinary(fname,pre)
# ELSE
# WHILE (line:=ch.readLine()) IS NOT NULL
# CALL m_chw.writeLine(sfmt("%1%2",pre,line))
# END WHILE
# END IF
# CALL m_chw.writeLine(sfmt("%1__CAT_EOF_END__",pre))
# CALL ch.close()
#END FUNCTION
#
#FUNCTION isBinary(fname)
# DEFINE fname,ext STRING
# DEFINE i INT
# LET ext=os.Path.extension(fname)
# FOR i=1 TO m_binarr.getLength()
# IF m_binarr[i]==ext THEN
# RETURN TRUE
# END IF
# END FOR
# RETURN FALSE
#END FUNCTION
#
#FUNCTION mysub(base64,index,linelength,len)
# DEFINE base64 STRING
# DEFINE index,linelength,len,endindex INT
# LET endindex=index+linelength-1
# RETURN base64.subString(index,IIF(endindex>len,len,endindex))
#END FUNCTION
#
#FUNCTION writeBinary(fname,pre)
# DEFINE fname,pre STRING
# DEFINE base64,chunk STRING
# DEFINE index,linelength,len INT
# LET linelength=IIF(m_bat,76,79)
# LET index=1
# LET base64=util.Strings.base64Encode(fname)
# LET len=base64.getLength()
# --spit out 80 char pieces
# LET chunk=mysub(base64,index,linelength,len)
# WHILE chunk.getLength()>0
# CALL m_chw.writeLine(sfmt("%1%2",pre,chunk))
# LET index=index+linelength
# LET chunk=mysub(base64,index,linelength,len)
# END WHILE
#END FUNCTION
#
#FUNCTION myerr(err)
# DEFINE err STRING
# DISPLAY "ERROR:",err
# EXIT PROGRAM 1
#END FUNCTION
#__CAT_EOF_END__
<file_sep>.SUFFIXES: .4gl .42m
.4gl.42m:
fglcomp -M -W all $<
all:: catsource.42m fglscriptify.42m
fglscriptify: all catsource.bat catsource.sh catsource.4gl fglscriptify.4gl
rm -f $@
fglrun fglscriptify.42m -o $@ catsource.bat catsource.sh catsource.4gl fglscriptify.4gl
fglscriptify.bat: all catsource.bat catsource.sh catsource.4gl fglscriptify.4gl
rm -f $@
fglrun fglscriptify.42m -o $@ catsource.bat catsource.sh catsource.4gl fglscriptify.4gl
dist: fglscriptify fglscriptify.bat
clean:
rm -f *.42?
distclean: clean
rm -f fglscriptify fglscriptify.bat
<file_sep>#!/bin/bash
DIR=`dirname "$0"`
#echo "DIR='$DIR'"
pushd "$DIR" >/dev/null
BINDIR=`pwd`
#echo "BINDIR='$BINDIR'"
popd > /dev/null
export _CATFILE="$BINDIR/`basename $0`"
export _CALLING_SCRIPT=`basename $0`
#echo "me:$_CATFILE"
firstcheck=`mktemp`
fglrun -V > $firstcheck
if [ $? -ne 0 ]
then
rm -f $firstcheck
echo "ERROR: no fglrun in the path"
exit 1
fi
ver=`cat $firstcheck | sed -n '/Genero virtual machine/q;p'`
major=`echo $ver | sed -n 's/^.* \([0-9]*\)\.\([0-9]*\).*$/\1/p'`
rm -f $firstcheck
if [ $major -lt 3 ]
then
echo "ERROR:fglrun version should be >= 3.0 ,current:$ver"
exit 1
fi
replace_dot(){
# replace dot with underscore
local dir=`dirname $1`
local base=`basename $1`
#genero doesn't like dots in the filename
base=`echo $base | sed -e 's/\./_/g'`
echo "$dir/$base"
}
# compute a unique temp filename and a unique directory
# without dots in the name
while true
do
_tmpfile=`mktemp`
_tmpdir_extractor=`dirname $_tmpfile`
rm -f $_tmpfile
_tmpfile=`replace_dot $_tmpfile`
_TMPDIR=`mktemp -d`
rm -rf $_TMPDIR
export _TMPDIR=`replace_dot $_TMPDIR`
if [ ! -e $_tmpfile ] && [ ! -e $_TMPDIR ]
then
break
fi
done
#echo "_tmpfile:$_tmpfile,_tmpdir_extractor:$_tmpdir_extractor,_TMPDIR:$_TMPDIR"
#we insert catsource.4gl on the next lines
cat >$_tmpfile.4gl <<EOF
#HERE_COMES_CATSOURCE
EOF
#now compile and run catsource from the temp location
pushd `pwd` > /dev/null
cd $_tmpdir_extractor
mybase=`basename $_tmpfile`
fglcomp -M $mybase.4gl
if [ $? -ne 0 ]
then
exit 1
fi
rm -f $mybase.4gl
popd > /dev/null
fglrun $_tmpfile.42m "$@"
mycode=$?
rm -f $_tmpfile.42m
rm -rf $_TMPDIR
exit $mycode
<file_sep># fglscriptify
create Genero 4gl "scripts" from 4GL source and resource files
## Motivation
Did you ever run into the trouble of getting
```
Module 'foo.42m': Bad version: Recompile your sources.
```
?
As I'm frequently changing Genero environments and the tools are now outside the fgl distribution I got this too often in the past.
fglscriptify changes this by creating a shell script/.bat file containing all sources and resources.
Upon launch the sources are extracted into a temporary directory,
compiled with the current Genero fglcomp/fglform tools and run with the current fglrun.
So in fact fglscriptify produces self extracting and self compiling scripts which are directly executable.
## Installation
fglscriptify did already scriptify itself and is distributed (of course ) as a single shell script/.bat file.
You can call it directly by specififying the path to it or copy it into a directory contained in the PATH variable.
## Usage
```
fglscriptify ?-o outputname? file ... mainmodule.4gl
```
If -outputname is omitted the script gets the name of the last 4GL module added.The last 4GL module added must be also the one containing the MAIN of the program.
## Samples
creates a script named foo
```
$ fglscriptify foo.per foo.4gl
```
creates a windows script foo.bat, the .bat extension is the indicator to create a Windows script.
```
$ fglscriptify -o foo.bat foo.per foo.4gl
```
creates a script using internally a text file
```
$ fglscriptify foo.txt foo.4gl
```
Accessing the text file in the program is
```
LET txtfile=os.Path.join(os.Path.dirname(arg_val(0)),"foo.txt")
```
| 02585d4f2e565a97a22f2d48f3945d0e297a501d | [
"Markdown",
"Makefile",
"Shell"
] | 5 | Makefile | leopatras/fglscriptify | 288d2a5cc27cb767a39a9edda3c41538ea341ad5 | 47acc6fbb61c11e987cf2d351ea9691674211d91 |
refs/heads/master | <file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HelperLibrary;
namespace HelperLibraryUnitTests
{
[TestClass]
public class AmountToWordTests
{
int value = 0;
string expected = "", result = "";
[TestMethod]
public void SingleDigit_FixedValue()
{
//Arrange
value = 1;
expected = "one";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 2;
expected = "two";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 3;
expected = "three";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 4;
expected = "four";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 5;
expected = "five";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 6;
expected = "six";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 7;
expected = "seven";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 8;
expected = "eight";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 9;
expected = "nine";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void DoubleDigit_FixedValue()
{
//Arrange
value = 11;
expected = "eleven";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 12;
expected = "twelve";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 13;
expected = "thirteen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 14;
expected = "fourteen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 15;
expected = "fifteen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 16;
expected = "sixteen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 17;
expected = "seventeen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 18;
expected = "eighteen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 19;
expected = "nineteen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 10;
expected = "ten";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 20;
expected = "twenty";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 30;
expected = "thirty";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 40;
expected = "forty";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 50;
expected = "fifty";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 60;
expected = "sixty";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 70;
expected = "seventy";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 80;
expected = "eighty";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 90;
expected = "ninety";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void AmountInHundreds()
{
//Arrange
value = 100;
expected = "one hundred";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 101;
expected = "one hundred one";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 210;
expected = "two hundred ten";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 311;
expected = "three hundred eleven";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 422;
expected = "four hundred twenty-two";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 987;
expected = "nine hundred eighty-seven";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void AmountInThousands()
{
//Arrange
value = 1000;
expected = "one thousand";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 2003;
expected = "two thousand three";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 10014;
expected = "ten thousand fourteen";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 14526;
expected = "fourteen thousand five hundred twenty-six";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 256128;
expected = "two hundred fifty-six thousand one hundred twenty-eight";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 999888;
expected = "nine hundred ninety-nine thousand eight hundred eighty-eight";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void AmountInMillions()
{
//Arrange
value = 1000000;
expected = "one million";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 1000001;
expected = "one million one";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 1000012;
expected = "one million twelve";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 1000240;
expected = "one million two hundred forty";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 1789453;
expected = "one million seven hundred eighty-nine thousand four hundred fifty-three";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 16745086;
expected = "sixteen million seven hundred forty-five thousand eighty-six";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
//Arrange
value = 987654321;
expected = "nine hundred eighty-seven million six hundred fifty-four thousand three hundred twenty-one";
//Act
result = Helper.ConvertAmountToWords(value);
//Assert
Assert.AreEqual(expected, result);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelperLibrary
{
public static class Helper
{
public static string ConvertAmountToWords(int value)
{
string amountInWords = "";
try
{
if (value == 10
|| value == 20
|| value == 30
|| value == 40
|| value == 50
|| value == 60
|| value == 70
|| value == 80
|| value == 90)
{
switch (value)
{
case 10: amountInWords = "ten"; break;
case 20: amountInWords = "twenty"; break;
case 30: amountInWords = "thirty"; break;
case 40: amountInWords = "forty"; break;
case 50: amountInWords = "fifty"; break;
case 60: amountInWords = "sixty"; break;
case 70: amountInWords = "seventy"; break;
case 80: amountInWords = "eighty"; break;
case 90: amountInWords = "ninety"; break;
}
}
else if (value < 10)
{
switch (value)
{
case 1: amountInWords = "one"; break;
case 2: amountInWords = "two"; break;
case 3: amountInWords = "three"; break;
case 4: amountInWords = "four"; break;
case 5: amountInWords = "five"; break;
case 6: amountInWords = "six"; break;
case 7: amountInWords = "seven"; break;
case 8: amountInWords = "eight"; break;
case 9: amountInWords = "nine"; break;
}
}
else if (value < 20)
{
switch (value)
{
case 11: amountInWords = "eleven"; break;
case 12: amountInWords = "twelve"; break;
case 13: amountInWords = "thirteen"; break;
case 14: amountInWords = "fourteen"; break;
case 15: amountInWords = "fifteen"; break;
case 16: amountInWords = "sixteen"; break;
case 17: amountInWords = "seventeen"; break;
case 18: amountInWords = "eighteen"; break;
case 19: amountInWords = "nineteen"; break;
}
}
else
{
int quotient = 0;
if ((value / 1000000) >= 1)
{
quotient = (int)(value / 1000000);
amountInWords = Helper.ConvertAmountToWords(quotient) + " million"
+ (value - (quotient * 1000000) == 0 ? "" : " ") + Helper.ConvertAmountToWords(value - (quotient * 1000000));
}
else if ((value / 1000) >= 1)
{
quotient = (int)(value / 1000);
amountInWords = Helper.ConvertAmountToWords(quotient) + " thousand"
+ (value - (quotient * 1000) == 0 ? "" : " ") + Helper.ConvertAmountToWords(value - (quotient * 1000));
}
else if ((value / 100) >= 1)
{
quotient = (int)(value / 100);
amountInWords = Helper.ConvertAmountToWords(quotient) + " hundred"
+ (value - (quotient * 100) == 0 ? "" : " ") + Helper.ConvertAmountToWords(value - (quotient * 100));
}
else if ((value / 10) >= 1)
{
quotient = (int)(value / 10);
amountInWords = Helper.ConvertAmountToWords(quotient * 10)
+ ((value - (quotient * 10)) == 0 ? "" : "-") + Helper.ConvertAmountToWords(value - (quotient * 10));
}
}
}
catch (Exception e) {
Console.WriteLine(e.Message);
//Incomplete -- there should be a logger class
}
return amountInWords;
}
}
}
<file_sep># Amount to Words Library
A library that converts numbers(integer) to words
## Prerequisites
- Visual Studio 2019
- Microsoft .NET Framework (4.5 and above)
## Parameters
- Any number greater than zero but less than 1 billion
- To quit the application press q or Q, then press enter
## Exception
- Other characters are not allowed and the console application will throw an error message
## Visual Studio Projects
> AmountToWordsConsoleApp
- Contains the console application
>HelperLibrary
- Contains the amount to words function / method (dll)
>HelperLibraryUnitTests
- Contains the test scenarios for the library
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HelperLibrary;
namespace AmountToWordsConsoleApp
{
class Program
{
static void Main(string[] args)
{
bool isEndLoop = false;
do
{
Console.WriteLine("Please any number(integer) to be converted to words (Press Q to exit): ");
string inputValue = Console.ReadLine();
isEndLoop = int.TryParse(inputValue, out int value);
if (isEndLoop)
{
Console.WriteLine(Helper.ConvertAmountToWords(Convert.ToInt32(inputValue)));
Console.WriteLine(""); // Space
}
else if (!inputValue.ToUpper().Equals("Q"))
{
Console.WriteLine("Invalid input value. Please enter a number");
isEndLoop = true; // reset until user enters Q
}
} while (isEndLoop);
}
}
}
| e2282003a1ce81fa86a40e3dbc842d8d0c5e2af8 | [
"Markdown",
"C#"
] | 4 | C# | ijerbb/AmtToWordsLib | 02e38a1c13aee7b4ad607f879f9add64ce77662c | 16c85a932a649647b282430d5c14b1078880dea5 |
refs/heads/master | <file_sep>WordPress website for fictional birding club.
To get project running start a site on a WordPress development tool (e.g. Local by Flywheel).
Create a new folder in the theme folder, add all the files to that folder and activate the folder in the WP-admin area (appearance -> themes).
<file_sep><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<header class="header">
<div class="header__container">
<h1 class="header__logo">
<a href="<?php echo site_url() ?>"><strong>Fictional</strong> Birding Club</a>
</h1>
<div class="mobile-nav hidden-on-desk">
<span class="js-search-trigger header__search-trigger "><i class="fa fa-search" aria-hidden="true"></i></span>
<span class="js-search-trigger header__search-trigger "><i class="fa fa-bars" aria-hidden="true"></i></span>
</div>
<div class="header__menu-group">
<nav class="main-navigation">
<ul>
<li <?php if (is_page('about-us') or wp_get_post_parent_id(0) == 11) echo 'class="current-menu-item"' ?>><a href="<?php echo site_url('/about-us') ?>">About Us</a></li>
<li><a href="#">Learn</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Blog</a></li>
</ul>
</nav>
<div class="dropdown-menu">
<div class="dropdown">
<p><a href="#" class="dropbtn">My Profile</a></p>
<div class="dropdown-content">
<a href="#">Login</a>
<a href="#">Sign Up</a>
</div>
</div>
</div>
<div class="searchbox">
<input style="font-family: FontAwesome;" placeholder='' />
</div>
</div>
</div>
</header><file_sep><?php
function birding_club_files() {
wp_enqueue_style('font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
wp_enqueue_style('birding_main_styles', get_stylesheet_uri());
wp_register_style('style', get_template_directory_uri() . '/src/styles/app.css', [], 1, 'all');
wp_enqueue_style('style');
wp_enqueue_script('jquery');
wp_register_script('app', get_template_directory_uri() . '/src/app.js', ['jquery'], 1, true);
wp_enqueue_script('app');
}
add_action('wp_enqueue_scripts', 'birding_club_files');
function birding_club_features() {
register_nav_menu('headerMenuLocation', 'Header Menu Location');
register_nav_menu('footerLocationOne', 'Footer Location One');
register_nav_menu('footerLocationTwo', 'Footer Location Two');
add_theme_support('title-tag');
}
add_action('after_setup_theme', 'birding_club_features');<file_sep><?php get_header(); ?>
<div class="page-banner">
<div class="page-banner__bg-image"style="background-image: url(<?php echo get_theme_file_uri('/images/Grackle-by-Phil-Gehlen.jpeg') ?>);"></div>
<div class="page-banner__content">
<h1 class="page-banner__headline">Welcome!</h1>
<h2 class="page-banner__headline--small">We’ll take your birding to a whole new level.</h2>
<h3 class="page-banner__headline--small">Why don’t you check out our latest <strong>events</strong>!</h3>
<a href="#">Read the latest news!</a>
</div>
</div>
<div class="main-content">
<div class="main-content__one">
<div class="main-content__inner">
<h2 class="main-content__inner--headline">Upcoming Events</h2>
<hr>
<div class="event">
<a class="event__date" href="#">
<span class="event__month">January</span>
<span class="event__day">1</span>
</a>
<div class="event__content">
<h5 class="event__title"><a href="#">Best day of the year for birders!</a></h5>
<p class="event__desc">Try and find as many birds as you can! All birds count!</p>
<a href="#" class="event__btn--gray"><strong>Learn more</strong></a>
</div>
</div>
<hr>
<div class="event">
<a class="event__date t-center" href="#">
<span class="event__month">Apr</span>
<span class="event__day">02</span>
</a>
<div class="event__content">
<h5 class="event__title headline"><a href="#">Member Picnic Party</a></h5>
<p>Live music, a taco truck and more can found in our third annual member picnic day.</p>
<a href="#" class="event__btn--gray"><strong>Learn more</strong></a>
</div>
</div>
<hr>
<div class="main-content__inner--btn-wrapper">
<a href="#" class="event__btn">View All Events</a>
</div>
</div>
</div>
<div class="main-content__two">
<div class="main-content__inner">
<h2 class="main-content__inner--headline">From Our Blogs</h2>
<hr>
<div class="event">
<a class="event__date event__date--beige t-center" href="#">
<span class="event__month">Jan</span>
<span class="event__day">20</span>
</a>
<div class="event__content">
<h5 class="event__title"><a href="#">We Were Voted Best Birding Club</a></h5>
<p>For the 2nd year in a row we are voted #1. </p>
<a href="#" class="event__btn--gray"><strong>Read more</strong></a>
</div>
</div>
<hr>
<div class="event">
<a class="event__date event__date--beige t-center" href="#">
<span class="event__month">Feb</span>
<span class="event__day">04</span>
</a>
<div class="event__content">
<h5 class="event__title"><a href="#">Birders in the National Spotlight</a></h5>
<p>Two of our birders have been in national news lately.</p>
<a href="#" class="event__btn--gray"><strong>Read more</strong></a>
</div>
</div>
<hr>
<div class="main-content__inner--btn-wrapper">
<p><a href="#" class="event__btn">View All Blog Posts</a></p>
</div>
</div>
</div>
</div>
<div class="carousel-wrapper">
<span id="item-1"></span>
<span id="item-2"></span>
<div class="carousel-item item-1" style="background-image: url(<?php echo get_theme_file_uri('/images/Bald-Eagle-by-Phil-Gehlen.png') ?>);">
<div class="carousel-item__content">
<div class="carousel-item__content--text">
<h2>Free Transportation</h2>
<p>All members have the chance to join our carpooling program.</p>
<p><a href="#" class="btn btn--blue">Learn more</a></p>
</div>
<div class="arrows">
<a class="arrow arrow-prev" href="#item-2"></a>
<a class="arrow arrow-next" href="#item-2"></a>
</div>
</div>
</div>
<div class="carousel-item item-2" style="background-image: url(<?php echo get_theme_file_uri('/images/Saw-Whet-Owl-by-Phil-Gehlen.png') ?>);">
<div class="carousel-item__content">
<div class="carousel-item__content--text">
<h2>Discount at your local retailer</h2>
<p>Member discounts awarded at several retailers.</p>
<p><a href="#" class="btn btn--blue">Learn more</a></p>
</div>
<div class="arrows">
<a class="arrow arrow-prev" href="#item-1"></a>
<a class="arrow arrow-next" href="#item-1"></a>
</div>
</div>
</div>
</div>
<?php get_footer();
?> | dbd8a653434b975f1ae887bbbeee1ad360763e58 | [
"Markdown",
"PHP"
] | 4 | Markdown | jessegeh/birding-club | 1d14f731c73c7b7f363e13f117a9c257de196229 | f3cd19de0326bb6f73026273792b0687dc2a2ebd |
refs/heads/master | <repo_name>Fa3ris/git-script<file_sep>/purge-git
#!/bin/bash
usage() {
echo -e "usage $0 [-d]\n
-d delete merged branches\n
must be in a git repo\n"
}
if ! $(git rev-parse > /dev/null 2>&1); then
echo this is not a git repo
usage
exit 1
# else
# echo this is a git repo
fi
DELETE=false
while getopts ":d" OPTION; do
case $OPTION in
d)
DELETE=true
echo "option $OPTION selected"
;;
*)
usage
exit 1
;;
esac
done
if [ "$DELETE" = true ]; then
git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d
else
echo 'branches to delete'
git branch --merged | egrep -v "(^\*|master|dev)"
fi
| 89979334c600c5edd0bf314850da91036cd98661 | [
"Shell"
] | 1 | Shell | Fa3ris/git-script | 4a43a2f3ba42960ccdd7ac2c2522067f03c40aa1 | 39b2d68b7fe2611d2c7125fc2bc639851ce58254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.