branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>#include <stdio.h>
int main(void) {
int arr[6]={8,4,1,9,6,2};
int sort[6];
int ctr, count, min;
for(ctr=0;ctr<sizeof(arr)/sizeof(arr[0]);ctr++)
{
sort[ctr] = arr[ctr];
}
for(ctr=0;ctr<sizeof(arr)/sizeof(arr[0]);ctr++)
{
for(count=ctr+1;count<sizeof(arr)/sizeof(arr[0]);count++)
{
if(sort[count]<sort[ctr])
{
min=sort[count];
sort[count]=sort[ctr];
sort[ctr]=min;
}
}
}
for(ctr=0;ctr<sizeof(arr)/sizeof(arr[0]);ctr++)
{
for(count=0;count<sizeof(arr)/sizeof(arr[0]);count++)
{
if(arr[ctr]==sort[count])
{
printf("%d --> %d\n",arr[ctr],sort[count+1]);
}
}
}
return 0;
}
|
5bbf215d5a562bb308ea83ed6656eee828695862
|
[
"C"
] | 1
|
C
|
GayathriPrabha/sorting-max
|
a2d5593e22a39cdf66fc9d7d9f977580c61e8b80
|
f83c275777b7680cd4967176c26c251c847fbec3
|
refs/heads/master
|
<repo_name>bingwenwuhen/tornado<file_sep>/ca.py
__author__ = 'Administrator'
import os
import tornado.web
import tornado.ioloop
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello world")
def post(self):
self.write("hello xiaxuan")
if __name__ == "__main__":
setting = {
'debug': True,
'static_path': os.path.join(os.path.dirname(__file__), "static"),
'template_path': os.path.join(os.path.dirname(__file__), "templates")
}
application = tornado.web.Application([
(r"/", MainHandler),
], **setting)
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
<file_sep>/test.py
__author__ = 'Administrator'
import os
c = {
"a": 1,
"b": 2
}
print (os.path.join(os.path.dirname(__file__), "templates"))
print(c)
del c
|
ba2dcc2b3305b466cba267155791487b15f6fa86
|
[
"Python"
] | 2
|
Python
|
bingwenwuhen/tornado
|
ceba4bd143c557c46ab1627d5abdbc60d48d3f60
|
07f97ce13a298efb0ddfe4d57e1235a3c478a93e
|
refs/heads/master
|
<file_sep>#ifndef PRECODE
#define PRECODE
#include <stdio.h>
#include <gtk/gtk.h>
struct card{
int num;
char name[1024];
int acquisition;
int type;
};
GdkColor red;
GdkColor green;
GdkColor gray;
GdkColor blue;
GdkColor yellow;
GdkColor color_tmp;
struct card card_list[256];
char mCardNum[1024];
int make_list_window(void);
void card_list_init(void);
enum C_Type{ GRAY, BLUE, GREEN, YELLOW, RED};
#endif
<file_sep>#include <string.h>
#include "pol_init.h"
static GtkWidget *list_window;
void card_clicked(GtkWidget *button, gpointer user_data)
{
int i;
strcpy(mCardNum,(char *)user_data);
//printf("%s\n", mCardNum);
}
void card_list_init(void ){
struct card list_tmp[256]={
{0, "下級船乗り", 1, 1},
{1, "中級船乗り", 2, 1},
{2, "上級船乗り", 3, 1},
{3, "少年", 0, 2},
{4, "聡明な少年", 0, 2},
{5, "学者", 0, 2},
{6, "財宝+1", 0, 3},
{7, "財宝+2", 0, 3},
{8, "財宝+3", 0, 3},
{9, "財宝+4", 0, 3},
{10, "財宝+5", 0, 3},
{11, "財宝+6", 0, 3},
{12, "財宝+7", 0, 3},
{13, "財宝+8", 0, 3},
{14, "財宝+9", 0, 3},
{15, "見張り", 0, 2},
{16, "新人水夫", 0, 2},
{17, "荒くれ", 0, 2},
{18, "航海長", 0, 2},
{19, "船医", 0, 2},
{20, "大砲", 0, 2},
{21, "現地案内人", 0, 2},
{22, "ネズミ害", 0, 2},
{23, "しごき", 0, 2},
{24, "港", 1, 2},
{25, "散財", 0, 2},
{26, "カリスマ", 0, 2},
{27, "雇われ水夫", 0, 2},
{28, "乱暴者", 0, 2},
{29, "カトラス", 0, 2},
{30, "補修", 0, 2},
{31, "ラム酒", 0, 2},
{32, "娼婦", 0, 2},
{33, "一方的同盟", 0, 2},
{34, "怠惰", 0, 2},
{35, "食糧不足", 0, 4},
{36, "嵐", 0, 4},
{37, "怪我人", 0},
{38, " ", 0},
{999, "", 0}
};
memcpy(card_list, list_tmp, sizeof(list_tmp));
*card_list=*list_tmp;
}
int make_list_window(){
GtkWidget *list_window;
GtkWidget *button;
GtkWidget *table;
int i;
list_window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (list_window), "Card List");
gtk_container_border_width (GTK_CONTAINER (list_window), 10);
table = gtk_table_new (5, 5, TRUE);
gtk_container_add (GTK_CONTAINER (list_window), table);
//ボタン作成
for(i=0;card_list[i].num<999;i++){
button = gtk_button_new_with_label (card_list[i].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (card_clicked), (gpointer)card_list[i].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, i/5, (i/5)+1, i%5, (i%5)+1);
switch(card_list[i].type){
case GRAY:
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &gray);
break;
case BLUE:
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &blue);
break;
case GREEN:
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &green);
break;
case YELLOW:
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &yellow);
break;
case RED:
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
break;
}
gtk_widget_show(button);
}
gtk_widget_show (table);
gtk_widget_show (list_window);
return;
}
GdkColor set_color(int num){
return gray;
}
<file_sep># Makefile 1 (「#」は行末までのコメント)
a32.out: main.o pol_init.o
gcc $$(pkg-config --cflags --libs gtk+-2.0) -o a32.out pol_init.o main.o -m32
pol_init.o: pol_init.c
gcc $$(pkg-config --cflags --libs gtk+-2.0) pol_init.c -c -m32
main.o: main.c
gcc $$(pkg-config --cflags --libs gtk+-2.0) main.c -c -m32
<file_sep>#include "pol_init.h"
void button_clicked(GtkButton *button, gpointer user_data)
{
//make_list_window();
gtk_button_set_label(button,mCardNum);
}
static void on_destroy(GtkWidget* widget, gpointer data)
{
gtk_main_quit ();
}
void make_window(){
GtkWidget *window;
GtkWidget *button;
GtkWidget *table;
int i;
{
gdk_color_parse ("blue", &blue);
gdk_color_parse ("red", &red);
gdk_color_parse ("yellow", &yellow);
//gdk_color_parse ("green", &green);
//gdk_color_parse ("lightgray", &green);
green.red = 0;
green.blue = 0;
green.green = 0xFFFF;
gray.red = 0xaaaa;
gray.blue = 0xaaaa;
gray.green = 0xaaaa;
}
/* 新しいウィンドウを作成 */
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
g_signal_connect(G_OBJECT (window), "destroy",
G_CALLBACK (on_destroy), NULL);
/* ウィンドウのタイトル */
gtk_window_set_title (GTK_WINDOW (window), "Deck View");
/* このウィンドウのボーダ幅を設定 */
gtk_container_border_width (GTK_CONTAINER (window), 10);
/*コンテナに配置(ボタンを垂直に配置している)*/
table = gtk_table_new (5, 5, TRUE);
gtk_container_add (GTK_CONTAINER (window), table);
//ボタン作成
{
//下級船乗り
for(i=0;i<5;i++){
button = gtk_button_new_with_label (card_list[0].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 0,1, i,i+1);
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &blue);
gtk_widget_show(button);
}
//カリスマ
for(i=0;i<2;i++){
button = gtk_button_new_with_label (card_list[26].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 1,2, i,i+1);
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &green);
gtk_widget_show(button);
}
for(i;i<5;i++){
button = gtk_button_new_with_label (card_list[38].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 1,2, i,i+1);
gtk_widget_show(button);
}
//樽
for(i=0;i<3;i++){
button = gtk_button_new_with_label (card_list[6].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 2,3, i,i+1);
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &yellow);
gtk_widget_show(button);
}
for(i;i<5;i++){
button = gtk_button_new_with_label (card_list[38].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 2,3, i,i+1);
gtk_widget_show(button);
}
//トラブル
for(i=0;i<2;i++){
button = gtk_button_new_with_label (card_list[35].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 3,4, i,i+1);
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
gtk_widget_show(button);
}
for(i;i<4;i++){
button = gtk_button_new_with_label (card_list[36].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 3,4, i,i+1);
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
gtk_widget_show(button);
}
for(i;i<5;i++){
button = gtk_button_new_with_label (card_list[38].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 3,4, i,i+1);
gtk_widget_show(button);
}
//予備
for(i=0;i<5;i++){
button = gtk_button_new_with_label (card_list[38].name);
gtk_signal_connect (GTK_OBJECT (button), "clicked",
GTK_SIGNAL_FUNC (button_clicked), (gpointer)card_list[0].name);
gtk_table_attach_defaults (GTK_TABLE(table), button, 4,5, i,i+1);
gtk_widget_show(button);
}
}
gtk_widget_show (button);
gtk_widget_show (table);
gtk_widget_show (window);
make_list_window();
gtk_main ();
return;
}
int main (int argc, char *argv[])
{
gtk_init (&argc, &argv);
card_list_init();
make_window();
return 0;
}
|
ee3e3f8efa080318fbcfcb27b3e90c3eb113adef
|
[
"C",
"Makefile"
] | 4
|
C
|
sysuke/pol_card
|
d8b9c831e54aed11db2a0c265bbec91ac86e23d9
|
ccf05fe72d336cbb14fe235dc163679b18c31ea2
|
refs/heads/main
|
<repo_name>Sahana012/Python-Code<file_sep>/forloop.py
myfriendlist = ["alina", "theresa", "maliha"]
for friend in myfriendlist:
print(friend)<file_sep>/countwords.py
introstring = input("Enter your introduction: ")
wordcount = 1
charcount = 0
for i in introstring:
charcount = charcount + 1
if(i == ' '):
wordcount = wordcount + 1
print("Number of word(s) in the string: ")
print(wordcount)
print("Number of characters(s) in the string: ")
print(charcount)<file_sep>/conditionals.py
age = int(input("Enter your age: "))
if(age > 18):
print("You are an adult")
elif(age > 12):
print("You are a teenager")
else:
print("You are a kid")<file_sep>/f.py
introString = "My name is Sahana. I am 11 years old."
words = introString.split()
print(words)<file_sep>/functions.py
f = open("text.txt")
fileLines = f.readlines()
for line in fileLines:
print(line)
|
af70f2fba7e85cbf2b13eface214dbef54c05fdb
|
[
"Python"
] | 5
|
Python
|
Sahana012/Python-Code
|
ff71d4548c992347ad63a114fc280cc2b44fa2cf
|
a21537dbe9f687575b2d45e8b0854e90df0acc1e
|
refs/heads/master
|
<repo_name>estark37/ratout<file_sep>/Makefile
all:
gcc -o ratout ratout.c -lcurl
gcc -o ratout-server ratout-server.c -lcurl -I /usr/include/libxml2 -lxml2<file_sep>/ratout.c
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <time.h>
#include <string.h>
#define REQ_FILE_PATH "/Users/estark37/Dropbox/Documents/school/cs294s-2/ratout-demo"
#define DOWNLOAD_URL "https://www.box.net/api/1.0/download/<auth token>/%s"
#define UPLOAD_URL "https://upload.box.net/api/upload/<auth token>/80421720"
#define SET_DESC_URL "https://www.box.net/api/1.0/rest?action=set_description&api_key=<api key>&auth_token=<auth token>&target=file&target_id=%s&description=%s"
#define GET_INFO_URL "https://www.box.net/api/1.0/rest?action=get_file_info&api_key=<api key>&auth_token=<auth token>&file_id=%s"
int upload_resp_size;
struct resp_buffer {
int len;
int size;
char* buf;
};
void download_response(CURL* curl, char* file_id, struct resp_buffer* download_resp) {
printf("Downloading response for file id %s\n", file_id);
char download_url[1024];
sprintf(download_url, DOWNLOAD_URL, file_id);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
curl_easy_setopt(curl, CURLOPT_URL, download_url);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
CURLcode res = curl_easy_perform(curl);
printf("Downloading from %s\n", download_url);
printf("%s\n", download_resp->buf);
}
void poll_for_response(CURL* curl, char* file_id, struct resp_buffer* poll_resp) {
CURLcode res;
char desc_url[512];
int keep_polling = 1;
char id[512];
strcpy(id, file_id);
sprintf(desc_url, GET_INFO_URL, id);
curl_easy_setopt(curl, CURLOPT_URL, desc_url);
while (keep_polling) {
poll_resp->len = 0;
printf("Checking for response... ");
res = curl_easy_perform(curl);
printf(" done\n");
char* description = strstr(poll_resp->buf, "<description>") + strlen("<description>");
if (description != NULL) {
char *end_desc = strstr(description, "</description>");
end_desc[0] = '\0';
if (strcmp(description, "Processed") == 0) {
keep_polling = 0;
poll_resp->len = 0;
download_response(curl, id, poll_resp);
}
}
}
}
size_t read_api_response(void* ptr, size_t size, size_t nmemb, struct resp_buffer* resp) {
if (!resp) return 0;
while (size*nmemb > resp->size - resp->len) {
// resize buffer
char* new_buf = malloc(2*resp->size);
if (!new_buf) {
printf("Could not allocate new buffer.\n");
return 0;
}
memcpy(new_buf, resp->buf, resp->len);
free(resp->buf);
resp->buf = new_buf;
resp->size = 2*resp->size;
}
memcpy(resp->buf+resp->len, ptr, size*nmemb);
resp->len += size*nmemb;
resp->buf[resp->len] = '\0';
return size*nmemb;
}
void create_request_file(char* url, char* fname) {
FILE* file;
sprintf(fname, "%s/ratout_%d", REQ_FILE_PATH, rand());
printf("File name: %s\n", fname);
file = fopen(fname, "w+");
if (file) {
fputs("test", file);
fclose(file);
} else printf("Could not create request file\n");
}
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("Usage: ./ratout http://url-to-fetch\n");
return(0);
}
char* url = argv[1];
CURL *curl;
CURLcode res;
char filename[512];
srand(time(NULL));
curl_global_init(CURL_GLOBAL_ALL);
printf("URL: %s\n", url);
create_request_file(url, filename);
struct curl_httppost *filepost = NULL;
struct curl_httppost *lastptr = NULL;
struct resp_buffer upload_resp;
upload_resp.size = 4096;
upload_resp.buf = malloc(4096);
upload_resp.len = 0;
curl_formadd(&filepost, &lastptr, CURLFORM_COPYNAME, "file", CURLFORM_FILE, filename, CURLFORM_END);
curl = curl_easy_init();
struct curl_slist *headerlist = NULL;
headerlist = curl_slist_append(headerlist, "Expect:");
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, UPLOAD_URL);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, filepost);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, read_api_response);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &upload_resp);
printf("Uploading file... ");
res = curl_easy_perform(curl);
printf(" done.\n");
printf("Got data response:\n");
printf("%s\n\n", upload_resp.buf);
upload_resp.len = 0;
char* id_index = strstr(upload_resp.buf, "id=");
char* space_index = strstr(id_index, " ");
space_index[-1] = '\0';
char desc_url[1024];
sprintf(desc_url, SET_DESC_URL, id_index+strlen("id=\""), url);
curl_easy_setopt(curl, CURLOPT_URL, desc_url);
printf("Setting description... ");
res = curl_easy_perform(curl);
printf(" done.\n");
upload_resp.len = 0;
poll_for_response(curl, id_index+strlen("id=\""), &upload_resp);
curl_easy_cleanup(curl);
curl_formfree(filepost);
curl_slist_free_all(headerlist);
}
if (upload_resp.buf) free(upload_resp.buf);
}
<file_sep>/ratout-server.c
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <time.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#define REQ_FILE_PATH "/Users/estark37/Dropbox/Documents/school/cs294s-2/ratout-demo/server-files"
#define GET_FILE_TREE_URL "https://www.box.net/api/1.0/rest?action=get_account_tree&api_key=<api key>&auth_token=<auth token>&folder_id=80421720¶ms[]=nozip"
#define UPLOAD_URL "https://upload.box.net/api/upload/<auth token>/80<PASSWORD>"
#define SET_DESC_URL "https://www.box.net/api/1.0/rest?action=set_description&api_key=<api key>&auth_token=<auth token>&target=file&target_id=%s&description=%s"
struct resp_buffer {
int len;
int size;
char* buf;
};
size_t read_api_response(void* ptr, size_t size, size_t nmemb, struct resp_buffer* resp) {
if (!resp) return 0;
while (size*nmemb > resp->size - resp->len) {
// resize buffer
char* new_buf = malloc(2*resp->size);
if (!new_buf) {
printf("Could not allocate new buffer.\n");
return 0;
}
memcpy(new_buf, resp->buf, resp->len);
free(resp->buf);
resp->buf = new_buf;
resp->size = 2*resp->size;
}
memcpy(resp->buf+resp->len, ptr, size*nmemb);
resp->len += size*nmemb;
resp->buf[resp->len] = '\0';
return size*nmemb;
}
void process_file(xmlNode* file, CURL* curl, struct resp_buffer* resp) {
printf("Processing request %s\n", xmlGetProp(file, "file_name"));
printf("Requesting URL %s...", xmlGetProp(file, "description"));
curl_easy_setopt(curl, CURLOPT_URL, xmlGetProp(file, "description"));
CURLcode res = curl_easy_perform(curl);
printf(" done.\n");
printf("Response from server: %s\n\n", resp->buf);
char fname[512];
sprintf(fname, "%s/%s", REQ_FILE_PATH, xmlGetProp(file, "file_name"));
FILE* f = fopen(fname, "w+");
if (f != NULL) {
fputs(resp->buf, f);
fclose(f);
} else {
printf("Could not create new file.\n");
return;
}
// upload the new file
struct curl_httppost *filepost = NULL;
struct curl_httppost *lastptr = NULL;
curl_formadd(&filepost, &lastptr, CURLFORM_COPYNAME, "file", CURLFORM_FILE, fname, CURLFORM_END);
struct curl_slist *headerlist = NULL;
headerlist = curl_slist_append(headerlist, "Expect:");
curl_easy_setopt(curl, CURLOPT_URL, UPLOAD_URL);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, filepost);
printf("Uploading file... ");
res = curl_easy_perform(curl);
printf(" done.\n");
char desc_url[1024];
sprintf(desc_url, SET_DESC_URL, xmlGetProp(file, "id"), "Processed");
curl_easy_setopt(curl, CURLOPT_URL, desc_url);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, NULL);
printf("Setting description %s... ", desc_url);
resp->len = 0;
res = curl_easy_perform(curl);
printf(" done.\n");
printf("Description response: %s\n", resp->buf);
}
void traverse_and_find_file(xmlNode* root, CURL* curl, struct resp_buffer* resp) {
if (!root) return;
if (xmlStrEqual(root->name, "file") && !xmlStrEqual(xmlGetProp(root, "description"), "Processed") && !xmlStrEqual(xmlGetProp(root, "description"), "")) {
process_file(root, curl, resp);
return;
}
xmlNode* cur = NULL;
for (cur = root->children; cur; cur = cur->next) {
traverse_and_find_file(cur, curl, resp);
}
}
int main() {
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
struct curl_httppost *filepost = NULL;
struct curl_httppost *lastptr = NULL;
struct resp_buffer resp;
resp.len = 0;
resp.size = 4096;
resp.buf = malloc(resp.size);
curl = curl_easy_init();
while (curl) {
resp.len = 0;
curl_easy_setopt(curl, CURLOPT_URL, GET_FILE_TREE_URL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, read_api_response);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp);
printf("Checking for new requests... ");
res = curl_easy_perform(curl);
printf(" done.\n");
xmlDocPtr doc;
doc = xmlReadMemory(resp.buf, resp.len, "noname.xml", NULL, 0);
if (doc == NULL) {
printf("Failed to parse XML\n");
printf("Resp: %s\n", resp.buf);
} else {
traverse_and_find_file(xmlDocGetRootElement(doc), curl, &resp);
xmlFreeDoc(doc);
}
}
if (resp.buf) free(resp.buf);
curl_easy_cleanup(curl);
}
|
aca2971d17ae9cc6a095697c86d519910afb1fe6
|
[
"C",
"Makefile"
] | 3
|
Makefile
|
estark37/ratout
|
3b44db92f1af082d344e10285e41c7a402b0b57a
|
4cc0835697f1809bc68fb75553771a3e31f9a94b
|
refs/heads/master
|
<repo_name>aspcodenet/CmsIocCore<file_sep>/CmsIocCore/Models/User.cs
using System.Collections.Generic;
namespace CmsIocCore.Models
{
public interface IMyLogger
{
void Log();
}
class Logger : IMyLogger
{
public void Log()
{
}
}
public interface IUserRepository
{
List<string> GetAll();
}
class UserRepository : IUserRepository
{
private readonly IMyLogger _logger;
public UserRepository(IMyLogger logger)
{
_logger = logger;
}
public List<string> GetAll()
{
return new List<string> { "Toppen", "Boppen" };
}
}
}
|
defbacd4f0b25b1f1dbcf461e8da3cdb11177538
|
[
"C#"
] | 1
|
C#
|
aspcodenet/CmsIocCore
|
010aa18f9f998e3fac8c7c6553db1945deebbc2c
|
e2ce3925e45feb75612e6e6933d0d2d012b32d2f
|
refs/heads/master
|
<file_sep>import React from "react";
import { connect } from "react-redux";
import styled from "styled-components";
import { motion } from "framer-motion";
const variants = {
open: {
x: 0,
y: 0,
opacity: 1,
transition: {
x: { stiffness: 1000, velocity: -100 },
},
},
closed: {
x: -300,
y: 0,
opacity: 0,
transition: {
x: { stiffness: 1000 },
},
},
};
const colors = ["#FF008C", "#D309E1", "#9C1AFF", "#7700FF", "#4400FF"];
const MenuItem = ({ idx, item: { displayText } }) => {
const style = { border: `2px solid ${colors[idx]}` };
return (
<ListItem
variants={variants}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.95 }}
onClick={() => alert("Still under construction. My apologies!")} // TODO: remove stub
>
<IconPlaceholder style={style} />
<TextPlaceholder style={style}>{displayText}</TextPlaceholder>
</ListItem>
);
};
const mapStateToProps = ({ theme }) => ({
theme,
});
export default connect(mapStateToProps, null)(MenuItem);
const ListItem = styled(motion.li)`
margin: 0 0 1.25rem 0;
padding: 0;
list-style: none;
display: flex;
align-items: center;
cursor: pointer;
`;
const IconPlaceholder = styled.div`
width: 2.5rem;
height: 2.5rem;
border-radius: 50%;
flex: 2.5rem 0;
margin-right: 1.25rem;
`;
const TextPlaceholder = styled.div`
border-radius: 5px;
padding-bottom: 10px;
color: ${(props) => props.theme.NEGATIVE};
font-size: 1rem;
width: 12.5rem;
height: 1.25rem;
flex: 1;
`;
<file_sep>import React from "react";
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-monokai";
export default ({ code }) => (
<AceEditor
value={code}
highlightActiveLine
mode="javascript"
theme="monokai"
setOptions={aceEditorOptions}
style={aceEditorStyles}
maxLines={Infinity}
/>
);
const aceEditorStyles = {
width: "100%",
borderRadius: "20px",
zIndex: 0,
fontSize: "16px",
};
const aceEditorOptions = {
showLineNumbers: true,
tabSize: 4,
};
<file_sep>/* eslint-disable react/jsx-pascal-case */
import React from "react";
import { connect } from "react-redux";
import styled from "styled-components";
import PostSeperator from "./PostSeperator";
import _100420 from "../posts/2020-04-10";
import _300320 from "../posts/2020-03-30";
import _160320 from "../posts/2020-03-16";
const Posts = () => (
<Div>
<_100420 />
<PostSeperator />
<_300320 />
<PostSeperator />
<_160320 />
<PostSeperator />
</Div>
);
const mapStateToProps = ({ theme }) => theme;
export default connect(mapStateToProps, null)(Posts);
const Div = styled.div`
text-align: start;
`;
<file_sep>/* eslint-disable react/jsx-filename-extension */
import React from "react";
import { connect } from "react-redux";
import styled, { ThemeProvider } from "styled-components";
import { motion } from "framer-motion";
import "./App.css";
import SideBar from "./components/SideBar";
import ViewToggle from "./components/ViewToggle";
import { Text, HeaderPrimary } from "./constants/fonts";
import Posts from "./components/Posts";
import PostSeperator from "./components/PostSeperator";
const App = (theme) => {
const animateView = {
background: theme.BACKGROUND_PRIMARY,
color: theme.PRIMARY,
transition: {
delay: 0.1,
type: "spring",
stiffness: 400,
damping: 40,
},
};
return (
<ThemeProvider theme={theme}>
<Div
animate={animateView}
transition={{ duration: 0.5 }}
className="App"
>
<ViewToggle />
<SideBar />
<PostContent>
<HeaderPrimary>
Welcome to my personal website
</HeaderPrimary>
<Text>
This website is still under construction. I hope for
this to be a repository of my ventures into software
engineering, as well as life in general!
</Text>
<PostSeperator />
<HeaderPrimary>
What I've been up to recently:
</HeaderPrimary>
<Posts />
</PostContent>
</Div>
</ThemeProvider>
);
};
const mapStateToProps = (state) => state.theme;
export default connect(mapStateToProps, null)(App);
const Div = styled(motion.div)`
overflow: scroll;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
line-height: 2;
`;
const PostContent = styled(motion.div)`
display: block;
padding: 10vh 10vw;
`;
<file_sep>export const CONTENT_TYPE = {
TEXT: "TEXT",
INPUT: "INPUT",
CODE: "CODE",
HEADER_PRIMARY: "HEADER_PRIMARY",
HEADER_SECONDARY: "HEADER_SECONDARY",
HEADER_TERTIARY: "HEADER_TERTIARY",
VARIABLE: "VARIABLE",
};
<file_sep>import React from "react";
import { Text, HeaderSecondary, HeaderTertiary } from "../../constants/fonts";
import CodeEditor from "../../components/CodeEditor";
export default () => (
<>
<HeaderSecondary>
Learning the basics of Redux Thunks - Mar 30 2020
</HeaderSecondary>
<HeaderTertiary>What is a thunk?</HeaderTertiary>
<Text>
Essentially, thunks are functions returned by functions. For
instance:
</Text>
<CodeEditor code={EXAMPLE_THUNK_CODE} />
<HeaderTertiary>Why use redux-thunk?</HeaderTertiary>
<Text>
Since reducers are pure functions by convention, dispatching API
calls/actions should not be accomplished within them. As such, we
can use the redux-thunk middleware to perform these actions.
</Text>
<HeaderTertiary>How does redux-thunk work?</HeaderTertiary>
<Text>
It is a middleware which calls functions which are passed in as
actions. Essentially, it allows us to dispatch functions as actions.
It's implementation is short and sweet:
</Text>
<CodeEditor code={REDUX_THUNK_CODE} />
</>
);
const EXAMPLE_THUNK_CODE = `
function wrapper() {
return function thunk() {
// In Redux, another dispatch / API call is usually nested here.
// For example:
fetch('/data);
};
}
`;
const REDUX_THUNK_CODE = `
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
`;
<file_sep>import React, { useState } from "react";
import styled from "styled-components";
import { motion } from "framer-motion";
import { Text, HeaderSecondary, HeaderTertiary } from "../../constants/fonts";
export default (theme) => {
const [text, setText] = useState("");
const [debounceWait, setDebounceWait] = useState(800);
function debounce(func, wait) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, wait);
};
}
const debouncedSetText = debounce(setText, debounceWait);
return (
<>
<HeaderSecondary>
Debounced Function practice - Mar 16 2020
</HeaderSecondary>
<Text>Whatever is typed into here</Text>
<Input
placeholder="Input text"
onChange={(e) => debouncedSetText(e.target.value)}
/>
<Text>will be echoed after</Text>
<Input
placeholder="(Default=800)"
type="number"
onChange={(e) => setDebounceWait(parseInt(e.target.value, 10))}
/>
<Text>miliseconds</Text>
<div style={{ color: theme.SECONDARY }}>
<HeaderTertiary>{text}</HeaderTertiary>
</div>
</>
);
};
const Input = styled(motion.input)`
width: 20rem;
height: 1.25rem;
border: ${(props) => props.theme.DEFAULT_BORDER};
&:focus {
outline: none;
}
padding: 0.25rem;
`;
<file_sep>import React from "react";
import styled from "styled-components";
import { motion } from "framer-motion";
import MenuItem from "./MenuItem";
const variants = {
open: {
transition: { staggerChildren: 0.07, delayChildren: 0.2 },
},
closed: {
transition: { staggerChildren: 0.05, staggerDirection: -1 },
},
};
const items = [
{
displayText: "BLOG",
tooltip: "Day to day musings",
},
{
displayText: "PORTFOLIO",
tooltip: "Things I've worked on",
},
{
displayText: "LEARNING PATH",
tooltip: "Things I have learnt or am learning",
},
{
displayText: "GITHUB",
tooltip: "My only social(?) media",
},
{
displayText: "RESUME",
tooltip: "Click to download",
},
]; // TODO: replace this stub
export default () => (
<UnorderedList variants={variants}>
{items.map((item, idx) => (
<MenuItem idx={idx} key={item.displayText} item={item} />
))}
</UnorderedList>
);
const UnorderedList = styled(motion.ul)`
margin: 0;
padding: 1.5rem;
position: absolute;
top: 6rem;
width: 15rem;
`;
<file_sep>import moment from "moment";
import { ADD_POST } from "../actionTypes";
import { CONTENT_TYPE } from "../../constants/post";
const initialState = {
isFetching: false,
data: [
{
title: "Learning the basics of Redux Thunks",
segments: [
{
header: "What is a thunk?",
body: [
{
type: CONTENT_TYPE.TEXT,
content: `Essentially, thunks are functions returned by functions. For
instance:`,
},
{
type: CONTENT_TYPE.CODE,
content: `
function wrapper() {
return function thunk() {
// In Redux, another dispatch / API call is usually nested here. For example:
fetch('/data);
};
}`,
},
],
},
{
header: "How does redux-thunk work?",
body: [
{
type: CONTENT_TYPE.TEXT,
content: `
It is a middleware which calls functions which are passed in as
actions. It's implementation is short and sweet:
`,
},
{
type: CONTENT_TYPE.CODE,
content: `
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
`,
},
],
},
],
author: "<PASSWORD>",
categories: ["Redux"],
date: moment("2020-03-16").toDate(),
hidden: false,
},
{
title: "Debounced Functions Practice",
segments: [
{
type: CONTENT_TYPE.TEXT,
content: "Whatever is typed into here",
},
{
type: CONTENT_TYPE.INPUT,
content: "Input text",
onChange: "{(e) => debouncedSetText(e.target.value)}",
},
{
type: CONTENT_TYPE.TEXT,
content: "will be echoed after",
},
{
type: CONTENT_TYPE.INPUT,
content: "Input text",
onChange:
"{(e) => setDebounceWait(parseInt(e.target.value, 10))}",
},
{
type: CONTENT_TYPE.TEXT,
content: "miliseconds",
},
{
type: CONTENT_TYPE.HEADER_TERTIARY,
content: "{text}",
style: "{{color: theme.SECONDARY}}",
},
],
author: "<PASSWORD>",
categories: ["Javascript"],
date: moment("2020-03-30").toDate(),
hidden: false,
},
],
};
export default function (state = initialState, action) {
switch (action.type) {
case ADD_POST:
return {
...state,
data: [...state.data, action.payload],
};
default:
return state;
}
}
<file_sep>import styled from "styled-components";
import { motion } from "framer-motion";
export const HeaderPrimary = styled(motion.h1)`
font-size: 2rem;
color: ${(props) => props.theme.PRIMARY};
`;
export const HeaderSecondary = styled(motion.h2)`
font-size: 1.5rem;
color: ${(props) => props.theme.SECONDARY};
`;
export const HeaderTertiary = styled(motion.h3)`
font-size: 1.25rem;
color: ${(props) => props.theme.TERTIARY};
`;
export const Text = styled(motion.p)`
font-size: 1rem;
color: ${(props) => props.theme.MAIN};
`;
<file_sep>---
title: Understanding Refs and the DOM
date: "2020-05-10"
---
## References
[Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html)
[React Hooks API](https://reactjs.org/docs/hooks-reference.html)
## When to use Refs
Refs should be avoided as far as possible, since React primarily defaults to declarative means of getting things done, whereas the use of Refs is characteristically imperative.
However, in some cases, the use of Refs are
<file_sep>export const TOGGLE_THEME = "TOGGLE_THEME";
export const ADD_POST = "ADD_POST";
<file_sep>import { combineReducers } from "redux";
import theme from "./theme";
import posts from "./posts";
export default combineReducers({ theme, posts });
<file_sep>---
title: Learning the Basics of TypeScript
date: "2020-05-11"
tags: "TypeScript"
---
## References
[TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/)
## Defining Types
> TypeScript = JavaSript + Type-System
### Assigning objects to variables
#### Previously in JavaScript
```js
const myUser = {
id: 0,
name: "Wallace",
};
```
#### Now in TypeScript
```ts
interface User {
name: string;
id: number;
}
// Assigning an object in the wrong shape will trigger a warning
const myUser: User = {
id: 0,
name: "Wallace",
};
```
### Class constructors
#### Previously in JavaScript
```js
class UserAccount {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
const myUser = new UserAccount(0, "Wallace");
```
#### Now in TypeScript
```ts
interface User {
id: number;
name: string;
}
class UserAccount {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
const myUser: User = new UserAccount(0, "Wallace");
```
### Functions
#### Previously in JavaScript
```js
function getUser(id) {
return User.findById(id);
}
```
#### Now in TypeScript
```ts
function getUser(id: number): User {
return User.findById(id);
}
```
## Composing Types
### Enumerating possible values (Unions)
```ts
type Weekdays = "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday";
```
### Providing variables to types (Generics)
```ts
type StringArray = Array<string>;
type ObjectWithNameArray = Array<{ name: string }>;
```
#### Declaring types with generics
```ts
interface HomogenousQueue<Type> {
push: (obj: Type) => void;
poll: () => Type;
}
// This line is a shortcut to tell TypeScript there is a
// constant called `backpack`, and to not worry about where it came from
declare const queue = HomogenousQueue<string>;
const someString = queue.pop()
queue.push(23); // Produces static error
```
## Structural Type System
> a.k.a. "duck typing" or "structural typing"
Essentially, if two objects have the **same shape**, they are **considered the same**.
An illustration:
```ts
interface Duck {
beakLengthInInches: number;
eggsLaid: number;
}
class YellowDuck {
beakLengthInInches: number;
eggsLaid: number;
constructor(beakLengthInInches: number, eggsLaid: number) {
this.beakLengthInInches = beakLengthInInches;
this.eggsLaid = eggsLaid;
}
}
function buyDuck(duck: Duck) {
...
}
const iHaveNoType = {
beakLengthInInches: 4,
eggsLaid: 3,
};
const yellowDuck = new YellowDuck(1, 2);
buyDuck(iHaveNoType); // No error
buyDuck(yellowDuck); // No error
```
<file_sep>// Learn here: https://www.ibrahima-ndaw.com/blog/build-a-sticky-nav-with-react/
<file_sep>export const BLACK = "#000000";
export const DARKER_GREY = "#2D3748";
export const DARKEST_GREY = "#282a36";
export const SKY_BLUE = "#8be9fd";
export const DARK_BLUE = "#333399";
export const PINK = "#ff79c6";
export const STEEL_GREY = "#718096";
export const CREAM = "#f8f8f2";
export const YELLOW = "#f1fa8c";
export const LIGHT_BLUE = "#E2E8F0";
export const WHITE = "#FFFFFF";
export const DARK_GREY = "#44475a";
export const SEA_GREEN = "#00b38f";
<file_sep>/* Utility function for parsing HTML from an input string
* Retrieved from https://stackoverflow.com/questions/31259295/javascript-allow-only-specific-html-tags
*/
export const stripTags = (input, allowed) => {
const allowedFormatted = (
`${allowed || ""}`.toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []
).join(""); // making sure the allowedFormatted arg is a string containing only tags in lowercase (<a><b><c>)
const tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
const commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input
.replace(commentsAndPhpTags, "")
.replace(tags, ($0, $1) =>
allowedFormatted.indexOf(`<${$1.toLowerCase()}>`) > -1 ? $0 : ""
);
};
|
6b700eaf51bacdc6a3ce62e1cb35909091d7d09c
|
[
"JavaScript",
"Markdown"
] | 17
|
JavaScript
|
wallacelim97/personal-website
|
7fa2ebda562d9eab9eaf3e2f6d2a357f55e687f0
|
ddc2dd0e67402d0ed3818ce08421cfdc238678eb
|
refs/heads/dev
|
<file_sep>import Phaser from 'phaser';
import setUserName from '../script';
import { putScore } from '../config/leaderboard';
export default class PlayerInputScene extends Phaser.Scene {
constructor() {
super('PlayerInput');
}
create() {
const latestUser = setUserName().getUserData();
if (latestUser) {
const inputUsername = latestUser.name;
if (inputUsername !== '') {
const loading = this.add.text(350, 250, 'Loading...', { color: 'white', fontFamily: 'Arial', fontSize: '24px ' });
putScore(inputUsername, latestUser.score[latestUser.score.length - 1]).then(() => {
loading.destroy();
this.scene.start('endGame');
}).catch((err) => {
this.add.text(350, 250, `Sorry Unable to set user ${err}`);
});
} else {
this.add.text(350, 250, 'Sorry Unable to set user');
}
}
}
}<file_sep>import gameOptions from '../script/config/options';
describe('Should have a configuration factory for general settings', () => {
test('option factory should be defined', () => {
expect(gameOptions).toBeDefined();
});
test('option factory should be an object', () => {
expect(typeof gameOptions).toBe('object');
});
test('option factory should have platformspeed', () => {
expect(gameOptions.platformSpeedRange).toBeDefined();
});
test('platformspeed property should be an array with values', () => {
expect(typeof gameOptions.platformSpeedRange).toBe('object');
});
test('option factory should have a mountain speed property', () => {
expect(gameOptions.mountainSpeed).toBeDefined();
});
test('mountainspeed property should be a number', () => {
expect(typeof gameOptions.mountainSpeed).toBe('number');
});
test('option factory should have a spawnRange property', () => {
expect(gameOptions.spawnRange).toBeDefined();
});
test('spawRange property should be an object with values', () => {
expect(typeof gameOptions.spawnRange).toBe('object');
});
test('option factory should have a platformSizeRange property', () => {
expect(gameOptions.platformSizeRange).toBeDefined();
});
test('platformSizeRange property should be an object with values', () => {
expect(typeof gameOptions.platformSizeRange).toBe('object');
});
test('option factory should have a platformHeightRange property', () => {
expect(gameOptions.platformHeightRange).toBeDefined();
});
test('platformHeightRange property should be an object with values', () => {
expect(typeof gameOptions.platformHeightRange).toBe('object');
});
test('option factory should have a platformHeighScale property', () => {
expect(gameOptions.platformHeighScale).toBeDefined();
});
test('platformHeighScale property should be an object with values', () => {
expect(typeof gameOptions.platformHeighScale).toBe('number');
});
test('option factory should have a platformVerticalLimit property', () => {
expect(gameOptions.platformVerticalLimit).toBeDefined();
});
test('platformVerticalLimit property should be an object with values', () => {
expect(typeof gameOptions.platformVerticalLimit).toBe('object');
});
test('option factory should have a playerGravity property', () => {
expect(gameOptions.playerGravity).toBeDefined();
});
test('playerGravity property should be an object with values', () => {
expect(typeof gameOptions.playerGravity).toBe('number');
});
});<file_sep>
# ninjaskrill

What the project contains:
- Used Javascript and Phaser 3 to implement a Shooter Game;
- Used the following packages apart from the standard ones:
- phaser
- webpack
- jest
- Set up ESlint in the repository;
- Created effective JavaScript code, that solved the problem;
- Used Webpack;
- Used ES6+;
- Dealt with async code;
- Tested the code using Jest;
- Sent and received data from a back-end endpoint;
- Used JSON format;
- Deployed the app to Netlify;
- Translated business requirements into software solutions;
- Multitasked and effectively manage time and prioritization;
- Used strong English written communication;
- Communicated information effectively to technical people.
Game Design Documentation I made on day 2: [GDD](src/assets/gdd.md)
# How to play
- Being a ninja is often a lot of hard work, but not this time.
- In this game you simply have to keep clicking on your screen and avoid danger.
- Click or tap the screen to jump. You can jump twice, you are a Ninja. Ninja's can do that.
- Try to become a `Black Ninja` by beating the Highest score.
- The game has:
- A score button to display a list of High scores and their users.
- A credit button to list credits.
- A How to button to guide users on how to play the game.
## Built with
- Javascript.
- Phaser 3.
- Jest.
## Live Demo
[Live link](https://raw.githack.com/kelibst/ninjaskrill/feature/dist/index.html)
## Getting Started
- Clone the repository on your local machine;
- Cd into the folder;
- Run `npm install`
- Run `npm run serve`;
- If you are using vs code install live serve extension.
- Visit `/dist` folder and right click on index.html and open with live server
- To run tests, type `npm run test`.
👤 **<NAME>**
- Github: [@kelibst](https://github.com/kelibst)
- Twitter: [@keli_booster](https://twitter.com/keli_booster)
- Linkedin: [<NAME>
](https://www.linkedin.com/in/kekeli-dogbevi-jiresse/)
## 🤝 Contributing
Contributions, issues and feature requests are welcome! Start by:
- Forking the project
- Cloning the project to your local machine
- `cd` into the project directory
- Run `git checkout -b your-branch-name`
- Make your contributions
- Push your branch up to your forked repository
- Open a Pull Request with a detailed description to the development branch of the original project for a review
## Show your support
Give a ⭐️ if you like this project!
<file_sep># Introduction
Okay `Ninja's` here is a list of what I planned to build in this game. If you are wondering: yeah, I call everyone Ninja in my game. It's for Ninja's.
# Story
## Intro
I am not sure what I should setup as intro but I think the line below should be cool, I want to appear totally liberal to the user.
Sometimes being a ninja is a lot of work right? You have to be alert and always ahead of your enemies, but other times being a ninja is as simple as jumping, collecting gold coins and literally, I mean literally avoiding fire. That isn't so hard is it?
Good luck!
# Gameplay
## Player
A ninja running around. That should be cool. A ninja should be able to jump twice. Ninja's can do that right?
## Enemy
- There is probably not a bigger any than falling it's worst if it's from a high platform.
- And of course there is fire.
# Developer's Notes
This project was developed in these stages:
- Stage 1: Learning how to use Phaser 3, following tutorials and how to setup a game's structure built with Javascript (1 day).
- Stage 2: Building this GDD (0.5 day).
- Stage 3: Creating the project's codes organizational structure (0.5 day).
- Stage 4: Creating the project's scenes (1 day)
- Stage 5: Creating the project's classes and tests (1 day).
- Stage 6: Testing the gameplay, fixing bugs and deployment (1 day).
# Making Of
This project was built using [Phaser 3](https://phaser.io/phaser3), [Webpack](https://webpack.js.org/) and Javascript.
# Acknowledgements
- This project was built during my course at [Microverse](https://www.microverse.org/), which is an amazing school where I learned how to program. Also, Microverse provided me with an [API](https://www.notion.so/Leaderboard-API-service-24c0c3c116974ac49488d4eb0267ade3) to keep the player's scores.
<file_sep>/* eslint-disable import/no-cycle */
import Phaser from 'phaser';
import config from '../config/config';
class giveCredit extends Phaser.Scene {
constructor() {
super('GiveCredit');
}
create() {
this.cameras.main.setBackgroundColor('8a0000');
this.creditsText = this.add.text(0, 0, 'Ninja Skrill \n Credits', { fontSize: '32px', fill: '#fff' });
this.image1 = this.add.image(400, 200, 'cover');
this.madeByText1 = this.add.text(0, 0, 'Created By: <NAME>', { fontSize: '26px', fill: '#fff' });
this.madeByText2 = this.add.text(0, 0, 'Big thanks to God almighty,\n and all those\n who in diverse ways\n contributed to the \n success of this game!', { fontSize: '26px', fill: '#fff' });
this.madeByText3 = this.add.text(0, 0, 'This project was built during\n\nmy course at Microverse!', { fontSize: '26px', fill: '#fff' });
this.madeByText4 = this.add.text(0, 0, 'Thanks to OpenGameArt.org for\n\nproviding the free assets\n\nI used in this game.', { fontSize: '26px', fill: '#fff' });
this.zone = this.add.zone(config.width / 2, config.height / 2, config.width, config.height);
this.keySpace = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
this.skipText = this.add.text(10, 10, 'Press SPACE \n Or click on the screen \n to skip', { fontSize: '10px', fill: '#fff' });
Phaser.Display.Align.In.Center(
this.creditsText,
this.zone,
);
Phaser.Display.Align.In.Center(
this.image1,
this.zone,
);
Phaser.Display.Align.In.Center(
this.madeByText1,
this.zone,
);
Phaser.Display.Align.In.Center(
this.madeByText2,
this.zone,
);
Phaser.Display.Align.In.Center(
this.madeByText3,
this.zone,
);
Phaser.Display.Align.In.Center(
this.madeByText4,
this.zone,
);
this.image1.setY(800);
this.madeByText1.setY(850);
this.madeByText2.setY(1100);
this.madeByText3.setY(1300);
this.madeByText4.setY(1800);
this.creditsTween = this.tweens.add({
targets: this.creditsText,
y: -200,
duration: 3000,
delay: 1000,
});
this.imageTween1 = this.tweens.add({
targets: this.image1,
y: -200,
duration: 13000,
delay: 1000,
});
this.madeByTween1 = this.tweens.add({
targets: this.madeByText1,
y: -200,
duration: 14000,
delay: 1000,
});
this.madeByTween2 = this.tweens.add({
targets: this.madeByText2,
y: -200,
duration: 20000,
delay: 1000,
});
this.madeByTween3 = this.tweens.add({
targets: this.madeByText3,
y: -200,
duration: 25000,
delay: 1000,
});
this.madeByTween4 = this.tweens.add({
targets: this.madeByText4,
y: -200,
duration: 35000,
delay: 1000,
});
}
goBack() {
this.scene.start('PreloadGame');
}
update() {
if (this.keySpace.isDown) {
this.goBack();
}
this.input.on('pointerdown', this.goBack, this);
}
}
export default giveCredit;<file_sep>/* eslint-disable no-unused-vars */
import Phaser from 'phaser';
import config from './assets/script/config/config';
import setUserName from './assets/script/script';
const user = setUserName().getUserData();
// reduce user score data to only 5
if (user) {
if (user.score.length > 5) {
user.score = user.score.sort((a, b) => b - a).slice(0, 5);
}
setUserName().updateData(user);
const Game = new Phaser.Game(config);
} else {
const user = setUserName().getUserData();
const Game = new Phaser.Game(config);
}
<file_sep>/* eslint-disable import/no-cycle */
/* eslint-disable no-new */
import Phaser from 'phaser';
import config from '../config/config';
import Button from '../config/buttons';
// preloadGame scene
class preloadGame extends Phaser.Scene {
constructor() {
super('PreloadGame');
}
create() {
// setting player animation
this.background = this.add.image(config.width / 2, config.height / 2, 'cover');
new Button(this, 400, 250, 'start_button', 'PlayGame');
new Button(this, 400, 300, 'score_btn', 'Leaderboard');
new Button(this, 400, 350, 'how_to', 'HowTo');
new Button(this, 750, 550, 'credit', 'GiveCredit');
}
}
export default preloadGame;<file_sep>import setUserName from '../script/script';
describe('Should have a factory for setting users', () => {
test('User object should be defined', () => {
expect(setUserName()).toBeDefined();
});
test('Should be able to create a user Object with a valid name', () => {
const user = setUserName().User('Keli');
expect(user.name).toBe('Keli');
});
test('Should have a score array to store\' s scores.', () => {
const user = setUserName().User('Keli');
expect(typeof user.score).toBe('object');
});
test('user object should have score property ', () => {
const user = setUserName().User('Keli');
expect(user.score).toEqual([]);
});
});<file_sep>/* eslint-disable import/no-cycle */
import Phaser from 'phaser';
import config from '../config/config';
import gameOptions from '../config/options';
import setUserData from '../script';
// playGame scene
class playGame extends Phaser.Scene {
constructor() {
super('PlayGame');
}
create() {
this.score = 0;
// this.add.image(3400,2400, 'background')
this.background = this.add.tileSprite(config.width / 2, config.height / 2, config.width, config.height, 'background');
this.scoreBoard = this.add.text(30, 20, `Score: ${this.score}`, { font: '30px Monospace', fill: 'yellow' });
this.scoreBoard.setShadow(3, 3, 'rgba(0,0,0,0.5)', 2);
// group with all active mountains.
this.mountainGroup = this.add.group();
// group with all active platforms.
this.platformGroup = this.add.group({
// once a platform is removed, it's added to the pool
removeCallback(platform) {
platform.scene.platformPool.add(platform);
},
});
// platform pool
this.platformPool = this.add.group({
// once a platform is removed from the pool, it's added to the active platforms group
removeCallback(platform) {
platform.scene.platformGroup.add(platform);
},
});
// group with all active coins.
this.coinGroup = this.add.group({
// once a coin is removed, it's added to the pool
removeCallback(coin) {
coin.scene.coinPool.add(coin);
},
});
// coin pool
this.coinPool = this.add.group({
// once a coin is removed from the pool, it's added to the active coins group
removeCallback(coin) {
coin.scene.coinGroup.add(coin);
},
});
// group with all active firecamps.
this.fireGroup = this.add.group({
// once a firecamp is removed, it's added to the pool
removeCallback(fire) {
fire.scene.firePool.add(fire);
},
});
// fire pool
this.firePool = this.add.group({
// once a fire is removed from the pool, it's added to the active fire group
removeCallback(fire) {
fire.scene.fireGroup.add(fire);
},
});
// adding a mountain
this.addMountains();
// keeping track of added platforms
this.addedPlatforms = 0;
// number of consecutive jumps made by the player so far
this.playerJumps = 0;
// adding a platform to the game, the arguments are platform width, x position and y position
this.addPlatform(config.width,
config.width / 2,
config.height * gameOptions.platformVerticalLimit[1]);
// adding the player;
this.player = this.physics.add.sprite(gameOptions.playerStartPosition, config.height * 0.7, 'player');
this.player.setGravityY(gameOptions.playerGravity);
this.player.setDepth(2);
// the player is not dying
this.dying = false;
// setting collisions between the player and the platform group
this.platformCollider = this.physics.add.collider(this.player, this.platformGroup, () => {
// play "run" animation if the player is on a platform
if (!this.player.anims.isPlaying) {
this.player.anims.play('run');
}
}, null, this);
// setting collisions between the player and the coin group
this.physics.add.overlap(this.player, this.coinGroup, (player, coin) => {
this.score += 1;
this.scoreBoard.setText(`Score: ${this.score}`);
this.tweens.add({
targets: coin,
y: coin.y - 100,
alpha: 0,
duration: 800,
ease: 'Cubic.easeOut',
callbackScope: this,
onComplete() {
this.coinGroup.killAndHide(coin);
this.coinGroup.remove(coin);
},
});
}, null, this);
// setting collisions between the player and the fire group
this.physics.add.overlap(this.player, this.fireGroup, () => {
this.dying = true;
this.player.anims.stop();
this.player.setFrame(2);
this.player.body.setVelocityY(-200);
this.physics.world.removeCollider(this.platformCollider);
}, null, this);
// checking for input
this.input.on('pointerdown', this.jump, this);
}
// adding mountains
addMountains() {
const rightmostMountain = this.getRightmostMountain();
if (rightmostMountain < config.width * 2) {
// change to tree
const mountain = this.physics.add.sprite(rightmostMountain + Phaser.Math.Between(50, 200), 600, 'mountain');
mountain.setOrigin(0.5, 1);
mountain.setScale(0.5);
mountain.body.setVelocityX(gameOptions.mountainSpeed * -1);
this.mountainGroup.add(mountain);
if (Phaser.Math.Between(0, 1)) {
mountain.setDepth(1);
}
mountain.setFrame(Phaser.Math.Between(0, 1));
this.addMountains();
}
}
// getting rightmost mountain x position
getRightmostMountain() {
let rightmostMountain = -200;
this.mountainGroup.getChildren().forEach((mountain) => {
rightmostMountain = Math.max(rightmostMountain, mountain.x);
});
return rightmostMountain;
}
// the core of the script: platform are added from the pool or created on the fly
addPlatform(platformWidth, posX, posY) {
this.addedPlatforms += 1;
let platform;
if (this.platformPool.getLength()) {
platform = this.platformPool.getFirst();
platform.x = posX;
platform.y = posY;
platform.active = true;
platform.visible = true;
this.platformPool.remove(platform);
platform.displayWidth = platformWidth;
platform.tileScaleX = 1 / platform.scaleX;
} else {
platform = this.add.tileSprite(posX, posY, platformWidth, 32, 'platform');
this.physics.add.existing(platform);
platform.body.setImmovable(true);
platform.body.setVelocityX(Phaser.Math.Between(
gameOptions.platformSpeedRange[0],
gameOptions.platformSpeedRange[1],
) * -1);
platform.setDepth(2);
this.platformGroup.add(platform);
}
this.nextPlatformDistance = Phaser.Math.Between(0, 0);
// if this is not the starting platform...
if (this.addedPlatforms > 1) {
// is there a coin over the platform?
if (Phaser.Math.Between(1, 100) <= gameOptions.coinPercent) {
if (this.coinPool.getLength()) {
const coin = this.coinPool.getFirst();
coin.x = posX;
coin.y = posY - 96;
coin.alpha = 1;
coin.active = true;
coin.visible = true;
this.coinPool.remove(coin);
} else {
const coin = this.physics.add.sprite(posX, posY - 96, 'coin');
coin.setImmovable(true);
coin.setVelocityX(platform.body.velocity.x);
coin.anims.play('rotate');
coin.setDepth(2);
this.coinGroup.add(coin);
}
}
// is there a fire over the platform?
if (Phaser.Math.Between(1, 100) <= gameOptions.firePercent) {
if (this.firePool.getLength()) {
const fire = this.firePool.getFirst();
fire.x = posX - platformWidth / 2 + Phaser.Math.Between(1, platformWidth);
fire.y = posY - 46;
fire.alpha = 1;
fire.active = true;
fire.visible = true;
this.firePool.remove(fire);
} else {
const fire = this.physics.add.sprite(posX - platformWidth / 2 + Phaser.Math.Between(1, platformWidth), posY - 46, 'fire');
fire.setImmovable(true);
fire.setVelocityX(platform.body.velocity.x);
fire.setSize(8, 2, true);
fire.anims.play('burn');
fire.setDepth(2);
this.fireGroup.add(fire);
}
}
}
}
// the player jumps when on the ground, or once in the air
// and obviously if the player is not dying
jump() {
const Dn = this.player.body.touching.down;
if ((!this.dying) && (Dn || (this.playerJumps > 0 && this.playerJumps < gameOptions.jumps))) {
if (this.player.body.touching.down) {
this.playerJumps = 0;
}
this.player.setVelocityY(gameOptions.jumpForce * -1);
this.playerJumps += 1;
// stops animation
this.player.anims.stop();
}
}
update() {
// game over
if (this.player.y > config.height) {
this.scene.pause('PlayGame');
// get the current user
const curUser = setUserData().getUserData();
// add the score to the score array
curUser.score.push(this.score);
setUserData().updateData(curUser);
// wait for 3 s and call the end scene
setTimeout(() => {
this.scene.start('PlayerInput');
}, 1000);
}
this.player.x = gameOptions.playerStartPosition;
this.background.tilePositionX -= 0.5;
// recycling platforms
let minDistance = config.width;
let rightmostPlatformHeight = 0;
this.platformGroup.getChildren().forEach((platform) => {
const platformDistance = config.width - platform.x - platform.displayWidth / 2;
if (platformDistance < minDistance) {
minDistance = platformDistance;
rightmostPlatformHeight = platform.y;
}
if (platform.x < -platform.displayWidth / 2) {
this.platformGroup.killAndHide(platform);
this.platformGroup.remove(platform);
}
}, this);
// recycling coins
this.coinGroup.getChildren().forEach((coin) => {
if (coin.x < -coin.displayWidth / 2) {
this.coinGroup.killAndHide(coin);
this.coinGroup.remove(coin);
}
}, this);
// recycling fire
this.fireGroup.getChildren().forEach((fire) => {
if (fire.x < -fire.displayWidth / 2) {
this.fireGroup.killAndHide(fire);
this.fireGroup.remove(fire);
}
}, this);
// recycling mountains
this.mountainGroup.getChildren().forEach((mountain) => {
if (mountain.x < -mountain.displayWidth) {
const rightmostMountain = this.getRightmostMountain();
mountain.x = rightmostMountain + Phaser.Math.Between(50, 200);
mountain.y = 600;
mountain.setFrame(Phaser.Math.Between(0, 1));
mountain.setScale(0.5);
if (Phaser.Math.Between(0, 1)) {
mountain.setDepth(1);
}
}
}, this);
// adding new platforms
if (minDistance > this.nextPlatformDistance) {
const nextPlatformWidth = Phaser.Math.Between(gameOptions.platformSizeRange[0],
gameOptions.platformSizeRange[1]);
const platformRandomHeight = gameOptions.platformHeighScale * Phaser.Math.Between(
gameOptions.platformHeightRange[0],
gameOptions.platformHeightRange[1],
);
const nextPlatformGap = rightmostPlatformHeight + platformRandomHeight;
const minPlatformHeight = config.height * gameOptions.platformVerticalLimit[0];
const maxPlatformHeight = config.height * gameOptions.platformVerticalLimit[1];
const nextPlatformHeight = Phaser.Math.Clamp(nextPlatformGap,
minPlatformHeight,
maxPlatformHeight);
this.addPlatform(nextPlatformWidth, config.width + nextPlatformWidth / 2, nextPlatformHeight);
}
}
}
export default playGame;<file_sep>/* eslint-disable no-unused-vars */
/* eslint-disable import/no-cycle */
import Phaser from 'phaser';
import setUserData from '../script';
import config from '../config/config';
import Button from '../config/buttons';
class endingScene extends Phaser.Scene {
constructor() {
super('endGame');
}
create() {
this.background = this.add.image(config.width / 2, config.height / 2, 'cover');
const curUser = setUserData().getUserData();
const suBstyle = {
font: 'bold 2rem Arial', fill: 'yellow', boundsAlignH: 'center', boundsAlignV: 'middle',
};
this.add.text(300, 300, ` ${curUser.name} Scored ${curUser.score[curUser.score.length - 1]}`, suBstyle);
const startButton = new Button(this, config.width / 2, config.height / 3, 'start_button', 'PreloadGame');
const leaderboardButton = new Button(this, config.width / 2, config.height / 3 + config.height / 10, 'score_btn', 'Leaderboard');
}
}
export default endingScene;<file_sep>/* eslint-disable no-new */
import Phaser from 'phaser';
import { getScores } from '../config/leaderboard';
import Button from '../config/buttons';
export default class LeaderboardScene extends Phaser.Scene {
constructor() {
super('Leaderboard');
}
create() {
this.cameras.main.setBackgroundColor('#000111');
const loading = this.add.text(250, 250, 'Loading...').setTint(0xff00ff);
new Button(this, 400, 550, 'menu', 'PreloadGame');
getScores().then((scores) => {
loading.destroy();
scores.sort((a, b) => b.score - a.score);
this.add.text(100, 20, 'RANK SCORE NAME').setTint(0xff00ff);
const consLen = scores.length < 6 ? scores.length : 6;
for (let i = 0; i <= consLen; i += 1) {
this.add.text(100, 90 * (i + 1), `Ninja ${i + 1} ${scores[i].score} ${scores[i].user}`).setTint(0xff00ff);
}
}).catch((err) => {
this.add.text(100, 100, `Error: ${err}`);
});
}
}<file_sep>/* eslint-disable import/no-cycle */
import BootScene from '../scenes/bootScene';
import GameScene from '../scenes/gameScene';
import preloadGame from '../scenes/preloadGame';
import playGame from '../scenes/playGame';
import scoreScene from '../scenes/scoreScene';
import PlayerInputScene from '../scenes/scoreSetScene';
import endingScene from '../scenes/endingScene';
import giveCredit from '../scenes/creditScene';
import howToScene from '../scenes/how_toScene';
const config = {
width: 800,
height: 600,
backgroundColor: 0x0c88c7,
scene: [BootScene,
GameScene,
preloadGame,
playGame,
scoreScene,
endingScene,
PlayerInputScene,
giveCredit,
howToScene],
physics: {
default: 'arcade',
},
pixelArt: true,
resize() {
const canvas = document.querySelector('canvas');
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const windowRatio = windowWidth / windowHeight;
const gameRatio = this.width / this.height;
if (windowRatio < gameRatio) {
canvas.style.width = `${windowWidth}px`;
canvas.style.height = `${windowWidth / gameRatio}px`;
} else {
canvas.style.width = `${windowHeight * gameRatio}px`;
canvas.style.height = `${windowHeight}px`;
}
},
};
export default config;<file_sep>/* eslint-disable import/no-cycle */
import Phaser from 'phaser';
import config from '../config/config';
class howToScene extends Phaser.Scene {
constructor() {
super('HowTo');
}
create() {
this.cameras.main.setBackgroundColor('8a0000');
this.creditsText = this.add.text(0, 0, 'Ninja Skrill \n How To play!', { fontSize: '32px', fill: '#fff' });
this.image1 = this.add.image(400, 200, 'cover');
this.madeByText2 = this.add.text(0, 0, 'Sometimes being a Ninja is hard work,\n But other times,\n it can be easy as \n running around, \n\n jumping, and literally avoiding fire.', { fontSize: '26px', fill: '#fff' });
this.madeByText3 = this.add.text(0, 0, 'In this game you don\'t have\n to do much . Run around wait for the \n right time to jump by \n tapping or clicking the screen\n to avoid danger.\n', { fontSize: '26px', fill: '#fff' });
this.madeByText4 = this.add.text(0, 0, 'Collect coins to increase \n you score and if\n you manage to beat one of the highest\n you can then earn \n your place at the table\n of real ninja on the leaderboard.', { fontSize: '26px', fill: '#fff' });
this.zone = this.add.zone(config.width / 2, config.height / 2, config.width, config.height);
this.keySpace = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
this.skipText = this.add.text(10, 10, 'Press SPACE \n Or click on the screen \n to skip', { fontSize: '10px', fill: '#fff' });
Phaser.Display.Align.In.Center(
this.creditsText,
this.zone,
);
Phaser.Display.Align.In.Center(
this.image1,
this.zone,
);
Phaser.Display.Align.In.Center(
this.madeByText2,
this.zone,
);
Phaser.Display.Align.In.Center(
this.madeByText3,
this.zone,
);
Phaser.Display.Align.In.Center(
this.madeByText4,
this.zone,
);
this.image1.setY(800);
this.madeByText2.setY(1100);
this.madeByText3.setY(1300);
this.madeByText4.setY(1800);
this.creditsTween = this.tweens.add({
targets: this.creditsText,
y: -200,
duration: 3000,
delay: 1000,
});
this.imageTween1 = this.tweens.add({
targets: this.image1,
y: -200,
duration: 13000,
delay: 1000,
});
this.madeByTween1 = this.tweens.add({
targets: this.madeByText1,
y: -200,
duration: 14000,
delay: 1000,
});
this.madeByTween2 = this.tweens.add({
targets: this.madeByText2,
y: -200,
duration: 20000,
delay: 1000,
});
this.madeByTween3 = this.tweens.add({
targets: this.madeByText3,
y: -200,
duration: 25000,
delay: 1000,
});
this.madeByTween4 = this.tweens.add({
targets: this.madeByText4,
y: -200,
duration: 35000,
delay: 1000,
});
}
goBack() {
this.scene.start('PreloadGame');
}
update() {
if (this.keySpace.isDown) {
this.goBack();
}
this.input.on('pointerdown', this.goBack, this);
}
}
export default howToScene;
|
b511d02feb7bb7750314793ded785b18a753d4a5
|
[
"JavaScript",
"Markdown"
] | 13
|
JavaScript
|
kelibst/ninjaskrill
|
0f90119a6daf66a4a62f24cf5feab8c44d04e2c9
|
a82776e4b20e46925d12f7f932ffa1c875b32ee4
|
refs/heads/master
|
<file_sep>/*jshint curly: true, asi: false, funcscope: false*//*globals $:false *//*globals console:false */
$(function() {
"use strict";
$('#search').on('click', function () {
var searchTerm = $('#searchTerm').val();
var url = "https://ru.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&format=json&callback=?";
$.ajax({
url: url,
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, status, jqXHR) {
$("#output").html();
for ( var i = data[1].length - 1; i >= 0; --i ) {
$('#output').prepend("<div class='well'><div><a href="+data[3][i]+"><h2>" + data[1][i]+ "</h2>" + "<p>" + data[2][i] + "</p></a></div></div>");
}
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
// Second part of task Create a Human Class
function Human() {
this.name = [
'Slava', 'Dima'
];
this.age = [
26, 18
];
this.sex = 'male';
this.height = 180;
this.weight =100;
}
function Worker() {
this.workPlace = 'factory';
this.salary = 500;
this.work = function() {
console.log('Work on the ' + this.workPlace + '!!!');
};
}
Worker.prototype = new Human();
var newWorker = new Worker();
console.log('Worker name', newWorker.name[0]);
console.log('Worker age', newWorker.age[0]);
newWorker.work();
function Student() {
this.studyPlace = 'DTUZT';
this.stipend = 200;
this.watchSerials = function() {
console.log('Skip your class in ' + this.studyPlace + ' and watch new season');
};
}
Student.prototype = new Human();
var newStudent = new Student();
console.log('Student name', newStudent.name[1]);
console.log('Student height', newStudent.height);
newStudent.watchSerials();
|
7431f5328382542db62d3053cfaa0c7f23e3caa2
|
[
"JavaScript"
] | 1
|
JavaScript
|
SviatoslavK/GoIT_JS_15-16
|
897079e3a3220eebaeb82218ecc033da0e920484
|
69c14d4a90aa71062a6a7abd1df5ad297ef1b9bc
|
refs/heads/master
|
<file_sep>-- require controller module
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local json = require "json"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local screenGroup
local myText
local function networkListenerClaimOffer(event)
if ( event.isError ) then
loadingText.text = "No Internet Connection.\nPull down screen to reload."
else
print("-------------------------------------\n\n\n")
print(event.response)
local t = json.decode( event.response )
local status = tostring(t.Status)
local errormessage = tostring(t.error.ERR_MSG)
print(status.."<->"..errormessage)
if status == "false" then
gerrormessage = errormessage
errorScreen()
else
claimSuccessScreen()
end
end
end
local function claimOffer() --1st step is get the offers
print("claimOffer")
-- loadingText.text = "loaded"
myText.text = "Trying again..."
url = "http://mondano.sg/api/membersProducts/claim/?".."fb_id="..gfbid.."&product_id="..gproducts[gproductindex].product_id.."&access_token="..gtoken
print(url)
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "<KEY>"
local params = {}
params.headers = headers
-- local body = { fb_id = "112123", product_id = "1" }
-- local body = "fb_id="..gfbid.."&product_id="..gproducts[gproductindex].product_id
-- local body = "fb_id=100006286952227&product_id=1"
-- local body = "language=en&apikey=yourapikeynoquotes"
-- params.body = body
-- print(params.body)
network.request( url, "GET", networkListenerClaimOffer, params )
end
local function shareButtonTouch( event )
print("shareButtonTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
end
if event.phase == "ended" then
print("shareButtonTouch")
claimOffer()
end
end
local function cancelButtonTouch( event )
print("cancelButtonTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
end
if event.phase == "ended" then
print("cancelButtonTouch")
dealsScreen()
end
end
function scene:createScene( event )
screenGroup = self.view
sww = display.newImage( "images/something_went_wrong.png")
sww.x = g.centerPos(sww)
sww.y = 100
g.scaleMe(sww)
screenGroup:insert(sww)
local options =
{
--parent = textGroup,
text = gerrormessage,
x = 100,
y = sww.y+sww.height,
width = 250, --required for multi-line and alignment
font = native.systemFont,
fontSize = 16,
align = "center" --new alignment parameter
}
myText = display.newText( options )
myText:setFillColor( 81/255, 115/255, 173/115 )
myText.x = 320/2 - (myText.width/2)
screenGroup:insert(myText)
local shareButton = widget.newButton
{
top = myText.y+myText.height+50,
left = 15,
id = "button",
defaultFile = "images/ok_try_again.png",
onEvent = shareButtonTouch
}
g.scaleMe(shareButton)
screenGroup:insert( shareButton )
local cancelButton = widget.newButton
{
top = myText.y+myText.height+50,
left =30+(shareButton.width/2),
id = "button",
defaultFile = "images/cancel.png",
onEvent = cancelButtonTouch
}
g.scaleMe(cancelButton)
screenGroup:insert( cancelButton )
print( "\n1: deals createScene event")
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
print( "1: enterScene event" )
myText.text = gerrormessage
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene<file_sep>-- require controller module
local storyboard = require "storyboard"
local widget = require "widget"
local g = require( "mod_globals" )
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
-- globals
gscreen = ""
gfbid = ""
-- gtoken = "<KEY>"
gtoken = ""
gloggedin = false
gmemberid = ""
gproducts = {} -- the offers these is populated at deals page
gproductindex = 1
gerrormessage = ""
gsuccessmessage = ""
gfbid = "761825596"
gloggedin = true
-----------------------------------------------------------------------------------
function resetTabs()
mywallet.isVisible = true
mywallet_b.isVisible = false
deals.isVisible = true
deals_b.isVisible = false
profilebutton.isVisible = false
profilebutton_b.isVisible = false
signup.isVisible = false
signup_b.isVisible = false
if gloggedin == true then
login_b.isVisible = true;
login.isVisible = false;
profilebutton.isVisible = true
profilebutton_b.isVisible = false
else
login_b.isVisible = false;
login.isVisible = true;
signup.isVisible = true
signup_b.isVisible = false
end
-- profile.isVisible = true
-- profile_b.isVisible = false
native.cancelWebPopup()
end
-- scene functions
function profileScreen(back)
resetTabs()
profilebutton_b.isVisible = true
-- deals_b.isVisible = true;
if not back then
end
storyboard.gotoScene( "profile" )
end
function claimSuccessScreen(back)
resetTabs()
-- deals_b.isVisible = true;
if not back then
end
storyboard.gotoScene( "claim_success" )
end
function errorScreen(back)
resetTabs()
-- deals_b.isVisible = true;
if not back then
end
storyboard.gotoScene( "error" )
end
function productShare(back)
resetTabs()
-- deals_b.isVisible = true;
if not back then
table.insert(g.lastScene, "share") -- push
print("pushed share")
end
print(gproductindex)
storyboard.gotoScene( "share" )
end
function productScreen(back)
resetTabs()
-- deals_b.isVisible = true;
if not back then
table.insert(g.lastScene, "product") -- push
print("pushed product")
end
print(gproductindex)
storyboard.gotoScene( "product" )
end
function dealsScreen(back)
resetTabs()
deals_b.isVisible = true;
if not back then
table.insert(g.lastScene, "deals") -- push
print("pushed deals")
end
storyboard.gotoScene( "deals" )
end
function signupScreen(back)
resetTabs()
if gloggedin == true then
profilebutton_b.isVisible = true;
else
signup_b.isVisible = true;
end
if not back then
table.insert(g.lastScene, "signup") -- push
print("pushed signup")
end
storyboard.gotoScene( "signup" )
end
function mywalletScreen(back)
resetTabs()
mywallet_b.isVisible = true;
if not back then
table.insert(g.lastScene, "mywallet") -- push
print("pushed mywallet")
end
storyboard.gotoScene( "mywallet" )
end
local function goBack()
if table.getn(g.lastScene) > 0 then
lastscene = g.lastScene[table.getn(g.lastScene)]
table.remove(g.lastScene) -- pop
print("popped "..lastscene)
lastscene = g.lastScene[table.getn(g.lastScene)]
if lastscene then
print ("Going back to "..lastscene);
if lastscene == "deals" then
dealsScreen(true)
elseif lastscene == "signup" then
signupScreen(true)
elseif lastscene == "mywallet" then
mywalletScreen(true)
elseif lastscene == "product" then
productScreen(true)
elseif lastscene == "share" then
productShare(true)
end
end
end
end
-----------------------------------------------------------------------------------
-- START LAYOUT
-- tabs
-- My Wallet
function mywalletTouch( event )
local object = event.target
if event.phase == "began" then
object.began = true
g.mouseDown(object)
end
if event.phase == "moved" then
g.mouseUp(object)
end
if event.phase == "ended" then
g.mouseUp(object)
if object.began == true then
mywalletScreen()
end
end
end
mywallet = display.newImage( "images/tab1_a.png")
mywallet.x = g.leftPos(mywallet)
mywallet.y = g.bottomPos(mywallet)
g.scaleMe(mywallet)
mywallet:addEventListener( "touch", mywalletTouch )
mywallet_b = display.newImage( "images/tab1_b.png")
mywallet_b.x = g.leftPos(mywallet_b)
mywallet_b.y = g.bottomPos(mywallet_b)
g.scaleMe(mywallet_b)
mywallet_b:addEventListener( "touch", mywalletTouch )
mywallet_b.isVisible = false
-- Deals
function dealsTouch( event )
local object = event.target
if event.phase == "began" then
object.began = true
g.mouseDown(object)
end
if event.phase == "moved" then
g.mouseUp(object)
end
if event.phase == "ended" then
g.mouseUp(object)
if object.began == true then
dealsScreen()
end
end
end
deals = display.newImage( "images/tab2_a.png")
deals.x = mywallet.width * g.scale
deals.y = g.bottomPos(deals)
g.scaleMe(deals)
deals:addEventListener( "touch", dealsTouch )
deals_b = display.newImage( "images/tab2_b.png")
deals_b.x = mywallet.width * g.scale
deals_b.y = g.bottomPos(deals_b)
g.scaleMe(deals_b)
deals_b:addEventListener( "touch", dealsTouch )
deals_b.isVisible = false
-- Sign up
function signupTouch( event )
local object = event.target
if event.phase == "began" then
object.began = true
g.mouseDown(object)
end
if event.phase == "moved" then
g.mouseUp(object)
end
if event.phase == "ended" then
g.mouseUp(object)
if object.began == true then
signupScreen()
end
end
end
signup = display.newImage( "images/tab3_a.png")
signup.x = (mywallet.width * g.scale) + (deals.width * g.scale)
signup.y = g.bottomPos(signup)
g.scaleMe(signup)
signup:addEventListener( "touch", signupTouch )
signup_b = display.newImage( "images/tab3_b.png")
signup_b.x = (mywallet.width * g.scale) + (deals.width * g.scale)
signup_b.y = g.bottomPos(signup_b)
g.scaleMe(signup_b)
signup_b:addEventListener( "touch", signupTouch )
signup_b.isVisible = false
-- Profile
function profilebuttonTouch( event )
local object = event.target
if event.phase == "began" then
object.began = true
g.mouseDown(object)
end
if event.phase == "moved" then
g.mouseUp(object)
end
if event.phase == "ended" then
g.mouseUp(object)
if object.began == true then
profileScreen()
end
end
end
profilebutton = display.newImage( "images/tab3b_a.png")
profilebutton.x = (mywallet.width * g.scale) + (deals.width * g.scale)
profilebutton.y = g.bottomPos(profilebutton)
g.scaleMe(profilebutton)
profilebutton:addEventListener( "touch", profilebuttonTouch )
profilebutton_b = display.newImage( "images/tab3b_b.png")
profilebutton_b.x = (mywallet.width * g.scale) + (deals.width * g.scale)
profilebutton_b.y = g.bottomPos(profilebutton_b)
g.scaleMe(profilebutton_b)
profilebutton_b:addEventListener( "touch", profilebuttonTouch )
profilebutton_b.isVisible = false
--login
function loginTouch( event )
local object = event.target
if event.phase == "began" then
object.began = true
g.mouseDown(object)
end
if event.phase == "moved" then
g.mouseUp(object)
end
if event.phase == "ended" then
g.mouseUp(object)
if object.began == true then
-- resetTabs()
-- signup_b.isVisible = true;
if gloggedin == true then
gloggedin = false
gfbid = "";
dealsScreen()
else
signupScreen()
-- gfbid = "<PASSWORD>040778<PASSWORD>"
-- gloggedin = true
end
--goBack()
end
end
end
login = display.newImage( "images/login.png")
login.x = g.leftPos(login)
login.y = g.topPos(login)
g.scaleMe(login)
login:addEventListener( "touch", loginTouch )
login_b = display.newImage( "images/logout.png")
login_b.x = g.leftPos(login_b)
login_b.y = g.topPos(login_b)
login_b:addEventListener( "touch", loginTouch )
g.scaleMe(login_b)
login_b.isVisible = false
logo = display.newImage( "images/logo.png")
logo.x = login.width * g.scale
logo.y = g.topPos(logo)
g.scaleMe(logo)
-- default call
resetTabs()
deals_b.isVisible = true;
dealsScreen()
--profileScreen()
-- mywalletScreen()
-- errorScreen()
-- claimSuccessScreen()
local function onKeyEvent( event )
local keyname = event.keyName;
if (event.phase == "up" and (event.keyName=="back" or event.keyName=="menu")) then
if keyname == "menu" then
-- goToMenuScreen()
elseif keyname == "back" then
goBack();
elseif keyname == "search" then
-- performSearch();
end
end
return true;
end
--add the runtime event listener
if system.getInfo( "platformName" ) == "Android" then Runtime:addEventListener( "key", onKeyEvent ) end
-- arrangements
local display_stage = display.getCurrentStage()
display_stage:insert( mywallet )
display_stage:insert( mywallet_b )
display_stage:insert( deals )
display_stage:insert( deals_b )
display_stage:insert( signup )
display_stage:insert( signup_b )
display_stage:insert( profilebutton )
display_stage:insert( profilebutton_b )
display_stage:insert( login )
display_stage:insert( login_b )<file_sep>-- require controller module
local http = require("socket.http")
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local json = require "json"
local crypto = require "crypto"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
local thememberid = 38
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- scene globals
local top = 10
local left = 10
local imageindex = 1
local actualimageindex = 1
local images = {} -- product image filenames
local actualimages = {} -- the actual image object
local productTitles = {} -- product titles
local productExpiryTexts = {} -- product expiry texts
local checks = {} -- check buttons
local products = {} -- the products
local mproducts = {} -- the products
local buttonAreas = {}
local bottomlines = {}
local memberproducts = {}
local lotsOfText = "Loading Your Wallet..."
local loadingText = display.newText(lotsOfText, left, top, display.contentWidth-20, 0, native.systemFont, 16)
loadingText:setFillColor( 81/255, 115/255, 173/255 )
local loadingText2 = display.newText(lotsOfText, left, top, display.contentWidth-20, 0, native.systemFont, 16)
loadingText2:setFillColor( 81/255, 115/255, 173/255 )
local scrollView
local scrollView2
local redeemtext = nil
local redeemimage = nil
local redeembutton = nil
local prodindex
-- http://d.pr/i/XArh -- my wallet screenshot
local function hideAll()
while actualimages[i] do
actualimages[i].isVisible = false
productTitles[i].isVisible = false
productExpiryTexts[i].isVisible = false
checks[i].isVisible = false
buttonAreas[i].isVisible = false
bottomlines[i].isVisible = false
i = i+1
end
top = 10
left = 10
imageindex = 1
actualimageindex = 1
images = {} -- product image filenames
actualimages = {} -- the actual image object
productTitles = {} -- product titles
productExpiryTexts = {} -- product expiry texts
checks = {} -- check buttons
products = {} -- the products
mproducts = {}
buttonAreas = {}
bottomlines = {}
end
local function networkRedeem( event )
if ( event.isError ) then
loadingText.text = "No Internet Connection.\nPull down screen to reload."
hideAll()
else
print ( "RESPONSE: " .. tostring(event.response) )
mywalletScreen()
end
--myText.isVisible = true
end
local function redeembuttonTouch(event)
print("redeembuttonTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
-- If the touch on the button has moved more than 10 pixels,
-- pass focus back to the scroll view so it can continue scrolling
if ( dy > 10 ) then
scrollView2:takeFocus( event )
end
end
if event.phase == "ended" then
print("button pressed")
if true then
url = "http://www.mondano.sg/api/membersProducts/redeem?fb_id="..gfbid.."&product_id="..mproducts[prodindex].products_id
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "MONDANO-aUHp-9awx@c1yGX580ZmPAkrsUKlucuFH4h"
local params = {}
params.headers = headers
network.request( url, "GET", networkRedeem, params )
end
end
end
local function networkListenerloadRedeemCode( event )
if ( event.isError ) then
print ( "Network error - download failed" )
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
end
-- the image
redeemimage = event.target
prodindex = redeemimage.x
offertype = redeemimage.y
width = redeemimage.width
height = redeemimage.height
g.scaleMe(redeemimage)
redeemimage.x = 0
redeemimage.y = 0
redeemimage.isVisible = true
scrollView2:insert(redeemimage)
loadingText2.isVisible = false
-- the title
if offertype == 1 or offertype == 2 then
redeemimage.y = 47
--local title = display.newText(ttext, 10, 10, display.contentWidth-20, 0, native.systemFont, 16)
local ttext = "Your unique redeem code is:\n"..mproducts[prodindex].redeemCode
if redeemtext == nil then
local options =
{
--parent = textGroup,
text = ttext,
x = 0,
y = 10,
width = 320, --required for multi-line and alignment
font = native.systemFontBold,
fontSize = 16,
align = "center" --new alignment parameter
}
redeemtext = display.newText(options)
redeemtext:setFillColor( 81/255, 115/255, 173/255 )
scrollView2:insert(redeemtext)
end
redeemtext.text = ttext
redeemtext.isVisible = true
elseif offertype == 3 then
if redeembutton == nil then
redeembutton = widget.newButton
{
left = 0,
top = 229,
id = "button",
height = 20,
defaultFile = "images/product_page_button.png",
onEvent = redeembuttonTouch
}
scrollView2:insert( redeembutton )
end
redeembutton.isVisible = true
end
scrollView2.isVisible = true
resetTabs()
end
local function loadRedeemCode(url, pindex)
prodindex = pindex
print("loadRedeemCode")
scrollView.isVisible = false
scrollView2.isVisible = true
loadingText2.text = "Loading Offer..."
loadingText2.isVisible = true
if redeemimage then
redeemimage.isVisible = false
end
if redeemtext then
redeemtext.isVisible = false
end
if redeembutton then
redeembutton.isVisible = false
end
-- local fname = system.getTimer()
local fname = crypto.digest( crypto.md5, url )
if(url) then
image = display.loadRemoteImage(
url,
"GET",
networkListenerloadRedeemCode,
fname..".png",
system.TemporaryDirectory,
prodindex, -- x carries the index of the product
tonumber(products[prodindex].offerType) -- y carries the offertype
)
else
end
end
-- get member products
local function networkListenerMemberProducts( event )
print("networkListenerMemberProducts")
if ( event.isError ) then
loadingText.text = "No Internet Connection.\nPull down screen to reload."
hideAll()
else
local t = json.decode( event.response )
--[[
[0] => stdClass Object
(
[MembersProduct] => stdClass Object
(
[id] => 14
[members_id] => 3
[products_id] => 4
[date_availed] => 2013-12-02 17:58:06
[reviewed] =>
[usedAs] =>
[claim_status] => 1
[redeemCode] => JTPD1PG1TJ
)
)
top = 10
left = 10
imageindex = 1
images = {} -- product image filenames
actualimages = {} -- the actual image object
productTitles = {} -- product titles
productExpiryTexts = {} -- product expiry texts
checks = {} -- check buttons
products = {} -- the products
buttonAreas = {}
--]]
products = {}
mproducts = {}
memberproducts = t.data
str = ""
--print(t.data[1].MembersProduct.id)
local imagestemp = {}
for i=1,table.getn(memberproducts) do
product = memberproducts[i].Offer
mproduct = memberproducts[i].MembersProduct
imgurl = product.thumbnailCircle
print(product.title.."<----------------\n\n")
print(product.offerType.."<----------------\n\n")
if imgurl then
table.insert(products, product)
table.insert(mproducts, mproduct)
table.insert(imagestemp, imgurl)
end
end
-- update expiry dates
for i=1,table.getn(productExpiryTexts) do
productExpiryTexts[i].text = products[i].expiryText
end
if(table.getn(imagestemp)>0) then
loadingText.text = ""
diff = table.getn(imagestemp) - table.getn(images)
if diff > 0 then
i = 0
n = table.getn(images) + 1
while i < diff do
print("image = "..imagestemp[n])
table.insert(images, imagestemp[n])
n = n + 1
i = i + 1
end
end
else
print("here 2")
loadingText.text = "Your Mondano Wallet is empty."
hideAll()
end
end
end
local function getMemberProducts() --1st step is get the offers
print("getMemberProducts")
-- loadingText.text = "loaded"
if gfbid == "" or gloggedin==false then
loadingText.text = "Please login to check your wallet."
hideAll()
else
url = "http://mondano.sg/api/membersProducts/byFacebookId?fbid="..gfbid
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "<KEY>"
local params = {}
params.headers = headers
network.request( url, "GET", networkListenerMemberProducts, params )
-- run this function again after 60 secs
timer.performWithDelay( 60000, getMemberProducts, 1 )
end
end
-- buttonAreas
local function buttonAreasTouch( event )
print("buttonAreasTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
-- If the touch on the button has moved more than 10 pixels,
-- pass focus back to the scroll view so it can continue scrolling
if ( dy > 10 ) then
scrollView:takeFocus( event )
end
end
if event.phase == "ended" then
print(products[object.imageindex].offerType.."<----------------\n\n")
if products[object.imageindex].offerType=="1" or products[object.imageindex].offerType=="2" or products[object.imageindex].offerType=="3" then
print(mproducts[object.imageindex].redeemCode.."<----------------\n\n")
print(products[object.imageindex].walletImg.."<----------------\n\n")
loadRedeemCode(products[object.imageindex].walletImg, object.imageindex)
else
if checks[object.imageindex].isVisible then
checks[object.imageindex].isVisible = false
else
checks[object.imageindex].isVisible = true
end
end
end
end
local function networkListenerloadImages( event )
if ( event.isError ) then
print ( "Network error - download failed" )
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
end
actualimageindex = event.target.x -- use the x as index hehehe
-- print ( "RESPONSE: "..actualimageindex, event.response.filename )
--limit image width to max 300
-- circle image
actualimages[actualimageindex] = event.target
width = actualimages[actualimageindex].width
height = actualimages[actualimageindex].height
-- actualimages[actualimageindex].width = 300
-- actualimages[actualimageindex].height = 300/width*height
g.scaleMe(actualimages[actualimageindex])
actualimages[actualimageindex].y = top
actualimages[actualimageindex].x = left
actualimages[actualimageindex].isVisible = true
scrollView:insert( actualimages[actualimageindex] )
print("actualimages "..actualimageindex)
-- product title
-- productTitle = display.newText(products[actualimageindex].title, 0, 0, display.contentWidth-20, 0, native.systemFont, 14)
productTitles[actualimageindex] = display.newText(products[actualimageindex].title, 0, 0, display.contentWidth-20, 0, native.systemFont, 14)
productTitles[actualimageindex].x = g.scaleWidth(actualimages[actualimageindex])+left+10
productTitles[actualimageindex].y = top+4
productTitles[actualimageindex]:setFillColor( 96/255, 96/255, 96/255 )
productTitles[actualimageindex].isVisible = true
scrollView:insert( productTitles[actualimageindex] )
-- productExpiryTexts
productExpiryTexts[actualimageindex] = display.newText(products[actualimageindex].expiryText, 0, 0, display.contentWidth-20, 0, native.systemFont, 10)
productExpiryTexts[actualimageindex].x = g.scaleWidth(actualimages[actualimageindex])+left+10
productExpiryTexts[actualimageindex].y = top+4+productTitles[actualimageindex].height
productExpiryTexts[actualimageindex]:setFillColor( 96/255, 96/255, 96/255 )
productExpiryTexts[actualimageindex].isVisible = true
scrollView:insert( productExpiryTexts[actualimageindex] )
-- check button
checks[actualimageindex] = display.newImage( "images/check.png")
checks[actualimageindex].x = g.scaleWidth(actualimages[actualimageindex])+left+240
checks[actualimageindex].y = top + 10
checks[actualimageindex].isVisible = false
g.scaleMe(checks[actualimageindex])
scrollView:insert( checks[actualimageindex] )
-- button
buttonAreas[actualimageindex] = widget.newButton
{
left = left,
top = top - 10,
id = "button"..actualimageindex,
defaultFile = "images/buttonarea.png",
onEvent = buttonAreasTouch
}
buttonAreas[actualimageindex].imageindex = actualimageindex
buttonAreas[actualimageindex].isVisible = true
scrollView:insert( buttonAreas[actualimageindex] )
top = top + g.scaleHeight(actualimages[actualimageindex]) + 10
bottomlines[actualimageindex] = display.newImage( "images/line.png")
bottomlines[actualimageindex].x = 0
bottomlines[actualimageindex].y = top
bottomlines[actualimageindex].isVisible = true
top = top + g.scaleHeight(bottomlines[actualimageindex]) + 10
g.scaleMe(bottomlines[actualimageindex])
scrollView:insert( bottomlines[actualimageindex] )
actualimageindex = actualimageindex + 1
-- arrange image reverse
-- actualimages[actualimageindex].y = 0
-- actualimages[actualimageindex].x = 0
-- arrangeImages()
end
local function loadImages()
print("loadImages")
loadingText.isVisible = true
-- local fname = system.getTimer()
local fname = crypto.digest( crypto.md5, images[imageindex] )
if(images[imageindex]) then
if imageindex == 1 then
print("------------------------------------------------------")
local topline = display.newImage( "images/line.png")
topline.x = 0
topline.y = 0
g.scaleMe(topline)
scrollView:insert( topline )
end
image = display.loadRemoteImage(
images[imageindex],
"GET",
networkListenerloadImages,
fname..".png",
system.TemporaryDirectory,
imageindex,
360
)
imageindex = imageindex + 1
else
loadingText.text = "You don't have any offers in your wallet"
end
end
local function loadImagesTicker( event )
-- print( "mywallet ticker "..imageindex.." "..table.getn(images) )
if imageindex <= table.getn(images) then
loadImages()
end
timer.performWithDelay( 1000, loadImagesTicker, 1 )
end
local function scrollListener( event )
-- print("scrollListener")
local phase = event.phase
local direction = event.direction
if "began" == phase then
elseif "moved" == phase then
elseif "ended" == phase then
end
if event.limitReached then
if "up" == direction then
loadingText.text = "Loading Your Wallet..."
getMemberProducts()
elseif "down" == direction then
loadingText.text = "Loading Your Wallet..."
getMemberProducts()
elseif "left" == direction then
elseif "right" == direction then
end
end
return true
end
-- Called when the scene's view does not exist:
function scene:createScene( event )
local screenGroup = self.view
print("topStatusBarContentHeight = "..display.topStatusBarContentHeight)
------------------------------------------------------------------------------------------------
-- start scene
local wallet_title = display.newImage( "images/wallet_title.png")
wallet_title.x = 0
wallet_title.y = 43+display.topStatusBarContentHeight
g.scaleMe(wallet_title)
-- wallet_title.isVisible = false
scrollView2 = widget.newScrollView
{
left = 0,
top = 43+display.topStatusBarContentHeight,
topPadding = 0,
bottomPadding = 0,
width = display.contentWidth,
height = display.contentHeight-49.5-43-display.topStatusBarContentHeight,
id = "onBottom1",
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
backgroundColor = { 1, 1, 1 }
}
scrollView2.isVisible = false
scrollView = widget.newScrollView
{
left = 0,
top = 43+display.topStatusBarContentHeight+g.scaleHeight(wallet_title),
topPadding = 0,
bottomPadding = 0,
width = display.contentWidth,
height = display.contentHeight-49.5-43-display.topStatusBarContentHeight-g.scaleHeight(wallet_title),
id = "onBottom",
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
backgroundColor = { 1, 1, 1 }
}
getMemberProducts()
timer.performWithDelay( 1000, loadImagesTicker, 1 )
scrollView:insert( loadingText )
scrollView2:insert( loadingText2 )
screenGroup:insert(scrollView)
screenGroup:insert(wallet_title)
screenGroup:insert(scrollView2)
print( "\n1: mywallet createScene event")
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
print( "1: enterScene event" )
scrollView.isVisible = true
scrollView2.isVisible = false
getMemberProducts()
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene<file_sep>-- require controller module
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local crypto = require "crypto"
local json = require "json"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local top = 10
local left = 10
local screenGroup
local scrollView
local myText
local loadingText = display.newText("Loading...", 10, top, display.contentWidth-20, 0, native.systemFont, 16)
loadingText:setFillColor( 81/255, 115/255, 173/255 )
local actualimage
local instructions
local shareButton
local cancelButton
local function networkListenerClaimOffer(event)
if ( event.isError ) then
loadingText.text = "No Internet Connection.\nPull down screen to reload."
else
print("-------------------------------------\n\n\n")
print(event.response)
local t = json.decode( event.response )
local status = tostring(t.Status)
local errormessage = tostring(t.error.ERR_MSG)
print(status.."<->"..errormessage)
if status == "false" then
gerrormessage = errormessage
errorScreen()
else
claimSuccessScreen()
end
end
end
local function claimOffer() --1st step is get the offers
print("claimOffer")
-- loadingText.text = "loaded"
url = "http://mondano.sg/api/membersProducts/claim/?".."fb_id="..gfbid.."&product_id="..gproducts[gproductindex].product_id.."&access_token="..gtoken
print(url)
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "<KEY>"
local params = {}
params.headers = headers
-- local body = { fb_id = "112123", product_id = "1" }
-- local body = "fb_id="..gfbid.."&product_id="..gproducts[gproductindex].product_id
-- local body = "fb_id=100006286952227&product_id=1"
-- local body = "language=en&apikey=yourapikeynoquotes"
-- params.body = body
-- print(params.body)
network.request( url, "GET", networkListenerClaimOffer, params )
end
local function scrollListener( event )
local phase = event.phase
local direction = event.direction
if "began" == phase then
elseif "moved" == phase then
elseif "ended" == phase then
end
if event.limitReached then
if "up" == direction then
elseif "down" == direction then
elseif "left" == direction then
elseif "right" == direction then
end
end
return true
end
-- Called when the scene's view does not exist:
function scene:createScene( event )
screenGroup = self.view
scrollView = widget.newScrollView
{
left = 0,
top = 43+display.topStatusBarContentHeight,
topPadding = 20,
bottomPadding = 0,
width = display.contentWidth,
height = display.contentHeight-49.5-43-display.topStatusBarContentHeight,
id = "onBottom",
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
backgroundColor = { 1, 1, 1 }
}
-- scrollView:insert(myText)
scrollView:insert( loadingText )
-- text
local options =
{
--parent = textGroup,
text = "When you claim this offer, you will share it on your Facebook Timeline so that your friends can learn about it as well. Click the button below to get the offer.",
x = 10,
y = top,
width = display.contentWidth-20, --required for multi-line and alignment
font = native.systemFont,
fontSize = 16,
align = "left" --new alignment parameter
}
instructions = display.newText( options )
instructions:setFillColor( 81/255, 115/255, 173/255 )
scrollView:insert( instructions )
screenGroup:insert(scrollView)
print( "\n1: deals createScene event")
end
local function shareButtonTouch( event )
print("shareButtonTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
if ( dy > 10 ) then
scrollView:takeFocus( event )
end
end
if event.phase == "ended" then
print("shareButtonTouch")
claimOffer()
end
end
local function cancelButtonTouch( event )
print("shareButtonTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
if ( dy > 10 ) then
scrollView:takeFocus( event )
end
end
if event.phase == "ended" then
print("cancelButton")
productScreen()
end
end
local function loadActualImage()
-- the image
width = actualimage.width
height = actualimage.height
actualimage.width = 300
actualimage.height = 300/width*height
-- g.scaleMe(actualimage)
actualimage.y = (top + instructions.height + 40)
actualimage.x = left
scrollView:insert( actualimage )
actualimage.isVisible = true
scrollView:insert( actualimage )
-- share button
shareButton = widget.newButton
{
left = left+5,
top = (top + actualimage.height + 30 + instructions.height + 40),
id = "button",
defaultFile = "images/share_button.png",
onEvent = shareButtonTouch
}
g.scaleMe(shareButton)
scrollView:insert( shareButton )
-- cancel button
cancelButton = widget.newButton
{
left = left + ( shareButton.width / 2) + 15 ,
top = (top + actualimage.height + 30 + instructions.height + 40),
id = "button",
defaultFile = "images/cancel.png",
onEvent = cancelButtonTouch
}
g.scaleMe(cancelButton)
scrollView:insert( cancelButton )
end
local function networkListener( event )
if ( event.isError ) then
print ( "Network error - download failed" )
dealsScreen()
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
end
loadingText.text = ""
print ( "RESPONSE: ", event.response.filename )
actualimage = event.target
loadActualImage()
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
top = 0
if actualimage then
actualimage.isVisible = false
end
loadingText.text = "Loading Image..."
loadingText.y = 175
-- myText.text = gproducts[gproductindex].prodDetail
-- print(gproductindex.." -- "..gproducts[gproductindex].prodDetail)
fname = crypto.digest( crypto.md5, gproducts[gproductindex].image )
local imagepath = system.pathForFile( fname..".png", system.TemporaryDirectory )
imagepath = string.gsub(imagepath, "\\", "/")
actualimage = display.newImage( imagepath )
if actualimage then
loadActualImage()
else
err = pcall(
function()
image = display.loadRemoteImage(
gproducts[gproductindex].image,
"GET",
networkListener,
fname..".png",
system.TemporaryDirectory,
centerX, 360
)
error()
end
)
end
print("error ?"..tostring(err))
print( "1: enterScene event" )
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene<file_sep>-- require controller module
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local json = require "json"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local screenGroup
local myText
local function successButtonTouch( event )
print("successButtonTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
end
if event.phase == "ended" then
print("successButtonTouch")
mywalletScreen()
end
end
local function cancelButtonTouch( event )
print("cancelButtonTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
end
if event.phase == "ended" then
print("cancelButtonTouch")
dealsScreen()
end
end
function scene:createScene( event )
screenGroup = self.view
local successButton = widget.newButton
{
top = 100,
id = "button",
defaultFile = "images/claim_success.png",
onEvent = successButtonTouch
}
successButton.x = g.centerPos(successButton)
g.scaleMe(successButton)
screenGroup:insert( successButton )
print( "\n1: deals createScene event")
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
print( "1: enterScene event" )
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene<file_sep>-- require controller module
local http = require("socket.http")
local storyboard = require "storyboard"
local dealsScene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local json = require "json"
local crypto = require "crypto"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- scene globals
local top = 0
local left = 10
local imageindex = 1
local actualimageindex = 1
local images = {} -- product image filenames
local actualimages = {} -- the actual image object
local buttonAreas = {}
local lotsOfText = "Loading Deals..."
local loadingText = display.newText(lotsOfText, left, top, display.contentWidth-20, 0, native.systemFont, 16)
loadingText:setFillColor( 81/255, 115/255, 173/255 )
local scrollView
local noInternet = false
-- buttonAreas
local function buttonAreasTouch( event )
print("buttonAreasTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
-- If the touch on the button has moved more than 10 pixels,
-- pass focus back to the scroll view so it can continue scrolling
if ( dy > 10 ) then
scrollView:takeFocus( event )
end
end
if event.phase == "ended" then
gproductindex = object.productindex
productScreen()
end
end
local function networkListener( event )
if ( event.isError ) then
print ( "Network error - download failed" )
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
end
actualimageindex = event.target.x -- use the x as index hehehe
--limit image width to max 300
actualimages[actualimageindex] = event.target
width = actualimages[actualimageindex].width
height = actualimages[actualimageindex].height
actualimages[actualimageindex].width = 300
actualimages[actualimageindex].height = 300/width*height
actualimages[actualimageindex].y = top
actualimages[actualimageindex].x = left
scrollView:insert( actualimages[actualimageindex] )
-- button
buttonAreas[actualimageindex] = widget.newButton
{
left = left,
top = top,
id = "button"..actualimageindex,
height = actualimages[actualimageindex].height,
defaultFile = "images/dealsbutton.png",
onEvent = buttonAreasTouch
}
buttonAreas[actualimageindex].productindex = actualimageindex
scrollView:insert( buttonAreas[actualimageindex] )
top = top + actualimages[actualimageindex].height + 10
actualimageindex = actualimageindex + 1
end
local function loadImages()
print("loadImages")
-- local fname = system.getTimer()
local fname = crypto.digest( crypto.md5, images[imageindex] )
if(images[imageindex]) then
local image
image = display.loadRemoteImage(
images[imageindex],
"GET",
networkListener,
fname..".png",
system.TemporaryDirectory,
imageindex, -- use the x as index hehehe
360
)
imageindex = imageindex + 1
end
end
local function networkListenerOffers( event )
if ( event.isError ) then
loadingText.text = "No Internet Connection.\nPull down screen to reload."
noInternet = true
else
print ( "RESPONSE: " .. event.response )
local t = json.decode( event.response )
offers = t.data.offers
gproducts = {}
for i=1, table.getn(offers) do
table.insert(gproducts, offers[i].Offer)
end
diff = table.getn(offers) - table.getn(images)
if diff > 0 then
i = 0
n = table.getn(images) + 1
while i < diff do
print("image = "..offers[n].Offer.image)
table.insert(images, offers[n].Offer.image)
n = n + 1
i = i + 1
end
loadImages()
end
end
end
local function getLatestImages()
print("getLatestImages")
url = "http://mondano.sg/api/offers/active"
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "<KEY>"
local params = {}
params.headers = headers
network.request( url, "GET", networkListenerOffers, params )
end
local function arrangeImages()
xtop = 0
ub = table.getn(actualimages)
while ub >= 1 do
actualimages[ub].x = left
actualimages[ub].y = xtop
xtop = xtop + actualimages[ub].height + 10
ub = ub - 1
end
end
local function loadImagesTicker( event )
-- print( "deals ticker "..imageindex.." "..table.getn(images) )
if imageindex <= table.getn(images) then
loadImages()
end
timer.performWithDelay( 1000, loadImagesTicker, 1 )
end
timer.performWithDelay( 1000, loadImagesTicker, 1 )
-- Our ScrollView listener
local function scrollListener( event )
local phase = event.phase
local direction = event.direction
if "began" == phase then
--print( "Began" )
elseif "moved" == phase then
elseif "ended" == phase then
end
-- If the scrollView has reached it's scroll limit
if event.limitReached then
if "up" == direction then
loadingText.text = "Loading Deals..."
if noInternet then
getLatestImages()
end
elseif "down" == direction then
loadingText.text = "Loading Deals..."
if noInternet then
getLatestImages()
end
elseif "left" == direction then
print( "Reached Left Limit" )
elseif "right" == direction then
print( "Reached Right Limit" )
end
end
return true
end
-- Called when the scene's view does not exist:
function dealsScene:createScene( event )
local screenGroup = self.view
------------------------------------------------------------------------------------------------
-- start scene
scrollView = widget.newScrollView
{
left = 0,
top = 43+display.topStatusBarContentHeight,
topPadding = 20,
bottomPadding = 0,
width = display.contentWidth,
height = display.contentHeight-49.5-43-display.topStatusBarContentHeight,
id = "onBottom",
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
backgroundColor = { 1, 1, 1 }
}
scrollView:insert( loadingText )
screenGroup:insert( scrollView )
getLatestImages()
print( "\n1: deals createScene event")
end
-- Called immediately after scene has moved onscreen:
function dealsScene:enterScene( event )
print( "1: enterScene event" )
end
-- Called when scene is about to move offscreen:
function dealsScene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function dealsScene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
dealsScene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
dealsScene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
dealsScene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
dealsScene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return dealsScene<file_sep>-- require controller module
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local crypto = require "crypto"
local json = require "json"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local top = 0
local left = 0
local screenGroup
local scrollView
local myText
local loadingText = display.newText("Loading ...", 10, top, display.contentWidth-20, 0, native.systemFont, 16)
loadingText:setFillColor( 81/255, 115/255, 173/255 )
local actualimage
local isAndroid = "Android" == system.getInfo( "platformName" )
local inputFontSize = 18
local tHeight = 30
if ( isAndroid or 1 ) then
inputFontSize = inputFontSize - 4
tHeight = tHeight + 10
end
local function scrollListener( event )
local phase = event.phase
local direction = event.direction
if "began" == phase then
elseif "moved" == phase then
elseif "ended" == phase then
end
if event.limitReached then
if "up" == direction then
elseif "down" == direction then
elseif "left" == direction then
elseif "right" == direction then
end
end
return true
end
local function popuplistener( event )
local shouldLoad = true
local url = event.url
loadingText.text = url
if nil ~= string.find( url, "successclosecorona" ) then
-- Close the web popup
gloggedin = true
shouldLoad = false
timer.performWithDelay( 500, mywalletScreen, 1 )
end
if nil ~= string.find( url, "closecorona" ) then
-- Close the web popup
shouldLoad = false
end
if event.errorCode then
-- Error loading page
print( "Error: " .. tostring( event.errorMessage ) )
shouldLoad = false
end
return shouldLoad
end
-- Called when the scene's view does not exist:
function scene:createScene( event )
screenGroup = self.view
--[[
scrollView = widget.newScrollView
{
left = 0,
top = 43+display.topStatusBarContentHeight,
topPadding = 20,
bottomPadding = 0,
width = display.contentWidth,
height = display.contentHeight-49.5-43-display.topStatusBarContentHeight,
id = "onBottom",
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
backgroundColor = { 1, 1, 1 }
}
profile = display.newImage( "images/profile_form.png")
profile.x = 0
profile.y = 0
g.scaleMe(profile)
scrollView:insert( profile )
-- first name
firstname = native.newTextField( 148, 80, 130, tHeight )
firstname.font = native.newFont( native.systemFontBold, inputFontSize )
firstname.hasBackground = false
firstname.text = "Please enter"
firstname:addEventListener( "userInput", textListener )
scrollView:insert( firstname )
-- last name
lastname = native.newTextField( 148, 80+30, 130, tHeight )
lastname.font = native.newFont( native.systemFontBold, inputFontSize )
lastname.hasBackground = false
lastname.text = "Please enter"
lastname:addEventListener( "userInput", textListener )
scrollView:insert( lastname )
local webView = native.newWebView( display.contentCenterX, display.contentCenterY, 320, 480 )
webView:request( "http://www.coronalabs.com/" )
scrollView:insert( webView )
scrollView:insert( loadingText )
screenGroup:insert(scrollView)
print( "\n1: deals createScene event")
popup = native.showWebPopup( 0,
43+display.topStatusBarContentHeight,
display.contentWidth,
display.contentHeight-49.5-43-display.topStatusBarContentHeight,
"http://e27.co" )
]]--
screenGroup:insert( loadingText )
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
local options =
{
hasBackground=false,
urlRequest=popuplistener
}
local popurl = "";
if gloggedin == false then
popurl = "http://www.mondano.sg/signup_form.php?_"..tostring(system.getTimer())..">oken="..gtoken
else
popurl = "http://www.mondano.sg/signup_form.php?_"..tostring(system.getTimer())..">oken="..gtoken.."&gfbid="..gfbid
end
native.showWebPopup( 0,
50+display.topStatusBarContentHeight, -- 43+display.topStatusBarContentHeight,
display.contentWidth,
display.contentHeight-53.5-43-display.topStatusBarContentHeight, --display.contentHeight-49.5-43-display.topStatusBarContentHeight,
popurl,
options
)
loadingText.y = 320 + 20
loadingText.isVisible = false
print( "1: enterScene event" )
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene<file_sep>-- require controller module
local http = require("socket.http")
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local json = require "json"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
local thememberid = 38
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- Called when the scene's view does not exist:
function scene:createScene( event )
local screenGroup = self.view
print("topStatusBarContentHeight = "..display.topStatusBarContentHeight)
-- scene globals
local top = 10
local left = 10
local imageindex = 1
local images = {} -- product image filenames
local actualimages = {} -- the actual image object
local products = {}
local goffers = {}
local gfbid = ""
local gmemberid = ""
local gmemberproducts = {}
local lotsOfText = "Loading Your Wallet..."
local loadingText = display.newText(lotsOfText, left, top, display.contentWidth-20, 0, native.systemFont, 16)
loadingText:setFillColor( 0, 0, 0 )
local scrollView
local function echo(str)
loadingText.text = str
end
local function getProduct(products_id)
--[[
[0] => stdClass Object
(
[Offer] => stdClass Object
(
[id] => 1
[product_id] => 1
[title] => California Fitness
[description] => 21-days Unlimited Gym Access Including Group X Classes
[image] => http://www.mondano.sg/img/phone_application/california_app_img.png
[discount] => Free
[detailURL] => http://www.mondano.sg/california-fitness
[created] => 2014-02-01 15:38:58
)
)
--]]
for i=1,table.getn(goffers) do
print(goffers[i].Offer.product_id.." "..products_id)
if tostring(goffers[i].Offer.product_id) == tostring(products_id) then
return goffers[i].Offer
end
end
return false
end
-- get member products
local function networkListenerMemberProducts( event )
if ( event.isError ) then
else
local t = json.decode( event.response )
--[[
[0] => stdClass Object
(
[MembersProduct] => stdClass Object
(
[id] => 14
[members_id] => 3
[products_id] => 4
[date_availed] => 2013-12-02 17:58:06
[reviewed] =>
[usedAs] =>
[claim_status] => 1
[redeemCode] => JTPD1PG1TJ
)
)
--]]
gmemberproducts = t.data
str = ""
--print(t.data[1].MembersProduct.id)
local imagestemp = {}
for i=1,table.getn(gmemberproducts) do
if tostring(gmemberproducts[i].MembersProduct.members_id) == tostring(gmemberid) then
product = getProduct(gmemberproducts[i].MembersProduct.products_id)
imgurl = product.thumbnailCircle
if imgurl then
table.insert(products, product)
table.insert(imagestemp, imgurl)
end
end
end
print("here 1 "..table.getn(imagestemp))
if(table.getn(imagestemp)>0) then
loadingText.text = ""
diff = table.getn(imagestemp) - table.getn(images)
if diff > 0 then
i = 0
n = table.getn(images) + 1
while i < diff do
print("image = "..imagestemp[n])
table.insert(images, imagestemp[n])
n = n + 1
i = i + 1
end
end
else
print("here 2")
loadingText.text = "Your Mondano Wallet is empty."
end
end
end
local function getMemberProducts() --1st step is get the offers
print("getMemberProducts")
-- loadingText.text = "loaded"
url = "http://mondano.sg/api/membersProducts/"
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "<KEY>"
local params = {}
params.headers = headers
network.request( url, "GET", networkListenerMemberProducts, params )
end
-- get member by fbid
local function networkListenerMemberByFbID( )
-- get member products
gmemberid = thememberid
-- gmemberid = nil
if gmemberid then
getMemberProducts()
else
loadingText.text = "Your must be signed in to access your wallet."
end
end
local function getMemberByFbID()
print("getMemberByFbID")
networkListenerMemberByFbID()
end
-- get latest offers
local function networkListenerLatestOffers( event )
if ( event.isError ) then
loadingText.text = "No Internet Connection.\nPull down screen to reload."
else
-- print ( "RESPONSE: " .. event.response )
local t = json.decode( event.response )
--[[
[0] => stdClass Object
(
[Offer] => stdClass Object
(
[id] => 1
[product_id] => 1
[title] => California Fitness
[description] => 21-days Unlimited Gym Access Including Group X Classes
[image] => http://www.mondano.sg/img/phone_application/california_app_img.png
[discount] => Free
[detailURL] => http://www.mondano.sg/california-fitness
[created] => 2014-02-01 15:38:58
)
)
--]]
goffers = t.data.offers -- populate global variable offers
-- get member by fb id
getMemberByFbID(gfbid)
end
end
local function getLatestOffers() --1st step is get the offers
print("getLatestOffers")
url = "http://mondano.sg/api/offers"
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "<KEY>"
local params = {}
params.headers = headers
network.request( url, "GET", networkListenerLatestOffers, params )
end
local function arrangeImages()
xtop = 0
ub = table.getn(actualimages)
while ub >= 1 do
actualimages[ub].x = left
actualimages[ub].y = xtop
xtop = xtop + actualimages[ub].height + 10
ub = ub - 1
end
end
local function networkListenerloadImages( event )
if ( event.isError ) then
print ( "Network error - download failed" )
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
end
-- print ( "RESPONSE: "..imageindex, event.response.filename )
--limit image width to max 300
-- circle image
actualimages[imageindex] = event.target
width = actualimages[imageindex].width
height = actualimages[imageindex].height
-- actualimages[imageindex].width = 300
-- actualimages[imageindex].height = 300/width*height
g.scaleMe(actualimages[imageindex])
actualimages[imageindex].y = top
actualimages[imageindex].x = left
scrollView:insert( actualimages[imageindex] )
top = top + g.scaleHeight(actualimages[imageindex]) + 10
local bottomline = display.newImage( "images/line.png")
bottomline.x = 0
bottomline.y = top
top = top + g.scaleHeight(bottomline) + 10
g.scaleMe(bottomline)
scrollView:insert( bottomline )
-- arrange image reverse
-- actualimages[imageindex].y = 0
-- actualimages[imageindex].x = 0
-- arrangeImages()
end
local function loadImages()
print("loadImages")
local fname = system.getTimer()
if(images[imageindex]) then
if imageindex == 1 then
print("------------------------------------------------------")
local topline = display.newImage( "images/line.png")
topline.x = 0
topline.y = 0
g.scaleMe(topline)
scrollView:insert( topline )
end
image = display.loadRemoteImage(
images[imageindex],
"GET",
networkListenerloadImages,
fname..".png",
system.TemporaryDirectory,
centerX, 360
)
imageindex = imageindex + 1
else
loadingText.text = "You don't have any offers in your wallet"
end
end
local function loadImagesTicker( event )
-- print( "mywallet ticker "..imageindex.." "..table.getn(images) )
if imageindex <= table.getn(images) then
loadImages()
end
timer.performWithDelay( 1000, loadImagesTicker, 1 )
end
local function scrollListener( event )
local phase = event.phase
local direction = event.direction
if "began" == phase then
elseif "moved" == phase then
elseif "ended" == phase then
end
if event.limitReached then
if "up" == direction then
-- loadingText.text = "Loading Your Wallet..."
getLatestOffers()
elseif "down" == direction then
-- loadingText.text = "Loading Your Wallet..."
getLatestOffers()
elseif "left" == direction then
elseif "right" == direction then
end
end
return true
end
------------------------------------------------------------------------------------------------
-- start scene
local wallet_title = display.newImage( "images/wallet_title.png")
wallet_title.x = 0
wallet_title.y = 43+display.topStatusBarContentHeight
g.scaleMe(wallet_title)
wallet_title.isVisible = true
scrollView = widget.newScrollView
{
left = 0,
top = 43+display.topStatusBarContentHeight+g.scaleHeight(wallet_title),
topPadding = 0,
bottomPadding = 0,
width = display.contentWidth,
height = display.contentHeight-49.5-43-display.topStatusBarContentHeight-g.scaleHeight(wallet_title),
id = "onBottom",
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
backgroundColor = { 1, 1, 1 }
}
getLatestOffers()
timer.performWithDelay( 1000, loadImagesTicker, 1 )
scrollView:insert( loadingText )
screenGroup:insert(scrollView)
screenGroup:insert(wallet_title)
print( "\n1: mywallet createScene event")
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
print( "1: enterScene event" )
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene<file_sep>-- require controller module
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local json = require "json"
local facebook = require("facebook")
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local appId = "621488324580194" -- Add your App ID here (also go into build.settings and replace XXXXXXXXX with your appId under CFBundleURLSchemes)
local apiKey = "<KEY>" -- Not needed at this time
local myText
local function networkloginOrSignup( event )
if ( event.isError ) then
myText.text = "No Internet Connection.\nPull down screen to reload."
noInternet = true
else
print ( "RESPONSE: " .. tostring(event.response) )
local t = json.decode( event.response )
if t.data.MSG then -- Already a member
gloggedin = true
mywalletScreen()
else
profileScreen()
end
myText.text = tostring(event.response)
end
--myText.isVisible = true
end
local function loginOrSignup()
url = "http://www.mondano.sg/api/MembersFreelahs/isMember?fbid="..gfbid
myText.text = url
local headers = {}
headers["Content-Type"] = "application/json"
headers["XH-MAG-API-KEY"] = "<KEY>"
local params = {}
params.headers = headers
network.request( url, "GET", networkloginOrSignup, params )
--[[
if 1 then -- if not yet registerd
profileScreen()
else
gloggedin = true
mywalletScreen()
end
]]--
end
local function fblistener( event )
myText.text = "in listener..."
txtx = "event.token: "..tostring(event.token).."\n"
txtx = txtx.."event.name: "..tostring(event.name).."\n"
txtx = txtx.."event.type: "..tostring(event.type).."\n"
txtx = txtx.."event.isError: "..tostring(event.isError).."\n"
txtx = txtx.."event.didComplete: "..tostring(event.didComplete).."\n"
txtx = txtx.."event.phase: "..tostring(event.phase).."\n"
txtx = txtx.."event.response: "..tostring(event.response).."\n"
-- myText.text = txtx
if ( "request" == event.type ) then
local response = tostring(event.response)
if response then
myText.text = "error 1"
response = json.decode( tostring(event.response) )
myText.text = "error 2"
txtx = txtx.."response.id: "..tostring(response.id).."\n"
txtx = txtx.."response.name: "..tostring(response.name).."\n"
gfbid = response.id
myText.text = txtx
myText.text = "loginOrSignup"
loginOrSignup()
end
elseif( "session" == event.type ) then
if event.token then
gtoken = tostring(event.token) -- set gtoken
facebook.request( "me" ) -- to get id
else
dealsScreen()
end
end
-- myText.text = txtx
end
-- Called when the scene's view does not exist:
function scene:createScene( event )
local screenGroup = self.view
local options =
{
--parent = textGroup,
text = "Sign up / Sign in",
x = 100,
y = 100,
width = 250, --required for multi-line and alignment
font = native.systemFont,
fontSize = 16,
align = "center" --new alignment parameter
}
myText = display.newText( options )
myText:setFillColor( 81/255, 115/255, 173/255 )
myText.x = 320/2 - (myText.width/2)
screenGroup:insert(myText)
print( "\n1: deals createScene event")
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
--facebook.login( appId, fblistener )
facebook.login( appId, fblistener, {"publish_actions", "email", "user_birthday"} )
myText.text = "Logging in..."
myText.isVisible = false
print( "1: enterScene event" )
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene<file_sep>-- Globals Module mod_globals.lua
local this = {}
-- Some pre-defined globals
this.scale = 0.5 --high res
this.lastScene = {}
-- extra functions
local function scaleHeight(obj)
width = obj.width * this.scale
val = width * obj.height / obj.width
print("height="..val)
return val
end
this.scaleHeight = scaleHeight
local function scaleWidth(obj)
val = obj.width * this.scale
return val
end
this.scaleWidth = scaleWidth
local function scaleMe(obj)
obj:scale(this.scale, this.scale)
end
this.scaleMe = scaleMe
local function topPos(obj)
return 0 + display.topStatusBarContentHeight
end
this.topPos = topPos
local function middlePos(obj)
pos = display.contentHeight / 2
pos = pos - (scaleHeight(obj) / 2)
return pos
end
this.middlePos = middlePos
local function bottomPos(obj)
pos = display.contentHeight - scaleHeight(obj)
return pos
end
this.bottomPos = bottomPos
local function leftPos(obj)
return 0
end
this.leftPos = leftPos
local function centerPos(obj)
pos = display.contentWidth / 2
pos = pos - (scaleWidth(obj) / 2)
return pos
end
this.centerPos = centerPos
local function rightPos(obj)
pos = display.contentWidth - scaleWidth(obj)
return pos
end
this.rightPos = rightPos
local function mouseDown(object)
object.alpha = 0.9;
-- object.x = object.x + 1;
-- object.y = object.y + 1;
end
this.mouseDown = mouseDown
local function mouseUp(object)
object.alpha = 1;
-- object.x = object.x - 1;
-- object.y = object.y - 1;
end
this.mouseUp = mouseUp
local function bounceY(obj)
pos = obj.y
t = 50
transition.to( obj, { time=t, delay=0, alpha=1.0, y = pos-3 })
transition.to( obj, { time=t, delay=t, alpha=1.0, y = pos+3 })
transition.to( obj, { time=t, delay=t*2, alpha=1.0, y = pos })
end
this.bounceY = bounceY
local function bounceRand(obj)
posY = obj.y
posX = obj.x
w = obj.width
h = obj.height
wp = obj.width * this.scale * 0.20
hp = obj.height * this.scale * 0.20
obj.width = obj.width + wp
obj.height = obj.height + hp
obj.x = obj.x - wp / 4
obj.y = obj.y - hp / 4
t = 20
transition.to( obj, { time=t, delay=t*0, alpha=1.0, width = w, height = h, x = posX, y = posY })
pix = 1
nx = math.random(pix*-1, pix)
ny = math.random(pix*-1, pix)
transition.to( obj, { time=t, delay=t*1, alpha=1.0, x = posX+nx, y = posY+ny })
nx = math.random(pix*-1, pix)
ny = math.random(pix*-1, pix)
transition.to( obj, { time=t, delay=t*2, alpha=1.0, x = posX+nx, y = posY+ny })
nx = math.random(pix*-1, pix)
ny = math.random(pix*-1, pix)
transition.to( obj, { time=t, delay=t*3, alpha=1.0, x = posX+nx, y = posY+ny })
transition.to( obj, { time=t, delay=t*4, alpha=1.0, x = posX, y = posY })
end
this.bounceRand = bounceRand
local function slideDown(obj, speed, delay)
obj.isVisible = true
if speed == nil then
speed = 200
end
if delay == nil then
delay = 0
end
if bounce == nil then
bounce = true
end
pos = obj.y
obj.alpha = 0
obj.y = obj.height / 2 * -1
if bounce == true then
transition.to( obj, { time=speed, delay=delay, alpha=1.0, y = pos, onComplete=bounceY })
elseif bounce == false then
transition.to( obj, { time=speed, delay=delay, alpha=1.0, y = pos })
end
end
this.slideDown = slideDown
local function explode(obj, speed, delay, bounce)
obj.isVisible = true
if speed == nil then
speed = 200
end
if delay == nil then
delay = 0
end
if bounce == nil then
bounce = false
end
origWidth = obj.width
origHeight = obj.height
width = scaleWidth(obj)
height = scaleHeight(obj)
x = obj.x
y = obj.y
obj.alpha = 0
obj.anchorX = 0.5
obj.anchorY = 0.5
obj.x = obj.x + width / 2
obj.y = obj.y + height / 2
obj.width = 0
obj.height = 0
if bounce == false then
transition.to( obj, { time=speed, delay=delay, alpha=1.0, width = origWidth, height = origHeight})
transition.to( obj, { time=1, delay=(speed+delay), anchorX=0, anchorY=0, x=x, y=y })
else
transition.to( obj, { time=speed, delay=delay, alpha=1.0, width = origWidth, height = origHeight})
transition.to( obj, { time=1, delay=(speed+delay), anchorX=0, anchorY=0, x=x, y=y, onComplete=bounceRand })
end
end
this.explode = explode
local function fadeIn(obj, speed, delay)
obj.isVisible = true
if speed == nil then
speed = 200
end
if delay == nil then
delay = 0
end
obj.alpha = 0
transition.to( obj, { time=speed, delay=delay, alpha=1.0})
end
this.fadeIn = fadeIn
-- Return globals module
return this<file_sep>-- require controller module
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local widget = require "widget"
local g = require( "mod_globals" )
local crypto = require "crypto"
local json = require "json"
-- configs
-- hide device status bar
display.setStatusBar( display.DefaultStatusBar )
display.setDefault( "background", 255/255, 255/255, 255/255 )
display.setDefault( "anchorX", 0 )
display.setDefault( "anchorY", 0 )
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local top = 0
local left = 0
local screenGroup
local scrollView
local myText
local loadingText = display.newText("Loading Product Details...", 10, top, display.contentWidth-20, 0, native.systemFont, 16)
loadingText:setFillColor( 81/255, 115/255, 173/255 )
local actualimage
local function scrollListener( event )
local phase = event.phase
local direction = event.direction
if "began" == phase then
elseif "moved" == phase then
elseif "ended" == phase then
end
if event.limitReached then
if "up" == direction then
elseif "down" == direction then
elseif "left" == direction then
elseif "right" == direction then
end
end
return true
end
-- Called when the scene's view does not exist:
function scene:createScene( event )
screenGroup = self.view
scrollView = widget.newScrollView
{
left = 0,
top = 43+display.topStatusBarContentHeight,
topPadding = 20,
bottomPadding = 0,
width = display.contentWidth,
height = display.contentHeight-49.5-43-display.topStatusBarContentHeight,
id = "onBottom",
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
backgroundColor = { 1, 1, 1 }
}
-- scrollView:insert(myText)
scrollView:insert( loadingText )
screenGroup:insert(scrollView)
print( "\n1: deals createScene event")
end
-- buttonArea
local function buttonAreaTouch( event )
print("buttonAreaTouch")
local object = event.target
if event.phase == "began" then
end
if ( event.phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
-- If the touch on the button has moved more than 10 pixels,
-- pass focus back to the scroll view so it can continue scrolling
if ( dy > 10 ) then
scrollView:takeFocus( event )
end
end
if event.phase == "ended" then
print("button pressed")
productShare()
end
end
local function loadActualImage()
width = actualimage.width
height = actualimage.height
actualimage.width = 320
actualimage.height = 320/width*height
-- g.scaleMe(actualimage)
actualimage.y = top
actualimage.x = left
scrollView:insert( actualimage )
actualimage.isVisible = true
-- button
buttonArea = widget.newButton
{
left = left,
top = top+228,
id = "button",
height = 20,
defaultFile = "images/product_page_button.png",
onEvent = buttonAreaTouch
}
scrollView:insert( actualimage )
scrollView:insert( buttonArea )
end
local function networkListener( event )
if ( event.isError ) then
dealsScreen()
else
event.target.alpha = 0
transition.to( event.target, { alpha = 1.0 } )
loadingText.text = ""
print ( "RESPONSE: ", event.response.filename )
actualimage = event.target
loadActualImage()
end
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
if actualimage then
actualimage.isVisible = false
end
loadingText.text = "Loading Product Details..."
-- myText.text = gproducts[gproductindex].prodDetail
-- print(gproductindex.." -- "..gproducts[gproductindex].prodDetail)
print(gproducts[gproductindex].product_id.."<--- product_id")
fname = crypto.digest( crypto.md5, gproducts[gproductindex].prodDetail )
local imagepath = system.pathForFile( fname..".png", system.TemporaryDirectory )
imagepath = string.gsub(imagepath, "\\", "/")
actualimage = display.newImage( imagepath )
if actualimage then
loadActualImage()
else
err = pcall(
function()
image = display.loadRemoteImage(
gproducts[gproductindex].prodDetail,
"GET",
networkListener,
fname..".png",
system.TemporaryDirectory,
centerX, 360
)
error()
end
)
end
print("error ?"..tostring(err))
print( "1: enterScene event" )
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene
|
ceba205cb53efb0bec956e749edb78913b478b27
|
[
"Lua"
] | 11
|
Lua
|
jairus/mondano
|
af575f5d85c4d016b40b627331d1561e88da23f5
|
2163e85b8b8556760d9ab24d7bc7aa722451cfaf
|
refs/heads/master
|
<repo_name>383366204/kt<file_sep>/src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import config from '../config/config.js'
Vue.use(Vuex)
const state = {
isIndex: true, //判断是否在首页
isLogin: false, //判断是否有登录
addresses: [], //收货地址
cart:[],
checkOutGoods: [],
token: null,
userInfo: {
nickName: '',
level: '',
email: '',
phone: '',
levelTime:Date,
headPicUrl:''
}
}
const getters = {
isLogin:state=>{
if (localStorage.getItem('isLogin')) {
state.isLogin = localStorage.getItem('isLogin')=="true"?true:false;
return state.isLogin;
}
else {
return state.isLogin;
}
},
token:state=>{
if (localStorage.getItem('token')) {
state.token = localStorage.getItem('token');
return state.token;
}
else {
return state.token;
}
},
userInfo:state=>{
if(localStorage.getItem('userInfo')){
state.userInfo = JSON.parse(localStorage.getItem('userInfo'));
return state.userInfo;
}
else{
return state.userInfo;
}
},
cart:state=>{
if(localStorage.getItem('cart')){
state.cart = JSON.parse(localStorage.getItem('cart'));
return state.cart;
}
else{
return state.cart;
}
}
}
const actions = {
}
const mutations = {
setIndexTrue(state) {
state.isIndex = true;
},
setIndexFalse(state) {
state.isIndex = false;
},
deleteFromCart(state, index){
state.cart.splice(index,1);
localStorage.setItem('cart',JSON.stringify(state.cart));
},
deleteFromCartByName(state, namesArray){
state.cart = state.cart.filter((product,index) => {
return !namesArray.includes(product.name);
})
localStorage.setItem('cart',JSON.stringify(state.cart));
},
addToCart(state, data){
state.cart.push(data);
localStorage.setItem('cart',JSON.stringify(state.cart));
},
replaceCart(state, data){
state.cart = data;
localStorage.setItem('cart',JSON.stringify(state.cart));
},
setUserInfo(state, data){
state.userInfo.nickName = data.nickName;
state.userInfo.level = data.level;
state.userInfo.email = data.email;
state.userInfo.phone = data.phone;
state.userInfo.levelTime = parseInt(Math.abs(new Date(data.levelTime) - new Date())/ 1000 / 60 / 60 / 24)
state.userInfo.headPicUrl = config.baseURL+''+data.headPicUrl;
localStorage.setItem('userInfo',JSON.stringify(state.userInfo));
},
login(state, data) {
//登录
state.isLogin = true;
localStorage.setItem('isLogin',true);
state.token = data.token;
localStorage.setItem('token',data.token);
mutations.setUserInfo(state,data);
// 设置头部
Vue.prototype.$ajax.defaults.headers.common['Authorization'] = getters.token(state);
}
,
logout(state, router) {
state.isLogin = false;
state.token = null;
localStorage.removeItem('isLogin');
localStorage.removeItem('token');
localStorage.removeItem('userInfo');
localStorage.removeItem('cart');
state.cart = [];
router.push({
path: '/'
});
},
setAddress(state, address) {
state.addresses = address;
},
setCheckOutGoods(state, checkOutGoods) {
state.checkOutGoods = checkOutGoods;
},
getVeriCode(state, getVeriParams) {
let param = {};
let ajax = getVeriParams.ajax;
if (getVeriParams.type == 'email') {
param.email = getVeriParams.userId;
} else if (getVeriParams.type == 'phone') {
param.phone = getVeriParams.userId;
}
// 获取验证码
ajax.put('api/user/verification', param)
.then(response => {
if (response.data.success) {
console.log(response.data.message);
}
})
.catch(err => {
console.log(err);
})
}
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
<file_sep>/src/config/config.js
let config = {
baseURL:'http://127.0.0.1:4040/'
}
module.exports = config;<file_sep>/README.md
# tt
> 团图网,采用vue.js技术开发
## 使用方法
``` bash
# 在主目录下安装依赖项
npm install
# 在 localhost:8080 运行服务器
npm run dev
# 打包命令
npm run build
# 打包并显示报告
npm run build --report
```
<file_sep>/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/views/Index'
import Cart from '@/views/cart'
import Detail from '@/views/Detail'
import Search from '@/views/search'
import LoginRegister from '@/views/login-register'
import Address from '@/views/address'
import OrderList from '@/views/orderList'
import Order from '@/views/order'
import CustomDesign from '@/views/customDesign'
import AccountSettings from '@/views/accountSettings'
import Inform from '@/views/inform'
import OrderSubmit from '@/views/orderSubmit'
import Contact from '@/views/contact';
import Introduce from '@/views/introduce';
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [{
path: '/',
name: 'Index',
component: Index
}, {
path: '/Introduce',
name: 'Introduce',
component: Introduce
},
{
path: '/Cart',
name: 'Cart',
component: Cart,
meta:{
requireAuth:true
}
},
{
path: '/Login',
name: 'LoginRegister',
component: LoginRegister
},
{
path: '/Address',
name: 'Address',
component: Address,
meta:{
requireAuth:true
}
},
{
path: '/OrderList',
name: 'OrderList',
component: OrderList,
meta:{
requireAuth:true
}
},
{
path: '/Order',
name: 'Order',
component: Order,
meta:{
requireAuth:true
}
},
{
path: '/Detail/:Category/:Grand/:Name',
name: 'Detail',
component: Detail
},
{
path: '/Search/:Filters?',
name: 'Search',
component: Search
},
{
path: '/AccountSettings',
name: 'AccountSettings',
component: AccountSettings,
meta:{
requireAuth:true
}
},
{
path: '/Inform',
name: 'Inform',
component: Inform,
meta:{
requireAuth:true
}
},
{
path: '/OrderSubmit',
name: 'OrderSubmit',
component: OrderSubmit,
meta:{
requireAuth:true
}
},
{
path:'/Contact',
name:'Contact',
component:Contact
}
]
})
|
399ed14f8ca4431046678e03a0d97cb28c7cca8f
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
383366204/kt
|
fd1e437678272f6b401e54a4d730e324567ea6e2
|
b2bb1f1a019488be274e65495af1b612cae99c0c
|
refs/heads/master
|
<repo_name>minhchuduc/Project_2<file_sep>/Basic_1.py
#Coding time: 1 minutes
def reverse_string(string):
return string[::-1]
if __name__ == '__main__':
input_str = raw_input('Input string: ')
output_str = reverse_string(input_str)
print "Reverse string is:", output_str
<file_sep>/hvn_spiral.py
# Time: 1hour
#!/usr/bin/env python
from pprint import pprint
import time
#Algo:
"""
We create a range(1,N)
go in directions until nothing left
"""
def go_spiral(matrix, start_r, start_c, step):
if len(numbers) <= 0:
return
def go_left(matrix, start_r, start_c):
global N
col = start_c
for i in range(N):
if matrix[start_r][col] == 0:
matrix[start_r][col] = numbers.pop()
last_mod = col
if col > 0:
col -= 1
return (start_r, last_mod)
def go_right(matrix, start_r, start_c):
global N
col = start_c
for i in range(N):
if matrix[start_r][col] == 0:
matrix[start_r][col] = numbers.pop()
last_mod = col
if col < N - 1:
col += 1
return (start_r, last_mod)
def go_up(matrix, start_r, start_c):
global N
row = start_r
for i in range(N):
if matrix[row][start_c] == 0:
matrix[row][start_c] = numbers.pop()
last_mod = row
if row > 0:
row -= 1
return (last_mod, start_c)
def go_down(matrix, start_r, start_c):
global N
row = start_r
for i in range(N):
if matrix[row][start_c] == 0:
matrix[row][start_c] = numbers.pop()
last_mod = row
if row < N - 1:
row += 1
return (last_mod, start_c)
def main():
global N
N = input('Nhap N: ')
time_start = time.time()
N = int(N)
global numbers
# Pop pop the tail, we need number increase, so create below list
numbers = range(N*N, 0, -1)
# create 2D matrix ,Filled with 0s
matrix = [[0 for _ in range(N)] for _ in range(N)]
#Start coordinate
last = (0, 0)
while len(numbers) > 0:
last = go_right(matrix, last[0], last[1])
if len(numbers) <= 0: break
last = go_down(matrix, last[0], last[1])
if len(numbers) <= 0: break
last = go_left(matrix, last[0], last[1])
if len(numbers) <= 0: break
last = go_up(matrix, last[0], last[1])
# pprint(matrix)
# Nice print
for i in matrix:
for k in i:
print k,
print
print time.time() - time_start
if __name__ == "__main__":
main()
<file_sep>/Advanced_4.py
#Coding time: 85 minutes
from __future__ import print_function # Use print as function (in Python 3.x)
def empty_square_matrix(size):
square_matrix = []
for i in range(size):
square_matrix.append([0])
for j in range(size-1):
square_matrix[i].append(0)
return square_matrix
def print_matrix_with_format(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print('{0:>4}'.format(str(matrix[i][j])), end='')
print("")
if __name__ == '__main__':
N = raw_input('Nhap N: ')
N = int(N)
spiral_matrix = empty_square_matrix(N)
numb = 1
max_layer = (N / 2) + (N % 2)
print('Total layer = ', max_layer)
for layer in range(max_layer):
for i in range(layer,N-layer-1):
spiral_matrix[layer][i] = numb
spiral_matrix[i][N-layer-1] = numb-layer + (N-layer-1)
spiral_matrix[N-layer-1][N-i-1] = numb-(2*layer) + 2*(N-layer-1)
spiral_matrix[N-i-1][layer] = numb-(3*layer) + 3*(N-layer-1)
numb += 1
numb = numb-(3*layer) + 3*(N-layer-1)
if N % 2 == 1:
spiral_matrix[N/2][N/2] = N*N # Freak, because behavior of range() function
print_matrix_with_format(spiral_matrix)<file_sep>/Basic_2_3.py
#Coding time: 80min
if __name__ == '__main__':
file_name = raw_input('File name to process: ')
input_file = open(file_name, 'r')
words_dict = {}
line_num = 0
while True:
line = input_file.readline()
line_num += 1
if not line: break
list_words = line.strip("\n").lower().split(" ")
for word in list_words:
words_dict.setdefault(word, []).append(line_num)
""" You can figure the line above by: run Python interpreter, a = {}, help(a)
It will show you all dict-methods """
freq = {}
for word in words_dict.keys():
freq[word] = len(words_dict[word]) # Calculate appearance frequency of each word.
words_dict[word] = list(set(words_dict[word])) # Convert list --> set --> list: muc. dich' la de "de-duplicate"
import sys
def my_sort_criteria(word):
max_freq = sys.maxint - freq[word]
return str(max_freq)+word # Return a string like: '9223372036854775801python', '9223372036854775805is',...
for word in sorted(words_dict.keys(), key=my_sort_criteria):
tmp_list = [ "%s" % element for element in words_dict[word] ] #Convert list like [1,2,3,4] to ['1','2',3','4']
""" Can also use alternative:
tmp_list = [ str(element) for element in words_dict[word] ] """
print freq[word], word, ' '.join(tmp_list) # Convert list like ['1','2',3','4'] to a string '1 2 3 4'
<file_sep>/Basic_2_3b.py
import string
if __name__ == '__main__':
filename = raw_input("File name to process: ")
input_file = open(filename, 'r')
words_dict = {}
exclude = set(string.punctuation + '\n')
for i, line in enumerate(input_file.readlines()):
line = ''.join(ch for ch in line if ch not in exclude)
for word in line.lower().split():
if word not in words_dict.keys():
words_dict[word] = [1, set([i+1])] # words_dict format: {word: [freq, set(line_numbers)]}, use "set" to auto-deduplicate
else: # existed in words_dict
words_dict[word][0] += 1
words_dict[word][1].add(i+1) # add to set(line_numbers)
words_list = [(-freq, word, line_numbers) for (word, (freq, line_numbers)) in words_dict.items()]
words_list.sort()
#print words_list
for freq, word, line_numbers in words_list:
print -freq, word, " ".join([str(i) for i in line_numbers])
|
210622965585479e8cd00c73a2be73920fd0f644
|
[
"Python"
] | 5
|
Python
|
minhchuduc/Project_2
|
6bdbdd39a69c0ad2ad4886d91f6b3dba22c0664a
|
005e2cf0aa559a157ec92a61e36b4d1da8c2b63b
|
refs/heads/main
|
<file_sep>contenu = open("sequences.fasta", "r") #ouvrir le fichier fasta
description = open("descriptions.txt", "w") #créer fichier text où on insérera les descriptions
ids = open("ids.txt", "w") #créer fichier text où on insérera les ids
compteur = 0
for ligne in contenu:
if ligne[0] == ">": #si le premier index est ">"
compteur += 1 #compter ces lignes
description.write(ligne[1:]) #écrire dans description.txt, en enlevant le premier caractère (soit ">")
ids.write(ligne[1:].split()[0]+"\n") #écrire en enlevant ">"; premier mot (avant premier espace de la ligne) et rajouter un saut de ligne
with open("sequences.fasta", "r") as contenu: #réitérer le fichier fraîchement
lignes = contenu.readlines() #lire les lignes
lignes_sequence1 = lignes[1:58] #les lignes 2 à 57 (index 1 à 58(non inclu)), soit les lignes de la séquence 1
sequence1 = sum(len(lignes.replace("\n", "")) for lignes in lignes_sequence1) #enleve sauts de lignes; ensuite somme caractères pour ces lignes
print("Il y a {} sequences".format(compteur)) #imprimer le nombre de lignes avec la fonction format()
print("Il y a {} acides aminees dans la premiere sequence".format(sequence1)) #imprimer la longueur avec la fonction format()
|
0cebeee5eece7457ec8af291c004d1aba2f5f770
|
[
"Python"
] | 1
|
Python
|
haddad-github/FASTA-Sequence-Reading
|
22f966fce8da477475972f6b255bc9e737937f19
|
b10e28b4d8c8bf0f6ecb2f0f951344b49b3b6247
|
refs/heads/master
|
<file_sep>package com.example.myapplication
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.dependencyInjection.Injectable
import com.example.myapplication.utilities.autoCleared
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import javax.inject.Inject
class MainActivity : AppCompatActivity(), Injectable, HasAndroidInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>
var binding by autoCleared<ActivityMainBinding>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
}
override fun androidInjector() = dispatchingAndroidInjector
}
<file_sep>package com.example.myapplication
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import javax.inject.Inject
class MainViewModel @Inject constructor(): ViewModel() {
val numbers: MutableLiveData<List<Int>> = MutableLiveData(emptyList())
fun addNumber() {
val oldNumbers = numbers.value!!.toMutableList()
val lastNumber = oldNumbers.lastOrNull()
if (lastNumber != null) {
oldNumbers.add(lastNumber + 1)
} else {
oldNumbers.add(1)
}
numbers.value = oldNumbers
}
}
<file_sep>package com.example.myapplication
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingComponent
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.myapplication.binding.FragmentDataBindingComponent
import com.example.myapplication.databinding.FragmentMainBinding
import com.example.myapplication.dependencyInjection.Injectable
import com.example.myapplication.utilities.autoCleared
import com.example.myapplication.utilities.toDp
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import javax.inject.Inject
class MainFragment : Fragment(), Injectable {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
lateinit var appExecutors: AppExecutors
val viewModel: MainViewModel by viewModels {
viewModelFactory
}
var binding by autoCleared<FragmentMainBinding>()
private var dataBindingComponent: DataBindingComponent = FragmentDataBindingComponent(this)
private var adapter by autoCleared<CenterFlowAdapter>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_main,
container,
false
)
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding.viewModel = viewModel
val manager = FlexboxLayoutManager(context, FlexDirection.ROW)
manager.justifyContent = JustifyContent.CENTER
manager.alignItems = AlignItems.CENTER
adapter = CenterFlowAdapter(
dataBindingComponent,
appExecutors,
recyclerView = binding.numberBallCollection,
cellSize = context?.resources?.getDimensionPixelSize(R.dimen.number_ball_size)?.toDp() ?: 32,
interItemSpacing = 4,
lineSpacing = 6
)
binding.numberBallCollection.layoutManager = manager
binding.numberBallCollection.adapter = adapter
viewModel.numbers.observe(viewLifecycleOwner, Observer {
adapter.submitList(it)
adapter.setPadding(it.size)
})
}
}
<file_sep>package com.example.myapplication
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.core.view.updatePadding
import androidx.databinding.DataBindingComponent
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.databinding.NumberBallItemBinding
import com.example.myapplication.utilities.toPx
import com.google.android.flexbox.FlexboxItemDecoration
import kotlin.math.ceil
import kotlin.math.floor
class CenterFlowAdapter(
private val dataBindingComponent: DataBindingComponent,
appExecutors: AppExecutors,
private val recyclerView: RecyclerView,
private val cellSize: Int,
private val interItemSpacing: Int,
private val lineSpacing: Int
) : DataBoundListAdapter<Int>(
appExecutors = appExecutors,
diffCallback = object: DiffUtil.ItemCallback<Int>() {
override fun areItemsTheSame(oldItem: Int, newItem: Int): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Int, newItem: Int): Boolean {
return oldItem == newItem
}
}
) {
override fun createBinding(parent: ViewGroup, viewType: Int): ViewDataBinding {
return DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.number_ball_item, parent, false, dataBindingComponent)
}
override fun bind(binding: ViewDataBinding, item: Int) {
(binding as? NumberBallItemBinding)?.let {
binding.number = item.toString()
}
}
fun setPadding(numberOfItems: Int) {
if (recyclerView.itemDecorationCount == 0) {
val divider = GradientDrawable()
divider.setSize(interItemSpacing.toPx(), lineSpacing.toPx())
val decoration = FlexboxItemDecoration(recyclerView.context)
decoration.setDrawable(divider)
decoration.setOrientation(FlexboxItemDecoration.BOTH)
recyclerView.addItemDecoration(decoration)
}
val width = recyclerView.width
if (width > 0) {
computAndUpdatePadding(numberOfItems, width)
} else {
val vto = recyclerView.viewTreeObserver
vto.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
recyclerView.viewTreeObserver.removeOnPreDrawListener(this)
computAndUpdatePadding(numberOfItems, recyclerView.width)
return true
}
})
}
}
private fun findMaxColumns(numItems: Double, cellsPerRow: Double): Double {
val columns = floor(numItems / ceil(numItems / cellsPerRow))
val rows = numItems / columns
if (rows > rows.toInt()) {
return findMaxColumns(numItems, columns)
}
return columns
}
private fun computAndUpdatePadding(numberOfItems: Int, width: Int) {
var cellsPerRow = (width + interItemSpacing.toPx()).toDouble() / (cellSize.toPx() + interItemSpacing.toPx()).toDouble()
val columns = findMaxColumns(numberOfItems.toDouble(), cellsPerRow)
cellsPerRow = if (columns == 1.0) ceil(cellsPerRow / 2) else columns
val remainingWidth = width - cellsPerRow * (cellSize.toPx() + interItemSpacing.toPx())
val padding = (remainingWidth / 2).toInt()
recyclerView.updatePadding(left = padding, right = padding)
recyclerView.invalidateItemDecorations()
}
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion build_versions.target_sdk
buildToolsVersion build_versions.build_tools
defaultConfig {
applicationId 'com.example.myapplication'
minSdkVersion build_versions.min_sdk
targetSdkVersion build_versions.target_sdk
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
versionCode 1
versionName "1.0.0"
vectorDrawables.useSupportLibrary true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
compileOptions {
sourceCompatibility javaVersion
targetCompatibility javaVersion
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation 'android.arch.work:work-runtime-ktx:1.0.1'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.arch.core:core-runtime:2.1.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta4'
implementation 'androidx.core:core-ktx:1.2.0-rc01'
implementation 'androidx.legacy:legacy-support-core-utils:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.legacy:legacy-support-v13:1.0.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-rc03'
implementation 'androidx.lifecycle:lifecycle-runtime:2.2.0-rc03'
implementation 'androidx.lifecycle:lifecycle-common-java8:2.2.0-rc03'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-rc03'
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.0-rc04'
implementation 'androidx.navigation:navigation-ui-ktx:2.2.0-rc04'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.vectordrawable:vectordrawable:1.1.0'
implementation 'com.google.android:flexbox:1.1.1'
implementation 'com.google.android.material:material:1.2.0-alpha03'
implementation 'com.google.dagger:dagger:2.25.4'
implementation 'com.google.dagger:dagger-android:2.25.4'
implementation 'com.google.dagger:dagger-android-support:2.25.4'
implementation "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
kapt 'com.google.dagger:dagger-compiler:2.25.4'
kapt 'com.google.dagger:dagger-android-processor:2.25.4'
}
<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
// Sdk and tools
kotlin_version = '1.3.61'
javaVersion = 1.8
build_versions = [min_sdk: 23, target_sdk: 28, build_tools: "28.0.3"]
}
repositories {
google()
jcenter()
maven { url 'http://dl.bintray.com/kotlin/kotlin-eap' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
plugins {
id "com.diffplug.gradle.spotless" version "3.13.0"
}
allprojects {
repositories {
google()
jcenter()
maven { url 'http://dl.bintray.com/kotlin/kotlin-eap' }
}
}
spotless {
kotlin {
target "**/*.kt"
ktlint('0.28.0')
}
}
|
8a6e392feb87122272f9516f57ec55b6a2969cb6
|
[
"Kotlin",
"Gradle"
] | 6
|
Kotlin
|
korydondzila/kotlin-centerflow
|
306f9c13abfe12b67941f5096c2a17b8836c9c17
|
d6c36f1adc9979f12e598cd02b7ed47bd5c40e9d
|
refs/heads/main
|
<repo_name>Chooosa/studio-front<file_sep>/src/components/ErrorFallback/error-fallback.component.jsx
import React, { useEffect } from 'react';
import axios from 'axios';
import { useLocation } from 'react-router-dom';
import moment from 'moment';
import { deviceDetect, browserName, browserVersion } from 'react-device-detect';
import {
ErrorBoundaryContainer
} from './error-fallback.styles';
import { API_URL } from '../../config';
import { useTranslation } from '../../hooks/translation';
const ErrorBoundary = ({ error }) => {
const { t } = useTranslation();
const location = useLocation();
useEffect(() => {
if (process.env.NODE_ENV === 'production') {
axios({
method: 'post',
url: `${API_URL}fronterror`,
data: {
route: location.pathname,
device: deviceDetect(),
error: error.toString(),
data: moment().format('DD-MM-YYYY'),
time: moment().format('HH:mm:ss'),
browser: {
name: browserName,
version: browserVersion
},
projectName: 'LilekovStudio'
}
})
.then(() => {
console.log('success')
})
.catch((e) => {
console.log('error: ', e)
})
}
}, [error, location]);
return (
<ErrorBoundaryContainer>
<p> {t('error_happened')} </p>
<p> {t('error_beign_fixed')} </p>
<a href={'https://lilekov-studio.com'}> {t('error_to_main_page')} </a>
</ErrorBoundaryContainer>
)
}
export default ErrorBoundary;<file_sep>/src/redux/color/color.reducer.jsx
import { CHANGE_COLOR } from './color.consts';
// const color0 = '#68D87A';
const color1 = '#3FB755';
const color2 = '#FF8A00';
const color3 = '#EE2A4E';
const color4 = '#2EBEF5';
const color5 = '#2A66F5';
const color6 = '#D92AF5';
const color7 = '#772AF5';
const INITIAL_STATE = {
color: 1,
themeColor: color1
}
const returnColor = (color) => {
switch (color) {
// case 0:
// return color0;
case 1:
return color1;
case 2:
return color2;
case 3:
return color3;
case 4:
return color4;
case 5:
return color5;
case 6:
return color6;
case 7:
return color7;
default:
return color1;
}
}
export const colorReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case CHANGE_COLOR:
return {
...state,
color: action.payload,
themeColor: returnColor(action.payload)
}
default:
return state
}
}<file_sep>/src/components/SectionWe/section-we.styles.jsx
import styled from 'styled-components';
import { CustomHeading, CustomText } from '../../styles/common';
export const WeWrapper = styled.section`
width: 100%;
display: flex;
flex-direction: column;
margin-bottom: 180px;
`
export const Heading = styled(CustomHeading)`
`
export const Text = styled(CustomText)`
max-width: 410px;
`<file_sep>/src/components/Plan/plan.component.jsx
import React, { useRef, useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux'
// import smoothscroll from 'smoothscroll-polyfill';
import {
PlanWrapper,
Button,
PlanContainer,
DescriptionWrapper,
SchemeWrapper,
Heading,
Text,
LineWrapper,
Line,
StepButton,
Dash,
ProgressLine,
ProgressDot,
LineLabel,
Dot
} from './plan.styles';
import { colorSelectors } from '../../redux/color/color.selectors';
import { AnimatePresence, AnimateSharedLayout, motion } from 'framer-motion';
import { setScroll } from '../../redux/scroll/scroll.actions'
import { useWindowDimensions } from '../../hooks/dimensions'
import Slider from './Slider/slider.component'
import { scrollSelectors } from '../../redux/scroll/scroll.selectors';
// import DraggableTabs from './DraggableTabs/draggable-tabs.component'
import { useTranslation } from '../../hooks/translation'
const Plan = ({ onOpenModal }) => {
const color = useSelector(colorSelectors.color);
const [currentStep, setCurrentStep] = useState(1);
const [transitionProgress, setTransitionProgress] = useState(1);
const refSheme = useRef();
const dispatch = useDispatch();
const { width } = useWindowDimensions();
const scroll = useSelector(scrollSelectors.to)
const progressLine1 = useRef();
const line1 = useRef();
const progressLine2 = useRef();
const line2 = useRef();
const progressLine3 = useRef();
const line3 = useRef();
const { t } = useTranslation();
useEffect(() => {
if (scroll === 'plan') {
refSheme.current?.scrollIntoView({
behavior: 'smooth',
block: 'center'
})
dispatch(setScroll(undefined))
}
}, [scroll, dispatch])
// const handleScroll = () => {
// // refApplication.current.scrollIntoView({ behavior: 'smooth' })
// dispatch(setScroll('request'))
// }
const descriptionTexts = [
<motion.div
key={1}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('interview')}
</Heading>
<Text>
{t('interview_desc_intro_first')}
<br />
<br />
{t('interview_desc_intro')}
<ul>
<li>
{t('interview_desc_list_first')}
</li>
<li>
{t('interview_desc_list_second')}
</li>
</ul>
{t('interview_desc_outro')}
</Text>
</motion.div>,
<motion.div
key={2}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('analysis')}
</Heading>
<Text>
{t('analysis_desc_intro')}
<ul>
<li>
{t('analysis_desc_list_first')}
</li>
{/* <li>
{t('analysis_desc_list_second')}
</li> */}
<li>
{t('analysis_desc_list_third')}
</li>
</ul>
{t('analysis_desc_outro')}
</Text>
</motion.div>,
<motion.div
key={3}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('budget')}
</Heading>
<Text>
<p> {t('budget_desc')} </p>
<br />
<p> {t('budget_desc_second')} </p>
</Text>
</motion.div>,
<motion.div
key={4}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('contract')}
</Heading>
<Text>
<p> {t('contract_desc')} </p>
<br />
<p> {t('contract_desc_second')} </p>
<br />
<p> {t('contract_desc_third')} </p>
<br />
</Text>
</motion.div>,
<motion.div
key={5}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('design_specification')}
</Heading>
<Text>
<p> {t('design_specification_desc')} </p>
<br />
<p> {t('design_specification_desc_second')} </p>
</Text>
</motion.div>,
<motion.div
key={6}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('prototyping')}
</Heading>
<Text>
<p> {t('prototyping_desc')} </p>
<br />
<p> {t('prototyping_desc_second')} </p>
</Text>
</motion.div>,
<motion.div
key={7}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('design')}
</Heading>
<Text>
<p> {t('design_desc')} </p>
<br />
<p>{t('design_desc_second')}</p>
<br />
<p>{t('design_desc_third')}</p>
</Text>
</motion.div>,
<motion.div
key={8}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('development')}
</Heading>
<Text>
<p> {t('development_desc')} </p>
<br />
<p> {t('development_desc_second')} </p>
</Text>
</motion.div>,
<motion.div
key={9}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('testing')}
</Heading>
<Text>
<p> {t('testing_desc')} </p>
<br />
<p> {t('testing_desc_second')} </p>
</Text>
</motion.div>,
<motion.div
key={10}
initial={{ x: '-100%' }}
animate={{ x: '0%' }}
exit={{ x: '100%' }}
transition={{ duration: 0.3 }}
>
<Heading>
{t('support')}
</Heading>
<Text>
<p> {t('support_desc')} </p>
<br />
<p> {t('support_desc_second')} </p>
</Text>
</motion.div>,
]
const handlePaintingOver = () => {
if (transitionProgress === 1) {
switch (currentStep) {
case 1:
return '0.0001px'
case 2:
return '39%'
case 3:
return '64%'
case 4:
return '89%'
case 5:
return '100%'
default:
return '100%'
}
} else if (transitionProgress > 1) {
return '100%'
} else {
return '0%'
}
}
const handlePaintingOver2 = () => {
if (transitionProgress === 2) {
if (currentStep > 4) {
switch (currentStep) {
case 5:
return '0.0001px'
case 6:
return '57%'
case 7:
return '89%'
case 8:
return '100%'
default:
return '100%'
}
} else {
return '0%'
}
} else if (transitionProgress > 2) {
return '100%'
} else {
return '0%'
}
}
const handlePaintingOver3 = () => {
if (transitionProgress === 3) {
if (currentStep > 7) {
switch (currentStep) {
case 8:
return '0.0001px'
case 9:
return '65%'
case 10:
return '100%'
default:
return '100%'
}
} else {
return '0%'
}
} else {
return '0%'
}
}
const handleTransitionEnd = () => {
if (line1.current?.offsetWidth === progressLine1.current?.offsetWidth) {
setTransitionProgress(2)
}
}
const handleTransitionEnd2 = () => {
if (progressLine1.current?.offsetWidth !== line1.current?.offsetWidth) {
setTransitionProgress(1)
}
if (line2.current?.offsetWidth === progressLine2.current?.offsetWidth) {
setTransitionProgress(3)
}
if (progressLine2.current?.offsetWidth === 0 && currentStep !== 5) {
setTransitionProgress(1)
}
}
const handleTransitionEnd3 = () => {
if (transitionProgress > 1) {
if (progressLine3.current?.offsetWidth === 0 && currentStep !== 8) {
setTransitionProgress(2)
}
}
}
return (
<PlanWrapper>
<PlanContainer>
<AnimateSharedLayout>
<DescriptionWrapper
layout
>
<AnimatePresence
exitBeforeEnter
>
{descriptionTexts[currentStep - 1]}
</AnimatePresence>
</DescriptionWrapper>
</AnimateSharedLayout>
<SchemeWrapper ref={refSheme}>
<LineWrapper>
<Line
ref={line1}
// lineWidth='calc(100% - 6%)'
lineWidth='100%'
>
<LineLabel
left={'0%'}
>
{t('first_stage')}
</LineLabel>
<Dot
left={'0.0001px'}
color={color}
active
/>
<LineLabel
left={'64%'}
>
{t('second_stage')}
</LineLabel>
<Dot
left={'64%'}
color={color}
active={currentStep >= 3}
/>
<ProgressLine
ref={progressLine1}
cusstomWidth={handlePaintingOver}
color={color}
onTransitionEnd={handleTransitionEnd}
/>
<ProgressDot
left={handlePaintingOver}
color={color}
currentStep={currentStep}
first
transitionProgress={transitionProgress}
/>
<Dash
left={'0.0001px'}
color={color}
active
>
<StepButton
color={color}
left={'0'}
onClick={() => setCurrentStep(1)}
dashLeft={'0'}
active={currentStep === 1}
isStage={true}
>
{t('interview')}
</StepButton>
</Dash>
<Dash
left={'39%'}
color={color}
active={currentStep >= 2}
>
<StepButton
color={color}
left={'-35px'}
onClick={() => setCurrentStep(2)}
active={currentStep === 2}
>
{t('analysis')}
</StepButton>
</Dash>
<Dash
left={'64%'}
color={color}
active={currentStep >= 3}
>
<StepButton
color={color}
left={'-22px'}
onClick={() => setCurrentStep(3)}
active={currentStep === 3}
isStage={true}
>
{t('budget')}
</StepButton>
</Dash>
<Dash
left={'89%'}
color={color}
active={currentStep >= 4}
>
<StepButton
color={color}
left={'-25px'}
onClick={() => setCurrentStep(4)}
active={currentStep === 4}
>
{t('contract')}
</StepButton>
</Dash>
</Line>
</LineWrapper>
<LineWrapper>
<Line
ref={line2}
>
<LineLabel
left={'0%'}
>
{t('third_stage')}
</LineLabel>
<Dot
left={'0.0001px'}
color={color}
active={currentStep >= 5}
/>
<ProgressLine
ref={progressLine2}
cusstomWidth={() => handlePaintingOver2}
color={color}
onTransitionEnd={handleTransitionEnd2}
/>
<ProgressDot
left={handlePaintingOver2}
color={color}
currentStep={currentStep}
two
transitionProgress={transitionProgress}
/>
<Dash
left={'0.0001px'}
color={color}
active={currentStep >= 5}
>
<StepButton
color={color}
left={'0'}
onClick={() => setCurrentStep(5)}
dashLeft={'0'}
active={currentStep === 5}
isStage={true}
>
{t('design_specification')}
</StepButton>
</Dash>
<Dash
left={'57%'}
color={color}
active={currentStep >= 6}
>
<StepButton
color={color}
left={'-70px'}
onClick={() => setCurrentStep(6)}
active={currentStep === 6}
>
{t('prototyping')}
</StepButton>
</Dash>
<Dash
left={'89%'}
color={color}
active={currentStep >= 7}
>
<StepButton
color={color}
left={'-20px'}
onClick={() => setCurrentStep(7)}
active={currentStep === 7}
>
{t('design')}
</StepButton>
</Dash>
</Line>
</LineWrapper>
<LineWrapper alignLeft style={{ paddingRight: '20px' }}>
<Line
ref={line3}
lineWidth={'75%'}>
<LineLabel
left={'0%'}
>
{t('fourth_stage')}
</LineLabel>
<Dot
left={'0.0001px'}
color={color}
active={currentStep >= 8}
/>
<LineLabel
left={'100%'}
>
{t('fifth_stage')}
</LineLabel>
<Dot
left={'100%'}
color={color}
active={currentStep >= 10}
/>
<ProgressLine
ref={progressLine3}
cusstomWidth={() => handlePaintingOver3}
color={color}
onTransitionEnd={handleTransitionEnd3}
/>
<ProgressDot
left={handlePaintingOver3}
color={color}
currentStep={currentStep}
three
transitionProgress={transitionProgress}
/>
<Dash
left={'0.0001px'}
color={color}
active={currentStep >= 8}
>
<StepButton
color={color}
left={'0'}
onClick={() => setCurrentStep(8)}
active={currentStep === 8}
isStage={true}
>
{t('development')}
</StepButton>
</Dash>
<Dash
left={'65%'}
color={color}
active={currentStep >= 9}
>
<StepButton
color={color}
left={'-40px'}
onClick={() => setCurrentStep(9)}
dashLeft={'0'}
active={currentStep === 9}
>
{t('testing')}
</StepButton>
</Dash>
<Dash
left={'100%'}
color={color}
active={currentStep >= 10}
>
<StepButton
color={color}
left={'0'}
onClick={() => setCurrentStep(10)}
active={currentStep === 10}
isStage={true}
>
{t('support')}
</StepButton>
</Dash>
</Line>
</LineWrapper>
</SchemeWrapper>
{
width < 850 &&
<Slider
refSheme={refSheme}
currentStep={currentStep}
setCurrentStep={setCurrentStep}
/>
}
</PlanContainer>
<Button onClick={onOpenModal} color={color}>
{t('leave_request')}
{/* <img src={postIco} alt='post' /> */}
</Button>
</PlanWrapper >
);
}
export default Plan;<file_sep>/src/components/ModalBase/modal-base.styles.jsx
import styled from 'styled-components';
export const ModalContainer = styled.div`
width: 600px;
height: max-content;
min-height: 300px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
/* background: transparent; */
/* background-color: red; */
border-radius: 8px;
position: relative;
padding: 10%;
overflow-x: hidden;
span {
font-weight: 500;
font-size: 16px;
line-height: 22px;
text-align: center;
color: #000000;
}
>div {
width: 100%;
height: 100%;
}
@media(max-width: 660px) {
width: 550px;
}
@media(max-width: 610px) {
width: 460px;
}
@media(max-width: 575px) {
width: 400px;
}
@media(max-width: 465px) {
width: 330px;
height: 400px;
}
@media(max-width: 399px) {
width: 300px;
}
@media(max-width: 370px) {
width: 280px;
/* height: 300px; */
}
@media(max-width: 345px) {
width: 260px;
}
@media(max-width: 325px) {
width: 250px;
}
`
export const CloseButton = styled.button`
position: absolute;
top: 15px;
right: 15px;
outline: none;
background: transparent;
border: none;
cursor: pointer;
width: 30px;
height: 30px;
padding: 0;
z-index: 10000;
>img {
width: 30px;
}
@media(max-width: 460px) {
top: 0;
right: 0;
}
`<file_sep>/src/hooks/dimensions.jsx
import { useState, useEffect } from 'react';
export const useWindowDimensions = () => {
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
const changeDimensions = () => {
setWidth(window.innerWidth)
setHeight(window.innerHeight)
}
useEffect(() => {
changeDimensions()
window.addEventListener('resize', changeDimensions)
return () => window.removeEventListener('resize', changeDimensions)
}, [])
return { height, width }
}<file_sep>/src/components/SectionRequest/section-request.styles.jsx
import styled from 'styled-components';
import { CustomButton } from '../../styles/common';
import InputMask from 'react-input-mask';
export const InputFieldsWrapper = styled.form`
display: flex;
flex-direction: column;
`
export const InputFieldsRowPosition = styled.div`
display: flex;
${props => props.customWidth > 800 ? 'flex-direction: row' : 'flex-direction: column'};
width: 100%;
height: 100%;
justify-content: center;
margin-bottom: 10px;
${props => props.customWidth < 800 ? 'align-items: center' : ''};
`
export const InputFieldsColumn = styled.div`
display: flex;
height: 100%;
/* max-height: 220px; */
width: 100%;
max-width: 460px;
flex-direction: column;
margin: 5px ${props => props.customWidth > 800 ? '10px' : '0px'} 5px 0px;
${props => props.customWidth > 800 ? 'align-items: space-between' : 'align-items: center;'}
`
export const InputWrapper = styled.div`
height: 60px;
width: 100%;
max-width: 460px;
position: relative;
:first-child {
margin-bottom: 20px;
}
:last-child {
margin-top: 20px;
}
`
export const InputField = styled(InputMask)`
height: 100%;
width: 100%;
background-color: #111111;
color: #707070;
border-width: 0px;
padding: 0px 25px;
font-size: 16px;
:focus {
border: 1px solid ${props => props.color ? props.color : '#3FB755'};
outline: none;
+ label{
color: ${props => props.color ? props.color : '#3FB755'};
font-size: 12px;
transform: translateY(-16px);
transition: 0.5s;
}
}
:placeholder-shown {
+ label {
opacity: 1;
}
}
`
export const ExtraInfoWrapper = styled.div`
height: 100%;
width: 100%;
max-width: 460px;
position: relative;
margin-bottom: 20px;
margin-top: ${props => props.customWidth < 800 ? '20px' : '0px'};
display: flex;
flex-direction: column;
`
export const ExtraInfo = styled.textarea`
height: 140px;
width: 100%;
max-width: 460px;
background-color: #111111;
color: #707070;
padding: 25px 25px;
resize: none;
border: 0px;
align-self: center;
font-size: 16px;
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}
::-webkit-scrollbar-thumb {
background-color: darkgrey;
outline: 1px solid slategrey;
}
:placeholder-shown {
+ label {
opacity: 1;
}
}
:focus {
border: 1px solid ${props => props.color ? props.color : '#3FB755'};
outline: none;
+label {
color: ${props => props.color ? props.color : '#3FB755'};
font-size: 12px;
transform: translateY(-16px);
transition: 0.5s;
}
}
`
export const LabelWrapper = styled.label`
position: absolute;
top: 20px;
left: 25px;
color: #707070;
transition: 0.5s;
opacity: 0;
`
export const FileInput = styled.input`
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
`
export const FileInputLabel = styled.label`
outline: none;
box-shadow: none;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
width: 100%;
max-width: 460px;
min-height: 60px;
background-color: white;
cursor: pointer;
transition-duration: 0.2s;
opacity: 1;
font-weight: 500;
font-size: 14px;
line-height: 19px;
color: #0A0A0A;
position: relative;
>img {
position: absolute;
right: 30px;
}
:hover {
opacity: 0.8;
}
`
export const Error = styled.span`
width: '100%';
color: #f82222;
font-weight: 200;
font-size: 14px;
line-height: 19px;
margin-top: 13px;
align-self: center;
`
export const Button = styled(CustomButton)`
align-self: center;
margin-top: ${props => props.width > 800 ? '50px' : '0px'};
background-color: ${props => props.color ? props.color : '#3FB755'};
border-width: 0px;
max-width: 460px;
color: #FFFFFF;
:hover {
opacity: ${props => props.disabled ? '1' : '0.8'};
}
`
export const Icon = styled.img`
position: absolute;
right: 20px;
`
export const PersonalDataAgreement = styled.div`
align-self: center;
display: flex;
width: 100%;
max-width: 460px;
margin-top: 24px;
border: 10px #fff;
>span {
font-weight: 200;
font-size: 14px;
line-height: 22px;
text-align: center;
color: #707070;
>a {
font-weight: 200;
font-size: 14px;
line-height: 22px;
color: #707070;
transition-duration: 0.2s;
border-bottom: 1px solid #707070;
padding-bottom: 5px;
}
a:hover {
transition-duration: 0.2s;
opacity: 0.8;
color: #fff;
border-color: #fff;
}
}
`
export const FilesList = styled.ul`
display: flex;
flex-direction: column;
margin-top: 20px;
padding: 0px 8%;
width: ${props => props.customWidth > 800 ? '100%' : props.customWidth > 600 ? '70%' : '100%'};
align-self: ${props => props.customWidth > 800 || props.customWidth < 600 ? 'flex-start' : 'center'};
>li {
color: transparent;
>div {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
>div {
display: flex;
align-items: center;
width: 80%;
>span {
display: block;
width: 100%;
word-wrap: break-word;
color: #707070;
}
>img {
height: 18px;
width: 18px;
margin-right: 6px;
}
}
>img {
height: 18px;
width: 18px;
}
}
}
`<file_sep>/src/components/Header/header.styles.jsx
import styled from 'styled-components';
export const HeaderWrapper = styled.header`
width: 100%;
height: max-content;
position: fixed;
display: flex;
justify-content: center;
transition-duration: 0.7s;
z-index: 2;
background-color: ${props => props.background ? '#0a0a0a' : 'transparent'};
/* background: linear-gradient(180deg, #090909 0%, rgba(9, 9, 9, 0) 126.63%); */
`
export const Background = styled.div`
position: absolute;
z-index: -1;
width: 100%;
transition-duration: 0.3s;
height: ${props => props.backgroundWidth ? '200px' : '70px'};
background: linear-gradient(180deg, #090909 0%, rgba(9, 9, 9, 0) 126.63%);
background: -moz-linear-gradient(180deg, #090909 0%, rgba(9, 9, 9, 0) 126.63%); /* FF3.6-15 */
background: -webkit-linear-gradient(180deg, #090909 0%, rgba(9, 9, 9, 0) 126.63%); /* Chrome10-25,Safari5.1-6 */
`<file_sep>/src/components/Header/DropdownMenu/dropdown-menu.styles.jsx
import styled from 'styled-components';
import { ButtonsWrapper } from '../Navbar/navbar.styles';
export const DropdownMenuWrapper = styled.nav`
display: flex;
justify-content: center;
padding-bottom: 20px;
width: 100%;
height: 200px;
position: absolute;
top: 70px;
left: 0;
/* border-bottom: 1px solid ${props => props.open ? props.color : 'transparent'}; */
/* background-color: #0a0a0a; */
z-index: 499;
overflow: hidden;
transition: all .6s ease;
${props => props.open ? 'max-height: 300px;' : `max-height: 0px; padding: 0;`}
`
export const DropdownMenuContainer = styled.div`
width: 100%;
max-width: 1200px;
height: max-content;
min-height: 200px;
display: flex;
justify-content: space-between;
margin: 0 20px;
`
export const WhiteSpace = styled.div`
width: 100px;
`
export const LinksWrapper = styled(ButtonsWrapper)`
/* padding-right: 65px; */
justify-content: flex-start;
margin-right: 55px;
`
export const LinksCell = styled.div`
display: flex;
flex-direction: column;
width: 100%;
max-width: 120px;
:nth-of-type(2) {
margin-right: 25px;
}
>a,span {
font-weight: 200;
font-size: 14px;
line-height: 19px;
letter-spacing: 0.05em;
color: #f9f9f9;
margin-bottom: 16px;
position: relative;
cursor: pointer;
::before {
content: "";
position: absolute;
height: 1px;
width: 0;
right: 0;
bottom: 2px;
z-index: -1;
opacity: 0;
transition: all 0.4s ease;
background-color: ${props => props.color ? props.color : '#3fb755'};
}
:hover::before {
opacity: 1;
width: 100%;
transition: all 0.4s ease;
}
/* :focus::before {
opacity: 1;
width: calc(100% - 10px);
transition: all 0.4s ease;
} */
}
`<file_sep>/src/components/Common/SectionHeader/section-header.component.jsx
import React, { useEffect, useState } from 'react';
import AnimatedNumbers from '../AnimatedNumbers/animated-numbers.component';
import { useInView } from 'react-intersection-observer';
import {
Description,
DescriptionContainer,
Content,
Header,
Title
} from './section-header.styles';
import { Fragment } from 'react';
const SectionHeader = ({
title,
description,
index,
show,
descriptionWidth,
headerDescriptionStyles,
headerContainerStyles,
padding,
nonAnimation = true,
nonNumber = false,
custom
}) => {
const [showSection, setShowSection] = useState(false)
const { ref, inView } = useInView({
threshold: 1,
})
useEffect(() => {
if (inView) {
setShowSection(true)
}
}, [inView])
return (
<Content
style={{ ...headerContainerStyles }}
padding={padding}
ref={ref}
>
{
nonAnimation ?
<Fragment>
<Header>
<Title>
{title}
</Title>
{
!nonNumber &&
<AnimatedNumbers
index={index}
show={show}
/>
}
</Header>
{custom?
custom:
<DescriptionContainer
style={{ ...headerDescriptionStyles }}
>
<Description customWidth={descriptionWidth}>
{description}
</Description>
</DescriptionContainer>
}
</Fragment>
:
<Fragment>
<Header>
<Title
style={{
transform: `translate(${showSection ? '0' : '-100vw'})`,
opacity: showSection ? 1 : 0,
transitionDuration: '0.5s'
}}
>
{title}
</Title>
<div
style={{
transform: `translate(${showSection ? '0' : '100vw'})`,
opacity: showSection ? 1 : 0,
transitionDuration: '0.5s'
}}
>
{
!nonNumber &&
<AnimatedNumbers
index={index}
show={show}
/>
}
</div>
</Header>
<DescriptionContainer
style={{
...headerDescriptionStyles,
transform: `translate(${showSection ? '0' : '-100vw'})`,
opacity: showSection ? 1 : 0,
transitionDuration: '0.5s'
}}
>
{
custom?
custom
: <Description customWidth={descriptionWidth}>
{description}
</Description>
}
</DescriptionContainer>
</Fragment>
}
</Content>
)
}
export default SectionHeader;
<file_sep>/src/components/Header/MobileMenu/mobile-menu.styles.jsx
import { motion } from 'framer-motion'
import styled from 'styled-components'
export const Container = styled(motion.div)`
position: fixed;
top: 70px;
left: 0;
display: flex;
width: 100%;
height: calc(100% - 70px);
display: flex;
flex-direction: column;
background-color: #0A0A0A;
z-index: 1200;
`
export const BodyItem = styled.span`
font-weight: ${props => props.active ? 500 : 200};
font-size: 16px;
line-height: 21px;
letter-spacing: 0.05em;
color: #F9F9F9;
margin-left: 10px;
margin-top: 12px;
>a {
font-weight: ${props => props.active ? 500 : 200};
font-size: 16px;
line-height: 21px;
letter-spacing: 0.05em;
color: #F9F9F9;
}
cursor: pointer;
`
export const Divider = styled(motion.div)`
background-color: ${props => props.color};
width: 100%;
height: 2px;
margin-top: 20px;
`
export const CustomLink = styled.span`
width: 100%;
cursor: pointer;
padding: 0 9%;
/* margin-right: 12px; */
margin-top: 23px;
font-weight: 600;
font-size: 20px;
line-height: 28px;
color: ${props => props.color ? props.color : '#F9F9F9'};
>a {
color: ${props => props.color ? props.color : '#F9F9F9'};
}
`<file_sep>/src/components/SectionCases/Case/case.styles.jsx
import styled from 'styled-components';
import { CustomButton } from '../../../styles/common';
export const CaseContainer = styled.div`
display: flex;
flex-direction: row;
width: 100%;
background-color: #111111;
height:450px;
@media(max-width: 768px) {
height: 380px;
}
@media(max-width: 600px) {
flex-direction: column-reverse;
height: auto;
}
`
export const ContentContainer = styled.div`
display: flex;
flex-direction: column;
min-width: 365px;
width: 100%;
max-width: 600px;
/* width: 365px; */
justify-content: space-between;
@media(max-width: 768px) {
min-width: 50%;
width: 50%;
}
@media(max-width: 600px) {
width: 100%;
min-width: 100%;
}
`
export const ContentTitle = styled.h2`
margin: 0;
padding: 0;
margin-bottom: 24px;
font-size: 24px;
color: #F9F9F9;
line-height: 33px;
@media(max-width: 500px) {
font-size: 20px;
line-height: 26px;
margin-bottom: 16px;
}
`
export const ContentDescription = styled.div`
font-size: 14px;
line-height: 20px;
letter-spacing: 0.3px;
color: #F9F9F9;
@media(max-width: 500px) {
font-size: 14px;
line-height: 18px;
}
`
export const ContentBody = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
width: 100%;
height: 100%;
padding: 10px 33px 10px 60px;
>div >ul {
padding-inline-start: 0px;
}
@media(max-width: 600px) {
width: 100%;
padding: 10px 33px 10px 8%;
height: 252px;
}
`
export const ActionButton = styled(CustomButton)`
border-color: ${props => props.color};
width: 100%;
max-width: 100%;
z-index: 1;
overflow: hidden;
@media (min-width: 600px) {
::after {
content: "";
background-color: ${props => props.color};
position: absolute;
z-index: -1;
padding: 0.85em 0.75em;
display: block;
left: -20%;
right: -20%;
top: 0;
bottom: 0;
transform: skewX(-45deg) scale(0, 1);
transition: all 0.4s ease;
}
:hover {
/* transition-duration: 0.4s; */
transition: all 0.4s ease-out;
::after {
transform: skewX(-45deg) scale(1, 1);
}
>img {
transition-duration: 0.2s;
transform: scale(1)
}
}
}
>img {
transition-duration: 0.2s;
transform: scale(0)
}
@media(max-width: 600px) {
background-color: ${props => props.color};
}
`
export const PreviewImage = styled.div`
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
> img {
flex-shrink: 0;
min-width: 100%;
min-height: 100%
}
@media(max-width: 600px) {
height: 320px;
}
`
export const CaseLogo = styled.img`
/* width: 100%; */
/* height: 100%; */
/* object-fit: cover; */
`
export const CaseLogoContainer = styled.div`
/* max-height: 96px; */
/* /* max-width: 200px; */
margin-bottom: 40px;
@media(max-width: 770px) {
/* max-height: 66px;
max-width: 140px; */
margin-bottom: 35px;
}
@media(max-width: 650px) {
/* max-height: 56px;
max-width: 140px; */
margin-bottom: 30px;
}
@media(max-width: 500px) {
/* max-height: 46px;
max-width: 120px; */
margin-bottom: 28px;
}
`<file_sep>/src/components/Header/DropdownMenu/dropdown-menu.component.jsx
import React, { useContext } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
import {
DropdownMenuWrapper,
DropdownMenuContainer,
WhiteSpace,
LinksWrapper,
LinksCell
} from './dropdown-menu.styles';
import { MenuContext } from '../../../context/menu-state';
import { colorSelectors } from '../../../redux/color/color.selectors';
import { setScroll } from '../../../redux/scroll/scroll.actions';
import { useTranslation } from '../../../hooks/translation';
const DropdownMenu = () => {
const { isMenuOpen, toggleMenuMode } = useContext(MenuContext);
const color = useSelector(colorSelectors.color);
const { t } = useTranslation();
const { pathname } = useLocation()
const dispatch = useDispatch()
const history = useHistory()
const handleNavigation = (link) => {
switch (link) {
case 'typing':
if (pathname === '/') {
dispatch(setScroll('typing'))
} else {
dispatch(setScroll('typing'))
history.push('/')
}
break;
case 'services':
if (pathname === '/') {
dispatch(setScroll('services'))
} else {
dispatch(setScroll('services'))
history.push('/')
}
break;
case 'cases':
if (pathname === '/') {
dispatch(setScroll('cases'))
} else {
dispatch(setScroll('cases'))
history.push('/')
}
break;
case 'plan':
if (pathname === '/') {
dispatch(setScroll('plan'))
} else {
dispatch(setScroll('plan'))
history.push('/')
}
break;
case 'applicationAll':
history.push('/works/Application/all')
break;
case 'websiteAll':
history.push('/works/Website/all')
break;
case 'application':
history.push('/services/Application')
break;
case 'website':
history.push('/services/Website')
break;
case 'service':
history.push('/services/Service')
break;
case 'guarantees':
history.push('/guarantees')
break;
case 'cooperation':
history.push('/cooperation')
break;
default:
break;
}
toggleMenuMode()
}
return (
<DropdownMenuWrapper open={isMenuOpen} color={color}>
<DropdownMenuContainer>
<WhiteSpace />
<LinksWrapper>
{/* <LinksCell color={color}>
<span to='/' onClick={() => handleNavigation('typing')}>
{t('main_page')}
</span>
<span onClick={() => handleNavigation('services')}>
{t('services')}
</span>
<span onClick={() => handleNavigation('cases')}>
{t('cases')}
</span>
<span onClick={() => handleNavigation('plan')}>
{t('work_plan')}
</span>
</LinksCell> */}
<LinksCell color={color}>
<span onClick={() => handleNavigation('applicationAll')}>
{t('apps')}
</span>
<span onClick={() => handleNavigation('websiteAll')}>
{t('sites')}
</span>
</LinksCell>
<LinksCell color={color}>
<span onClick={() => handleNavigation('application')}>
{t('apps')}
</span>
<span onClick={() => handleNavigation('website')}>
{t('sites')}
</span>
<span onClick={() => handleNavigation('service')}>
{t('other_services')}
</span>
</LinksCell>
{/* <LinksCell color={color}>
<span onClick={() => handleNavigation('guarantees')}>
{t('guarantees')}
</span>
<span onClick={() => handleNavigation('cooperation')}>
{t('collaboration')}
</span>
</LinksCell> */}
{/* <LinksCell color={color}>
</LinksCell> */}
</LinksWrapper>
<LinksCell color={color}>
{/* <a href='tel:+79995357879'>
8 999 535 78 79
</a>
<a href='mailto:<EMAIL>'>
Email
</a>
<a href='tg://resolve?domain=lilekov_evgeniy'>
Telegram
</a>
<a href="https://wa.me/79995357879" target='_blank' rel='nofollow noopener noreferrer'>
WhatsApp
</a>
<a href='viber://add?number=79995357879' target="_blank" rel='nofollow noopener noreferrer'>
Viber
</a> */}
</LinksCell>
</DropdownMenuContainer>
</DropdownMenuWrapper>
);
}
export default DropdownMenu;<file_sep>/src/App.styles.jsx
import styled from 'styled-components';
export const AppWrapper = styled.div`
min-height: 100vh;
width: 100%;
overflow-x: hidden;
background-color: #0a0a0a;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
-webkit-overflow-scrolling: auto;
`
export const AppContainer = styled.div`
width: 100%;
/* max-width: 956px; */
max-width: 1200px;
margin: 70px auto 0 auto;
z-index:1;
-webkit-overflow-scrolling: auto;
/* padding: 0 20px;
@media(max-width: 768px) {
padding: 10px;
} */
`<file_sep>/src/pages/NotFound/not-found.styles.jsx
import styled from 'styled-components'
import { CustomButton } from '../../styles/common'
export const NotwFoundWrapper = styled.div`
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
padding: 80px 0;
`
export const ImageWrapper = styled.div`
position: relative;
z-index: 1;
>svg {
position: relative;
z-index: 50;
>path:last-of-type {
fill: ${props => props.color};
}
}
`
export const DescriptionWrapper = styled.div`
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
`
export const DescriptionLabel = styled.span`
font-weight: ${props => props.color ? 'normal' : '600'};
font-size: 16px;
line-height: 27px;
color: ${props => props.color ? props.color : '#F9F9F9'};
text-align: center;
margin-bottom: 20px;
`
export const CustomLink = styled(CustomButton)`
border-color: ${props => props.color};
background-color: ${props => props.color};
margin-top: 4px;
`
export const GhostWrapper = styled.div`
position: absolute;
bottom: 53px;
left: 156px;
z-index: 10;
overflow: hidden;
width: 52px;
height: 100px;
animation: ${props => props.hover ? 'ghostHover 1.5s infinite' : 'none'};
>svg {
transform: translateX(${props => props.translate});
transition-duration: 0.8s;
position: absolute;
bottom: 18px;
left: -13px;
}
@keyframes ghostHover {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-3px);
}
100% {
transform: translateY(0);
}
}
`
export const UfoWrapper = styled.div`
position: absolute;
top: 0;
left: 60px;
transition-duration: 1.5s;
transform: translateX(${props => props.translate});
animation: ${props => props.hover ? 'hover 1.5s infinite' : 'none'};
>svg{
>path:first-of-type {
fill: ${props => props.color};
}
}
@keyframes hover {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-5px);
}
100% {
transform: translateY(0);
}
}
`
export const UfoGlowWrapper = styled.div`
position: absolute;
bottom: 26px;
left: 50px;
visibility: ${props => props.blink ? 'visible' : 'hidden'};
transition-duration: 0.4s;
>svg {
>path {
fill: ${props => props.color};
}
}
`<file_sep>/src/components/Tabs/tabs.component.jsx
import React, { useEffect, useState, Fragment, useRef } from 'react';
import { useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom/cjs/react-router-dom.min';
import { useWindowDimensions } from '../../hooks/dimensions';
import { colorSelectors } from '../../redux/color/color.selectors';
import BottomTabBar from '../BottomTab/bottom-tab.component';
import {
AnimatedLine,
TabHeader,
TabsHeader,
TabsHeaderOuterContainer,
TabBodyContainer
} from './tabs.styles';
const Tabs = ({
children,
tabNames,
tabOverride,
tabNamesEng,
language,
changeCurrentTub = false
}) => {
const [currentTab, setCurrentTab] = useState(tabOverride ? tabOverride : 0)
const color = useSelector(colorSelectors.color)
const headerRef = useRef()
const [animatedLineStyles, setAnimatedLineStyles] = useState({ width: 0, offset: 0 })
const { width } = useWindowDimensions()
const { pathname } = useLocation()
useEffect(() => {
if (width > 612) {
const rect = headerRef.current.children[currentTab].getBoundingClientRect()
const parentOffset = headerRef.current?.offsetLeft
const width = headerRef.current ? rect.width : 0
const offset = headerRef.current ? rect.left - parentOffset : 0
setAnimatedLineStyles({ width: width, offset: offset })
}
}, [currentTab, width, language])
useEffect(() => {
if (changeCurrentTub) {
changeCurrentTub(currentTab)
}
}, [currentTab, changeCurrentTub])
const handleTabChange = (index) => {
localStorage.setItem('requestType', 'tab: ' + tabNames[index] + ' page: ' + pathname)
setCurrentTab(index)
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
})
}
return (
<Fragment>
<TabsHeaderOuterContainer>
{
width > 612 ?
<Fragment>
<TabsHeader
ref={headerRef}
>
{
tabNames.map((name, index) => {
const ref = React.createRef()
return <TabHeader
key={index}
onClick={() => handleTabChange(index)}
color={color}
ref={ref}
active={index === currentTab}
animate={{
color: index === currentTab ? color : '#f9f9f9',
}}
transition={{
duration: 0.3
}}
>
{language === 'ru' ? name : tabNamesEng[index]}
</TabHeader>
})
}
</TabsHeader>
<AnimatedLine
animate={{
width: animatedLineStyles.width,
x: animatedLineStyles.offset
}}
transition={{
duration: 0.3
}}
color={color}
/>
</Fragment>
:
<BottomTabBar
tabNames={tabNames}
currentTab={currentTab}
onTabClick={handleTabChange}
/>
}
</TabsHeaderOuterContainer>
<TabBodyContainer>
{/* <AnimatePresence> */}
{
children.map((child, index) => {
return (
<Fragment
key={index}
>
{
currentTab === index ?
child
: null
}
</Fragment>
)
})
}
{/* </AnimatePresence> */}
</TabBodyContainer>
</Fragment>
)
}
export default Tabs;<file_sep>/src/components/SectionTyping/section-typing.components.jsx
import React, { useRef, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { TypingWrapper, Text } from './section-typing.styles';
import TypingText from '../TypingText/typing-text.component';
import { scrollSelectors } from '../../redux/scroll/scroll.selectors';
import { setScroll } from '../../redux/scroll/scroll.actions';
import { useTranslation } from '../../hooks/translation';
const SectionTyping = () => {
const dispatch = useDispatch()
const scroll = useSelector(scrollSelectors.to)
const ref = useRef()
const { t } = useTranslation();
useEffect(() => {
if (scroll === 'typing') {
window.scroll({
behavior: 'smooth',
top: 0,
left: 0
})
dispatch(setScroll(undefined))
}
}, [scroll, dispatch])
return (
<TypingWrapper ref={ref}>
<Text> {t('we_develop')} </Text>
<TypingText textsArray={[
t('mobile_apps'),
t('website'),
t('interfaces'),
t('promotion_strategies')
]} />
</TypingWrapper>
);
}
export default SectionTyping;<file_sep>/src/redux/language/language.actions.jsx
import {constants} from './language.constants';
export const setLanguage = (lang) => {
const action = {
type: constants.SET_LANGUAGE,
payload: {lang}
};
return action;
}<file_sep>/src/pages/Services/services.component.jsx
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useSelector } from 'react-redux'
import Tabs from '../../components/Tabs/tabs.component';
import {
PageContainer,
PageHeader,
PageTitle,
Button
} from './services.styles';
import { useWindowDimensions } from '../../hooks/dimensions';
import SectionRequest from '../../components/SectionRequest/section-request.component';
import { contentSelectors } from '../../redux/content/content.selectors';
import ServiceTab from '../../components/ServiceTab/service-tab.component';
import { useTranslation } from '../../hooks/translation';
import ModalRequest from '../../components/ModalRequest/modal-request.component';
import { colorSelectors } from '../../redux/color/color.selectors';
const ServicesPage = () => {
const { itemId, section } = useParams()
const { width } = useWindowDimensions()
const services = useSelector(contentSelectors.services)
const works = useSelector(contentSelectors.cases)
const { t, language } = useTranslation()
const [currentTab, setCurrentTub] = useState(0)
const [openModal, setOpenModal] = useState(false)
const color = useSelector(colorSelectors.color)
const onOpenModal = () => {
setOpenModal(true)
}
const onCloseModal = () => {
setOpenModal(false)
}
const changeCurrentTub = (tab) => {
setCurrentTub(tab)
}
useEffect(() => {
window.scrollTo(0, 0)
if (itemId === 'all') {
window.scrollTo(0, 0)
}
return () => {
localStorage.setItem('scroll', 'false')
}
}, [itemId])
return (
<PageContainer>
<PageHeader
>
<PageTitle>
{t('services') + ':'}
</PageTitle>
</PageHeader>
{
services ?
<Tabs
tabNames={['Мобильные приложения', 'Сайты', 'Доп.услуги']}
tabNamesEng={['Mobile apps', 'Websites', 'Other services']}
language={language}
tabOverride={section === 'Website' ? 1 : section === 'Service' ? 2 : undefined}
changeCurrentTub={changeCurrentTub}
>
{services.map((service, index) => {
return <ServiceTab
key={index}
service={service}
currentTab={currentTab}
works={works}
/>
})}
</Tabs>
: null
}
{
width > 800 ?
<SectionRequest index={2} padding={'0px'} nonNumber={true} closeModal={onCloseModal} /> :
<Button onClick={onOpenModal} color={color}>
{t('leave_request')}
</Button>
}
<ModalRequest
open={openModal}
onClose={onCloseModal}
/>
</PageContainer>
)
}
export default ServicesPage;<file_sep>/src/components/PortfolioExampleImages/portfolio-example-images.component.jsx
import React from 'react';
import {
TableWrapper,
ItemWrapper,
AppTitle,
AppDescription,
DescriptionWrapper,
TitleWrapper,
PortfolioExampleWrapper,
TableWrapperMobile,
ItemWrapperMobile,
AdditionalInfo,
} from './portfolio-example-images.styles';
import examplePng from '../../assets/example.png';
import examplePngTwo from '../../assets/example_2.png';
const PortfolioExampleImages = () => {
const caseItem = {
images: [{id: 1, source: examplePng},
{id: 2, source: examplePng},
{id: 3, source: examplePngTwo},
{id: 4, source: examplePng},
{id: 5, source: examplePng},
{id: 6, source: examplePngTwo},
{id: 7, source: examplePngTwo},
{id: 8, source: examplePng},
],
numColumns: 4,
title: 'Название приложения',
description: {
partOne: `Приложение для изучения башкирского делового языка, с возможностью тренировки и проверки знаний, с дополнительным функционалом, который позволял бы закреплять и тестировать знания. Цель – научить русскоязычных пользователей понимать документацию на башкирском языке.`,
partTwo: `Разработанное нами приложение полностью выполняет свою функцию – помогает изучить башкирский деловой язык с нуля и здесь же можно проверить свои знания. Оно было многократно протестировано на разных устройствах, показало высокую надёжность и удобство в использовании`,
addInfo: 'Тут какая-нибудь доп информация',
}
}
function makeFullScreen(itemId) {
var divObj = document.getElementById(itemId);
if (divObj.requestFullscreen) {
divObj.requestFullscreen();
}
else if (divObj.msRequestFullscreen) {
divObj.msRequestFullscreen();
}
else if (divObj.mozRequestFullScreen) {
divObj.mozRequestFullScreen();
}
else if (divObj.webkitRequestFullscreen) {
divObj.webkitRequestFullscreen();
} else {
}
}
function detectDevice(){
return !!navigator.maxTouchPoints ? 'mobile' : 'computer'
}
return (
<PortfolioExampleWrapper>
<TitleWrapper>
<AppTitle>
{caseItem.title}
</AppTitle>
</TitleWrapper>
<DescriptionWrapper device={detectDevice()}>
<AppDescription>
{caseItem.description.partOne}
</AppDescription>
<AppDescription>
{caseItem.description.partTwo}
</AppDescription>
</DescriptionWrapper>
{
caseItem.description.addInfo ?
<AdditionalInfo device={detectDevice()}>
{caseItem.description.addInfo}
</AdditionalInfo>
:
<div />
}
{
detectDevice() === 'computer' ?
<TableWrapper>
{
caseItem.images.map((item) => {
return (
<ItemWrapper
id={item.id}
key={item.id}
columns={caseItem.numColumns}
src={item.source}
onClick={()=>makeFullScreen(item.id)}
/>
)
})
}
</TableWrapper>
:
<TableWrapperMobile>
{
caseItem.images.map((item) => {
return (
<ItemWrapperMobile
id={item.id}
key={item.id}
src={item.source}
onClick={()=>makeFullScreen(item.id)}
/>
)
})
}
</TableWrapperMobile>
}
</PortfolioExampleWrapper>
);
}
export default PortfolioExampleImages;<file_sep>/src/assets/translation/ru.js
export const ru = {
menu: 'Меню',
services: 'Услуги',
other: 'Разное',
contacts: 'Контакты',
main_page: 'Главная',
apps: 'Приложения',
sites: 'Сайты',
other_services: 'Доп. услуги',
cases: 'Кейсы',
guarantees: 'Гарантии',
collaboration: 'Сотрудничество',
we_develop: 'Мы разрабатываем :',
mobile_apps: 'Мобильные приложения',
website: 'Веб-сайты',
interfaces: 'Интерфейсы',
promotion_strategies: 'Стратегии продвижения',
web_interfaces: 'Веб-интерфейсы',
your_goals: 'Мы сможем вам помочь если:',
your_goals_idea: 'У вас есть идея для мобильного приложения, и вы не знаете с чего начать',
your_goals_product: 'У вас уже есть сайт и для привлечения новых пользователей вам необходимо мобильное приложение',
your_goals_site: 'Вам необходимо расширить уже существующий функционал',
your_goals_desc: 'Оставьте заявку - и мы сможем решить вашу проблему!',
// your_goals_desc: `Сразу после обращения мы решаем главную проблему – как обеспечить максимальную пользу от нашего продукта для клиента. Оставляя заявку - вы получаете оптимальное решение для вашего бизнеса.`,
go_to_portfolio: 'Перейти к портфолио',
about_us: 'Наша команда',
about_us_desc: `Мы все разные, но цель у нас одна - создание качественного продукта`,
services_desc: `Наша студия предоставляет полный спектр услуг
по созданию и продвижению сайтов, мобильных приложений и веб интерфейсов. Под разный бюджет.`,
mobile_apps_desc: 'Разработаем мобильное приложение под платформы Android или IOS с соблюдением современных стандартов и требований. Все этапы – от создания дизайна до готового продукта.',
websites_desc: 'Создание стильных и быстрых сайтов – одно из наших основных направлений. От идеи до публикации готового проекта, со строгим соблюдением сроков.',
more_button: 'Подробнее',
cases_desc: `Актуальные работы нашей студии с описанием задачи и её решением.`,
whole_work: 'Смотреть кейс',
all_works: 'Портфолио',
about_team: 'О нашей команде',
about_team_desc: `Создание сайтов и приложений – сложный и многогранный процесс, поэтому в нашей дружной команде работают специалисты разного профиля.`,
about_team_desc_second: `У нас есть верстальщики, дизайнеры, копирайтеры, менеджер. Это позволяет нам работать над проектом самостоятельно, от начала и до конца, без лишних задержек. Все наши специалисты имеют соответствующее образование, приобрели большой опыт в своей сфере и неоднократно принимали участие в работе над разными проектами различной сложности. Поэтому мы с уверенностью можем утверждать, что и Ваш заказ выполним максимально быстро и качественно.`,
work_plan: 'План работы',
work_plan_desc: `Cостоит из нескольких этапов, на каждом из которых привлекаются разные специалисты нашей команды. Это обеспечивает высокое качество и скорость разработки.`,
first_stage: 'Этап 1',
second_stage: 'Этап 2',
third_stage: 'Этап 3',
fourth_stage: 'Этап 4',
fifth_stage: 'Этап 5',
interview: 'Интервью',
interview_desc_intro_first: 'Этап интервью – один из важнейших. Он позволяет больше узнать о целях создания сайта или приложения, а также о результатах, которые должны быть достигнуты.',
interview_desc_intro: `Здесь мы с вашей помощью:`,
interview_desc_list_first: 'Узнаём ваши пожелания по дизайну и реализации проекта.',
interview_desc_list_second: 'Получаем информацию о вашем бизнесе для использования в работе.',
// interview_desc_list_third: 'Предложить вам некоторые полезные бонусы.',
interview_desc_outro: `Всё это нужно, чтобы готовый продукт был адаптирован именно под ваш бизнес,
полностью соответствовал вашим ожиданиям и выполнял свою работу на отлично.`,
analysis: 'Аналитика',
analysis_desc_intro: `На этом этапе мы проводим UX исследование вашего будущего проекта:`,
analysis_desc_list_first: 'Оцениваем нишу и анализируем основных конкурентов.',
// analysis_desc_list_second: 'Смотрим и анализируем основных конкурентов.',
analysis_desc_list_third: 'Решаем, какими методами лучше всего будет достичь результата.',
analysis_desc_outro: `Конечно, это только предварительный этап работы, который вас ни к чему не обязывает. Но здесь уже формируются пути и этапы работы. Появляется набросок плана, на основе которого можно построить дальнейший процесс разработки.`,
briefing: 'Брифирование',
briefing_desc_intro: `Этап создания брифа – один из важнейших. Он позволяет больше узнать о целях создания сайта или приложения, а также о результатах, которые должны быть достигнуты. Здесь мы с вашей помощью:`,
briefing_desc_list_first: 'Узнаём ваши пожелания по дизайну и реализации проекта.',
briefing_desc_second: 'Получаем информацию о вашем бизнесе для использования в работе.',
briefing_desc_outro: `Всё это нужно, чтобы готовый продукт был адаптирован именно под ваш бизнес, полностью соответствовал вашим ожиданиям и выполнял свою работу на отлично.`,
budget: 'Смета',
budget_desc: `На основе полученной информации мы уже имеем
полное представление, какой именно проект вы хотите получить
и какого результата достичь. И мы можем составить полный план
по его реализации – рассчитать, сколько времени это займёт у разных
специалистов команды и какие средства нужно будет использовать.`,
budget_desc_second: `На этом этапе мы уже можем предоставить вам
расчёт стоимости работы. Вы получите смету и будете точно знать,
сколько будет стоить ваш проект.`,
contract: 'Договор',
contract_desc: `Заключение договора – важный этап нашего
сотрудничества.`,
contract_desc_second: `Он подписывается после того, как
проект прошёл обсуждение и был утверждён.
После этого мы приступаем к работе над ним.`,
contract_desc_third: `Договор – официальный документ, который
закрепляет обязательства всех сторон. Так
как мы работаем официально, то составление
этого документа является обязательным. И мы
всегда выполняем все указанные в нём пункты.
Для каждого проекта он отличается, так как
объём работ и сроки бывают разными.`,
design_specification: 'Тех.задание',
design_specification_desc: `Разработка технического задания – основа
всей дальнейшей работы. Это план, по которому
будет проходить разработка, которая содержит
в себе много этапов. Чем подробнее задание,
тем меньше возникает задержек и прочих
непредвиденных ситуаций.`,
design_specification_desc_second: `На этапе проработки технического задания
становится понятно, какие именно специалисты
будут привлекаться и будет отведено
определённое время на их работу. Каждому
из них будет поставлена конкретная задача.`,
prototyping: 'Прототипирование',
prototyping_desc: `Тщательно пророботанный прототип сокращает время на дальнейших
этапах разработки. Он поможет вам представить проект в конечном виде и
внести корректировки до начала работ.`,
prototyping_desc_second: `Вложенное в прототип время сокращает количество
доработок, которые могут появиться по завершении разработки.`,
design: 'Дизайн',
design_desc: `От дизайнера зависит, как будет выглядеть сайт
или приложение, понравится ли будущим пользователям.`,
design_desc_second: `Этот важный этап является одним из ключевых – лишь
после него к работе подключаются разработчики. И здесь
наши клиенты уже могут увидеть, как будет выглядеть
их проект в итоге.`,
design_desc_third: `Все стадии работы проходят в тесном контакте с клиентом
и при необходимости вносятся корректировки. Одобренный
дизайн поступает в дальнейшую работу.`,
development: 'Разработка',
development_desc: `Этот этап отличается для каждого проекта и
представляет собственно его создание. В это
время все привлечённые специалисты работают
над своей частью технического задания.
В итоге получается завершённый продукт – сайт
или приложение, с полным функционалом, который
требовался клиенту.`,
development_desc_second: `Вы, как заказчик, получаете отчёты о ходе работы
над Вашим проектом и всегда знаете, на каком
этапе он находится.`,
testing: 'Тестирование',
testing_desc: `Создать сайт или приложение – ещё не всё и
просто передавать его клиентам сразу после
разработки опрометчиво. Поэтому мы сначала
проводим тестирование – проверяем готовый
продукт на разных устройствах, в разных
условиях, и находим все моменты, когда
сайт или приложение могут работать неправильно.
Все найденные проблемы устраняются.`,
testing_desc_second: `Вы получаете свой проект всесторонне
проверенным – мы гарантируем качество.`,
support: 'Сопровождение',
support_desc: `Даже после сдачи готового проекта некоторое
время он нуждается в сопровождении. В это
время наши клиенты получают всестороннюю
помощь от нашей команды, учатся обращаться
со своим новым сайтом или приложением.`,
support_desc_second: `На этом этапе вы всегда можете
рассчитывать на нашу помощь и обратиться с любыми вопросам.`,
scedule_button: 'Записаться',
leave_request: 'Оставить заявку',
leave_request_desc: `Закажите разработку проекта
или запишитесь на бесплатную консультацию и получите
наши рекомендации, узнайте стоимость и сроки разработки.`,
your_name: 'Ваше имя:',
your_phone: 'Номер телефона:',
your_email: 'E-mail:',
message: 'Сообщение',
attatch_file_button: 'Прикрепить файл',
request_sent: 'Заявка отправлена',
error_name: 'Введите имя',
error_phone: 'Введите корректный телефон',
error_no_email: 'Введите email',
error_invalid_email: 'Введите корректный email',
error_text: 'Напишите Ваше сообщение',
personal_data_agreement: `Нажимая “Отправить заявку” вы соглашаетесь с порядком обработки `,
personal_data_agreement_ref: 'персональных данных.',
adress_first: '127015, Москва,',
adress_second: 'Большая Новодмитровская улица, 23с6',
privacy_policy: 'Политика конфиденциальности',
go_to_map_button: 'Перейти к карте',
portfolio: 'Портфолио',
cooperation_desc: `Мы открыты для сотрудничества с другими организациями или специалистами, связанными с разработкой сайтов или программного обеспечения для мобильных устройств. Если вы заинтересованы в этом, то можете оставить здесь свою заявку или связаться с нашим менеджером. Мы рассмотрим ваше предложение в короткие сроки и ответим вам по указанным контактам.`,
guarantees_desc: `Мы работаем официально и предоставляем своим клиентам различные виды гарантий. Поэтому вы можете быть спокойны насчёт того, что ваш проект будет выполнен строго по заданию, в указанные сроки, и переплачивать ничего сверх договора не придётся. Если мы берёмся за работу, то относимся к ней с полной ответственностью.`,
guarantees_law: 'Юридические:',
guarantees_law_desc_first: `После детального изучения проекта и перед тем как начать им заниматься, мы документируем все этапы работы и составляем договор.`,
guarantees_law_desc_second: `В нём прописаны все сроки и стоимость работ, как по этапам, так и общая.`,
guarantees_law_desc_third: `Этим мы гарантируем нашим клиентам получение выполненного проекта в срок.`,
guarantees_law_desc_fourth: `Для нас же это стимул обозначенные сроки строго соблюдать. Также в договоре прописана наша ответственность в случае нарушения нами сроков.`,
guarantees_tech: 'Технические:',
guarantees_tech_desc_intro: 'Мы обеспечиваем качество готового проекта:',
guarantees_tech_desc_list_first: 'При составлении ТЗ учитываем получение наилучших результатов.',
guarantees_tech_desc_list_second: 'В работе используем только самые современные и надёжные технологии.',
guarantees_tech_desc_list_third: 'Перед сдачей проводим разностороннее тестирование и устраняем все найденные проблемы.',
guarantees_tech_desc_outro: 'Передача проекта происходит только после того, как он полностью готов и прошёл многократную проверку.',
guarantees_manage: 'Организационные:',
guarantees_manage_desc_intro: 'Процесс разработки у нас полностью прозрачен для клиента:',
guarantees_manage_desc_list_first: 'Мы регулярно высылаем отчёты по проделанной работе.',
guarantees_manage_desc_list_second: 'Даём возможность посмотреть, что сделано на данный момент и попробовать готовый функционал.',
guarantees_manage_desc_outro: 'Вы всегда будете в курсе продвижения работы по вашему заказу и сможете сами видеть процесс, и даже участвовать в нём.',
guarantees_support: 'Вспомогательные:',
guarantees_support_desc_intro: 'Даже когда ваш проект готов, и вы его приняли, мы не оставим вас с ним наедине:',
guarantees_support_desc_list_first: 'Составим план развития или продвижения на ближайшее время.',
guarantees_support_desc_list_second: 'Будем устранять найденные недостатки в течении года в рамках гарантийного обслуживания.',
guarantees_support_desc_outro: 'В будущем при необходимости по вашему запросу мы сможем быстро добавлять или изменять функционал – как авторам, нам это будет сделать гораздо проще, чем сторонним программистам.',
error_happened: `Произошла ошибка`,
error_beign_fixed: `Мы работаем над решением проблемы`,
error_to_main_page: `Вернуться на главную`,
notfound_desc_first: 'ОООООПС! Страницы, которую вы ищите не существует',
notfound_desc_second: 'Перейдите на главную страницу, пожалуйста',
notfound_button_label: 'Вернуться на главную',
contacts_requisites: 'Реквизиты компании',
service_analytics: "Выявление Ваших потребностей, анализ ЦА и конкурентов, уточнение, планирование и составление ТЗ ",
service_prototype: "Черновая реализация с базовой функциональностью для анализа работы приложения",
service_design: "Определения тематики мобильного приложения, правки и утверждения дизайна",
service_development: "Верстка экранов мобильного приложения, подключение, настройка, тестирование и отладка ",
service_publication: "Прохождение модерации и требований для публикации ",
service_analytics_title: "Аналитика и оценка",
service_prototype_title: "Прототипирование ",
service_design_title: "Разработка дизайна",
service_development_title: "Разработка приложения",
service_publication_title: "Публикация в сторах",
service_analytics_web: "Выявляение Ваших потребнстей, анализ ЦА и конкурентов, уточнение, планирование и составление ТЗ ",
service_prototype_web: "Черновая реализация сайта с базовой функциональностью для анализа работы ",
service_design_web: "Определения тематики сайта, правки и утверждения дизайна",
service_development_web: "Верстка страниц сайта, подключение, настройка, тестирование и отладка ",
service_publication_web: "Прохождение модерации и требований для публикации ",
service_analytics_title_web: "Аналитика и оценка",
service_prototype_title_web: "Прототипирование ",
service_design_title_web: "Разработка дизайна",
service_development_title_web: "Разработка сайта",
service_publication_title_web: "Публикация в сеть",
job_developer: "Developer",
job_full_stack: "Full Stack Developer",
job_front_developer: "Frontend/App Developer",
job_backend_developer: "Backend Developer",
job_mobile_developer: "Mobile Apps Developer",
job_designer: "UI/UX Designer",
job_manager: "Project manager",
job_jenya: "Chief/Backend Developer",
Lilekov_Evgeniy: '<NAME>',
Kotler_Roman: '<NAME>',
Sergey_Yukhanov: '<NAME>',
Andrey_Eruh: '<NAME>',
Anna_Kulikova: '<NAME>',
Nasir_Imanov: '<NAME>',
Sergey_Luchinkin: '<NAME>',
Olga_Salnikova: '<NAME>'
}<file_sep>/src/components/TypingText/typing-text.styles.jsx
import styled from 'styled-components';
export const TypingTextWrapper = styled.div`
height: 60px;
color: ${props => props.color};
.Typist {
display: flex;
align-items: center;
.Cursor {
z-index: 1;
height: 42px;
>div {
background-color:${props => props.color};
}
@media (max-width: 700px) {
height: 36px;
}
@media (max-width: 600px) {
height: 32px;
}
@media (max-width: 500px) {
height: 26px;
}
@media (max-width: 430px) {
height: 24px;
}
@media (max-width: 400px) {
height: 22px;
}
@media (max-width: 370px) {
height: 20px;
}
}
}
`
export const Text = styled.span`
color: ${props => props.color};
margin-right: 10px;
font-weight: 800;
font-size: 42px;
line-height: 50px;
letter-spacing: 1.5px;
position: relative;
@media (max-width: 700px) {
font-size: 36px;
line-height: 44px;
}
@media (max-width: 600px) {
font-size: 32px;
line-height: 40px;
}
@media (max-width: 500px) {
font-size: 26px;
line-height: 34px;
}
@media (max-width: 430px) {
font-size: 24px;
line-height: 30px;
letter-spacing: 0;
}
@media (max-width: 400px) {
font-size: 22px;
line-height: 28px;
margin-right: 5px;
}
@media (max-width: 370px) {
font-size: 20px;
line-height: 26px;
}
`
export const CursorWrapper = styled.div`
display: inline-flex;
width: 5px;
height: 42px;
opacity: 1;
animation: blink 1.2s linear infinite;
@keyframes blink {
0% { opacity: 1.0; }
50% { opacity: 0.0; }
100% { opacity: 1.0; }
}
@media (max-width: 700px) {
height: 36px;
width: 3px;
}
@media (max-width: 600px) {
height: 32px;
}
@media (max-width: 500px) {
height: 26px;
}
@media (max-width: 430px) {
height: 24px;
}
@media (max-width: 400px) {
height: 22px;
}
@media (max-width: 370px) {
height: 20px;
}
`<file_sep>/src/pages/Cooperation/cooperation.component.jsx
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import Section from '../../components/Common/Section/section.component';
import ModalRequest from '../../components/ModalRequest/modal-request.component';
import SectionRequest from '../../components/SectionRequest/section-request.component';
import { useWindowDimensions } from '../../hooks/dimensions';
import { useTranslation } from '../../hooks/translation';
import { colorSelectors } from '../../redux/color/color.selectors';
import {
CooperationWrapper,
Button
} from './cooperation.styles';
const Cooperation = () => {
const { t } = useTranslation();
const [openModal, setOpenModal] = useState(false)
const color = useSelector(colorSelectors.color)
const { width } = useWindowDimensions()
const onOpenModal = () => {
setOpenModal(true)
}
const onCloseModal = () => {
setOpenModal(false)
}
useEffect(() => {
window.scrollTo(0, 0)
}, [])
return (
<CooperationWrapper>
<Section
index={1}
nonNumber={true}
title={t('collaboration')}
description={t('cooperation_desc')}
descriptionWidth={'610px'}
headerContainerStyles={{
marginTop: '110px',
marginBottom: '0px',
}}
/>
{
width > 800 ?
<SectionRequest index={2} padding={'0px'} nonNumber={true} /> :
<Button onClick={onOpenModal} color={color}>
{t('leave_request')}
</Button>
}
<ModalRequest
open={openModal}
onClose={onCloseModal}
/>
{/* <SectionRequest index={2} /> */}
</CooperationWrapper>
)
}
export default Cooperation;<file_sep>/src/components/ServicesItemWrapper/Slider/slider.component.jsx
import { useAnimation, useMotionValue } from 'framer-motion';
import React, { useEffect, useRef, useState } from 'react';
import {
SliderContainer
} from './slider.styles';
const Slider = ({ children, width }) => {
const x = useMotionValue(0)
const containerRef = useRef()
const [dragConstraints, setDragConstraints] = useState(0)
const dragControl = useAnimation()
useEffect(() => {
if (containerRef.current) {
const sliderWidth = containerRef.current.getBoundingClientRect().width
setDragConstraints(width - sliderWidth)
}
}, [width])
return (
<div style={{ position: 'relative' }}>
<div style={{ overflow: 'hidden' }} ref={containerRef}>
<SliderContainer
dragDirectionLock={true}
drag="x"
initial={{ x: 0 }}
style={{ x, }}
animate={dragControl}
dragConstraints={{
left: -dragConstraints,
right: 0
}}
dragTransition={{ bounceDamping: 10, bounceStiffness: 100 }}
>
{children}
</SliderContainer>
</div>
</div>
)
}
export default Slider;<file_sep>/src/components/Header/Navbar/navbar.component.jsx
import React, { useContext, useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import {
NavbarContainer,
ButtonsWrapper,
LangToggleButton,
CustomLink,
DropdownMenuWrapper,
DropDownContainer,
LinksCell,
Link
} from './navbar.styles';
import MenuButton from '../MenuButton/menu-button.component';
import { MenuContext } from '../../../context/menu-state';
import Logo from '../../Logo/logo.component';
import { colorSelectors } from '../../../redux/color/color.selectors';
import { useTranslation } from '../../../hooks/translation';
import { setLanguage } from '../../../redux/language/language.actions'
const Navbar = ({
openMenu,
setOpenMenu,
setBackgroundWidth,
backgroundWidth
}) => {
const themeColor = useSelector(colorSelectors.color);
const { isMenuOpen } = useContext(MenuContext);
const { t, language } = useTranslation();
const dispatch = useDispatch();
const history = useHistory()
const [menuVisible, setMenuVisible] = useState(0)
const toggleLang = (bName) => {
let lang = bName === 'ru' ? 'en' : 'ru';
dispatch(setLanguage(lang))
}
const handleNavigation = (link) => {
switch (link) {
case 'applicationAll':
history.push('/works/Application/all')
break;
case 'websiteAll':
history.push('/works/Website/all')
break;
case 'application':
history.push('/services/Application')
break;
case 'website':
history.push('/services/Website')
break;
case 'service':
history.push('/services/Service')
break;
case 'guarantees':
history.push('/guarantees')
break;
case 'cooperation':
history.push('/cooperation')
break;
default:
break;
}
setOpenMenu(0)
setMenuVisible(0)
}
const handleOpenMenu = (numbTub) => {
let tab
if (numbTub === 1) {
switch (openMenu) {
case 0:
tab = 1
break;
case 1:
tab = 0
break;
case 2:
tab = 1
break;
default:
tab = 0
break;
}
}
if (numbTub === 2) {
switch (openMenu) {
case 0:
tab = 2
break;
case 1:
tab = 2
break;
case 2:
tab = 0
break;
default:
tab = 0
break;
}
}
setOpenMenu(tab)
}
const variants = {
open: ({ item }) => ({
opacity: 1,
y: '0px',
transition: {
duration: item * 0.1
}
}),
close: ({ item, count }) => ({
opacity: 0,
y: `-${item * 35}px`,
transition: {
duration: item * 0.1
}
})
}
useEffect(() => {
if (openMenu === 1) {
setMenuVisible(1)
}
if (openMenu === 2) {
setMenuVisible(2)
}
}, [openMenu])
return (
<NavbarContainer open={isMenuOpen}>
<Logo setOpenMenu={setOpenMenu} />
<ButtonsWrapper>
{/* <MenuButton> {t('menu')} </MenuButton> */}
<DropdownMenuWrapper>
<MenuButton
isOpen={openMenu === 1}
onOpen={() => handleOpenMenu(1)}
>
{t('portfolio')}
</MenuButton>
<DropDownContainer visible={menuVisible === 1} none={backgroundWidth}>
<LinksCell color={themeColor}>
<Link
color={themeColor}
custom={{
item: 1,
count: 2
}}
animate={openMenu === 1 ? 'open' : 'close'}
variants={variants}
onClick={() => handleNavigation('applicationAll')}
>
{t('apps')}
</Link>
<Link
color={themeColor}
custom={{
item: 2,
count: 2
}}
animate={openMenu === 1 ? 'open' : 'close'}
variants={variants}
onClick={() => handleNavigation('websiteAll')}
onAnimationComplete={() => {
if (openMenu === 0) {
setBackgroundWidth(false)
setMenuVisible(0)
}
}}
>
{t('sites')}
</Link>
</LinksCell>
</DropDownContainer>
</DropdownMenuWrapper>
<DropdownMenuWrapper>
<MenuButton
isOpen={openMenu === 2}
onOpen={() => handleOpenMenu(2)}
>
{t('services')}
</MenuButton>
<DropDownContainer visible={menuVisible === 2} none={backgroundWidth}>
<LinksCell color={themeColor}>
<Link
color={themeColor}
custom={{
item: 1,
count: 3
}}
animate={openMenu === 2 ? 'open' : 'close'}
variants={variants}
onClick={() => handleNavigation('application')}
>
{t('apps')}
</Link>
<Link
color={themeColor}
custom={{
item: 2,
count: 3
}}
animate={openMenu === 2 ? 'open' : 'close'}
variants={variants}
onClick={() => handleNavigation('website')}
>
{t('sites')}
</Link>
<Link
color={themeColor}
custom={{
item: 3,
count: 3
}}
animate={openMenu === 2 ? 'open' : 'close'}
variants={variants}
onClick={() => handleNavigation('service')}
onAnimationComplete={() => {
if (openMenu === 0) {
setBackgroundWidth(false)
setMenuVisible(0)
}
}}
>
{t('other_services')}
</Link>
</LinksCell>
</DropDownContainer>
</DropdownMenuWrapper>
<CustomLink customMargin onClick={() => history.push('/cooperation')} > {t('collaboration')}</CustomLink>
<CustomLink onClick={() => history.push('/contacts')} > {t('contacts')}</CustomLink>
</ButtonsWrapper>
<div>
<a href='tel:+79995357879'>
<CustomLink color={themeColor}>
8 999 535 78 79
</CustomLink>
</a>
<LangToggleButton
onClick={(e) => toggleLang(e.nativeEvent.target.name)} name={language} >
{language}
</LangToggleButton>
</div>
{/* <MenuButton color={themeColor}>{t('contacts')}</MenuButton> */}
</NavbarContainer>
);
}
export default Navbar;<file_sep>/src/components/WorkItem/work-item.styles.jsx
import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
padding: 34px 70px 34px 70px;
display: flex;
flex-direction: column;
background: #111111;
margin-top: 110px;
/* margin-bottom: 20px; */
@media(max-width: 600px) {
margin-top: 50px;
padding: 30px;
}
@media(max-width: 450px) {
margin-top: 50px;
padding: 25px 15px;
}
`
export const Title = styled.h3`
font-weight: 500;
font-size: 24px;
line-height: 20px;
color: #F9F9F9;
`
export const TextContent = styled.div`
display: flex;
width: 100%;
justify-content: space-between;
@media(max-width: 600px) {
flex-direction: column;
}
`
export const TextSection = styled.p`
width: 47%;
font-weight: 200;
font-size: 14px;
line-height: 20px;
letter-spacing: 0.3px;
color: #F9F9F9;
@media(max-width: 600px) {
width: 100%;
margin-bottom: 10px;
}
`
export const SliderContainer = styled.div`
width: 100%;
margin-top: 60px;
@media(max-width: 600px) {
margin-top: 30px;
}
`
export const SlideImage = styled.img`
/* width: auto !important; */
padding: 0px 5px;
/* cursor: pointer; */
user-select: none;
`
export const SlideContainer = styled.div`
display: flex;
justify-content: center;
:focus {
outline: none !important
}
`<file_sep>/src/components/AnimatedHeaderMobile/AnimatedHeaderSection/animated_header_section.styles.jsx
import styled from 'styled-components';
export const AnimatedHeaderSectionContainer = styled.div`
width: 100%;
max-width: 500px;
display: flex;
flex-direction: column;
align-items: flex-start;
margin-bottom: 50px;
`
export const SectionHeader = styled.span`
font-size: 20px;
line-height: 27px;
color: #fff;
opacity: 0.9;
margin-bottom: 10px;
`
export const SectionText = styled.span`
font-size: 14px;
line-height: 19px;
color: #fff;
opacity: 0.7;
`<file_sep>/src/components/ServiceTab/AnimatedDescription/AnimatedPath/animated_path.styles.jsx
import { motion } from 'framer-motion';
import styled from 'styled-components';
export const AnimatedGroup = styled.g`
>path {
fill: ${props => props.animationEnd? props.color : `url("#gradient${props.index}")`};
}
`
export const FirstStop = styled(motion.stop)`
`
export const SecondStop = styled(motion.stop)`
`
export const ThirdStop = styled(motion.stop)`
`<file_sep>/src/App.jsx
import React, { useEffect, useRef, useState } from 'react';
import { Redirect, Route, Switch, useLocation } from "react-router-dom";
import useErrorBoundary from "use-error-boundary";
import smoothscroll from 'smoothscroll-polyfill';
import { AppWrapper, AppContainer } from './App.styles';
import MenuState from './context/menu-state';
import Header from './components/Header/header.component';
import Footer from './components/Footer/footer.component';
import ErrorFallback from './components/ErrorFallback/error-fallback.component';
import Main from './pages/Main/main.component';
import WorksPage from './pages/Works/works.component';
import Cooperation from './pages/Cooperation/cooperation.component';
import Guarantees from './pages/Guarantees/guarantees.component';
import Loader from './components/Loader/loader.component';
import { useDispatch } from 'react-redux';
import { fetchContent } from './redux/content/content.actions';
import ServicesPage from './pages/Services/services.component';
import AnimatedBackground from './components/AnimatedBackground/animated-background.component';
import Contacts from './pages/Contacts/contacts.component';
import NotFound from './pages/NotFound/not-found.component';
smoothscroll.polyfill();
// window.__forceSmoothScrollPolyfill__ = true;
function App() {
// const [loading, setLoading] = useState(true)
const location = useLocation()
const { pathname } = useLocation()
const dispatch = useDispatch()
const containerRef = useRef()
// const addr = window.localStorage.getItem('address')
// const [websites, setWebsites] = useState(addr ? addr : 'contacts')
const [endLoader, setEndLoader] = useState(false)
const [animationHeight, setAnimationHeight] = useState(containerRef.current?.clientHeight)
// const setAddr = () => {
// setWebsites('kontakty')
// window.localStorage.setItem('address', 'kontakty')
// }
useEffect(() => {
localStorage.setItem('scroll', false)
}, [])
useEffect(() => {
setAnimationHeight(containerRef.current?.clientHeight)
localStorage.setItem('requestType', null)
}, [pathname])
useEffect(() => {
dispatch(fetchContent())
}, [dispatch])
const { ErrorBoundary, didCatch, error } = useErrorBoundary();
return (
<AppWrapper>
{
didCatch ? <ErrorFallback error={error} /> :
<ErrorBoundary>
<MenuState>
<Header />
</MenuState>
<AppContainer id="app-container" ref={containerRef}>
{/* <AnimatePresence > */}
<Switch location={location} key={location.pathname}>
<Redirect from="/:url*(/+)" to={pathname.slice(0, -1)} />
<Route exact path='/' component={Main} />
<Route exact path='/works/:section/:itemId' component={WorksPage} />
{/* <Route exact path='/works/:section/:itemId' component={WorksPage} /> */}
<Route exact path='/services/:section' component={ServicesPage} />
<Route exact path='/cooperation' component={Cooperation} />
<Route exact path='/guarantees' component={Guarantees} />
<Route exact path={`/contacts`} component={Contacts} />
<Route path='/' >
<NotFound endLoader={endLoader} error={error} />
</Route>
</Switch>
{/* </AnimatePresence> */}
{/* <button onClick={() => setAddr()}>change</button> */}
</AppContainer>
<AnimatedBackground animationHeight={animationHeight} />
<Footer />
</ErrorBoundary>
}
<Loader setEndLoader={setEndLoader} />
</AppWrapper>
);
}
export default App;<file_sep>/src/pages/Main/main.component.jsx
import React, { Fragment, useRef, useState } from 'react';
// import { useInView, InView } from 'react-intersection-observer';
import { MainWrapper } from './main.styles';
import SectionTyping from '../../components/SectionTyping/section-typing.components';
import SectionGoals from '../../components/SectionGoals/section-goals.component';
import ServicesSection from '../../components/ServicesSection/services-section.component';
import SectionWe from '../../components/SectionWe/section-we.component';
// import SectionAbout from '../../components/SectionAbout/section-about.component';
import SectionPlan from '../../components/SectionPlan/section-plan.component';
import SectionCases from '../../components/SectionCases/section-cases.component';
import ModalRequest from '../../components/ModalRequest/modal-request.component';
// import SectionRequest from '../../components/SectionRequest/section-request.component';
// import AnimatedBackground from '../../components/AnimatedBackground/animated-background.component';
const Main = () => {
const refCases = useRef();
const refApplication = useRef();
const [openModal, setOpenModal] = useState(false)
const onOpenModal = (key) => {
localStorage.setItem('requestType', key)
setOpenModal(true)
}
const onCloseModal = () => {
setOpenModal(false)
}
return (
<Fragment>
<MainWrapper>
<SectionTyping />
<SectionGoals onOpenModal={() => onOpenModal('Главная страница 1-й раздел')} />
<SectionWe />
<ServicesSection />
<SectionCases refCases={refCases} />
<SectionPlan refApplication={refApplication} onOpenModal={() => onOpenModal('Главная страница план работы')} />
<ModalRequest
open={openModal}
onClose={onCloseModal}
/>
</MainWrapper>
</Fragment>
);
}
export default Main;<file_sep>/src/redux/content/content.selectors.jsx
export const contentSelectors = {
cases: state => state.content.content.cases,
services: state => state.content.content.services,
}<file_sep>/src/redux/rootReducer.jsx
import { combineReducers } from 'redux';
import { colorReducer } from './color/color.reducer';
import { contentReducer } from './content/content.reducer';
import { languageReducer } from './language/language.reducer';
import { scrollReducer } from './scroll/scroll.reducer';
export const rootReducer = combineReducers({
color: colorReducer,
content: contentReducer,
scroll: scrollReducer,
language: languageReducer,
})<file_sep>/src/components/Header/MobileNavbar/mobile-navbar.component.jsx
import React, { useContext } from 'react';
import { useDispatch } from 'react-redux';
import {
Container,
IconButton,
LangToggleButton
} from './mobile-navbar.styles';
import { ReactComponent as BurgerSVG } from '../../../assets/burger.svg';
import { ReactComponent as PhoneSVG } from '../../../assets/phone.svg';
import { useSelector } from 'react-redux';
import { colorSelectors } from '../../../redux/color/color.selectors';
import Logo from '../../Logo/logo.component';
import { MenuContext } from '../../../context/menu-state';
import { useTranslation } from '../../../hooks/translation';
import { setLanguage } from '../../../redux/language/language.actions';
const MobileNavbar = ({ setOpenMenu }) => {
const color = useSelector(colorSelectors.color)
const { isMenuOpen, toggleMenuMode } = useContext(MenuContext)
const { language } = useTranslation()
const dispatch = useDispatch()
const toggleLang = (bName) => {
let lang = bName === 'ru' ? 'en' : 'ru';
dispatch(setLanguage(lang))
}
return (
<Container>
<IconButton
color={color}
onClick={toggleMenuMode}
open={isMenuOpen}
>
<BurgerSVG />
</IconButton>
<Logo setOpenMenu={setOpenMenu} />
<LangToggleButton
onClick={(e) => toggleLang(e.nativeEvent.target.name)} name={language}
open={isMenuOpen}>
{language}
</LangToggleButton>
<IconButton>
<a href='tel:+79995357879'>
<PhoneSVG />
</a>
</IconButton>
</Container>
)
}
export default MobileNavbar;<file_sep>/src/components/ServiceTab/service-tab.component.jsx
import React, { useState } from 'react';
import InView from 'react-intersection-observer';
import ServicesItemWrapper from '../ServicesItemWrapper/services-item-wrapper.component';
import { useTranslation } from '../../hooks/translation';
import {
TabContainer,
TabHeader,
CardsWrapper,
CardsContainer
} from './service-tab.styles';
import { useDispatch, useSelector } from 'react-redux';
import { colorSelectors } from '../../redux/color/color.selectors';
import AnimatedCard from '../Common/AnimatedCard/animated-card.component';
import AnimatedNumbersNew from '../AnimatedNumberNew/animated_number_new.component';
import { useWindowDimensions } from '../../hooks/dimensions';
import AnimatedHeaderMobile from '../AnimatedHeaderMobile/animated_header_mobile.component';
import { setScroll } from '../../redux/scroll/scroll.actions';
const ServiceTab = ({ service, currentTab, works }) => {
const [animate, setAnimate] = useState(false)
const { language } = useTranslation();
const color = useSelector(colorSelectors.color)
const { t } = useTranslation();
const { width } = useWindowDimensions()
const dispatch = useDispatch()
const handleViewportChange = (e, entry) => {
if (e && entry && (entry.intersectionRatio >= 0.5)) {
if (!animate) {
setAnimate(true)
}
} else if (!e || (entry.intersectionRatio < 0.5)) {
setAnimate(false)
}
}
const handleCardClick = (card) => {
localStorage.setItem('requestType', card)
dispatch(setScroll('request'))
}
return (
<TabContainer>
<InView
as='div'
onChange={handleViewportChange}
threshold={0.5}
>
{
currentTab !== 2 ?
<TabHeader>
{
width < 600 ?
<AnimatedHeaderMobile currentTab={currentTab} />
:
<AnimatedNumbersNew currentTab={currentTab} />
}
</TabHeader> :
<CardsWrapper>
<CardsContainer>
<AnimatedCard
t={t}
description={language === 'ru' ? service.Description1 : service.DescriptionEng1}
title={language === 'ru' ? service.Title1 : service.TitleEng1}
color={color}
showButton={false}
onCardClick={() => handleCardClick(service.Title1)}
/>
<AnimatedCard
t={t}
description={language === 'ru' ? service.Description2 : service.DescriptionEng2}
title={language === 'ru' ? service.Title2 : service.TitleEng2}
color={color}
showButton={false}
onCardClick={() => handleCardClick(service.Title2)}
/>
</CardsContainer>
<CardsContainer>
<AnimatedCard
t={t}
description={language === 'ru' ? service.Description3 : service.DescriptionEng3}
title={language === 'ru' ? service.Title3 : service.TitleEng3}
color={color}
showButton={false}
onCardClick={() => handleCardClick(service.Title3)}
/>
<AnimatedCard
t={t}
description={language === 'ru' ? service.Description4 : service.DescriptionEng4}
title={language === 'ru' ? service.Title4 : service.TitleEng4}
color={color}
showButton={false}
onCardClick={() => handleCardClick(service.Title4)}
/>
</CardsContainer>
</CardsWrapper>
}
</InView>
{
currentTab !== 2 &&
<ServicesItemWrapper
works={works}
currentTab={currentTab}
/>
}
</TabContainer>
)
}
export default ServiceTab;<file_sep>/src/components/Tabs/tabs.styles.jsx
import styled from 'styled-components';
import {motion} from 'framer-motion';
export const TabsHeaderOuterContainer = styled.div`
display: flex;
flex-direction: column;
width:100%;
`
export const TabsHeader = styled.div`
display: flex;
justify-content: flex-start;
width: 100%;
`
export const TabHeader = styled(motion.span)`
font-size: 32px;
color: ${props => props.active? props.color: '#F9F9F9'};
line-height: 44px;
margin-right: 8%;
/* font-weight: bold;
font-family: initial; */
cursor: pointer;
display: flex;
@media(max-width: 895px) {
margin-right:6%;
&:last-child {
margin-right:0;
}
}
@media(max-width: 780px) {
margin-right:5%;
font-size: 28px;
}
@media(max-width: 675px) {
margin-right:3.5%;
font-size: 26px;
}
`
export const AnimatedLine = styled(motion.div)`
background-color: ${props => props.color};
height: 4px;
width: 0;
`
export const TabBodyContainer = styled.div`
width: 100%;
`<file_sep>/src/components/Header/MobileMenu/MenuSection/menu-section.component.jsx
import React from 'react';
import {
HeaderText,
MenuItemBody,
MenuItemContainer,
MenuItemHeader
} from './menu-section.styles';
import { ReactComponent as ArrowSVG } from '../../../../assets/ArrowRight.svg';
import { useState } from 'react';
const variants = {
hidden: {
x: -855,
transition: {
duration: 0.5,
}
},
shown: {
x: 0,
transition: {
duration: 0.5,
}
}
}
const MenuSection = ({ title, children, color, keepOpen }) => {
const [open, setOpen] = useState(keepOpen ? true : false)
const toggleSection = () => {
setOpen(c => !c)
}
return (
<MenuItemContainer
variants={variants}
>
<MenuItemHeader
onClick={toggleSection}
open={open}
color={color}
>
<HeaderText color={color}>{title}</HeaderText>
<ArrowSVG />
</MenuItemHeader>
<MenuItemBody
open={open}
>
{children}
</MenuItemBody>
</MenuItemContainer>
)
}
export default MenuSection;<file_sep>/src/redux/content/content.reducer.jsx
import {constants} from './content.constants';
const INITIAL_STATE = {
content: {
cases: {
apps: [],
websites: []
},
services: undefined
},
loading: false,
error: undefined
}
export const contentReducer = (state=INITIAL_STATE, action) => {
switch (action.type) {
case constants.FETCH_CONTENT_PENDING:
return {
...state,
loading: true
}
case constants.FETCH_CONTENT_FAILURE:
return {
...state,
loading: false,
error: action.payload
}
case constants.FETCH_CONTENT_SUCCESS:
return {
...state,
loading: false,
error: undefined,
content: action.payload
}
default:
return state;
}
}<file_sep>/src/components/SectionCases/Case/case.component.jsx
import React from 'react';
import ReactMarkdown from 'react-markdown';
import {
ActionButton,
CaseContainer,
ContentContainer,
ContentDescription,
ContentTitle,
ContentBody,
PreviewImage,
CaseLogo,
CaseLogoContainer
} from './case.styles';
import { CMS_URL } from '../../../config';
import { useSelector } from 'react-redux';
import { colorSelectors } from '../../../redux/color/color.selectors';
import { useHistory } from 'react-router-dom';
import { useTranslation } from '../../../hooks/translation';
import { useWindowDimensions } from '../../../hooks/dimensions';
const Case = ({ caseToDisplay }) => {
const color = useSelector(colorSelectors.color)
const history = useHistory()
const { t, language } = useTranslation()
const { width } = useWindowDimensions()
const handleNavigation = (id) => {
history.push(`/works/${caseToDisplay.Type}/${id}`)
}
return (
<CaseContainer>
<ContentContainer>
<ContentBody>
{caseToDisplay.Logo ?
<CaseLogoContainer>
<CaseLogo style={{
width: caseToDisplay.Logo.width * (width > 800 ? 1 : width > 600 ? 0.7 : 0.6),
height: caseToDisplay.Logo.height * (width > 800 ? 1 : width > 600 ? 0.7 : 0.6)
}} src={CMS_URL + caseToDisplay.Logo.url} alt="logo" />
</CaseLogoContainer>
: <ContentTitle>
{language === 'ru' ? caseToDisplay.Title : caseToDisplay.TitleEng}
</ContentTitle>
}
<ContentDescription>
<ReactMarkdown>
{language === 'ru' ? caseToDisplay.ShortDescription : caseToDisplay.ShortDescriptionEng}
</ReactMarkdown>
</ContentDescription>
</ContentBody>
<ActionButton
color={color}
onClick={() => handleNavigation(caseToDisplay.id)}
>
{t('whole_work')}
</ActionButton>
</ContentContainer>
<PreviewImage
>
<img src={CMS_URL + caseToDisplay.MainImage.url} alt='title' />
</PreviewImage>
</CaseContainer>
)
}
export default Case;<file_sep>/src/components/Loader/loader.styles.jsx
import styled, { keyframes, css } from 'styled-components';
export const LoaderContainer = styled.div`
width: 100%;
height: 100%;
background-color: #0a0a0a;
display: flex;
justify-content: center;
align-items: center;
position: fixed;
z-index: 1500;
flex-direction: column;
transition-duration: 0.6s;
`
const dash = (color) => keyframes`
75% {
stroke-dashoffset: 0;
fill:#0a0a0a;
}
100% {
fill: ${color};
stroke-dashoffset: 0;
}
`
export const Logo = styled.div`
height: auto;
>svg > path {
stroke-dasharray: 100;
stroke-dashoffset: 100;
fill:#0a0a0a;
stroke: ${props => props.color ? props.color : '#F9F9F9'};
/* transition-duration: 2s; */
animation: ${props => css`${dash(props.color)} 1.5s linear forwards`};
}
`
<file_sep>/src/components/ImageCarousel/image-carousel.components.jsx
import React, { useEffect, useState } from 'react'
import Slider from 'react-slick';
import { Container, SlideImage, ImageWrapper, SliderText, SliderTextContainer, SlideContainer } from './image-carousel.styles'
import { useWindowDimensions } from '../../hooks/dimensions';
import { useTranslation } from '../../hooks/translation';
import { isMobile, isTablet } from 'react-device-detect';
const jobTitles = [
"job_jenya",
"job_designer",
"job_full_stack",
"job_front_developer",
"job_manager",
"job_front_developer"
]
const names = [
"Lilekov_Evgeniy",
"Anna_Kulikova",
"Sergey_Yukhanov",
"Olga_Salnikova",
"Andrey_Eruh",
"Kotler_Roman",
// "Nasir_Imanov",
// "Sergey_Luchinkin",
]
const ImageCarousel = ({ imageArray, imageSmileArray }) => {
const { width } = useWindowDimensions()
const [countSlidesToShow, setCountSlidesToShow] = useState(5)
const [smileImage, setSmileImage] = useState(null)
const { t } = useTranslation()
const handleChangePhoto = (index) => {
if (index || index === 0) {
if (!isMobile && !isTablet) {
setSmileImage(index)
}
} else {
setSmileImage(null)
}
}
const handleClick = (index) => {
if (isMobile || isTablet) {
if (smileImage === index) {
setSmileImage(null)
} else {
setSmileImage(index)
}
}
}
useEffect(() => {
let count
if (width > 1240) {
count = 5
} else if (width > 940) {
count = 4
} else if (width > 700) {
count = 3
} else if (width > 500) {
count = 2
} else {
count = 1
}
count = imageArray.length < count ? imageArray.length : count
setCountSlidesToShow(count)
}, [width, countSlidesToShow, imageArray])
return (
<Container>
<Slider
dots={true}
// variableWidth={true}
swipeToSlide={true}
initialSlide={0}
infinite={false}
rows={1}
arrows={false}
slidesToShow={countSlidesToShow}
focusOnSelect={false}
slidesToScroll={1}
>
{
imageArray.map((image, index) => {
return (
<SlideContainer key={index}>
<ImageWrapper >
<div style={{ width: 'max-content', position: 'relative' }}>
<SlideImage
src={index === smileImage ? imageSmileArray[index] : image}
key={index}
alt='team'
onMouseEnter={() => handleChangePhoto(index)}
onMouseLeave={() => handleChangePhoto()}
onClick={() => handleClick(index)}
>
</SlideImage>
<SliderTextContainer>
<SliderText>
{t(names[index])}
</SliderText>
<SliderText>
{t(jobTitles[index])}
</SliderText>
</SliderTextContainer>
</div>
</ImageWrapper>
</SlideContainer>
)
})
}
</Slider>
</Container>
)
}
export default ImageCarousel<file_sep>/src/components/ModalRequest/modal-request.styles.jsx
import styled from 'styled-components'
export const ModalContainer = styled.div`
width: 80vw;
max-width: 1050px;
height: max-content;
min-height: 300px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
/* background: transparent; */
background-color: #0a0a0a;
border-radius: 8px;
position: relative;
padding: 8%;
padding-bottom: 10px;
overflow-x: hidden;
>div {
width: 100%;
height: 100%;
}
@media(max-width: 768px) {
min-width: 100vw;
min-height: 100vh;
}
`
export const CloseButton = styled.button`
position: absolute;
top: 15px;
right: 15px;
outline: none;
background: transparent;
border: none;
cursor: pointer;
width: 30px;
height: 30px;
padding: 0;
z-index: 10000;
>img {
width: 30px;
}
`<file_sep>/src/redux/scroll/scroll.selectors.jsx
export const scrollSelectors = {
to: state => state.scroll.to
}<file_sep>/src/components/AnimatedHeaderMobile/animate_header_mobile.styles.jsx
import styled from 'styled-components';
export const AnimatedHeaderContainer = styled.div`
display: flex;
flex-direction: column;
width: 100%;
justify-content: center;
align-items: center;
`
<file_sep>/src/components/Map/custom-map.component.jsx
import React from 'react';
import { YMaps, Map, Placemark } from 'react-yandex-maps';
import { MapContainer } from './custom-map.styles';
const mapData = {
center: [55.802796, 37.584640],
zoom: 14,
};
const coordinate = [55.802796, 37.584640]
const CustomMap = () => (
<MapContainer>
<YMaps className='yandexMap'>
<Map
defaultState={mapData}
className='mapContainer'
style={{ width: '480px', height: '300px' }}
>
<Placemark geometry={coordinate} options={{iconLayout:'default#image', iconImageHref: '/pin.svg', iconImageSize: [55, 55], }}/>
</Map>
</YMaps>
</MapContainer>
);
export default CustomMap;<file_sep>/src/components/Common/AnimatedCard/animated-card.styles.jsx
import styled from 'styled-components';
import { motion } from 'framer-motion';
export const CardContainer = styled(motion.div)`
flex: 1 1 100%;
background-color: #111111;
border: ${props => props.noBorder ? 'none' : '1px solid #1C1C1C'};
position: relative;
height: 317px;
display: flex;
flex-direction: column;
justify-content: space-between;
overflow: hidden;
@media(max-width: 600px) {
height: auto;
}
`
export const CardInnerContainer = styled.div`
border: 1px solid #1C1C1C;
position: relative;
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100%;
&:hover {
border-color: ${props => props.color}
}
`
export const CardBody = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
padding: 8%;
flex: 1 1 100%;
@media(max-width: 600px) {
padding-top: 50px;
padding-bottom: 50px;
min-height: 164px;
}
`
export const Title = styled(motion.span)`
font-size: 24px;
line-height: 32px;
color: #F9F9F9;
max-width: ${props => props.showButton ? '12ch' : '90%'};
${props => props.showButton ? '' : `
@media(max-width: 1005px) {
font-size: 20px;
line-height: 24px;
}
@media(max-width: 720px) {
font-size: 18px;
line-height: 22px;
}
@media(max-width: 500px) {
font-size: 20px;
line-height: 24px;
}
@media(max-width: 420px) {
font-size: 18px;
line-height: 22px;
}
@media(max-width: 340px) {
font-size: 16px;
line-height: 20px;
}
`}
`
export const Description = styled(motion.span)`
margin-top: 12px;
font-size: 14px;
color: #F9F9F9;
line-height: 20px;
letter-spacing: .3px;
@media(max-width: 600px) {
padding: 8%;
margin-top: 0;
padding-top: 0;
}
`
export const Button = styled(motion.button)`
position: relative;
outline: none;
box-shadow: none;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
width: 100%;
min-height: 60px;
border: ${props => `1px solid ${props.color}`};
border-radius: 2px;
background-color: ${props => props.color};
cursor: pointer;
transition-duration: 0.2s;
opacity: 1;
font-weight: 500;
font-size: 14px;
line-height: 19px;
color: #fefefe;
>div >svg {
transition-duration: 0.3s;
}
&:hover {
>div >svg {
transform: scale(1.2);
}
}
`
export const Icon = styled.div`
position: absolute;
right: 20px;
`
export const CardHeader = styled(motion.div)`
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
outline: none;
`
export const CardIcon = styled(motion.div)`
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
transition-duration: 0.3s;
-webkit-tap-highlight-color:transparent;
&:hover {
transform: scale(1.1);
}
`
export const CardOverlay = styled(motion.div)`
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-start;
`<file_sep>/src/components/Header/MobileMenu/MenuSection/menu-section.styles.jsx
import { motion } from 'framer-motion';
import styled from 'styled-components';
export const MenuItemContainer = styled(motion.div)`
display: flex;
flex-direction: column;
padding: 0 9%;
`
export const MenuItemHeader = styled.div`
display: flex;
flex-direction: row;
cursor: pointer;
margin-right: 12px;
margin-top: 23px;
align-items: center;
>svg {
transition-duration: 0.3s;
transform: ${props => props.open? 'rotateZ(90deg)': 'rotateZ(0deg)'};
>path {
stroke: ${props => props.color? props.color: '#F9F9F9'};
}
}
`
export const HeaderText = styled.span`
font-weight: 600;
font-size: 20px;
line-height: 28px;
color: ${props => props.color? props.color: '#F9F9F9'};
`
export const MenuItemBody = styled.div`
display: flex;
flex-direction: column;
transition-duration: 0.6s;
overflow: hidden;
${props => props.open ? 'max-height: 200px;' : `max-height: 0px; padding: 0;`};
`
<file_sep>/src/redux/language/language.reducer.jsx
import {constants} from './language.constants';
const INITIAL_STATE = {
language: 'ru'
}
export const languageReducer = (state = INITIAL_STATE, action) => {
switch(action.type) {
case constants.SET_LANGUAGE:
return {
...state,
language: action.payload.lang
}
default:
return state
}
}<file_sep>/src/components/AnimatedNumberNew/animated_number_new.styles.jsx
import styled from 'styled-components';
export const AnimatedNumbersContainer = styled.div`
width: 100%;
`<file_sep>/src/components/SectionWe/section-we.component.jsx
import React from 'react';
import Section from '../Common/Section/section.component';
import { useTranslation } from '../../hooks/translation';
import ImageCarousel from '../ImageCarousel/image-carousel.components';
import Evgeny from '../../assets/Team/eugene.jpeg'
import Anna from '../../assets/Team/ann.jpeg'
import Sergey from '../../assets/Team/sergey.jpeg'
import Olga from '../../assets/Team/olga.jpeg'
import Andrey from '../../assets/Team/andrew.jpeg'
import Roman from '../../assets/Team/roma.jpg'
import EvgenySmile from '../../assets/Team/eugene_smile.jpeg'
import AnnaSmile from '../../assets/Team/ann_smile.jpeg'
import SergeySmile from '../../assets/Team/sergey_smile.jpeg'
import OlgaSmile from '../../assets/Team/olga_smile.jpeg'
import AndreySmile from '../../assets/Team/andrew_smile.jpeg'
import RomanSmile from '../../assets/Team/roma_smile.jpg'
const imageArray = [
Evgeny, // 1
Anna, // 2
Sergey, // 3
Olga, // 4
Andrey, // 5
Roman, // 6
]
const imageSmileArray = [
EvgenySmile,
AnnaSmile,
SergeySmile,
OlgaSmile,
AndreySmile,
RomanSmile
]
const SectionWe = () => {
const { t } = useTranslation();
return (
<Section
title={t('about_us')}
description={t('about_us_desc')}
index={2}
descriptionWidth={'390px'}
>
<ImageCarousel imageArray={imageArray} imageSmileArray={imageSmileArray} />
</Section>
);
}
export default SectionWe;<file_sep>/src/components/Header/MenuButton/menu-button.component.jsx
import React from 'react';
import { MenuButtonContainer } from './menu-button.styles';
// import { MenuContext } from '../../../context/menu-state';
// import ArrowSVG from '../../../assets/arrow.svg'
const MenuButton = ({ children, color, isOpen, onOpen }) => {
// const { isMenuOpen, toggleMenuMode } = useContext(MenuContext);
// const onOpenMenu = () => {
// toggleMenuMode();
// };
return (
<MenuButtonContainer
active={isOpen}
onClick={onOpen}
color={color}
>
{children}
<svg width="10" height="7" viewBox="0 0 10 7" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 5.00012L4.46967 5.53045L5 6.06078L5.53033 5.53045L5 5.00012ZM0.46967 1.53045L4.46967 5.53045L5.53033 4.46979L1.53033 0.469792L0.46967 1.53045ZM5.53033 5.53045L9.53033 1.53045L8.46967 0.469792L4.46967 4.46979L5.53033 5.53045Z" fill="none" />
</svg>
{/* <svg class="logo__left-side" width="39" height="45" viewBox="0 0 39 45" fill="none" xmlns="http://www.w3.org/2000/svg">
<use xlinkHref='../../../assets.svg#arrow' />
</svg> */}
{/* <img src={arrowSVG} alt="Arrow" /> */}
</MenuButtonContainer >
);
}
export default MenuButton;<file_sep>/src/redux/color/color.selectors.jsx
export const colorSelectors = {
colorNumber: (state) => state.color.color,
color: (state) => state.color.themeColor
}<file_sep>/src/components/TypingText/typing-text.component.jsx
import React, { useState, useEffect } from 'react';
import Typist from 'react-typist';
import { useSelector } from 'react-redux';
import { TypingTextWrapper, CursorWrapper, Text } from './typing-text.styles';
import { colorSelectors } from '../../redux/color/color.selectors';
const TypingText = ({ textsArray }) => {
const themeColor = useSelector(colorSelectors.color);
const [typing, setTyping] = useState(true)
const [textIndex, setTextIndex] = useState(0)
const cursorOptions = {
show: true,
blink: true,
element: <CursorWrapper color={themeColor}> </CursorWrapper>,
hideWhenDone: false,
hideWhenDoneDelay: 1000,
}
useEffect(() => {
setTyping(true);
}, [typing]);
const handleTyping = (index) => {
setTyping(false)
if (index < textsArray.length - 1) {
setTextIndex(index + 1)
} else {
setTextIndex(0)
}
}
return (
<TypingTextWrapper color={themeColor}>
{
typing ?
// textsArray.map((text) => {
<Typist
avgTypingDelay={70}
stdTypingDelay={20}
startDelay={1000}
cursor={cursorOptions}
onTypingDone={() => handleTyping(textIndex)}
>
<Text >
{textsArray[textIndex]}
</Text>
{
<Typist.Backspace count={textsArray[textIndex]?.length} delay={2000} />
}
</Typist>
// })
: ''
}
</TypingTextWrapper>
);
}
export default TypingText;<file_sep>/src/components/SectionRequest/section-request.component.jsx
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Formik } from 'formik';
import * as yup from 'yup';
import axios from 'axios';
import {
InputFieldsWrapper,
InputFieldsRowPosition,
InputWrapper,
InputField,
LabelWrapper,
FileInput,
FileInputLabel,
Button,
Icon,
PersonalDataAgreement,
Error,
InputFieldsColumn,
ExtraInfoWrapper,
ExtraInfo,
FilesList,
} from './section-request.styles';
import Section from '../Common/Section/section.component';
import { colorSelectors } from '../../redux/color/color.selectors';
import { useWindowDimensions } from '../../hooks/dimensions';
// import Send from '../../assets/post.png';
import Attach from '../../assets/attach.png';
import Delete from '../../assets/delete.png';
import { API_URL } from '../../config';
import { scrollSelectors } from '../../redux/scroll/scroll.selectors';
import { setScroll } from '../../redux/scroll/scroll.actions';
import { useTranslation } from '../../hooks/translation';
import privacyPolicy from '../../assets/privacyPolicy.pdf'
import { useLocation } from 'react-router-dom/cjs/react-router-dom.min';
const SectionRequest = ({
refApplication,
index,
padding,
nonNumber
}) => {
const themeColor = useSelector(colorSelectors.color);
const { width } = useWindowDimensions();
const dispatch = useDispatch()
const scroll = useSelector(scrollSelectors.to)
const ref = useRef()
const { t } = useTranslation();
const [isRequestSent, setIsRequestSent] = useState(false);
const { pathname } = useLocation()
const getValidation = (t) => {
const validationSchema = yup.object().shape({
email: yup.string()
.email('error_invalid_email')
.when('phone', {
is: (val) => {
if (val) {
return true
}
return false
},
then: yup.string(),
otherwise: yup.string().required('error_email'),
}),
phone: yup.string()
.when('email', {
is: (val) => {
if (val) {
return true
}
return false
},
then: yup.string(),
otherwise: yup.string().required('error_phone')
})
.min(12, 'error_phone')
.max(12, 'error_phone'),
// .required('error_phone'),
name: yup.string()
.trim()
.required('error_name'),
text: yup.string()
.trim()
.required('error_text'),
}, [['email', 'phone']])
return validationSchema
}
const memGetValidation = useMemo(
() => getValidation(t),
[t]
)
const [filesArray, setFilesArray] = useState([]);
const sendRequest = async (values, { resetForm }) => {
const formData = new FormData();
formData.append('name', values.name);
formData.append('email', values.email);
formData.append('phone', values.phone);
formData.append('text', values.text);
let requestType = localStorage.getItem('requestType')
if (!requestType) {
requestType = 'page: ' + pathname
}
formData.append('section', requestType)
filesArray.forEach((file) => {
formData.append('file', file);
})
try {
const resp = await axios.post(`${API_URL}application`, formData);
resetForm();
setFilesArray([]);
setIsRequestSent(true);
// onCloseModal()
return resp;
}
catch (err) {
}
}
const addFile = (file) => {
let filesSize = 0;
if (file && file.lastModified) {
filesArray.forEach((file) => {
filesSize += file.size
})
if (filesSize < 30000000) {
if (filesArray.find((item) => item.name === file.name) === undefined) {
setFilesArray([...filesArray, file]);
}
}
}
}
const removeFile = (name) => {
let files = filesArray;
setFilesArray(
() => files.filter((item) => item.name !== name)
)
}
useEffect(() => {
if (scroll === 'request') {
window.scroll({
top: ref.current.getBoundingClientRect().top - 220,
behavior: 'smooth'
})
dispatch(setScroll(undefined))
}
}, [scroll, dispatch])
return (
<Section
title={t('leave_request')}
description={t('leave_request_desc')}
index={index}
nonNumber={nonNumber}
headerContainerStyles={{
marginBottom: '40px'
}}
threshold={0.3}
descriptionWidth={'390px'}
reff={refApplication}
padding={padding}
>
<Formik
initialValues={{ email: '', name: '', phone: '', text: '' }}
onSubmit={sendRequest}
validationSchema={memGetValidation}
validateOnChange={false}
>
{({ handleChange, values, handleSubmit, errors, setFieldValue }) => (
<InputFieldsWrapper onSubmit={handleSubmit} ref={ref} >
<InputFieldsRowPosition customWidth={width}>
<InputFieldsColumn customWidth={width}>
<InputWrapper>
<InputField
placeholder=' '
value={values.name}
color={themeColor}
name='name'
id='name'
onChange={handleChange('name')}
/>
<LabelWrapper htmlFor='name'> {t('your_name')} </LabelWrapper>
{/* <Error>{errors.name}</Error> */}
</InputWrapper>
<InputWrapper>
<InputField
placeholder=' '
mask='+79999999999'
value={values.phone}
type='tel'
id='tel'
color={themeColor}
name='phone'
onChange={event => setFieldValue('phone', event.target.value.replace(/_/g, ''))}
/>
<LabelWrapper htmlFor='tel'>{t('your_phone')}</LabelWrapper>
{/* <Error>{errors.phone}</Error> */}
</InputWrapper>
<InputWrapper>
<InputField
placeholder=' '
value={values.email}
color={themeColor}
name='email'
id='email'
onChange={handleChange('email')}
/>
<LabelWrapper htmlFor='email'>{t('your_email')}</LabelWrapper>
{/* <Error>{errors.email}</Error> */}
</InputWrapper>
</InputFieldsColumn>
<InputFieldsColumn>
<ExtraInfoWrapper customWidth={width}>
<ExtraInfo
placeholder=' '
value={values.text}
name='text'
id='text'
onChange={handleChange('text')}
color={themeColor}
/>
<LabelWrapper htmlFor='text'>{t('message')}</LabelWrapper>
{/* <Error>{errors.text}</Error> */}
</ExtraInfoWrapper>
<FileInput
onChange={(event) => addFile(event.target.files[0])}
multiple
id='file'
type='file'
>
</FileInput>
<FileInputLabel htmlFor='file'>
{t('attatch_file_button')}
<Icon src={Attach} />
</FileInputLabel>
<FilesList customWidth={width}>
{filesArray.map((item) => {
return (
item ?
<li key={item.lastModified}
>
<div>
<div>
<img src={Attach} alt='' />
<span>{item.name}</span>
</div>
<img src={Delete}
style={{ cursor: 'pointer' }}
alt=''
onClick={() => removeFile(item.name)} />
</div>
</li>
:
null
)
})}
</FilesList>
</InputFieldsColumn>
</InputFieldsRowPosition>
<Button
color={themeColor}
type='submit'
disabled={isRequestSent}
>
{isRequestSent ? t('request_sent') : t('leave_request')}
{/* <Icon src={Send} /> */}
</Button>
<Error>
<p>{t(errors.name)}</p>
<p>{t(errors.phone)}</p>
<p>{t(errors.email)}</p>
<p>{t(errors.text)}</p>
</Error>
</InputFieldsWrapper>
)}
</Formik>
<PersonalDataAgreement>
<span>
{t('personal_data_agreement')}
<a href={privacyPolicy} target='_blank' rel='nofollow noopener noreferrer'>
{t('personal_data_agreement_ref')}
</a>
</span>
</PersonalDataAgreement>
</Section>
)
}
export default SectionRequest;<file_sep>/src/components/SectionGoals/GoalsList/goals_list.styles.jsx
import styled from 'styled-components';
export const ListContainer = styled.div`
width: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
margin-top: 40px;
`
export const Goal = styled.p`
padding: 0;
margin: 10px 0px 10px 0px;
font-family: Manrope;
font-style: normal;
font-weight: 200;
font-size: 14px;
line-height: 20px;
/* or 125% */
letter-spacing: 0.05em;
color: #F9F9F9;
>svg {
margin-right: 14px;
>circle {
stroke: ${props => props.color}
}
}
@media (max-width: 550px) {
font-size: 13px;
line-height: 17px;
}
@media (max-width: 420px) {
font-size: 12px;
line-height: 15px;
}
`
export const Description = styled.span`
font-family: Manrope;
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 22px;
letter-spacing: 0.05em;
color: #F9F9F9;
max-width: 110ch;
margin-top: 5px;
@media (max-width: 550px) {
font-size: 14px;
line-height: 18px;
}
@media (max-width: 420px) {
font-size: 12px;
line-height: 16px;
}
`<file_sep>/src/components/ServiceTab/service-tab.styles.jsx
import styled from 'styled-components';
import { motion } from 'framer-motion';
export const TabContainer = styled(motion.div)`
width: 100%;
display: flex;
flex-direction: column;
padding-top: 28px;
margin-bottom: 145px;
@media(max-width: 600px) {
padding: 12px 0px 0px 0px;
margin-bottom: 60px;
}
`
export const TabHeader = styled.div`
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
`
export const Description = styled.div`
width: 100%;
max-width: 570px;
font-weight: 200;
font-size: 14px;
line-height: 20px;
letter-spacing: 0.3px;
color: #F9F9F9;
@media(max-width: 600px) {
max-width: initial;
}
`
export const NumberContainer = styled.div`
@media(max-width: 611px) {
display: none;
}
`
export const DescriptionWrapper = styled.div`
width: 100%;
display: flex;
flex-direction: column;
`
export const DescriptionContainer = styled.div`
width: 100%;
display: flex;
justify-content: ${props => props.justify ? 'space-evenly' : 'space-between'};
border-top: 2px solid transparent;
border-color: ${props => props.justify ? props.color : 'transparent'};
transition-duration: 0.5s;
@media(min-width: 1120px) {
>div {
padding: ${props => props.justify ? '30px 10px 0 10px' : '0 10px 30px 10px'};
}
}
@media(max-width: 1120px) {
align-items: center;
flex-direction: column;
border: none;
/* transform: translateX(-100px); */
}
`
export const DescriptionText = styled.div`
width: 100%;
max-width: 345px;
color: #F9F9F9;
padding: 0 10px;
transition-duration: 0.5s;
position: relative;
h4 {
margin-top: 0;
}
@media(max-width: 1120px) {
padding: 30px 10px;
}
@media(min-width: 1120px) {
transform: translateX(0)!important;
}
`
export const Separator = styled.div`
width: 2px;
padding: 0!important;
background-color: ${props => props.color};
transition-duration: 0.5s;
@media(max-width: 1120px) {
display: none;
}
`
export const SeparatorMin = styled.div`
width: 100px;
height: 2px;
padding: 0!important;
background-color: ${props => props.color};
transition-duration: 0.5s;
display: none;
@media(min-width: 1120px) {
display: none;
}
`
export const CardsWrapper = styled.div`
width: 100%;
display: flex;
flex-direction: column;
`
export const CardsContainer = styled.div`
width: 100%;
display: flex;
@media(max-width: 600px) {
flex-direction: column;
}
`<file_sep>/src/components/Common/Section/section.component.jsx
import React, { useState } from 'react';
import InView from 'react-intersection-observer';
import { Container } from './section.styles';
import SectionHeader from '../SectionHeader/section-header.component';
const Section = ({
title,
index,
description,
descriptionWidth,
children,
threshold,
headerContainerStyles,
headerDescriptionStyles,
reff,
padding,
nonAnimation,
nonNumber,
custom
}) => {
const [animate, setAnimate] = useState(false)
const handleViewportChange = (e, entry) => {
if (e && entry && (threshold ? entry.intersectionRatio >= threshold : entry.intersectionRatio >= 0.5)) {
if (!animate) {
setAnimate(true)
}
} else if (!e || (threshold ? entry.intersectionRatio < threshold : entry.intersectionRatio < 0.5)) {
setAnimate(false)
}
}
return (
<InView
as='div'
onChange={handleViewportChange}
threshold={threshold ? threshold : 0.5}
>
<Container
ref={reff}
>
<SectionHeader
title={title}
custom={custom}
description={description}
index={index}
show={animate}
descriptionWidth={descriptionWidth}
headerContainerStyles={headerContainerStyles}
headerDescriptionStyles={headerDescriptionStyles}
padding={padding}
nonAnimation={nonAnimation}
nonNumber={nonNumber}
/>
{children}
</Container>
</InView>
)
}
export default Section;
<file_sep>/src/components/SectionAbout/section-about.component.jsx
import React from 'react';
// import {
// AboutWrapper,
// Heading,
// Text
// } from './section-about.styles';
import Section from '../Common/Section/section.component';
import { useTranslation } from '../../hooks/translation';
const SectionAbout = () => {
const {t} = useTranslation();
return (
<Section
title={t('about_team')}
description={
<div>
<p>
{
t('about_team_desc')
}
</p>
<p>
{
t('about_team_desc_second')
}
</p>
</div>
}
index={5}
descriptionWidth={'610px'}
/>
);
}
export default SectionAbout;<file_sep>/src/hooks/translation.jsx
import { useSelector } from 'react-redux';
import translations from '../assets/translation';
import { languageSelectors } from '../redux/language/language.selectors';
export const useTranslation = () => {
const appTranslations = translations;
const currentLanguageCode = useSelector(languageSelectors.language);
const t = (pattern) => {
return appTranslations.translationsMap[currentLanguageCode][pattern];
};
return {t, language: currentLanguageCode};
};<file_sep>/src/redux/content/content.actions.jsx
import axios from 'axios';
import { constants } from './content.constants';
import { CMS_URL } from '../../config';
const fetchContentPending = () => ({
type: constants.FETCH_CONTENT_PENDING
})
const fetchContentSuccess = (content) => ({
type: constants.FETCH_CONTENT_SUCCESS,
payload: content
})
const fetchContentFailure = (error) => ({
type: constants.FETCH_CONTENT_FAILURE,
payload: error
})
export const fetchContent = () => {
return (dispatch) => {
dispatch(fetchContentPending)
let content;
let cases;
let apps;
let websites;
axios(`${CMS_URL}/cases?_sort=Type:ASC,Priority:Desc`)
.then((response) => {
for (var i = 0; i < response.data.length; i++) {
if (response.data[i].Type === 'Website') {
response.data[i].Gallery.forEach((image) => {
image.width = 800
image.height = 481
})
apps = response.data.slice(0, i)
websites = response.data.slice(i, response.data.length)
break;
} else if (response.data[i].Type === 'Application') {
response.data[i].Gallery.forEach((image) => {
image.width = 224
image.height = 473
})
}
}
axios(`${CMS_URL}/services?_sort=id:ASC`)
.then((response) => {
cases = {
apps,
websites
}
content = {
cases,
services: response.data
}
dispatch(fetchContentSuccess(content))
})
})
.catch((err) => {
dispatch(fetchContentFailure(err))
})
}
}
<file_sep>/src/components/ServicesSection/services-section.styles.jsx
import styled from 'styled-components';
export const ServicesContainer = styled.section`
display: flex;
flex-direction: column;
width: 100%;
`
export const CardContainer = styled.div`
width: 100%;
flex-direction: row;
display: flex;
@media(max-width: 600px) {
flex-direction: column;
}
cursor: default;
`
<file_sep>/src/components/Plan/plan.styles.jsx
import { motion } from 'framer-motion';
import styled from 'styled-components';
import { CustomButton, CustomHeading, CustomText } from '../../styles/common';
export const PlanWrapper = styled.div`
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
background-color: #111;
overflow: hidden;
padding: 77px 35px 80px 20px;
margin-bottom: 17px;
/* height: 670px; */
@media(max-width: 850px) {
padding: 0px 20px 50px 20px;
}
@media(max-width: 480px) {
padding: 0 20px 40px 15px;
}
@media(max-width: 410px) {
padding: 0 20px 40px 15px;
}
@media(max-width: 370px) {
padding: 0 23px 40px 15px;
}
`
export const Button = styled(CustomButton)`
align-self: center;
border-color: ${props => props.color};
/* margin-top: 40px; */
margin-right: 56px;
/* transition-duration: 0.4s; */
z-index: 1;
overflow: hidden;
::after {
content: "";
background-color: ${props => props.color};
position: absolute;
z-index: -1;
padding: 0.85em 0.75em;
display: block;
left: -20%;
right: -20%;
top: 0;
bottom: 0;
transform: skewX(-45deg) scale(0, 1);
transition: all 0.4s ease;
}
:hover {
/* transition-duration: 0.4s; */
transition: all 0.4s ease-out;
::after {
transform: skewX(-45deg) scale(1, 1);
}
}
@media(max-width: 850px) {
margin-right: 0;
margin-top: 30px;
}
/* background-color: ${props => props.color}; */
`
export const Heading = styled(CustomHeading)`
margin-top: 0;
font-size: 24px;
line-height: 32px;
/* @media(max-width: 850px) {
display: none;
} */
`
export const Text = styled(CustomText)`
>ul, ol {
padding-left: 18px;
>li {
line-height: 22px;
}
}
`
export const PlanContainer = styled.div`
height: 100%;
display: flex;
justify-content: center;
@media(max-width: 850px) {
flex-direction: column-reverse;
align-items: center;
/* padding-top: 60px; */
}
`
export const DescriptionWrapper = styled(motion.div)`
display: flex;
flex-direction: column;
max-width: 370px;
min-width: 300px;
margin-right: 113px;
min-height: 450px;
overflow: hidden;
@media(max-width: 1020px) {
margin-right: 80px;
}
@media(max-width: 850px) {
margin-right: 0;
min-height: 380px;
}
@media(max-width: 410px) {
margin-left: 20px;
margin-right: 15px;
}
`
export const SchemeWrapper = styled.div`
/* margin-top: 40px; */
width: 100%;
max-width: 480px;
/* width: 50%; */
display: flex;
flex-direction: column;
/* justify-content: space-between; */
height: 100%;
/* align-items: flex-end; */
`
export const LineWrapper = styled.div`
width: 100%;
height: 50px;
display: flex;
flex-direction: column;
/* justify-content: space-between; */
align-items: ${props => props.alignLeft ? 'flex-start' : 'flex-end'};
position: relative;
margin-top: 40px;
margin-bottom: 50px;
@media(max-width: 410px) {
margin-bottom: 30px;
}
`
export const Line = styled.div`
width: ${props => props.lineWidth ? props.lineWidth : '100%'};
height: 2px;
background-color: #404040;
position: relative;
z-index: 1;
`
export const LineStep = styled(motion.div)`
position: absolute;
height: 100%;
width: ${props => props.width};
left:${props => props.left};
/* background-color: ${props => props.active ? props.color : 'transparent'}; */
z-index: 20;
transition: all 0.5s ease;
`
export const StepButton = styled.button`
outline: none;
background-color: transparent;
border: none;
border-bottom: 1px solid ${props => props.active ? props.color : 'transparent'};
cursor: pointer;
transition-duration: 0.2s;
width: max-content;
font-weight: 200;
font-size: 14px;
line-height: 20px;
letter-spacing: 0.05em;
color: ${props => props.active || props.isStage ? props.color : '#F9F9F9'};
margin-top: 20px;
padding: 0;
padding-bottom: 5px;
position: absolute;
left: ${props => props.left};
z-index: 19;
:hover {
color: ${props => props.color};
transition-duration: 0.2s;
}
@media(max-width: 410px) {
font-size: 12px;
line-height: 16px;
}
`
export const ProgressLine = styled.div`
position: absolute;
width: ${props => props.cusstomWidth};
height: 100%;
background-color: ${props => props.color};
transition: all 0.5s ease;
`
export const Dash = styled.div`
width: 2px;
height: 12px;
background-color: ${props => props.active ? props.color : '#404040'};
/* top: 2px; */
left: ${props => props.left};
position: absolute;
z-index: 0;
transition-duration: 0.2s;
`
const visibilityDot = (props) => {
if (props.first && props.transitionProgress === 1) {
return 'visible'
} else if (props.first) {
return 'hidden'
}
if (props.two && props.transitionProgress === 2) {
return 'visible'
} else if (props.two) {
return 'hidden'
}
if (props.three && props.transitionProgress === 3) {
return 'visible'
} else if (props.three) {
return 'hidden'
}
// if (props.first && props.currentStep < 5) {
// return 'visible'
// }
// if (props.first && props.currentStep >= 5) {
// return 'hidden'
// }
// if (props.two && props.currentStep > 4 && props.currentStep < 9) {
// return 'visible'
// }
// if (props.two && props.currentStep >= 9) {
// return 'hidden'
// }
// if (props.three && props.currentStep > 8) {
// return 'visible'
// } else {
// return 'hidden'
// }
}
export const ProgressDot = styled.div`
width: 10px;
height: 10px;
background-color: ${props => props.color};
position: absolute;
top: -4px;
border-radius: 50%;
left: calc(${props => props.left} - 4px);
transition: left 0.5s ease;
visibility: ${props => visibilityDot(props)};
`
export const Dot = styled.div`
width: 10px;
height: 10px;
background-color: ${props => props.active ? props.color : '#404040'};
position: absolute;
top: -4px;
border-radius: 50%;
left: calc(${props => props.left} - 4px);
transition-duration: 0.2s;
`
// visibility: ${props => props.currentStep >= 5 ? 'hidden' : 'visible'};
export const LineLabel = styled.span`
color: #f9f9f9;
font-weight: 500;
font-size: 14px;
line-height: 20px;
letter-spacing: 0.05em;
position: absolute;
left: ${props => props.left};
top: -36px;
width: max-content;
`<file_sep>/src/components/WorkItem/Slider/slider.component.jsx
import { useAnimation, useMotionValue } from 'framer-motion';
import React, { useEffect, useRef, useState } from 'react';
import { ReactComponent as ArrowRight } from '../../../assets/right-arrow.svg';
import { ReactComponent as ArrowLeft } from '../../../assets/left-arrow.svg';
import {
SliderContainer,
ArrowContainer
} from './slider.styles';
import { useSelector } from 'react-redux';
import { colorSelectors } from '../../../redux/color/color.selectors';
const Slider = ({ children, width, screenWidth, slideWidth }) => {
const x = useMotionValue(0)
const containerRef = useRef()
const [dragConstraints, setDragConstraints] = useState(0)
const color = useSelector(colorSelectors.color)
const dragControl = useAnimation()
useEffect(() => {
if (containerRef.current) {
const sliderWidth = containerRef.current.getBoundingClientRect().width
setDragConstraints(width - sliderWidth)
}
}, [width])
const NextArrow = () => {
return <ArrowContainer onClick={() => {
if (x.get() > -dragConstraints) {
x.stop()
var currentSlide = Math.round((Math.abs(x.get()) / slideWidth))
var newLocation;
if ((dragConstraints + x.get()) < slideWidth) {
newLocation = - dragConstraints
} else {
newLocation = - (currentSlide + 1) * slideWidth
}
dragControl.start({ x: newLocation })
}
}} color={color} right={true}>
<ArrowRight />
</ArrowContainer>
}
const PrevArrow = () => {
return <ArrowContainer onClick={() => {
if (x.get() < 0) {
var currentSlide = Math.round(Math.abs(x.get() / slideWidth))
var newLocation;
if (currentSlide === 0) {
newLocation = 0
} else {
newLocation = - (currentSlide - 1) * slideWidth
}
x.stop()
dragControl.start({ x: newLocation })
}
}} color={color} right={false}>
<ArrowLeft />
</ArrowContainer>
}
return (
<div style={{ position: 'relative' }} onTouchMove={(e) => e.stopPropagation()}>
{screenWidth > 600 ?
<PrevArrow />
: null
}
<div style={{ overflowX: 'hidden' }} ref={containerRef}>
<SliderContainer
dragDirectionLock={true}
drag="x"
initial={{ x: 0 }}
style={{ x, }}
animate={dragControl}
dragConstraints={{
left: -dragConstraints,
right: 0
}}
dragTransition={{ bounceDamping: 10, bounceStiffness: 100 }}
>
{children}
</SliderContainer>
</div>
{screenWidth > 600 ?
<NextArrow />
: null
}
</div>
)
}
export default Slider;<file_sep>/src/pages/NotFound/not-found.component.jsx
import React, { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import {
NotwFoundWrapper,
ImageWrapper,
DescriptionWrapper,
DescriptionLabel,
CustomLink,
GhostWrapper,
UfoWrapper,
UfoGlowWrapper
} from './not-found.styles'
import { colorSelectors } from '../../redux/color/color.selectors'
import { ReactComponent as Numbers } from '../../assets/404.svg'
import { ReactComponent as Ghost } from '../../assets/ghost.svg'
import { ReactComponent as Ufo } from '../../assets/ufo.svg'
import { ReactComponent as UfoGlow } from '../../assets/ufo-glow.svg'
import { useTranslation } from '../../hooks/translation'
const NotFound = ({ endLoader }) => {
const history = useHistory()
const { t } = useTranslation();
const color = useSelector(colorSelectors.color)
const [ufoTranslate, setUfoTranslate] = useState(false)
const [ufoHover, setUfoHover] = useState(false)
const [ufoGlowBlink, setUfoGlowBlink] = useState(false)
const [ghostTranslate, setGhostTranslate] = useState(false)
const [ghostHover, setGhostHover] = useState(false)
useEffect(() => {
if (endLoader) {
setTimeout(() => {
setUfoTranslate(true)
}, 300);
}
}, [endLoader])
useEffect(() => {
if (ufoTranslate) {
setTimeout(() => {
setUfoHover(true)
setUfoGlowBlink(true)
setTimeout(() => {
setGhostTranslate(true)
}, 500);
}, 1500);
}
}, [ufoTranslate])
useEffect(() => {
if (ghostTranslate) {
setTimeout(() => {
setGhostHover(true)
}, 800);
}
}, [ghostTranslate])
const handleNavigation = () => {
history.push('/')
}
return (
<NotwFoundWrapper>
<ImageWrapper color={color}>
<Numbers />
<GhostWrapper
translate={ghostTranslate ? '0' : '-100%'}
hover={ghostHover}
>
<Ghost />
</GhostWrapper>
<UfoGlowWrapper
color={color}
blink={ufoGlowBlink}
>
<UfoGlow />
</UfoGlowWrapper>
<UfoWrapper
translate={ufoTranslate ? '0' : '-100vw'}
hover={ufoHover}
color={color}
>
<Ufo />
</UfoWrapper>
</ImageWrapper>
<DescriptionWrapper>
<DescriptionLabel>{t('notfound_desc_first')}</DescriptionLabel>
<DescriptionLabel color={color}>{t('notfound_desc_second')}</DescriptionLabel>
<CustomLink onClick={handleNavigation} color={color}>{t('notfound_button_label')}</CustomLink>
</DescriptionWrapper>
</NotwFoundWrapper>
)
}
export default NotFound<file_sep>/src/components/ServicesItemWrapper/services-item-wrapper.component.jsx
import React, { useEffect, useState } from 'react';
import { CMS_URL } from '../../config';
import { useWindowDimensions } from '../../hooks/dimensions';
import {
ComponentWrapper,
SlideImage,
SlideContainer,
SlideOverlay
} from './services-item-wrapper.styles';
import { useHistory } from 'react-router';
import Slider from './Slider/slider.component'
let callback;
const ServicesItemWrapper = ({ works, currentTab }) => {
const [content, setContent] = useState([])
const { width } = useWindowDimensions()
const [imageWidth, setImageWidth] = useState(345)
const [imageHeight, setImageHeight] = useState(700)
const [idCases, setCasesId] = useState([])
const history = useHistory()
useEffect(() => {
if (width > 1070) {
setImageWidth(345)
setImageHeight(700)
} else if (width > 380) {
setImageWidth(300)
setImageHeight(600)
} else {
setImageWidth(250)
setImageHeight(400)
}
}, [width, imageWidth, currentTab])
useEffect(() => {
if (width) {
let appsImages = []
let id = []
if (currentTab === 0) {
works.apps.map((app) => {
appsImages.push({ img: app.MainImageServices, logo: app.Logo })
id.push(app.id)
return appsImages
})
} else {
works.websites.map((app) => {
appsImages.push({ img: app.MainImageServices, logo: app.Logo })
id.push(app.id)
return appsImages
})
}
setCasesId(id)
setContent(appsImages)
}
}, [works, currentTab, width])
const registerCallBack = () => {
callback = true
}
const cancelCallback = (e) => {
if (callback) {
callback = false
}
}
const handleMouseUp = (id) => {
if (callback) {
if (currentTab === 0) {
history.push(`/works/Application/${id}`)
} else {
history.push(`/works/Website/${id}`)
}
}
}
return (
<ComponentWrapper>
<Slider
width={(imageWidth * content.length) + (16 * content.length)}
screenWidth={width}
slideWidth={imageWidth}
slideCount={content.length}
>
{
content.length > 0 ? content.map((image, index) => {
return (
<div key={index}>
<SlideContainer
style={{ width: imageWidth, height: imageHeight }}
// onClick={() => handleNavigation(idCases[index])}
onMouseDown={registerCallBack}
onMouseMove={cancelCallback}
onMouseUp={() => handleMouseUp(idCases[index])}
key={index}
>
<SlideOverlay
translate={imageWidth}
apps={currentTab === 0}
imgWidth={width < 400 && currentTab === 1 ? image.logo?.width * 0.45 : width < 600 ? image.logo?.width * 0.6 : currentTab === 1 ? image.logo?.width * 0.7 : image.logo?.width}
>
<img draggable={false} src={CMS_URL + image.logo?.url} alt='logo' />
<img draggable={false} src={CMS_URL + image.logo?.url} alt='logo' />
</SlideOverlay>
<SlideImage
id='slide'
apps={currentTab === 0}
src={CMS_URL + image.img?.url}
key={index}
alt='itemImage'
draggable={false}
/>
</SlideContainer>
</div>
)
})
: null
}
</Slider>
</ComponentWrapper>
)
}
export default ServicesItemWrapper;<file_sep>/src/components/AnimatedHeaderMobile/AnimatedHeaderSection/animated_header_section.jsx
import React, { useState } from 'react';
import { InView } from 'react-intersection-observer';
import AnimatedNumbers from '../../Common/AnimatedNumbers/animated-numbers.component';
import {
AnimatedHeaderSectionContainer,
SectionHeader,
SectionText
} from './animated_header_section.styles';
const AnimatedHeaderSection = ({ title, index, text }) => {
const [animate, setAnimate] = useState(false)
const handleViewportChange = (e, entry) => {
if (e && entry && (entry.intersectionRatio >= 1)) {
if (!animate) {
setAnimate(true)
}
}
}
return (
<InView
threshold={1}
onChange={handleViewportChange}
style={{ width: '100%', maxWidth: '500px' }}
>
<AnimatedHeaderSectionContainer>
<AnimatedNumbers
index={index}
duration={0.3}
show={animate}
/>
<SectionHeader>
{title}
</SectionHeader>
<SectionText>
{text}
</SectionText>
</AnimatedHeaderSectionContainer>
</InView>
)
}
export default AnimatedHeaderSection;
<file_sep>/src/components/SectionPlan/section-plan.component.jsx
import React from 'react';
import Section from '../Common/Section/section.component';
import Plan from '../Plan/plan.component';
import { useTranslation } from '../../hooks/translation';
// import {
// PlanWrapper,
// Heading,
// Text
// } from './section-plan.styles';
const SectionPlan = ({ refApplication, onOpenModal }) => {
const { t } = useTranslation()
return (
<Section
// reff={refPlan}
title={t('work_plan')}
description={t('work_plan_desc')}
index={5}
descriptionWidth={'480px'}
>
<Plan refApplication={refApplication} onOpenModal={onOpenModal} />
</Section>
);
}
export default SectionPlan;<file_sep>/src/components/SectionGoals/section-goals.component.jsx
import React from 'react';
import { useSelector } from 'react-redux';
import { colorSelectors } from '../../redux/color/color.selectors';
import Section from '../Common/Section/section.component';
import { useTranslation } from '../../hooks/translation';
import {
Button
} from './section-goals.styles';
import GoalsList from './GoalsList/goal_list.component';
const SectionGoals = ({ onOpenModal }) => {
const color = useSelector(colorSelectors.color);
const { t } = useTranslation()
return (
<Section
title={t('your_goals')}
description={t('your_goals_desc')}
index={1}
headerContainerStyles={{
marginBottom: '40px'
}}
descriptionWidth={'370px'}
custom={<GoalsList />}
>
<Button onClick={onOpenModal} color={color}>
{t('leave_request')}
</Button>
</Section>
);
}
export default SectionGoals;<file_sep>/src/styles/common.jsx
import styled from 'styled-components';
import { motion } from 'framer-motion';
export const CustomButton = styled(motion.button)`
outline: none;
box-shadow: none;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
width: 100%;
max-width: 400px;
min-height: 60px;
border: 1px solid #3fb755;
border-radius: 2px;
background-color: transparent;
cursor: pointer;
transition-duration: 0.2s;
opacity: 1;
font-weight: 500;
font-size: 14px;
line-height: 19px;
color: #fefefe;
position: relative;
>img {
position: absolute;
right: 30px;
}
`
export const CustomHeading = styled(motion.h2)`
font-weight: 800;
font-size: 42px;
line-height: 50px;
color: #F9F9F9;
margin-bottom: 12px;
@media (max-width: 600px) {
font-size: 28px;
line-height: 32px;
}
`
export const CustomText = styled(motion.span)`
font-weight: 200;
font-size: 14px;
line-height: 20px;
letter-spacing: 0.05em;
color: #F9F9F9;
width: 100%;
max-width: 400px;
`<file_sep>/src/components/ServicesItemWrapper/services-item-wrapper.styles.jsx
import styled from 'styled-components';
export const ComponentWrapper = styled.div`
display: flex;
flex-direction: column;
${props => props.sliderWidth ? 'align-items: center;' : ''};
width: 100%;
margin: 80px 5px 0px 5px;
padding: 0 20px;
@media(max-width: 612px) {
padding: 0;
margin-top: 50px;
}
.slick-slider {
${props => props.sliderWidth ? 'width:' + props.sliderWidth + 'px;' : ''}
/* width: 500px; */
}
.slick-dots li.slick-active button:before {
opacity: 1;
color: #F9F9F9;
}
.slick-dots li button:before {
opacity: 1;
color: rgba(196, 196, 196, 0.6);
font-size: 8px;
}
.slick-slide {
text-align: center;
}
.slick-dots {
bottom: -35px;
}
`
export const SlideContainer = styled.div`
display: flex;
justify-content: center;
/* padding: ${props => props.countSlide ? '0' : '20px'}; */
/* padding: 8px; */
margin: 8px;
overflow: hidden;
border-radius: 6px;
cursor: pointer;
text-align: center;
position: relative;
z-index: 10;
@media(max-width: 420px) {
padding: 5px;
}
`
export const SlideImage = styled.img`
width: 100%;
`
export const SlideImageBig = styled.img`
padding: 0px 5px;
width: 100%;
/* max-width: 800px; */
`
export const SlideOverlay = styled.div`
width: 100%;
height: 100%;
position: absolute;
z-index: 100;
background-color: rgba(10,10,10,0.6);
/* background: */
backdrop-filter: blur(2px);
transition-duration: 0.3s;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
>img {
width: ${props => props.imgWidth}px;
/* transition-duration: ${props => props.apps ? '0.5s' : '0.8s'}; */
transition-duration: 0.8s;
opacity: 1;
position: absolute;
:first-of-type {
clip-path: polygon(0 0, 62% 0%, 32% 100%, 0 100%);
}
:last-of-type {
clip-path: polygon(61% 0, 100% 0%, 100% 100%, 31% 100%);
}
}
@media(min-width: 768px) {
:hover {
background-color: rgba(0,0,0,0);
transition-duration: 0.3s;
backdrop-filter: blur(0);
>img {
/* transition-duration: ${props => props.apps ? '0.5s' : '0.8s'}; */
transition-duration: 0.8s;
:first-of-type {
transform: translateX(-${props => props.translate - 100}px) translateY(${props => props.translate + 100}px);
}
:last-of-type {
transform: translateX(${props => props.translate - 100}px) translateY(-${props => props.translate + 100}px);
}
}
}
}
`
export const ArrowContainer = styled.div`
position: absolute;
top: calc(50% - 20px);
${props => !props.right ? 'left: -40px;' : 'right: -45px;'}
z-index: 1;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
/* background-color: ${props => props.color}; */
cursor: pointer;
`<file_sep>/src/components/BottomTab/bottom-tab.component.jsx
import React, { useEffect, useState } from 'react';
import {
BottomTab,
BottomTabBarContainer,
BottomTabBarInnerContainer,
BottomTabContainer,
BottomTabIcon,
BottomTabTitle
} from './bottom-tab.styles';
import { ReactComponent as WWWSVg } from '../../assets/sites.svg';
import { ReactComponent as ServicesSVG } from '../../assets/services.svg';
import { ReactComponent as AppsSVg } from '../../assets/apps.svg';
import { useSelector } from 'react-redux';
import { colorSelectors } from '../../redux/color/color.selectors';
import { useRef } from 'react';
import { useTranslation } from '../../hooks/translation';
const assets = {
'Мобильные приложения': {
icon: <AppsSVg />,
name: 'Приложения',
nameEng: 'Apps'
},
'Сайты': {
icon: <WWWSVg />,
name: 'Сайты',
nameEng: 'Websites'
},
'Доп.услуги': {
icon: <ServicesSVG />,
name: 'Услуги',
nameEng: 'Services'
}
}
const BottomTabBar = ({ tabNames, onTabClick, currentTab }) => {
const color = useSelector(colorSelectors.color)
const lastOffset = useRef(0)
const direction = useRef(0)
const scrollDown = useRef(false)
const [scrollD, setScrollD] = useState(false)
const { language } = useTranslation()
useEffect(() => {
let cleanupFunction = false;
const handleScroll = () => {
const pageOffset = window.pageYOffset
const height = window.innerHeight
const fullHeight = document.body.offsetHeight
if (pageOffset < 0) {
return
} else {
if (fullHeight - (pageOffset + height) < 100) {
if (!scrollDown.current) {
scrollDown.current = true
setScrollD(true)
}
} else {
if (pageOffset - lastOffset.current > 0) {
if (direction !== -1) {
scrollDown.current = true
setScrollD(true)
}
direction.current = -1
} else {
if (direction !== 1) {
scrollDown.current = false
setScrollD(false)
}
direction.current = 1
}
lastOffset.current = pageOffset
}
}
}
let timeout
if (!cleanupFunction) {
timeout = setTimeout(() => {
lastOffset.current = window.pageYOffset
document.addEventListener('scroll', handleScroll)
return () => {
document.removeEventListener('scroll', handleScroll)
}
}, 2000)
}
return () => {
cleanupFunction = true
clearTimeout(timeout)
}
}, [])
return (
<BottomTabContainer
// initial={{y: 0 }}
// animate={{y: scrollDown? 80: 0}}
// transition={{
// duration: 0.5
// }}
hide={scrollD}
>
<BottomTabBarContainer
color={color}
>
<BottomTabBarInnerContainer>
{
tabNames.map((name, index) => {
return (
<BottomTab
key={index}
onClick={() => onTabClick(index)}
>
<BottomTabIcon
active={index === currentTab}
>
{
assets[name].icon
}
</BottomTabIcon>
<BottomTabTitle
active={index === currentTab}
>
{
language === 'ru' ? assets[name].name : assets[name].nameEng
}
</BottomTabTitle>
</BottomTab>
)
})
}
</BottomTabBarInnerContainer>
</BottomTabBarContainer>
</BottomTabContainer>
)
}
export default BottomTabBar;<file_sep>/src/components/ServiceTab/AnimatedDescriptionWeb/AnimatedPath/animated_path.jsx
import { useAnimation } from 'framer-motion';
import React, { useEffect, useState, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { colorSelectors } from '../../../../redux/color/color.selectors';
import {
AnimatedGroup,
FirstStop,
SecondStop,
ThirdStop
} from './animated_path.styles'
const AnimatedPath = ({ path, index, duration, start, callback }) => {
const firstControls = useAnimation()
const secondControls = useAnimation()
const thirdControls = useAnimation()
const color = useSelector(colorSelectors.color)
const [animationEnd, setAnimationEnd] = useState(false)
const onAnimationStep = (color, duration) => {
const animationStep = {
stopColor: color,
transition: {
duration: duration,
ease: 'linear'
}
}
return animationStep
}
const memoAnimationStep = useMemo(() => onAnimationStep(color, duration), [color, duration])
useEffect(() => {
let cleanupFunction = false;
if (start) {
const animation = async () => {
firstControls.stop()
secondControls.stop()
thirdControls.stop()
await firstControls.start(memoAnimationStep)
await secondControls.start(memoAnimationStep)
return await thirdControls.start(memoAnimationStep)
}
animation()
.then(() => {
if (!cleanupFunction) {
setAnimationEnd(true)
if (callback) {
callback()
}
}
})
}
return () => {
firstControls.stop()
secondControls.stop()
thirdControls.stop()
cleanupFunction = true
}
}, [firstControls, secondControls, thirdControls, color, start, memoAnimationStep, callback])
return (
<AnimatedGroup index={index} animationEnd={animationEnd} color={color}>
<linearGradient id={`gradient${index}`} x1={'0%'} y1={'50%'} x2={'100%'} y2={'50%'} >
<FirstStop
initial={{
stopColor: '#414141'
}}
animate={firstControls}
offset="0%"
>
</FirstStop>
<SecondStop
offset="50%"
initial={{
stopColor: '#414141'
}}
animate={secondControls}
></SecondStop>
<ThirdStop
offset="100%"
initial={{
stopColor: '#414141'
}}
animate={thirdControls}
></ThirdStop>
</linearGradient>
{path}
</AnimatedGroup>
)
}
export default AnimatedPath;<file_sep>/src/components/WorkItem/Slider/slider.styles.jsx
import { motion } from 'framer-motion';
import styled from 'styled-components';
export const SliderContainer = styled(motion.div)`
display: flex;
flex-wrap: no-wrap;
`
export const ArrowContainer = styled.div`
position: absolute;
top: calc(50% - 20px);
${props => !props.right ? 'left: -50px;' : 'right: -55px;'}
z-index: 1;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
/* background-color: ${props => props.color}; */
cursor: pointer;
`<file_sep>/src/components/WorksTab/works-tab.styles.jsx
import styled from 'styled-components';
import {motion} from 'framer-motion';
export const TabContainer = styled(motion.div)`
width: 100%;
display: flex;
flex-direction: column;
padding-top: 28px;
@media(max-width: 600px) {
padding-top: 12px;
}
`
export const TabHeader = styled.div`
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
`
export const Description = styled.p`
width: 100%;
max-width: 394px;
font-weight: 200;
font-size: 14px;
line-height: 20px;
letter-spacing: 0.3px;
color: #F9F9F9;
@media(max-width: 600px) {
max-width: initial;
}
`
export const NumberContainer = styled.div`
@media(max-width: 611px) {
display: none;
}
`<file_sep>/src/components/BottomTab/bottom-tab.styles.jsx
import styled from 'styled-components';
export const BottomTabContainer = styled.div`
width: 100%;
position: fixed;
bottom: 0;
left: 0;
display: flex;
justify-content: center;
z-index: 1;
transition-duration: 0.5s;
transform: ${props => `translateY(${props.hide? 80: 0}px)`};
`
export const BottomTabBarContainer = styled.div`
width: 100%;
max-width: 400px;
background-color: ${props => props.color};
height: 57px;
display: flex;
flex-direction: row;
justify-content: center;
@media(min-width:401px) {
border-radius: 10px;
margin-bottom: 15px;
}
`
export const BottomTabBarInnerContainer = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
width: 70%;
height: 100%;
padding: 8px 0px;
`
export const BottomTab = styled.div`
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100%;
align-items: center;
cursor: pointer;
`
export const BottomTabIcon = styled.div`
>svg >path {
stroke: ${props => props.active? '#ffffff' :'rgba(0, 0, 0, 0.5)'};
}
`
export const BottomTabTitle = styled.div`
/* color: ${props => props.active? '#111111' :'#ffffff'}; */
color: ${props => props.active? '#ffffff' :'rgba(0, 0, 0, 0.5)'};
font-weight: 500;
font-size: 10px;
line-height: 11px;
/* identical to box height */
`<file_sep>/src/components/Common/AnimatedNumbers/animated-numbers.styles.jsx
import styled from 'styled-components';
import {motion} from 'framer-motion';
export const AnimatedNumber = styled.div`
>svg {
fill: url(${props => `#grad${props.index}`});
>path {
fill: url(${props => `#grad${props.index}`});
}
}
`
export const FirstStop = styled(motion.stop)`
`
export const SecondStop = styled(motion.stop)`
`
export const ThirdStop = styled(motion.stop)`
`
<file_sep>/src/redux/language/language.selectors.jsx
export const languageSelectors = {
language: (state) => state.language.language
}<file_sep>/src/components/ModalRequest/modal-request.component.jsx
import React, { forwardRef } from 'react'
import Dialog from '@material-ui/core/Dialog';
import Slide from '@material-ui/core/Slide';
import { styled } from '@material-ui/core/styles';
import { ModalContainer, CloseButton } from './modal-request.styles';
import closeIcon from '../../assets/close-icon.svg'
import SectionRequest from '../SectionRequest/section-request.component';
import { useWindowDimensions } from '../../hooks/dimensions';
const Transition = forwardRef(function Transition(props, ref) {
return <Slide direction="up" ref={ref} {...props} />;
});
const CustomDialog = styled(Dialog)({
width: '100%',
height: '100%'
})
const ModalRequest = ({
open,
onClose
}) => {
const { width } = useWindowDimensions()
return (
<CustomDialog
open={open}
TransitionComponent={Transition}
disableScrollLock={width > 768 ? true: false}
id='modal-base'
scroll='body'
keepMounted
onClose={onClose}
aria-labelledby="alert-dialog-slide-title"
aria-describedby="alert-dialog-slide-description"
maxWidth={'xl'}
fullScreen={width < 769}
>
<ModalContainer>
<CloseButton onClick={onClose}>
<img src={closeIcon} alt='Закрыть' />
</CloseButton>
{
open&&
<SectionRequest
// index={5}
nonNumber={true}
onCloseModal={onClose}
/>
}
</ModalContainer>
</CustomDialog >
);
}
export default ModalRequest<file_sep>/src/components/Header/header.component.jsx
import React, { useEffect, useRef, useState, useContext } from 'react';
import { HeaderWrapper, Background } from './header.styles';
import useOnClickOutside from '../../hooks/onClickOutside';
import { MenuContext } from '../../context/menu-state';
import Navbar from './Navbar/navbar.component';
// import DropdownMenu from './DropdownMenu/dropdown-menu.component';
import { useWindowDimensions } from '../../hooks/dimensions';
import MobileNavbar from './MobileNavbar/mobile-navbar.component';
import MobileMenu from './MobileMenu/mobile-menu.component';
const Header = () => {
const headerRef = useRef();
const { width } = useWindowDimensions()
const [openMenu, setOpenMenu] = useState(0)
const [backgroundWidth, setBackgroundWidth] = useState(false)
useEffect(() => {
if (openMenu) {
setBackgroundWidth(true)
}
// else {
// setBackgroundWidth(false)
// }
}, [openMenu])
const { isMenuOpen } = useContext(MenuContext);
useOnClickOutside(headerRef, () => {
if (openMenu) {
setOpenMenu(0)
}
})
return (
<HeaderWrapper ref={headerRef} background={isMenuOpen}>
{
width < 960 && !isMenuOpen ?
<Background backgroundWidth={backgroundWidth} />
: width > 960 ?
<Background backgroundWidth={backgroundWidth} />
: null
}
{
width > 960 ?
<Navbar
openMenu={openMenu}
setOpenMenu={setOpenMenu}
setBackgroundWidth={setBackgroundWidth}
backgroundWidth={backgroundWidth}
/>
: <MobileNavbar setOpenMenu={setOpenMenu} />
}
{
width > 960 ?
// <DropdownMenu />
null
:
<MobileMenu />
}
</HeaderWrapper>
);
}
export default Header;<file_sep>/src/components/Map/custom-map.styles.jsx
import styled from 'styled-components';
export const MapContainer = styled.div`
border-radius: 12px;
display: flex;
justify-content: center;
align-items: center;
.mapContainer {
/* width: 466px;
height: 291px; */
border-radius: 12px;
overflow: hidden;
}
`<file_sep>/src/pages/Works/works.component.jsx
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import Tabs from '../../components/Tabs/tabs.component';
import WorksTab from '../../components/WorksTab/works-tab.component';
import {
PageContainer,
PageHeader,
PageTitle,
Button
} from './works.styles';
import { useWindowDimensions } from '../../hooks/dimensions';
import SectionRequest from '../../components/SectionRequest/section-request.component';
import { useSelector } from 'react-redux';
import { contentSelectors } from '../../redux/content/content.selectors';
import { useTranslation } from '../../hooks/translation';
import ModalRequest from '../../components/ModalRequest/modal-request.component';
import { colorSelectors } from '../../redux/color/color.selectors';
const WorksPage = () => {
const works = useSelector(contentSelectors.cases)
const { itemId, section } = useParams()
const { width } = useWindowDimensions()
const { t, language } = useTranslation()
const [openModal, setOpenModal] = useState(false)
const color = useSelector(colorSelectors.color)
const onOpenModal = () => {
setOpenModal(true)
}
const onCloseModal = () => {
setOpenModal(false)
}
useEffect(() => {
window.scrollTo(0, 0)
if (itemId === 'all') {
window.scrollTo(0, 0)
}
return () => {
localStorage.setItem('scroll', 'false')
}
}, [itemId])
return (
<PageContainer>
<PageHeader>
<PageTitle>
{t('portfolio')}:
</PageTitle>
</PageHeader>
<Tabs
tabNames={['Мобильные приложения', 'Сайты']}
tabOverride={section === 'Website' ? 1 : undefined}
language={language}
tabNamesEng={['Mobile apps', 'Websites']}
>
<WorksTab
description={t('mobile_apps_desc')}
works={works.apps}
/>
<WorksTab
description={t('websites_desc')}
works={works.websites}
/>
</Tabs>
{
width > 800 ?
<div style={{ marginTop: '110px' }}>
<SectionRequest index={2} padding={'0px'} nonNumber={true} />
</div>
: <Button onClick={onOpenModal} color={color}>
{t('leave_request')}
</Button>
}
<ModalRequest
open={openModal}
onClose={onCloseModal}
/>
</PageContainer>
)
}
export default WorksPage
|
d0d537faf542054303d75cf024d97902318301f8
|
[
"JavaScript"
] | 80
|
JavaScript
|
Chooosa/studio-front
|
ecc187e653f4a2a58652ca8d0cbb698fd158a574
|
6dacabb35a95514d2501d6e5af0d8e85b6ccd215
|
refs/heads/master
|
<file_sep>class CoffeeMachine:
def __init__(self, milk,coffee,sugar):
self.milk = milk
self.coffee = coffee
self.sugar = sugar
def make_coffee(self,milk,coffee,sugar):
if milk > self.milk and coffee > self.coffee and sugar > self.sugar:
min = milk - self.milk
min2 = coffee - self.coffee
min3 = sugar - self.sugar
print(f"Не достаточно \n молока-{min}\n кофе-{min2}\n сахара-{min3}")
elif milk > self.milk and coffee > self.coffee and sugar < self.sugar:
min = milk - self.milk
min2 = coffee - self.coffee
print(f"Не достаточно молока-{min} и кофе-{min2}")
elif milk > self.milk and coffee < self.coffee and sugar > self.sugar:
min = milk - self.milk
min2 = coffee - self.coffee
print(f"Не достаточно молока-{min} и сахара-{min2}")
elif milk < self.milk and coffee > self.coffee and sugar > self.sugar:
min = sugar - self.sugar
min2 = coffee - self.coffee
print(f"Не не достаточно кофе-{coffee} и сахара-{sugar}")
elif milk > self.milk and coffee < self.coffee and sugar < self.sugar:
min = milk - self.milk
print(f"Не достаточно молока-{min}")
elif milk < self.milk and coffee > self.coffee and sugar < self.sugar:
min = coffee - self.coffee
print(f"Не достаточно кофе-{min}")
elif milk < self.milk and coffee < self.coffee and sugar > self.sugar:
min = sugar - self.sugar
print(f"Не достаточно сахара-{min}")
elif milk < self.milk and coffee < self.coffee and sugar < self.sugar:
self.__substract_milk(milk)
self.__substract_coffee(coffee)
self.__subtsract_sugar(sugar)
print(f"Кофе готов \nмолока-{self.milk}\nкофе-{self.coffee}\nсахара{self.sugar}")
def __substract_milk(self,milk):
self.milk -= milk
def __substract_coffee(self,coffee):
self.coffee -= coffee
def __subtsract_sugar(self,sugar):
self.sugar -= sugar
def main():
coffemachine = CoffeeMachine(1000,1000,1000)
coffemachine.make_coffee(1111,2222,3333)
if __name__ == "__main__":
main()
def main():
coffemachine = CoffeeMachine(1000,1000,1000)
coffemachine.make_coffee(222,444,666)
if __name__ == "__main__":
main()
|
80ae2211de8072ec381271e81a0e77f900dc3750
|
[
"Python"
] | 1
|
Python
|
muslinovsultan/ekzamen
|
92260712b64cd49f43f3fdbe7ebdebca3ff78358
|
6528e281d172b0a8a1417118b62eefc9a8c64787
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// SimpleAnimations
//
// Created by <NAME> on 20.09.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Spring
class ViewController: UIViewController {
@IBOutlet var animationView: SpringView!
@IBOutlet var detailsLabel: SpringLabel!
let animation = Animation.getAnimation()
var currentAnimation = 0
override func viewDidLoad() {
super.viewDidLoad()
animationView.isHidden = true
}
@IBAction func animationButtonTapped(_ sender: SpringButton) {
animationView.isHidden = false
showAnimation(view: animationView)
showAnimation(view: detailsLabel)
showLabel()
nextAnimation(sender: sender)
updateAnimation()
}
private func nextAnimation(sender: SpringButton) {
if currentAnimation + 1 < animation.count {
sender.setTitle(animation[currentAnimation].name, for: .normal)
}
}
private func showAnimation(view: Springable) {
if currentAnimation < animation.count {
view.animation = animation[currentAnimation].name
view.curve = animation[currentAnimation].curve
view.duration = animation[currentAnimation].duration
view.damping = animation[currentAnimation].damping
view.velocity = animation[currentAnimation].velocity
view.scaleX = animation[currentAnimation].scaleX
view.scaleY = animation[currentAnimation].scaleY
view.rotate = animation[currentAnimation].rotate
view.animate()
}
}
private func showLabel() {
if currentAnimation < animation.count {
detailsLabel.text = ("""
name \(animation[currentAnimation].name)
curve \(animation[currentAnimation].curve)
duration \(String(format: "%.3f", animation[currentAnimation].duration))
damping \(String(format: "%.3f", animation[currentAnimation].damping))
velocity \(String(format: "%.3f", animation[currentAnimation].velocity))
scale X \(String(format: "%.3f", animation[currentAnimation].scaleX))
scale Y \(String(format: "%.3f", animation[currentAnimation].scaleY))
rotate \(String(format: "%.3f", animation[currentAnimation].rotate))
""")
currentAnimation += 1
}
}
private func updateAnimation() {
if currentAnimation == animation.count {
currentAnimation = 0
}
}
}
<file_sep>//
// Model.swift
// SimpleAnimations
//
// Created by <NAME> on 21.09.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
struct Animation {
let name: String
let curve: String
let duration: CGFloat
let scaleX: CGFloat
let scaleY: CGFloat
let rotate: CGFloat
let damping: CGFloat
let velocity: CGFloat
}
extension Animation {
static func getAnimation() -> [Animation] {
var animation: [Animation] = []
let animations = DataManager.shared.animations.shuffled()
let curves = DataManager.shared.curves.shuffled()
for index in 0 ..< animations.count {
animation.append(Animation(name: animations[index],
curve: curves[index],
duration: CGFloat.random(in: 0.1...1),
scaleX: CGFloat.random(in: 0...1),
scaleY: CGFloat.random(in: 0...1),
rotate: CGFloat.random(in: 0...1),
damping: CGFloat.random(in: 0...1),
velocity: CGFloat.random(in: 0...1)))
}
return animation
}
}
|
9421939cad76f7c321fea9cb16602359834e3c6c
|
[
"Swift"
] | 2
|
Swift
|
KevinWendelCrumb/SimpleAnimationsApp
|
aa17ffe3bf6802e9641f283df1db7f0355997c74
|
0b7d651c16d1c0275571cba43bd20b8b15278b23
|
refs/heads/master
|
<file_sep>package DoAn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class kiemtra {
public static boolean isNumberic(String x) {
try {
Double.parseDouble(x);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static boolean date(String x) {
SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
df.setLenient(false);
try {
df.parse(x);
return true;
} catch (ParseException e) {
return false;
}
}
public static boolean phone(String x) {
try {
String phonePattern = "\\d{10}";
if (x.matches(phonePattern)) {
return true;
}
} catch (Exception e) {
}
return false;
}
public static boolean checkName(String x) {
int i = 0;
String a;
for (; i < x.length(); i++) {
a = String.valueOf(x.charAt(i));
if (isNumberic(a) == true) {
return true;
}
}
return false;
}
public static boolean checkMNV(String x, File file) {
BufferedReader f = null;
String line;
String[] linenew;
try {
f = new BufferedReader(new FileReader(file));
while ((line = f.readLine()) != null) {
linenew = line.split(" ");
if (linenew[0].equals(x)) {
return true;
}
}
} catch (IOException e) {
}
return false;
}
}
<file_sep>package DoAn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public interface thaotac {
void add(String x);
void add();
void delete(String x);
void delete();
void save();
// void find(String x);
// void sort();
}
<file_sep>package DoAn;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Scanner;
public class chitiethoadon implements thaotac {
public String MaHD;
public String MaSP;
public int Sl;
public long Gia;
String line, line1;
String[] linenew, linenew1;
File file = new File("chitiethoadon.txt");
File file3 = new File("hoadon.txt");
Scanner input = new Scanner(System.in);
public chitiethoadon() {
MaHD = null;
MaSP = null;
Sl = 0;
Gia = 0;
}
public void xuatCTHD(String x) {
BufferedReader f = null;
System.out.println("Ma hoa don :" + x);
System.out.printf("%-20s%-20s%-20s\n", "MaSP", "SL", "Gia");
try {
f = new BufferedReader(new FileReader(file));
while ((line = f.readLine()) != null) {
linenew = line.split(" ");
if (linenew[0].equals(x)) {
System.out.printf("%-20s%-20s%-20s\n", linenew[1], linenew[2], linenew[3]);
}
}
} catch (IOException e) {
}
}
public String toString() {
return MaHD + " " + MaSP + " " + Sl + " " + Gia;
}
@Override
public void add(String x) {
try {
FileWriter file1 = new FileWriter(file, true);
BufferedReader file2 = new BufferedReader(new FileReader(file));
Writer out = new BufferedWriter(file1);
// try {
// f3 = new BufferedReader(new FileReader(file3));
// while ((line1 = f3.readLine()) != null) {
// linenew1 = line1.split(" ");
// if (x.equals(linenew1[0])) {
// MaHD = linenew1[0];
// }
// }
// } catch (IOException e) {
// }
//
dsHoadon d = new dsHoadon();
d.docFile();
MaHD=x;
System.out.println("Hay nhap ma san pham");
MaSP = input.nextLine();
System.out.println("Hay nhap So luong");
String d5=input.nextLine();
while(kiemtra.isNumberic(d5)!=true)
{
System.out.println("Sai!");
d5=input.nextLine();
}
Sl=Integer.valueOf(d5);
System.out.println("Hay nhap gia tien");
String d6=input.nextLine();
while(kiemtra.isNumberic(d5)!=true)
{
System.out.println("Sai!");
d6=input.nextLine();
}
Gia = Integer.valueOf(d6);
System.out.println();
out.write("\n"+toString());
out.close();
System.out.println(file.getAbsolutePath());
} catch (IOException e) {
System.out.println("Error " + e);
}
}
@Override
public void add() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(String x) {
}
@Override
public void delete() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void save() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DoAn;
/**
*
* @author Admin
*/
public class drink extends sanpham {
public static String LOAISP;
public drink(){};
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DoAn;
/**
*
* @author Admin
*/
public class food extends sanpham {
public static String LOAISP="Food";
public food(String MAHANG, String TENHANG, String NSX, String HSD, String NCC, String LOAI, int SOLUONG, String DONVI) {
super(MAHANG, TENHANG, NSX, HSD, NCC, LOAI, SOLUONG, DONVI);
LOAI=LOAISP;
}
public food(){
super();
LOAI=food.LOAISP;
}
}
<file_sep>package DoAn;
import java.util.Scanner;
public class Nhanvien extends ConNguoi {
protected String MaNV;
Scanner input = new Scanner(System.in);
public String toString() {
return MaNV + " " + Hoten + " " + Ngaysinh + " " + SDT;
}
public Nhanvien() {
super();
MaNV = null;
}
public Nhanvien(String Hoten, String Ngaysinh, String SDT, String MaNV) {
super(Hoten, Ngaysinh, SDT);
this.MaNV = MaNV;
}
@Override
public void nhap() {
System.out.println("Hay nhap vao ma nhan vien ");
MaNV = input.nextLine();
super.nhap();
}
@Override
public void xuat() {
System.out.printf("%-20s", MaNV);
super.xuat();
}
public String getMaNV() {
return MaNV;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DoAn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
/**
*
* @author Admin
*/
public class Admin extends Account {
File file = new File("admin.txt");
String line;
String[] linenew;
public boolean dangnhap(String x, String y) {
String line;
String[] linenew;
BufferedReader f = null;
try {
f = new BufferedReader(new FileReader(file));
while ((line = f.readLine()) != null) {
linenew = line.split(" ");
if (x.equals(linenew[0]) && y.equals(linenew[1])) {
System.out.println("Ban da dang nhap thanh cong");
return true;
}
}
} catch (Exception e) {
}
System.out.println("Sai!!Vui long nhap lai");
return false;
}
public void taoUser() {
}
}
<file_sep>
package DoAn;
import java.util.Scanner;
public class MAIN {
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
String d;
System.out.println("Ban muon dang nhap voi vai tro gi ?");
System.out.println("0-Thoat chuong trinh");
System.out.println("1-Admin");
System.out.println("2-User");
System.out.println("====================================");
System.out.print("HAY NHAP LUA CHON :");
d = input.nextLine();
while (kiemtra.isNumberic(d) != true) {
System.out.println("Sai!");
System.out.print("HAY NHAP LUA CHON (bang so): ");
d = input.nextLine();
}
int ktt=0;
while (1 == 1) {
switch (d) {
case "0": {
return;
}
case "1": {
while(ktt!=1){
Admin d2 = new Admin();
System.out.print("Tai khoan :");
String taikhoan = input.nextLine();
System.out.print("Mat khau :");
String matkhau = input.nextLine();
if (d2.dangnhap(taikhoan, matkhau) == true) {
System.out.println("Xin chao admin");
System.out.println("0-Thoat");
System.out.println("1-Quan ly nhan vien");
System.out.println("2-Quan ly khach hang");
System.out.println("3-Quan li san pham");
System.out.println("4-Quan li hoa don");
System.out.println("5-Quan li phieu nhap");
System.out.println("6-Quan li phieu xuat");
System.out.print("HAY NHAP LUA CHON :");
String d3 = input.nextLine();
while (d3!="0") {
switch (d3) {
case "0":{
ktt=1;
break;
}
case "1": {
dsNhanvien d7 = new dsNhanvien();
d7.docFile();
System.out.println("1-Xuat danh sach nhan vien");
System.out.println("2-Thao tac tren danh sach nhan vien ");
System.out.print("HAY NHAP LUA CHON :");
String d5 = input.nextLine();
while (kiemtra.isNumberic(d5) != true) {
System.out.println("Sai!");
System.out.print("HAY NHAP LUA CHON (bang so): ");
d5 = input.nextLine();
}
int d6 = Integer.valueOf(d5);
switch (d6) {
case 1: {
System.out.println("Danh sach nhan vien ");
d7.xuatds();
}
break;
case 2: {
d7.thaotac();
}
break;
}
}
break;
case "2": {
System.out.println("Quan li khach hang");
dsKhachHang d8 = new dsKhachHang();
d8.docFile();
System.out.println("1-Xuat danh sach khach hang");
System.out.println("2-Thao tac tren danh sach khach hang");
System.out.println("HAY NHAP LUA CHON :");
String d9 = input.nextLine();
while (kiemtra.isNumberic(d9) != true) {
System.out.println("Sai!");
System.out.println("Sai!");
System.out.print("HAY NHAP LUA CHON (bang so): ");
d9 = input.nextLine();
}
int d10 = Integer.valueOf(d9);
switch (d10) {
case 1: {
System.out.println("Danh sach khach hang ");
d8.xuatds();
}
break;
case 2: {
d8.thaotac();
}
break;
}
}
break;
case "3": {
dssanpham d10 = new dssanpham();
d10.docFile();
System.out.println("QUAN LY SAN PHAM");
System.out.println("1-Xuat danh sach san pham");
System.out.println("2-Them san pham");
System.out.println("3-Xoa san pham");
String d11 = input.nextLine();
while (kiemtra.isNumberic(d11) == false) {
System.out.println("Sai!");
d11 = input.nextLine();
}
int d12 = Integer.valueOf(d11);
switch (d12) {
case 1: {
d10.xuat();
}
break;
case 2: {
d10.add();
}
break;
case 3: {
d10.delete();
}
break;
}
}
break;
case "4": {
dsHoadon d11 = new dsHoadon();
chitiethoadon d15 = new chitiethoadon();
d11.docFile();
System.out.println("1-Xuat hoa don");
System.out.println("2-Them hoa don");
System.out.println("3-Chinh sua hoa don");
String d12 = input.nextLine();
while (kiemtra.isNumberic(d12) != true) {
System.out.println("Sai!");
System.out.println("Hay nhap lai");
d12 = input.nextLine();
}
int d13 = Integer.valueOf(d12);
switch (d13) {
case 1: {
d11.xuat();
}
break;
case 2: {
System.out.println("Nhap ma hoa don");
String d14 = input.nextLine();
d11.add(d14);
}
break;
case 3: {
}
break;
}
}
break;
case "5": {
dsPhieunhap d19 = new dsPhieunhap();
dschitietphieunhap d16 = new dschitietphieunhap(); //change
d19.docFile();
System.out.println("1-Xuat phieu nhap");
System.out.println("2-Them phieu nhap");
System.out.println("3-Xuat chi tiet phieu nhap");
String d17 = input.nextLine();
while (kiemtra.isNumberic(d17) != true) {
System.out.println("Sai!!!!!!!!!!");
System.out.println("1-Xuat phieu nhap");
System.out.println("2-Them phieu nhap");
System.out.println("3-Xuat chi tiet phieu nhap");
d17 = input.nextLine();
}
while (kiemtra.isNumberic(d17) == true) {
int d18 = Integer.valueOf(d17);
switch (d18) {
case 1: {
System.out.println("Danh sach phieu nhap");
d19.xuat();
}
break;
case 2: {
System.out.println("Hay nhap vao ma phieu nhap moi");
String d20 = input.nextLine();
d19.add(d20); //change
d16.xuat(d20);
}
break;
case 3: {
System.out.println("Hay nhap vao ma phieu nhap can xem");
String d21 = input.nextLine();
d16.docfile();
d16.xuat(d21); //change
}
break;
default: {
break;
}
}
}
}
break;
default: {
System.out.println("Sai!Vui long nhap lai");
d3 = input.nextLine();
}
}
if(ktt==1)
{
break;
}
}
}
else
{
System.out.println("Ban da nhap sai mk hoac ten tk!");
System.out.println("Ban muon thoat khong?Y/N");
String kt=input.nextLine();
if(kt.equals("Y")||kt.equals("y"))
{
ktt=1;
}
else
continue;
}
}
System.out.println("Ban muon vao che do User khong?Y/N");
String kt=input.nextLine();
if(kt.equals("y")||kt.equals("Y"))
{
}
else
return;
}
case "2": {
System.out.println("CHE DO USER");
User d99 = new User();
System.out.print("Tai khoan :");
String taikhoan = input.nextLine();
System.out.print("Mat khau : ");
String matkhau = input.nextLine();
if (d99.dangnhap(taikhoan, matkhau) == true) {
System.out.print("Tai khoan :");
taikhoan = input.nextLine();
System.out.print("Mat khau : ");
matkhau = input.nextLine();
}
}
break;
default: {
System.out.println("SAI!Vui Long Nhap Lai");
d = input.nextLine();
}
}
}
}
}
|
7df50ecc698ce6dd163e14f7607b64f50a914591
|
[
"Java"
] | 8
|
Java
|
haidang-lhd/oop
|
e47feac391afb0bec331e48421d5f19fd53e6b5e
|
1e3e9474ade5a6b323fdb22ce69e413e5554a738
|
refs/heads/master
|
<file_sep>import java.util.Random;
import java.awt.Graphics2D;
public class Pipe {
private boolean active;
private int gapSize;
private Sprite spritePipeUpper,
spritePipeLower;
public Pipe(String spritePathU, String spritePathL, int gapSize) {
Random rand;
int pipeWidth, pipeHeight, lowerPipeUpperBound;
this.gapSize = gapSize;
rand = new Random();
lowerPipeUpperBound = rand.nextInt((int)Math.floor((Game.windowHeight * 0.75) - this.gapSize)) + this.gapSize;
pipeWidth = (int)(Game.windowWidth / 600 * 60);
pipeHeight = (int)(Game.windowHeight * 0.75);
this.spritePipeUpper = new Sprite(null, Game.windowWidth, lowerPipeUpperBound - (int)(Game.windowHeight * 0.75) - this.gapSize, pipeWidth, pipeHeight);
this.spritePipeLower = new Sprite(null, Game.windowWidth, lowerPipeUpperBound, pipeWidth, pipeHeight);
this.spritePipeUpper.loadImage(spritePathU);
this.spritePipeLower.loadImage(spritePathL);
this.active = true;
}
public boolean detectCollision(Sprite sprite) {
return (Sprite.detectCollision(this.spritePipeUpper, sprite) || Sprite.detectCollision(this.spritePipeLower, sprite));
}
public boolean detectScore(Sprite sprite) {
if (this.active && sprite.getX() > this.getSpriteL().getX() + this.getSpriteL().getWidth())
{
this.active = false;
return true;
}
return false;
}
public void evaluate() {
this.spritePipeUpper.moveX(-100 * Game.deltaTime);
this.spritePipeLower.moveX(-100 * Game.deltaTime);
}
public void draw(Graphics2D g) {
this.spritePipeUpper.draw(g);
this.spritePipeLower.draw(g);
}
public Sprite getSpriteU() {
return this.spritePipeUpper;
}
public Sprite getSpriteL() {
return this.spritePipeLower;
}
}<file_sep>import org.json.JSONObject;
import org.json.JSONException;
import java.io.*;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel implements KeyListener {
/* Constants */
private static final String configFile = "resource/config.json";
private static final int gameStateMenu = 0,
gameStateRunning = 1,
gameStateEnded = 2; // Pixels a pipe takes in space (left margin + pipe width + right margin)
/* Static variables */
protected static int windowWidth = 1200,
windowHeight = 800;
protected static float deltaTime;
private static boolean debug = false;
protected static JSONObject config = null;
/* Variables */
private int gameState, // Indicates the state of the game
framesPerSecond,
score;
private long frameDurationTime;
private Sprite spriteMainBg,
spriteGround,
spritePath;
private Bird bird;
private Pipe[] pipes;
/* Methods */
public Game (JFrame frame, JSONObject config) {
Game.config = config;
this.setFps(Game.configGetInt(new String[] {"game", "fps"}));
this.gameState = Game.gameStateMenu;
this.setupUI();
frame.addKeyListener(this);
}
public static void main(String[] args) {
File configFile;
FileInputStream configFileStream;
JSONObject config;
byte[] configFileContent;
Game game;
JFrame frame;
long frameBeginningTime;
// Load configuration
configFile = new File(Game.configFile);
try {
configFileStream = new FileInputStream(configFile);
} catch (IOException e) {
System.out.printf("in main: Failed to create file input stream for config: %s\n", e.getMessage());
return;
}
configFileContent = new byte[(int)configFile.length()];
try {
configFileStream.read(configFileContent);
configFileStream.close();
} catch (IOException e) {
System.out.printf("in main: failed to read config file: %s\n", e.getMessage());
return;
}
try {
config = new JSONObject(new String(configFileContent));
} catch (JSONException e) {
System.out.printf("in main: failed to setup json object for config: %s\n", e.getMessage());
return;
}
// Initialise JFrame
try {
frame = new JFrame(config.getJSONObject("text").getString("title"));
} catch (JSONException e) {
System.out.printf("in main: failed to load title from config: %s\n", e.getMessage());
return;
}
// Initialise Game
game = new Game(frame, config);
frame.add(game);
frame.setSize(Game.windowWidth, Game.windowHeight);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Game Loop
for(;;) {
frameBeginningTime = System.currentTimeMillis();
game.repaint();
// Wait until frame is over
while(frameBeginningTime > System.currentTimeMillis() - game.getFrameDuration());
}
}
public void setupUI() {
this.spriteMainBg = new Sprite(null, 0, 0, Game.windowWidth * 3, (int)(Game.windowHeight * 0.75));
this.spriteGround = new Sprite(null, 0, (int)(Game.windowHeight * 0.75 + Game.windowHeight / 400 * 6), Game.windowWidth * 2, (int)(Game.windowHeight * 0.25));
this.spritePath = new Sprite(null, 0, (int)(Game.windowHeight * 0.75), Game.windowWidth * 2, (int)(Game.windowHeight / 400 * 6));
this.spriteMainBg.loadImage(Game.configGetString(new String[] {"sprite", "background", "path"}));
this.spriteGround.loadImage(Game.configGetString(new String[] {"sprite", "ground", "path"}));
this.spritePath.loadImage(Game.configGetString(new String[] {"sprite", "pathway", "path"}));
this.bird = new Bird(Game.configGetString(new String[] {"sprite", "bird", "path"}));
}
@Override
public void paint(Graphics g) {
Graphics2D g2d;
super.paint(g);
g2d = (Graphics2D)g;
// Turn on antialiasing
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Draw background etc.
this.spriteMainBg.moveX((float)(-40 * Game.deltaTime));
if (!this.spriteMainBg.inBounds(new Rectangle(-Game.windowWidth * 2, 0, Game.windowWidth * 5, (int)(Game.windowHeight * 0.75))))
this.spriteMainBg.setX(0);
this.spriteGround.moveX(-100 * Game.deltaTime);
if (!this.spriteGround.inBounds(new Rectangle(-600, (int)(Game.windowHeight * 0.75), Game.windowWidth * 3, (int)(Game.windowHeight * 0.25))))
this.spriteGround.setX(0);
this.spritePath.moveX(-100 * Game.deltaTime);
if (!this.spritePath.inBounds(new Rectangle(-600, (int)(Game.windowHeight * 0.75), Game.windowWidth * 3, (int)(Game.windowHeight * 0.25))))
this.spritePath.setX(0);
this.spriteMainBg.draw(g2d);
this.spritePath.draw(g2d);
// Check game state and handle accordingly
if (this.gameState == Game.gameStateMenu) {
this.handleMenu(g2d);
}
else if (this.gameState == Game.gameStateRunning) {
this.handleRunning(g2d);
}
else if (this.gameState == Game.gameStateEnded) {
this.handleEnded(g2d);
} else {
throw new java.lang.RuntimeException(String.format("in paint: unknown game state: %d", this.gameState));
}
this.spriteGround.draw(g2d);
if (Game.debug)
{
Game.drawCenteredText(g2d,
"Debug enabled",
new Rectangle(0, 0, Game.windowWidth / 5, Game.windowHeight / 10),
new Font("Courier New", Font.PLAIN, 28));
}
}
private void handleMenu(Graphics2D g) {
drawCenteredText(g,
Game.configGetString(new String[] {"text", "title"}),
new Rectangle(0, 0, Game.windowWidth, Game.windowHeight / 3),
new Font("Ubuntu", Font.BOLD, 28));
drawCenteredText(g,
Game.configGetString(new String[] {"text", "menu", "instruction"}),
new Rectangle(0, 0, Game.windowWidth, Game.windowHeight / 2),
new Font("Ubuntu", Font.BOLD, 28));
if (this.bird.getY() > Game.windowHeight * 0.45)
this.bird.flap();
this.bird.evaluate();
this.bird.draw(g);
}
private void handleRunning(Graphics2D g) {
Rectangle r;
int i, j, maxPipeCount;
Sprite s;
this.bird.evaluate();
this.bird.draw(g);
maxPipeCount = Game.configGetInt(new String[] {"game", "maxPipeCount"});
for (i = 0; i < maxPipeCount; i++)
{
this.pipes[i].evaluate();
if (this.pipes[i].getSpriteL().inBounds(new Rectangle(Game.windowWidth - (int)(Game.windowWidth / maxPipeCount),
0,
(int)(Game.windowWidth / maxPipeCount * 2),
Game.windowHeight * 2))) break;
}
if (i == maxPipeCount) {
for (i = 0; i < maxPipeCount;)
{
s = this.pipes[i].getSpriteL();
if (s.inBounds(new Rectangle(-s.getWidth() * 2,
0,
s.getWidth() * 2,
Game.windowHeight * 2)))
{
for (j = 0; j < maxPipeCount - 1; j++)
this.pipes[j] = this.pipes[j + 1];
this.pipes[maxPipeCount - 1] = new Pipe(Game.configGetString(new String[] {"sprite", "pipeUpper", "path"}),
Game.configGetString(new String[] {"sprite", "pipeLower", "path"}),
(int)(Game.windowHeight * 0.2));
} else break;
}
}
for (i = 0; i < maxPipeCount; i++)
this.pipes[i].draw(g);
if (Game.debug)
{
g.setColor(Color.RED);
r = this.bird.getSprite().getDimensions();
g.drawRect((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight());
g.drawRect(Game.windowWidth - (int)(Game.windowWidth / maxPipeCount), 0, (int)(Game.windowWidth / maxPipeCount * 2), Game.windowHeight);
for (i = 0; i < maxPipeCount; i++) {
r = this.pipes[i].getSpriteU().getDimensions();
g.drawRect((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight());
r = this.pipes[i].getSpriteL().getDimensions();
g.drawRect((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight());
}
g.setColor(Color.BLACK);
}
if (!this.bird.inBounds(new Rectangle(0, (int)(-Game.windowHeight / 3), Game.windowWidth, + (int)(Game.windowHeight / 3 + Game.windowHeight * 0.75 + Game.windowHeight / 400 * 6))))
this.gameState = Game.gameStateEnded;
for (i = 0; i < maxPipeCount; i++) // TODO: We don't really need to check all pipes here. But overhead is little
{
s = this.bird.getSprite();
if (this.pipes[i].detectCollision(s))
this.gameState = Game.gameStateEnded;
else if (this.pipes[i].detectScore(s))
{
this.score++;
}
}
if (this.score > 0)
{
g.setColor(Color.WHITE);
Game.drawCenteredText(g, String.format("%d", this.score), new Rectangle(0, 0, Game.windowWidth, (int)(Game.windowHeight * 0.75)), new Font("Ubuntu", Font.BOLD, 48));
g.setColor(Color.BLACK);
}
}
private void handleEnded(Graphics2D g) {
int i;
if (this.bird.inBounds(new Rectangle(0, -1000, Game.windowWidth, (int)(Game.windowHeight * 0.75 + Game.windowHeight / 400 * 6) + 1000)) )
this.bird.evaluate();
this.bird.moveX(-100 * Game.deltaTime);
this.bird.draw(g);
for (i = 0; i < Game.configGetInt(new String[] {"game", "maxPipeCount"}); i++)
{
this.pipes[i].evaluate();
this.pipes[i].draw(g);
}
drawCenteredText(g,
Game.configGetString(new String[] {"text", "end", "gameover"}),
new Rectangle(0, 0, Game.windowWidth, Game.windowHeight / 3),
new Font("Ubuntu", Font.BOLD, 36));
drawCenteredText(g,
Game.configGetString(new String[] {"text", "end", "instruction"}),
new Rectangle(0, 0, Game.windowWidth, Game.windowHeight / 2),
new Font("Ubuntu", Font.PLAIN, 28));
g.setColor(Color.WHITE);
drawCenteredText(g,
String.format(Game.configGetString(new String[] {"text", "end", "score"}), this.score),
new Rectangle(0, 0, Game.windowWidth, (int)(Game.windowHeight / 1.5)),
new Font("Ubuntu", Font.BOLD, 28));
g.setColor(Color.BLACK);
}
private static void drawCenteredText(Graphics2D g, String text, Rectangle rect, Font font) {
FontMetrics metrics;
int x, y;
// Calculate position
metrics = g.getFontMetrics(font);
x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Draw
g.setFont(font);
g.drawString(text, x, y);
}
// Key listener overrides
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
System.exit(0);
}
if (this.gameState == Game.gameStateMenu)
{
int i;
switch (e.getKeyCode()) {
case KeyEvent.VK_SPACE:
this.gameState = Game.gameStateRunning;
this.score = 0;
this.pipes = new Pipe[Game.configGetInt(new String[] {"game", "maxPipeCount"})];
for (i = 0; i < Game.configGetInt(new String[] {"game", "maxPipeCount"}); i++)
this.pipes[i] = new Pipe(Game.configGetString(new String[] {"sprite", "pipeUpper", "path"}), Game.configGetString(new String[] {"sprite", "pipeLower", "path"}), (int)(Game.windowHeight * 0.2));
this.bird.flap();
break;
case KeyEvent.VK_D:
Game.debug = true;
break;
}
}
else if (this.gameState == Game.gameStateRunning)
{
switch (e.getKeyCode()) {
case KeyEvent.VK_SPACE:
this.bird.flap();
break;
}
} else if (this.gameState == Game.gameStateEnded)
{
switch(e.getKeyCode()) {
case KeyEvent.VK_R:
this.gameState = Game.gameStateMenu;
this.bird.reset();
break;
}
}
}
@Override
public void keyReleased(KeyEvent e) {}
// Settings stuff etc.
private void setFps(int fps) {
if (fps > 1000)
fps = 1000;
this.framesPerSecond = fps;
this.frameDurationTime = 1000 / fps;
Game.deltaTime = 1 / (float)fps;
}
protected int getFps() {
return this.framesPerSecond;
}
protected long getFrameDuration() {
return this.frameDurationTime;
}
protected static float configGetFloat(String[] d) {
int i;
JSONObject jo;
try {
jo = configGetDict(d[0]);
for (i = 1; i < d.length - 1; i++) {
jo = jo.getJSONObject(d[i]);
}
return (float)jo.getDouble(d[d.length - 1]);
} catch (JSONException e) {
System.out.printf("in configGetString: failed call to getInt: %s\n", e.getMessage());
}
return -1;
}
protected static int configGetInt(String[] d) {
int i;
JSONObject jo;
try {
jo = configGetDict(d[0]);
for (i = 1; i < d.length - 1; i++) {
jo = jo.getJSONObject(d[i]);
}
return jo.getInt(d[d.length - 1]);
} catch (JSONException e) {
System.out.printf("in configGetString: failed call to getInt: %s\n", e.getMessage());
}
return -1;
}
protected static String configGetString(String[] d) {
int i;
JSONObject jo;
try {
jo = configGetDict(d[0]);
for (i = 1; i < d.length - 1; i++) {
jo = jo.getJSONObject(d[i]);
}
return jo.getString(d[d.length - 1]);
} catch (JSONException e) {
System.out.printf("in configGetString: failed call to getInt: %s\n", e.getMessage());
}
return null;
}
protected static JSONObject configGetObject(String dict, String option) {
try {
return Game.configGetDict(dict).getJSONObject(option);
} catch (JSONException e) {
System.out.printf("in configGetObject: failed call to GetJSONObject: %s\n", e.getMessage());
}
return null;
}
protected static JSONObject configGetDict(String dict) {
try {
return Game.config.getJSONObject(dict);
} catch (JSONException e) {
System.out.printf("in configGetDict: failed call to getJSONObject: %s\n", e.getMessage());
}
return null;
}
}<file_sep># java-flappybird
Flappy Bird in java with JFrames
I wrote this game in the course of a school project.
It's my first game and slightly bigger application in java.
Enjoy
|
06c6ac805ce9556ee6a940fb3ddee861388908c7
|
[
"Markdown",
"Java"
] | 3
|
Java
|
e3ntity/java-flappybird
|
b1a0b52e5b7fc8f279974e1a90b472d5a9636256
|
ac805a43f3950320c52b236a41f263bb44a7e4c7
|
refs/heads/main
|
<file_sep>var mouse_event="empty"
var lp_x,lp_y
canvas=document.getElementById("mycanvas");
ctx=canvas.getContext("2d");
color="black";
width_of_line=1
canvas.addEventListener("mousedown",my_mousedown);
function my_mousedown(e){
mouse_event="mousedown";
color=document.getElementById("color").value;
width_of_line=document.getElementById("line_width").value;
}
canvas.addEventListener("mouseup",my_mouseup);
function my_mouseup(e){
mouse_event="mouseup";
}
canvas.addEventListener("mouseleave",my_mouseleave);
function my_mouseleave(e){
mouse_event="mouseleave";
}
canvas.addEventListener("mousemove",my_mousemove);
function my_mousemove(e){
current_position_of_mousex=e.clientX-canvas.offsetLeft;
current_position_of_mousey=e.clientY-canvas.offsetTop;
if(mouse_event=="mousedown")
{ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = width_of_line;
ctx.moveTo(lp_x,lp_y);
ctx.lineTo(current_position_of_mousex,current_position_of_mousey);
ctx.stroke();
}
lp_x=current_position_of_mousex;
lp_y=current_position_of_mousey;
}
function cleararea(){
ctx.clearRect(0,0,canvas.width,canvas.height);
}
|
b69b6a70cc6eed25e83cbb0e38dcf2a7b56cc1b7
|
[
"JavaScript"
] | 1
|
JavaScript
|
Manish2468/Paintingcanvas
|
a8fe6fe09912ef7df26899a02825212094a14d45
|
7ceb8fd94123ff1cddecb0c099a3b460d7b80042
|
refs/heads/master
|
<repo_name>CeramicSkate0/BadcCommandLine<file_sep>/ComLine.c
/**
* After reading user input, the steps are:
* (1) fork a child process-X
* (2) the child process will invoke execvp()-X
* (3) if command included &, parent will invoke wait()-X
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
#define MAX_LINE 80
#define MAX_CMD_LEN 80
#define HISTORY_COUNT 10
int history(char *hist[], int current)
{
int i = current;
int hist_num = 1;
hist[0]="history";
do
{
if (hist[i])
{
printf("%4d %s\n", hist_num, hist[i]);
hist_num++;
}
i = (i + 1) % HISTORY_COUNT;
} while (i != current);
return 0;
}
int recenthistory(char *hist[], int current)
{
int i = current;
int hist_num = 1;
printf("%4d %s\n", hist_num, hist[i-1]);
return 0;
}
int findhistory(char *hist[], int current)
{
int i = current;
int hist_num = 1;
printf("%4d %s\n", hist_num, hist[i-1]);
return 0;
}
int main()
{
char cmd[MAX_LINE];
char *hist[HISTORY_COUNT];
int i, current = 0;
int ii=0;
char *args[MAX_LINE/2 + 1];/* command line (of 80) has max of 40 arguments */
memset(args, 0, sizeof(args));
for (i = 0; i < HISTORY_COUNT; i++)
{
hist[i] = NULL;
}
while (1)
{
ii=0;
printf("OShw>");
if (cmd[strlen(cmd) ] == '\n')
cmd[strlen(cmd) ] = '\0';
free(hist[current]);
hist[current] = strdup(cmd);
current = (current + 1) % HISTORY_COUNT;
//readin inputs
fgets(cmd, MAX_LINE, stdin);
fflush(stdout);
//parse inputs
args[ii] = strtok(cmd, " \n");
if (strcmp(cmd, "history") == 0)
history(hist,current);
else if (strcmp(cmd, "!!") == 0)
recenthistory(hist,current);
else if (strcmp(cmd, "!0") == 0)
{
int hist_num = 1;
printf("%4d %s\n", hist_num, hist[0]);
}
else if (strcmp(cmd, "!1") == 0)
{
int hist_num = 2;
printf("%4d %s\n", hist_num, hist[1]);
}
else if (strcmp(cmd, "!2") == 0)
{
int hist_num = 3;
printf("%4d %s\n", hist_num, hist[2]);
}
else if (strcmp(cmd, "!3") == 0)
{
int hist_num = 4;
printf("%4d %s\n", hist_num, hist[3]);
}
else if (strcmp(cmd, "!4") == 0)
{
int hist_num = 5;
printf("%4d %s\n", hist_num, hist[4]);
}
else if (strcmp(cmd, "!5") == 0)
{
int hist_num = 6;
printf("%4d %s\n", hist_num, hist[5]);
}
else if (strcmp(cmd, "!6") == 0)
{
int hist_num = 7;
printf("%4d %s\n", hist_num, hist[6]);
}
else if (strcmp(cmd, "!7") == 0)
{
int hist_num = 8;
printf("%4d %s\n", hist_num, hist[7]);
}
else if (strcmp(cmd, "!8") == 0)
{
int hist_num = 9;
printf("%4d %s\n", hist_num, hist[8]);
}
else if (strcmp(cmd, "!9") == 0)
{
int hist_num = 10;
printf("%4d %s\n", hist_num, hist[9]);
}
else if (strcmp(cmd, "forkit") == 0)
break;
if (strncmp(cmd, "&", 1) == 0)
{
wait(NULL);
}
pid_t pid = fork();
if (pid<0)
{
printf("!!!-ERROR-!!!\n");
}
else if (pid == 0)//child
{
execvp(args[ii],args);
}
else
{
wait(NULL);
}
ii++;
}
return 0;
}
<file_sep>/README.md
# BadcCommandLine
I know almost nothing about C. This is just here to show I could do it.
|
ec47493d7cf3ba82ee19e4b43c5861929460386a
|
[
"Markdown",
"C"
] | 2
|
C
|
CeramicSkate0/BadcCommandLine
|
3f32d6fecec74bb044d98739ae30dba12a6d876d
|
e4d4d5165286d1d5052a428ce7b2b29caed27353
|
refs/heads/master
|
<file_sep># scrape_last.fm
Use to scrape users, music, and related information using Last.fm API.
# getUser
Scrape users from a Last.fm group. Save usernames to user_list.csv.
# getTracks
Scrape banned and loved tracks for each user in user_list.csv. Save results to user_BannedTracks.csv, user_LovedTracks.csv, and user_log.csv.
Similarly, this can be extend to include other Last.fm track related API, e.g. getRecentTracks, getTopTracks.
# user_info
Get basic information for users in previous step. (country, age, gender).
# track_info
Get infotmation for tracks in users' banned and loved lists. (album, playcount, tags, artist, duration).
<file_sep>require 'httparty'
require 'url'
api_key = "<KEY>"
def getResponse(url)
cnt_err = 0
while cnt_err <= 5
begin
encoded_uri = URI::encode url
response = HTTParty.get(encoded_uri, :verify => false)
break
rescue
cnt_err += 1
puts "Connection error, retry #{cnt_err} secs later..."
sleep(cnt_err)
response = nil
next
end
end
return response
end
def getTrackInfo(response)
r = ""
if !(response.nil?)
begin
h = JSON.parse(response.body)
len = h["track"]["duration"]
hot = h["track"]["playcount"]
alb = h["track"]["album"]["title"]
tag = h["track"]["toptags"]["tag"]
arr = []
if tag.nil?
tags = ""
else
if tag.is_a? Array
tag.each{|x| arr << x["name"]}
tags = arr.join("--")
else
tags = tag["name"]
end
end
r = len + "," + hot + "," + q(alb) + "," + tags
rescue
return r
end
end
return r
end
def q(str)
return '"' + str + '"'
end
# get all tracks from banned and loved tracks
puts "fetching tracks..."
f = File.open("user_BannedTracks.csv",:encoding=>'utf-8')
f2 = File.open("user_LovedTracks.csv",:encoding=>'utf-8')
track = []
f.each{|line|
line = line.chomp
ln = line.split(',')
str = ln[1] + "-" + ln[2]
track << str
}
f.close
f2.each{|line|
line = line.chomp
ln = line.split(',')
str = ln[1] + "-" + ln[2]
track << str
}
f2.close
track = track.uniq
f = File.open("tracks_info.csv","wb")
cnt = 0
track.each{|line|
line = line.chomp
ln = line.split('"-"')
art = ln[0].gsub('"','')
trk = ln[1].gsub('"','')
cnt += 1
puts "Processing track no.#{cnt}."
url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=#{api_key}&artist=#{art}&track=#{trk}&format=json"
response = getResponse(url)
f.puts q(art) + "," + q(trk) + "," + getTrackInfo(response)
}
f.close<file_sep>require 'httparty'
require 'url'
api_key = "<KEY>"
Limit_banned = 20
Limit_loved = 200
def getResponse(url)
cnt_err = 0
while cnt_err <= 5
begin
encoded_uri = URI::encode url
response = HTTParty.get(encoded_uri, :verify => false)
break
rescue
cnt_err += 1
puts "Connection error, retry #{cnt_err} secs later..."
sleep(cnt_err)
response = nil
next
end
end
return response
end
def getUserInfo(response)
r = ""
if !(response.nil?)
begin
h = JSON.parse(response.body)
loc = h["user"]["country"]
age = h["user"]["age"]
sex = h["user"]["gender"]
reg = h["user"]["registered"]["unixtime"]
r = loc + "," + age + "," + sex + "," + reg
rescue
return r
end
end
return r
end
arr_user = []
f = File.open("user_log.csv","r")
f.each{|line|
line = line.chomp
ln = line.split(',')
if ln[1].to_i >= Limit_banned && ln[2].to_i >= Limit_loved
user << ln[0]
end
}
f.close
arr_user = arr_user.uniq
f = File.open("users_info.csv","wb")
cnt = 0
arr_user.each{|uid|
cnt += 1
puts "Processing user no.#{cnt}."
url = "http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=#{uid}&api_key=#{api_key}&format=json"
response = getResponse(url)
f.puts uid + "," + getUserInfo(response)
}
f.close<file_sep>require 'httparty'
require 'url'
# Last.fm API Key
api_key = "<KEY>"
# no. of banned and loved tracks that users should at least have
# change this to 0 when fetching all users
Limit_banned = 20
Limit_loved = 200
# functions
def getBannedTracks(response)
r = []
begin
h = JSON.parse(response.body)
rescue
return r
end
arr = h["bannedtracks"]["track"]
cnt = 0
begin
if !(arr.nil?)
if arr.is_a? Hash
if arr["@attr"].nil?
cnt += 1
artist = arr["artist"]["name"]
music = arr["name"]
timestamp = arr["date"]["uts"].to_s
r << '"' + artist + '","' + music + '",' + timestamp
end
else
arr.each{|x|
if x["@attr"].nil?
cnt += 1
artist = x["artist"]["name"]
music = x["name"]
timestamp = x["date"]["uts"].to_s
r << '"' + artist + '","' + music + '",' + timestamp
end
}
end
end
rescue
f = File.open("error_log.txt","a")
f.puts response
f.close
end
return r
end
def getLovedTracks(response)
r = []
begin
h = JSON.parse(response.body)
rescue
return r
end
arr = h["lovedtracks"]["track"]
cnt = 0
begin
if !(arr.nil?)
if arr.is_a? Hash
if arr["@attr"].nil?
cnt += 1
artist = arr["artist"]["name"]
music = arr["name"]
timestamp = arr["date"]["uts"].to_s
r << '"' + artist + '","' + music + '",' + timestamp
end
else
arr.each{|x|
if x["@attr"].nil?
cnt += 1
artist = x["artist"]["name"]
music = x["name"]
timestamp = x["date"]["uts"].to_s
r << '"' + artist + '","' + music + '",' + timestamp
end
}
end
end
rescue
f = File.open("error_log.txt","a")
f.puts response
f.close
end
return r
end
def getPageVol(response,str)
case str
when "Banned"
track_str = "bannedtracks"
when "Loved"
track_str = "lovedtracks"
end
h = JSON.parse(response.body)
r = h[track_str]["@attr"]["total"]
return r.to_i
end
# read in usernames
arr_user = []
f = File.open("user_list.csv","r")
f.each_line{|line|
line = line.chomp
arr_user << line
}
f.close
# files to save results
f2 = File.open("user_BannedTracks.csv","a") # users' banned tracks
f3 = File.open("user_LovedTracks.csv","a") # users' loved tracks
f4 = File.open("user_log.csv","a") # record no. of tracks
cnt = 0
cnt_get = 0
arr_user.each{|uid|
cnt += 1
puts "Processing user no.#{cnt}, #{cnt_get} fetched."
# get the amount of tracks
# banned
while true
begin
url = "http://ws.audioscrobbler.com/2.0/?method=user.getbannedtracks&user=#{uid}&limit=1&api_key=#{api_key}&format=json"
encoded_uri = URI::encode url
response = HTTParty.get(encoded_uri, :verify => false)
break
rescue
puts "Connection error, retry 3 secs later..."
sleep(3)
next
end
end
begin
vol_banned = getPageVol(response,"Banned")
rescue
vol_banned = 0
end
# loved
while true
begin
url = "http://ws.audioscrobbler.com/2.0/?method=user.getlovedtracks&user=#{uid}&limit=1&api_key=#{api_key}&format=json"
encoded_uri = URI::encode url
response = HTTParty.get(encoded_uri, :verify => false)
break
rescue
puts "Connection error, retry 3 secs later..."
sleep(3)
next
end
end
begin
vol_loved = getPageVol(response,"Loved")
rescue
vol_loved = 0
end
# set an upper bound for maximun number of tracks to fetch
vol_banned = 1500 if vol_banned >= 1500
vol_loved = 1500 if vol_loved >= 1500
# when the user satisfy the condition
if vol_banned >= Limit_banned && vol_loved >= Limit_loved
cnt_get += 1
# banned tracks
cnt_err = 0
while cnt_err <= 5
begin
url = "http://ws.audioscrobbler.com/2.0/?method=user.getbannedtracks&user=#{uid}&limit=#{vol_banned}&api_key=#{api_key}&format=json"
encoded_uri = URI::encode url
response = HTTParty.get(encoded_uri, :verify => false)
break
rescue
cnt_err += 1
puts "Connection error (banned: #{vol_banned}), retry #{cnt_err} secs later..."
sleep(cnt_err)
response = nil
next
end
end
result = getBannedTracks(response)
if result.nil?
size_banned = 0
elsif result.size == 1
f2.puts '"' + uid + '",' + result[0]
size_banned = 1
else
result.each{|line|
f2.puts '"' + uid + '",' + line
}
size_banned = result.size
end
# loved tracks
cnt_err = 0
while cnt_err <= 5
begin
url = "http://ws.audioscrobbler.com/2.0/?method=user.getlovedtracks&user=#{uid}&limit=#{vol_loved}&api_key=#{api_key}&format=json"
encoded_uri = URI::encode url
response = HTTParty.get(encoded_uri, :verify => false)
break
rescue
cnt_err += 1
puts "Connection error (loved: #{vol_loved}), retry #{cnt_err} secs later..."
sleep(cnt_err)
response = nil
next
end
end
result = getLovedTracks(response)
if result.nil?
size_loved = 0
elsif result.size == 1
f3.puts '"' + uid + '",' + result[0]
size_loved = 1
else
result.each{|line|
f3.puts '"' + uid + '",' + line
}
size_loved = result.size
end
f4.puts '"' + uid + '",' + size_banned.to_s + "," + size_loved.to_s
end
}
f2.close
f3.close
f4.close<file_sep># encoding: UTF-8
require 'mechanize'
group_name = "Addicted to Last.fm"
f = File.open("user_list.csv","wb") # save user list here
url_name = group_name.gsub(" ","+")
agent = Mechanize.new
# get page number first
while true
begin
page = agent.get("http://www.last.fm/group/#{url_name}/members?memberspage=1")
break
rescue
sleep(2)
next
end
end
page_no = page.search("a[class='pagelink lastpage']")[0].text.to_i
for i in 1..page_no
puts "Fetching page no.#{i}..."
while true # keep fetching until success
begin
page = agent.get("http://www.last.fm/group/#{url_name}/members?memberspage=#{i}")
break
rescue # in case connection failures
sleep(2)
next
end
end
page.search("strong").search("a").map do |text|
uid = text.attributes['href'].text.gsub("/user/","")
f.puts uid
end
end
f.close
|
4b2598eeb0492413892072f9dc621cfe8fd83aa0
|
[
"Markdown",
"Ruby"
] | 5
|
Markdown
|
taozhaojie/scrape_last.fm
|
75761befbe64585555a7f2c007e7015ee3c269f8
|
7266ef5f1bec80e8677695929db4605fe57c3caa
|
refs/heads/master
|
<file_sep>import os
os.getcwd() # returns the current directory
os.chdir('D:\DESKTOP') # changes the directory
os.system('mkdir today') # Run the cmd mkdir in the system shell
import os
dir(os)
help(os) #help
import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/bulid/executables', 'installer')
|
11c901e6e69107c96f64315d6369b90647e0e023
|
[
"Python"
] | 1
|
Python
|
qinyanjuidavid/Hands_On_Python
|
0a2af169a596b5e3a4a4790632b46c9ef6847faa
|
2fce51742d6fc09bb10123a4b3b58a220a6c6b48
|
refs/heads/master
|
<repo_name>quanhieu188/QLCoffeeShop<file_sep>/DoanhThu.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QLNVApp
{
class DoanhThu
{
public string KhachHang { get; set; }
public string Date { get; set; }
public string SoTien { get; set; }
public DoanhThu(string khachHang, string date, string soTien)
{
this.KhachHang = khachHang;
this.Date = date;
this.SoTien = soTien;
}
}
}
<file_sep>/frmQLNV.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace QLNVApp
{
public partial class frmQLNV : Form
{
public frmQLNV()
{
InitializeComponent();
}
List<NV> GetNV()
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM NhanVien";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List<NV> list = new List<NV>();
string maNV, ho, ten, chucvu, calamviec;
while (dr.Read())
{
maNV = dr[0].ToString();
ho = dr[1].ToString();
ten = dr[2].ToString();
chucvu = dr[3].ToString();
calamviec = dr[4].ToString();
NV sup = new NV(maNV, ho, ten, chucvu, calamviec);
list.Add(sup);
}
dr.Close();
cn.Close();
return list;
}
public int CheckNV(string MaNV)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM NhanVien";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string maNV;
while (dr.Read())
{
maNV = dr[0].ToString();
if (MaNV == maNV)
return 0;
}
dr.Close();
cn.Close();
return 1;
}
private void btAdd_Click(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string maNV, ho, ten, chucvu, calamviec;
maNV = txtMaNV.Text;
ho = txtHo.Text;
ten = txtTen.Text;
chucvu = txtChucVu.Text;
calamviec = txtCaLamViec.Text;
if (string.IsNullOrEmpty(maNV))
return;
if (CheckNV(maNV) == 0)
MessageBox.Show("Them that bai", "Them nhan vien");
else
{
string sql = "INSERT INTO NhanVien VALUES('" + maNV + "', N'" + ho + "', N'" + ten + "', N'" + chucvu + "', N'" + calamviec + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Them that bai", "Them nhan vien");
else
dgvNV.DataSource = GetNV();
cn.Close();
}
}
private void btFix_Click(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string maNV, ho, ten, chucvu, calamviec;
maNV = txtMaNV.Text;
ho = txtHo.Text;
ten = txtTen.Text;
chucvu = txtChucVu.Text;
calamviec = txtCaLamViec.Text;
if (string.IsNullOrEmpty(maNV))
return;
string sql = "UPDATE NhanVien SET Ho = N'" + ho + "',Ten = N'" + ten + "',ChucVu = N'" + chucvu + "',CaLamViec = N'" + calamviec + "' WHERE MaNV = '" + maNV + "'";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Sua that bai", "Sua Nhan Vien");
else
dgvNV.DataSource = GetNV();
cn.Close();
}
private void btDel_Click(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string maNV, ho, ten, chucvu, calamviec;
maNV = txtMaNV.Text;
ho = txtHo.Text;
ten = txtTen.Text;
chucvu = txtChucVu.Text;
calamviec = txtCaLamViec.Text;
string sql = "DELETE FROM NhanVien WHERE MaNV = '" + maNV + "'";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Xoa that bai", "Xoa Nhan Vien");
else
dgvNV.DataSource = GetNV();
cn.Close();
}
private void frmQLNV_Load(object sender, EventArgs e)
{
List<NV> list = GetNV();
dgvNV.DataSource = list;
//txtMaNV.DataBindings.Add("Text", list, "MaNV");
//txtHo.DataBindings.Add("Text", list, "Ho");
//txtTen.DataBindings.Add("Text", list, "Ten");
//txtChucVu.DataBindings.Add("Text", list, "ChucVu");
//txtCaLamViec.DataBindings.Add("Text", list, "CaLamViec");
}
private void dgvNV_CellEnter(object sender, DataGridViewCellEventArgs e)
{
try
{
txtMaNV.Text = dgvNV.CurrentRow.Cells[0].Value.ToString();
txtHo.Text = dgvNV.CurrentRow.Cells[1].Value.ToString();
txtTen.Text = dgvNV.CurrentRow.Cells[2].Value.ToString();
txtChucVu.Text = dgvNV.CurrentRow.Cells[3].Value.ToString();
txtCaLamViec.Text = dgvNV.CurrentRow.Cells[4].Value.ToString();
}
catch (Exception)
{
}
}
}
}
<file_sep>/Kho.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QLNVApp
{
class Kho
{
public string ID { get; set; }
public string Name { get; set; }
public string PriceS { get; set; }
public string PriceM { get; set; }
public string PriceL { get; set; }
public string SoLuong { get; set; }
public Kho(string id, string name, string prices, string pricem, string pricel, string soluong)
{
this.ID = id;
this.Name = name;
this.PriceS = prices;
this.PriceM = pricem;
this.PriceL = pricel;
this.SoLuong = soluong;
}
}
}
<file_sep>/frmQLDoanhThu.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace QLNVApp
{
public partial class frmQLDoanhThu : Form
{
public frmQLDoanhThu()
{
InitializeComponent();
}
List<DoanhThu> GetDoanhThu()
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM DoanhThu";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List<DoanhThu> list = new List<DoanhThu>();
string khachHang, date, soTien;
while (dr.Read())
{
khachHang = dr[0].ToString();
date = dr[1].ToString();
soTien = dr[2].ToString();
DoanhThu sup = new DoanhThu(khachHang, date, soTien);
list.Add(sup);
}
dr.Close();
cn.Close();
return list;
}
public int CheckDT(string KhachHang)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM DoanhThu";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string khachHang;
while (dr.Read())
{
khachHang = dr[0].ToString();
if (KhachHang == khachHang)
return 0;
}
dr.Close();
cn.Close();
return 1;
}
private void btAdd_Click(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string khachHang, date, soTien;
khachHang = txtKhachHang.Text;
date = txtDate.Text;
soTien = txtSoTien.Text;
if (string.IsNullOrEmpty(khachHang))
return;
if (CheckDT(khachHang) == 0)
MessageBox.Show("Them that bai", "Them doanh thu");
else
{
string sql = "INSERT INTO DoanhThu VALUES('" + khachHang + "', N'" + date + "', N'" + soTien + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Them that bai", "Them doanh thu");
else
dgvDoanhThu.DataSource = GetDoanhThu();
cn.Close();
}
}
private void frmQLDoanhThu_Load(object sender, EventArgs e)
{
List<DoanhThu> list = GetDoanhThu();
dgvDoanhThu.DataSource = list;
//txtKhachHang.DataBindings.Add("Text", list, "KhachHang");
//txtDate.DataBindings.Add("Text", list, "Date");
//txtSoTien.DataBindings.Add("Text", list, "SoTien");
}
private void btFix_Click_1(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string khachHang, date, soTien;
khachHang = txtKhachHang.Text;
date = txtDate.Text;
soTien = txtSoTien.Text;
if (string.IsNullOrEmpty(khachHang))
return;
string sql = "UPDATE DoanhThu SET NgayThangNam = N'" + date + "',SoTien = N'" + soTien + "' WHERE KhachHang = '" + khachHang + "'";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
try
{
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Sua that bai", "Sua doanh thu");
else
dgvDoanhThu.DataSource = GetDoanhThu();
}
catch (Exception)
{
MessageBox.Show("Nhap sai ngay thang nam");
}
cn.Close();
}
private void btDel_Click_1(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string khachHang,ngayThangNam,soTien;
khachHang = txtKhachHang.Text;
ngayThangNam = txtDate.Text;
soTien = txtSoTien.Text;
string sql = "DELETE FROM DoanhThu WHERE KhachHang = '" + khachHang + "' AND NgayThangNam = '" + ngayThangNam + "' AND SoTien = '" + soTien + "'";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Xoa that bai", "Xoa doanh thu");
else
dgvDoanhThu.DataSource = GetDoanhThu();
cn.Close();
}
private void dgvDoanhThu_CellEnter(object sender, DataGridViewCellEventArgs e)
{
try
{
txtKhachHang.Text = dgvDoanhThu.CurrentRow.Cells[0].Value.ToString();
txtDate.Text = dgvDoanhThu.CurrentRow.Cells[1].Value.ToString();
txtSoTien.Text = dgvDoanhThu.CurrentRow.Cells[2].Value.ToString();
}
catch (Exception)
{
}
}
}
}
<file_sep>/TT.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QLNVApp
{
class TT
{
public string Name { get; set; }
public string Price { get; set; }
public string SoLuong { get; set; }
public TT(string name,string price,string soLuong)
{
this.Name = name;
this.Price = price;
this.SoLuong = soLuong;
}
}
}
<file_sep>/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace QLNVApp
{
public partial class frmCoffeeShop : Form
{
public frmCoffeeShop()
{
InitializeComponent();
}
private void frmCoffeeShop_Load(object sender, EventArgs e)
{
this.Show();
this.Enabled = false;
frmLogin frm = new frmLogin();
DialogResult result = frm.ShowDialog();
if (result == DialogResult.OK)
{
this.Enabled = true;
}
}
private void khoToolStripMenuItem_Click(object sender, EventArgs e)
{
frmQLKho frm = new frmQLKho();
frm.ShowDialog();
}
private void doanhThuToolStripMenuItem_Click(object sender, EventArgs e)
{
frmQLDoanhThu frm = new frmQLDoanhThu();
frm.ShowDialog();
}
private void nhânViênToolStripMenuItem_Click(object sender, EventArgs e)
{
frmQLNV frm = new frmQLNV();
frm.ShowDialog();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void thanhToánToolStripMenuItem_Click(object sender, EventArgs e)
{
ThanhToan frm = new ThanhToan();
frm.ShowDialog();
}
private void doanhThuToolStripMenuItem_Click_1(object sender, EventArgs e)
{
frmQLDoanhThu frm = new frmQLDoanhThu();
frm.ShowDialog();
}
private void nguyênLiệuToolStripMenuItem_Click(object sender, EventArgs e)
{
frmQLKho frm = new frmQLKho();
frm.ShowDialog();
}
}
}
<file_sep>/ThanhToan.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace QLNVApp
{
public partial class ThanhToan : Form
{
double Tong = 0.0;
public ThanhToan()
{
InitializeComponent();
}
private void Add_Click(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string name, size, soLuong, price;
name = cbName.SelectedValue.ToString();
size = cbSize.SelectedItem.ToString();
soLuong = numericUpDown1.Value.ToString();
if (int.Parse(soLuong) != 0)
{
string sql = "SELECT * FROM Kho WHERE ID = '" + name + "'";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
name = dr[1].ToString();
if (size == "S")
price = dr[2].ToString();
else if (size == "M")
price = dr[3].ToString();
else price = dr[4].ToString();
dgvDrink.Rows.Add(name, price, soLuong);
Tong = Tong + (double.Parse(price) * double.Parse(soLuong));
txtTong.Text = Tong.ToString();
}
dr.Close();
cn.Close();
}
}
List<Kho> GetKho()
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM Kho";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List<Kho> list = new List<Kho>();
string id, name, prices, pricem, pricel, soluong;
while (dr.Read())
{
id = dr[0].ToString();
name = dr[1].ToString();
prices = dr[2].ToString();
pricem = dr[3].ToString();
pricel = dr[4].ToString();
soluong = dr[5].ToString();
Kho sup = new Kho(id, name, prices, pricem, pricel, soluong);
list.Add(sup);
}
dr.Close();
cn.Close();
return list;
}
private void ThanhToan_Load(object sender, EventArgs e)
{
List<Kho> list = GetKho();
cbName.DataSource = list;
cbName.DisplayMember = "Name";
cbName.ValueMember = "ID";
}
private void btLamMoi_Click(object sender, EventArgs e)
{
dgvDrink.Rows.Clear();
txtTong.Text = "";
Tong = 0;
cbName.SelectedItem = null;
cbSize.SelectedItem = null;
numericUpDown1.Value = 0;
}
public int CheckDoanhThu(string KhachHang, string Date)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM DoanhThu";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string khachHang, date, tong;
while (dr.Read())
{
khachHang = dr[0].ToString();
date = dr[1].ToString();
tong = dr[2].ToString();
if (KhachHang == khachHang && Date == date && Tong == double.Parse(tong))
return 0;
}
dr.Close();
cn.Close();
return 1;
}
private void btThanhToan_Click(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string khachHang, date;
khachHang = txtKhachHang.Text;
date = txtDate.Text;
// them vao bang doanh thu
if (string.IsNullOrEmpty(khachHang) || string.IsNullOrEmpty(date))
return;
if (CheckDoanhThu(khachHang, date) == 0)
MessageBox.Show("Them that bai", "Them thanh toan");
else
{
string sql = "INSERT INTO DoanhThu VALUES('" + khachHang + "', N'" + date + "', N'" + Tong + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
try
{
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Them that bai", "Them thanh toan");
else
MessageBox.Show("Them thanh cong");
}
catch (Exception)
{
MessageBox.Show("Nhap sai ngay thang nam");
}
cn.Close();
}
// them vao bang
}
private void btXoa_Click(object sender, EventArgs e)
{
if(dgvDrink.Rows.Count > 1)
{
int x = dgvDrink.SelectedRows[0].Index;
int y = dgvDrink.Columns[2].Index;
int z = dgvDrink.Columns[1].Index;
double soLuong = double.Parse(dgvDrink.Rows[x].Cells[y].Value.ToString());
double price = double.Parse(dgvDrink.Rows[x].Cells[z].Value.ToString());
Tong -= soLuong * price;
txtTong.Text = Tong.ToString();
dgvDrink.Rows.RemoveAt(dgvDrink.SelectedRows[0].Index);
}
else
{
dgvDrink.Rows.Clear();
txtTong.Text = "";
Tong = 0;
}
}
}
}
<file_sep>/Login.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace QLNVApp
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void btLogin_Click(object sender, EventArgs e)
{
string userName = txtUserName.Text.Trim();
string passWord = txtPassWord.Text;
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(passWord))
{
MessageBox.Show("Can nhap du username va password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (Login(userName, passWord) == true)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
DialogResult result = MessageBox.Show("Username hoac password khong dung!", "Login", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
if (result == DialogResult.Cancel)
{
Application.Exit();
}
else
{
txtUserName.Focus();
}
}
}
}
private void btCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private bool Login(string username, string password)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
cn.Open();
string sql = "SELECT COUNT(Account) FROM TaiKhoan WHERE Account = '" + username + "' AND Password = '" + password + "'";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
int count = (int)cmd.ExecuteScalar();
cn.Close();
if (count == 1)
return true;
else
return false;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Enter))
{
btLogin.PerformClick();
return true;
}
else if (keyData == (Keys.Escape))
{
btCancel.PerformClick();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void frmLogin_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>/NV.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QLNVApp
{
class NV
{
public string MaNV { get; set; }
public string Ho { get; set; }
public string Ten { get; set; }
public string ChucVu { get; set; }
public string CaLamViec { get; set; }
public NV(string maNV, string ho, string ten, string chucvu, string calamviec)
{
this.MaNV = maNV;
this.Ho = ho;
this.Ten = ten;
this.ChucVu = chucvu;
this.CaLamViec = calamviec;
}
}
}
<file_sep>/frmQLKho.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace QLNVApp
{
public partial class frmQLKho : Form
{
public frmQLKho()
{
InitializeComponent();
}
List<Kho> GetKho()
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM Kho";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List<Kho> list = new List<Kho>();
string id, name, prices, pricem, pricel, soluong;
while (dr.Read())
{
id = dr[0].ToString();
name = dr[1].ToString();
prices = dr[2].ToString();
pricem = dr[3].ToString();
pricel = dr[4].ToString();
soluong = dr[5].ToString();
Kho sup = new Kho(id, name, prices, pricem, pricel, soluong);
list.Add(sup);
}
dr.Close();
cn.Close();
return list;
}
public int CheckKho(string ID)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string sql = "SELECT * FROM Kho";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string id;
while (dr.Read())
{
id = dr[0].ToString();
if (ID == id)
return 0;
}
dr.Close();
cn.Close();
return 1;
}
private void frmQLKho_Load(object sender, EventArgs e)
{
List<Kho> list = GetKho();
dgvKho.DataSource = list;
//txtID.DataBindings.Add("Text", list, "ID");
//txtName.DataBindings.Add("Text", list, "Name");
//txtPriceS.DataBindings.Add("Text", list, "PriceS");
//txtPriceM.DataBindings.Add("Text", list, "PriceM");
//txtPriceL.DataBindings.Add("Text", list, "PriceL");
//txtSoLuong.DataBindings.Add("Text", list, "SoLuong");
}
private void btAdd_Click_1(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string id, name, prices, pricem, pricel, soluong;
id = txtID.Text;
name = txtName.Text;
prices = txtPriceS.Text;
pricem = txtPriceM.Text;
pricel = txtPriceL.Text;
soluong = txtSoLuong.Text;
if (string.IsNullOrEmpty(id))
return;
if (CheckKho(id) == 0)
MessageBox.Show("Them that bai", "Them san pham");
else
{
string sql = "INSERT INTO Kho VALUES('" + id + "', N'" + name + "', N'" + prices + "', N'" + pricem + "', N'" + pricel + "', N'" + soluong + "')";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Them that bai", "Them san pham");
else
dgvKho.DataSource = GetKho();
cn.Close();
}
}
private void btDel_Click_1(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string id;
id = txtID.Text;
string sql = "DELETE FROM Kho WHERE ID = '" + id + "'";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Xoa that bai", "Xoa San Pham");
else
dgvKho.DataSource = GetKho();
cn.Close();
}
private void btFix_Click(object sender, EventArgs e)
{
string cnStr = "Data Source=DESKTOP-67RKQE5\\SQLEXPRESS;Initial Catalog=QLQuanCafe;Integrated Security=True";
SqlConnection cn = new SqlConnection(cnStr);
string id, name, prices, pricem, pricel, soluong;
id = txtID.Text;
name = txtName.Text;
prices = txtPriceS.Text;
pricem = txtPriceM.Text;
pricel = txtPriceL.Text;
soluong = txtSoLuong.Text;
if (string.IsNullOrEmpty(id))
return;
string sql = "UPDATE Kho SET Name = N'" + name + "',PriceS = N'" + prices + "',PriceM = N'" + pricem + "',PriceL = N'" + pricel + "',SoLuong = N'" + soluong + "' WHERE ID = '" + id + "'";
SqlCommand cmd = new SqlCommand(sql, cn);
cn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
if (numberOfRows <= 0)
MessageBox.Show("Sua that bai", "Sua san pham");
else
dgvKho.DataSource = GetKho();
cn.Close();
}
private void dgvKho_CellEnter(object sender, DataGridViewCellEventArgs e)
{
try
{
txtID.Text = dgvKho.CurrentRow.Cells[0].Value.ToString();
txtName.Text = dgvKho.CurrentRow.Cells[1].Value.ToString();
txtPriceS.Text = dgvKho.CurrentRow.Cells[2].Value.ToString();
txtPriceM.Text = dgvKho.CurrentRow.Cells[3].Value.ToString();
txtPriceL.Text = dgvKho.CurrentRow.Cells[4].Value.ToString();
txtSoLuong.Text = dgvKho.CurrentRow.Cells[5].Value.ToString();
}
catch (Exception)
{
}
}
}
}
|
71f4475fe084b98c3d3abd1568b5603e0f43433a
|
[
"C#"
] | 10
|
C#
|
quanhieu188/QLCoffeeShop
|
daf2de8b9c6ebcf5c10c7f776a6b374b3654cd13
|
1a9e077ffe70395f56653602831a1cf08b226c61
|
refs/heads/master
|
<file_sep># -large-integer-arithmetic-algorithm
a program in VS C++ 2017 to implement the large integer arithmetic algorithm shown in class. Let's assume the threshold to switch from the large integer arithmetic algorithm to the standard multiplication algorithm is 2. When your program is running, it should first prompt the user for twononnegativeintegersentered on one line butseparated by at least one space. It then computes the result using the large integer arithmetic algorithmshown in class. The result is then displayed on the screen. Your program then verifies the result by multiplying the two integers again using the standard multiplication method. The result should also be displayed on the screen.The following shows a scenarioof running a sample program, where user's inputs are represented in boldface.Enter two nonnegativeintegers: 87111653The result determined using the large integer arithmeticalgorithmis10149763The result determined using the standard algorithmis10149763
<file_sep>#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
const int THREADHOLD = 2;
int prod(int u, int v)
{
int uDigit = 0,
vDigit = 0,
num1 = u,
num2 = v;
while (num1 != 0) { num1 /= 10; uDigit++; }
while (num2 != 0) { num2 /= 10; vDigit++; }
int n = max(uDigit, vDigit);
if (u == 0 || v == 0)
return 0;
else if (n < THREADHOLD)
return v*u;
else
{
int m = n / 2,
i = pow(10, m),
x = u / i,
y = u % i,
w = v / i,
z = v % i,
r = prod(x + y, w + z),
p = prod(x, w),
q = prod(y, z);
return p * pow(10, 2 * m) + (r - q - p)*i + q;
}
}
int main()
{
int num1 = -1, num2 = -1,product;
while (num1 < 0 || num2 < 0)
{
cout << "Enter two non negative numbers: " << endl;
cin >> num1>> num2;
}
product = prod(num1, num2);
cout << "The result determined using the large integer arithmetic algorithm is " << product << endl;;
cout << "The result determined using the standard algorithm is " << num1*num2;
char c;
cin >> c;
return 0;
}
|
5596eae1b27528ac0bd96505c390a13c89dc9b34
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
jiahuij/-large-integer-arithmetic-algorithm
|
64ff9ce87f677cb1c1f6deed5d465383cb01e546
|
b6a6053e043fc3e0ee0a16adbb6fc5f713510b4c
|
refs/heads/master
|
<file_sep>---
layout: docs
title: Ideas
---
The ideas are the foundation of Sagefy's architecture. The ideas are broad and based on highly common patterns in memory and learning research. Use the ideas to provide a sense of direction.
1. Do One Thing at a Time
2. Set & Adhere to Goals
3. Adapt to Prior Knowledge
4. Build the Graph
5. Empower Choice
6. Dive Deep
7. Make It Real
8. Learn Together
## 1. Do One Thing at a Time
Our memory system is powerful but limited. We are most effective when focusing on one task at a time.
### What do we mean by "Do One Thing at a Time"?
* Only do one specific activity at any given point in time.
* Avoid multitasking.
* Prefer one source of input and one source of output at a time.
* Scaffold the learner to success.
* Avoid extraneous choices.
* Stay focused and eliminate tangents.
* Account for memory limits -- chunking, pretraining, and modality.
### How does Sagefy implement this idea?
* The user can only be presented one card at a time.
* The user only works on one unit at a time.
* When the learner must make a choice about which subject or unit to pursue, the learner is only presented with the choice.
* A contributor can only change one entity at a time.
## 2. Set & Adhere to Goals
Defining small, achievable goals and constantly checking against them builds better, more focused content.
### What do we mean by "Set & Adhere to Goals"?
* Always define the goal.
* Focus content on exploring the different facets of the goal.
* Remove content that is not needed for the goal.
* Eliminate distractions.
* Define both knowledge and skills.
* Keep the learner aware of their progress.
### How does Sagefy implement this idea?
* Units are defined by their goal, or objective.
* Cards must be attached to a unit.
* Subjects can be small or large, but they always have a single description.
* Flagging enables users to remove irrelevant content.
## 3. Adapt to Prior Knowledge
The strongest predictor of how much we will learn is what we already know. Every learning experience must be adapted to the learner's prior knowledge.
### What do we mean by "Adapt to Prior Knowledge"?
* Adjust the challenge level to the learner's knowledge.
* Ensure a learner knows what they need to in order to complete a task.
* Focus on areas of weakness.
* Focus on building knowledge.
* Connect new information with prior knowledge.
* Scaffold the learner to success.
* Use assessment to optimize learning.
### How does Sagefy implement this idea?
* Cards and units have requires, which ensures the learner has sufficient prior knowledge.
* The algorithms which sequence show cards, units, and subjects that are available to the learner.
* The algorithms which sequence the entities focus on improving the learner's prior knowledge.
* A diagnostic assessment means learners can build prior knowledge where lacking.
* A learner with high prior knowledge can skip to more relevant areas.
## 4. Build the Graph
Our memory system works by forming relationships. Mastery is the result of an organized thought process. Students link new information with information that they already know.
### What do we mean by "Build the Graph"?
* Show how information is organized directly to the learner.
* Relate information to prior information.
* Task the learner with organizational challenges.
* Use technology to automate organization.
* Keep the learner aware of their progress.
### How does Sagefy implement this idea?
* The three basic entities are easy to remember and have a clear hierarchy.
* Subjects can embed each other, allowing for a variety of organizational structures.
* A card must belong to a unit, which defines its purpose.
* A unit can only have a single goal, limiting extraneous information.
* Requires are available for cards and units, allowing for the system to automatically keep things organized with low effort.
* Contributors do not organize courses, but simply describe relationships. The algorithms handle keeping things organized to the learner.
## 5. Empower Choice
### What do we mean by "Empower Choice"?
* Autonomy is an intrinsic motivator. Choice fuels autonomy.
### How does Sagefy implement this idea?
## 6. Dive Deep
Route memorizing isn't enough. We must be able to use our knowledge.
### What do we mean by "Dive Deep"?
* Practice!
* Go beyond route memorization. Challenge the learner to explain, analyse, apply, and synthesize.
* Build metacognitive capabilities.
* Go in for the long term. Use spaced repetition.
* Focus on developing areas of weakness.
* Remove barriers to going deep.
* Effective, timely feedback.
* Seek mastery. Learn components, integration, and application.
### How does Sagefy implement this idea?
* Subjects can contain subjects and units. Subjects can scale out extensively.
* Cards are flexible in format. This flexibility means we can ask for more than comprehesion.
* By removing complexity in the data structure, we make room for more depth by adding flexibility.
* The system encourages spaced repetition to ensure maximum retention of knowledge.
## 7. Make it Real
We rely on real-life experiences to guide to our learning.
### What do we mean by "Make it Real"?
* Connect material with real life problems.
* Use images and videos to connect with the visual processing center.
* Present the problem first, and allow the learner to arrive at the solution.
* Avoid overly formal or showy presentation.
* Open-ended work, worked examples, problem-based learning, simulations, and games.
* "Why?" -- Support the purpose of learning.
### How does Sagefy implement this idea?
* The flexibility of card formats allows using audio, images, and video.
* Cards can have requires, allowing for more involved projects based on problem-based learning.
## 8. Learn Together
We are more effective as team or as a community. Often, but not always.
### What do we mean by "Learn Together"?
* Allow more experienced learners to pair up and group up.
* Invite discussion at all levels.
* Use consensus to build.
* Communicate and log.
* Return to the community.
* Be honest with learners.
* Hold users accountable.
* Don't cover up non-private information.
* Invite and offer feedback regularly.
* Peer tutoring and mentoring.
### How does Sagefy implement this idea?
* Learners can work on cards together.
* Discussions are available for all cards, units, and subjects.
* Creating and editing content uses the consensus model.
* Everything is open source.
* Documentation throughout.
* Everything in the cards is public by default.
* Providing basic analytics to everyone means we can have more honest conversations.
* Everything is up for discussion and can be flagged.
* Sagefy is open source and is built on open source software.
---
What next? [Continue to "Data Structure"](/Data-Structure).
<file_sep>const { div } = require('../../helpers/tags')
module.exports = function homePage() {
return div('Welcome Home')
}
<file_sep>FROM python:3.6-alpine
ADD . /www
WORKDIR /www
RUN apk update
RUN apk add gcc python3-dev musl-dev build-base linux-headers pcre-dev
RUN apk add postgresql-dev
RUN apk add uwsgi
RUN pip install -r requirements.txt
RUN pip install https://github.com/unbit/uwsgi/archive/uwsgi-2.0.zip#egg=uwsgi
# ^^^ LOCAL ONLY
CMD ["uwsgi", "--ini", "./uwsgi.ini"]
<file_sep>FROM golang:1.10.3-alpine3.7
ADD . /server
WORKDIR /server
CMD ["go", "run", "index.go"]
<file_sep>// Connect a view to the state
module.exports = function connect(view) {
return mapStateToProps => (state, actions) =>
view(mapStateToProps(state), actions)
}
|
b8b246311fdd54dfa9b18dbd7a5b59fe1a235c73
|
[
"Markdown",
"JavaScript",
"Dockerfile"
] | 5
|
Markdown
|
kelre/sagefy
|
863fad1dffe58f194bc7dee8f5eb29ee7a88859c
|
6270206241979bb2f2b00aceef2bce0d3a9cd879
|
refs/heads/master
|
<repo_name>andershow7/curso_java_ee<file_sep>/src/main/java/br/com/restful/resource/HelloResource.java
package br.com.restful.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
@Path("/hello")
public class HelloResource {
Gson gson = new Gson();
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response get(){
return Response.ok("Hello Word!").build();
}
}
|
a79746aa455c32a3a039e3677480d53d0c76070d
|
[
"Java"
] | 1
|
Java
|
andershow7/curso_java_ee
|
7d32f288a4b4f3171bfe4e41417bdea7af9bc79d
|
60e1dc9d0aaf7773d301b79afc6a687117f39e14
|
refs/heads/master
|
<file_sep>import { response } from "express";
const API_TOKEN = "CLE_API";
export function getDataApi(link){
const url = '' + API_TOKEN;
return fetch(link)
.then((response) => response.json())
.catch((error) => console.log(error))
}<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React, { Component} from 'react';
import {Button,Text, Input,Avatar, Icon,ListItem,Divider} from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import {View ,Image,StyleSheet,FlatList, ImageBackground,Platform, TextInput,ScrollView,SafeAreaView, TouchableOpacity} from 'react-native';
import { DrawerItems } from 'react-navigation-drawer';
import {createAppContainer} from 'react-navigation'
import {createDrawerNavigator} from 'react-navigation-drawer';
import {createStackNavigator} from 'react-navigation-stack';
import DatePicker from 'react-native-datepicker';
import DepotData from './helpers/DepotData';
import ReleveData from './helpers/ReleveData';
import RechargementData from './helpers/RechargementData';
import TransfertData from './helpers/TransfertData';
class MyAccountScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View style={styles.logoPay}>
<Text h4 style={{color:'white'}}>Discount</Text>
<Text h4 style={{color:'#FCDD00'}}>Pay</Text>
</View>
<View style={styles.headerCompte}>
<Text style={{color:'white', fontSize:25}}><NAME></Text>
<Text style={{color:'white', fontSize:20}}>4 325 856 FCFA</Text>
<Icon type='entypo' name='eye-with-line' color='white'/>
</View>
<View style={styles.OptionsCompteOne}>
<TouchableOpacity activeOpacity = { .5 } onPress={() => this.props.navigation.navigate('MyReleveHome')}>
<Image id='releve' source={require('../assets/icons/relev_dpay_white.png')} style={{width:75,height:75,marginEnd:15,marginStart:20}} resizeMode='contain'/>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .5 } onPress={() => this.props.navigation.navigate('MyDepotHome')}>
<Image id='depot' source={require('../assets/icons/depôt_dpay.png')} style={{width:75,height:75,marginEnd:15,marginStart:20}} resizeMode='contain'/>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .5 } onPress={() => this.props.navigation.navigate('MyRechargementHome')}>
<Image id='retrait' source={require('../assets/icons/retrait_dpay.png')} style={{width:75,height:75,marginEnd:15,marginStart:20}} resizeMode='contain'/>
</TouchableOpacity>
</View>
<View style={{flexDirection:'row',}}>
<Text style={{color:'white', fontSize:18,marginEnd:26,marginStart:40}}>Relevé</Text>
<Text style={{color:'white', fontSize:18,marginEnd:26,marginStart:40}}>Depôt</Text>
<Text style={{color:'white', fontSize:18,marginEnd:26,marginStart:5}}>Rechargement</Text>
</View>
<View style={styles.OptionsCompteTwo}>
<TouchableOpacity activeOpacity = { .5 } onPress={() => this.props.navigation.navigate('MyTransfertHome')}>
<Image source={require('../assets/icons/transfert_dpay.png')} style={{width:75,height:75,marginEnd:15,marginStart:20}} resizeMode='contain'/>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .5 } onPress={() => this.props.navigation.navigate('MyBonusHome')}>
<Image source={require('../assets/icons/map_dpay.png')} style={{width:75,height:75,marginEnd:15,marginStart:20}} resizeMode='contain'/>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .5 } onPress={() => this.props.navigation.navigate('MyDcardHome')}>
<Image source={require('../assets/icons/card_dpay.png')} style={{width:75,height:75,marginEnd:15,marginStart:20}} resizeMode='contain'/>
</TouchableOpacity>
</View>
<View style={{flexDirection:'row', justifyContent:'center', margin:5, padding:5,}}>
<Text style={{color:'white', fontSize:18,marginEnd:26,marginStart:23}}>Transfert</Text>
<Text style={{color:'white', fontSize:18,marginEnd:26,marginStart:23}}>Localiser</Text>
<Text style={{color:'white', fontSize:18,marginEnd:26,marginStart:23}}>Dcard</Text>
</View>
</ScrollView>
);
}
}
class ReleveScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View style={{}}>
<View style={{flexDirection:'row',marginTop:2,backgroundColor:'#7f8c8d',height:35}}>
<Text style={{color:'white',marginLeft:8,marginTop:6}}>Du</Text>
<Text style={{color:'white',marginLeft:95,marginTop:6}}>au</Text>
<Text style={{color:'white',marginLeft:110,marginTop:6}}>Type Transaction</Text>
</View>
<View style={{flexDirection:'row',marginTop:2,height:35}}>
<Text style={{color:'white',marginLeft:8,marginTop:6}}>21-01-2020</Text>
<Text style={{color:'white',marginLeft:30,marginTop:6}}>04-02-2020</Text>
<Text style={{color:'white',marginLeft:63,marginTop:6}}>Orange Money</Text>
</View>
<View style={{marginLeft:8}}>
<TouchableOpacity activeOpacity = { .5 } >
<Button title='Rechercher' onPress={() => this.props.navigation.navigate('MyDepotSucess')} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</TouchableOpacity>
</View>
</View>
<View>
<View style={{ marginTop:27}}>
<View style={{ flex:1,flexDirection: 'row',justifyContent: 'space-between', backgroundColor:'#ecf0f1'}}>
<Text style={{marginTop:8, color:'red',marginLeft:8}}>Transactions Récentes</Text>
<Button title="Tout Afficher" buttonStyle={styles.btnAll} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}}/>
</View>
</View>
<View style={{backgroundColor:'#7f8c8d',marginTop:2, height:35,flexDirection:'row'}}>
<Text style={{color:'white',marginTop:8,fontSize:14, marginLeft:6}}>Compte</Text>
<Text style={{color:'white',marginLeft:40,marginTop:8,fontSize:14}}>Libellé</Text>
<Text style={{color:'white',marginLeft:60,marginTop:8,fontSize:14}}>Montant</Text>
<Text style={{color:'white',marginLeft:58,marginTop:8,fontSize:14}}>Détail</Text>
</View>
{
dataReleve.map((l, i) => (
<ListItem onPress={()=>alert('OK')}
subtitleStyle={styles.titleListDepo}
titleStyle={styles.libelleDepot}
containerStyle={styles.bgListem}
rightTitleStyle={styles.priceDepot}
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
subtitle={l.subtitle}
rightTitle ={l.rightTitle}
bottomDivider
chevron
/>
))
}
</View>
</ScrollView>
);
}
}
class DepotScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View>
<Text style={styles.idcard}>Effectuer un dépôt</Text>
<View style={styles.inputdepot}>
<TextInput style={{borderRadius:27, width:300, marginLeft:25}} placeholder="Entrez le montant"/>
</View>
<View style={{marginLeft:8}}>
<TouchableOpacity activeOpacity = { .5 } >
<Button title='Deposer' onPress={() => this.props.navigation.navigate('MyDepotSucess')} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</TouchableOpacity>
</View>
<View style={{ marginTop:10}}>
<View style={{ flex:1,flexDirection: 'row',justifyContent: 'space-between', backgroundColor:'#ecf0f1'}}>
<Text style={{marginTop:8, color:'red',marginLeft:8}}>Depôts Récents</Text>
<Button title="Tout Afficher" buttonStyle={styles.btnAll} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}}/>
</View>
</View>
<View style={{backgroundColor:'#7f8c8d',marginTop:2, height:35,flexDirection:'row'}}>
<Text style={{color:'white',marginTop:8,fontSize:14, marginLeft:6}}>Compte</Text>
<Text style={{color:'white',marginLeft:40,marginTop:8,fontSize:14}}>Libellé</Text>
<Text style={{color:'white',marginLeft:60,marginTop:8,fontSize:14}}>Montant</Text>
<Text style={{color:'white',marginLeft:58,marginTop:8,fontSize:14}}>Détail</Text>
</View>
{
dataDepot.map((l, i) => (
<ListItem
subtitleStyle={styles.titleListDepo}
titleStyle={styles.libelleDepot}
containerStyle={styles.bgListem}
rightTitleStyle={styles.priceDepot}
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
subtitle={l.subtitle}
rightTitle ={l.rightTitle}
bottomDivider
chevron
/>
))
}
</View>
</ScrollView>
);
}
}
class RechargementScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View>
<Text style={styles.idcard}>Effectuer un rechargement</Text>
<View style={styles.inputdepot}>
<TextInput style={{borderRadius:27, width:300, marginLeft:25}} placeholder="Entrez le montant"/>
</View>
<View style={{marginLeft:8}}>
<TouchableOpacity activeOpacity = { .5 } >
<Button title='Recharger' onPress={() => this.props.navigation.navigate('MyDepotSucess')} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</TouchableOpacity>
</View>
<View style={{ marginTop:10}}>
<View style={{ flex:1,flexDirection: 'row',justifyContent: 'space-between', backgroundColor:'#ecf0f1'}}>
<Text style={{marginTop:8, color:'red',marginLeft:8}}>Rechargements Récents</Text>
<Button title="Tout Afficher" buttonStyle={styles.btnAll} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}}/>
</View>
</View>
</View>
<View style={{backgroundColor:'#7f8c8d',marginTop:2, height:35,flexDirection:'row'}}>
<Text style={{color:'white',marginTop:8,fontSize:14, marginLeft:6}}>Compte</Text>
<Text style={{color:'white',marginLeft:40,marginTop:8,fontSize:14}}>Libellé</Text>
<Text style={{color:'white',marginLeft:60,marginTop:8,fontSize:14}}>Montant</Text>
<Text style={{color:'white',marginLeft:58,marginTop:8,fontSize:14}}>Détail</Text>
</View>
<View>
{
dataRechargement.map((l, i) => (
<ListItem
subtitleStyle={styles.titleListDepo}
titleStyle={styles.libelleDepot}
containerStyle={styles.bgListem}
rightTitleStyle={styles.priceDepot}
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
subtitle={l.subtitle}
rightTitle ={l.rightTitle}
bottomDivider
chevron
/>
))
}
</View>
</ScrollView>
);
}
}
class TransfertScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View>
<View style={{flexDirection:'row'}}>
<Text style={{color:'white', marginLeft:8,marginTop:8}}>Montant à transférer</Text>
<Text style={{color:'white', marginLeft:95,marginTop:8}}>DPY Bénéficiare</Text>
</View>
<View style={{flexDirection:'row'}}>
<View style={styles.inputransfertmontant}>
<TextInput placeholder="Entrez le montant" style={{marginLeft:8}}/>
</View>
<View style={styles.inputransfertdesti}>
<TextInput placeholder="DPY-XXX XXX XXX" style={{marginLeft:8}}/>
</View>
</View>
<View style={{marginLeft:8,marginTop:4}}>
<TouchableOpacity activeOpacity = { .5 } >
<Button title='Transférer' onPress={() => this.props.navigation.navigate('MyDepotSucess')} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</TouchableOpacity>
</View>
<View style={{ marginTop:18}}>
<View style={{ flex:1,flexDirection: 'row',justifyContent: 'space-between', backgroundColor:'#ecf0f1'}}>
<Text style={{marginTop:8, color:'red',marginLeft:8}}>Transferts Récents</Text>
<Button title="Tout Afficher" buttonStyle={styles.btnAll} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}}/>
</View>
</View>
</View>
<View style={{backgroundColor:'#7f8c8d',marginTop:2, height:35,flexDirection:'row'}}>
<Text style={{color:'white',marginTop:8,fontSize:14, marginLeft:6}}>Compte</Text>
<Text style={{color:'white',marginLeft:40,marginTop:8,fontSize:14}}>Libellé</Text>
<Text style={{color:'white',marginLeft:60,marginTop:8,fontSize:14}}>Montant</Text>
<Text style={{color:'white',marginLeft:58,marginTop:8,fontSize:14}}>Détail</Text>
</View>
<View>
{
dataTransfert.map((l, i) => (
<ListItem
subtitleStyle={styles.titleListDepo}
titleStyle={styles.libelleDepot}
containerStyle={styles.bgListem}
rightTitleStyle={styles.priceDepot}
key={i}
leftAvatar={{ source: { uri: l.avatar_url } }}
title={l.name}
subtitle={l.subtitle}
rightTitle ={l.rightTitle}
bottomDivider
chevron
/>
))
}
</View>
</ScrollView>
);
}
}
class BonusScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View><Text></Text></View>
</ScrollView>
);
}
}
class DcardScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View>
<Text style={styles.idcard}>Numéro de la carte</Text>
<View style={styles.inputcard}>
<TextInput style={{borderRadius:27, width:300, marginLeft:25}} placeholder='XXXX XXXX XXXX XXX'/>
</View>
<Text style={styles.idcard}>Noms & Prénoms</Text>
<View style={styles.inputcard}>
<TextInput style={{borderRadius:27, width:300, marginLeft:25}} placeholder='<NAME>'/>
</View>
<Text style={styles.idcard}>Date Expiration</Text>
<View style={styles.inputdateexpir}>
<TextInput placeholder="MM" />
<TextInput placeholder="AA" />
</View>
<Text style={styles.idcard}>Client Identification</Text>
<View style={styles.inputcard}>
<TextInput style={{borderRadius:27, width:300, marginLeft:25}} placeholder='00X XXX XXXX'/>
</View>
<View style={styles.btnLogin}>
{/* onPress={() => {alert('super');}} */}
<TouchableOpacity activeOpacity = { .5 } >
<Button title='Ajouter Carte' onPress={() => this.props.navigation.navigate('MyDcardView')} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
}
}
class DcardViewScreen extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View >
<Text style={{color:'white',marginTop:8,marginLeft:8}}>Coordonnées</Text>
</View>
<View style={{flexDirection:'column'}}>
<View style={styles.inputcardwithdata}>
<TextInput style={{position:'absolute',zIndex:-1}}/>
</View>
<View style={styles.inputcardwithdata}>
<TextInput style={{position:'absolute',zIndex:-1}}/>
</View>
</View>
<View style={{marginTop:50,marginLeft:10,position:'absolute',backgroundColor:'red',width:299}}><Text style={{fontSize:17, color:'white', fontWeight:'bold'}}>DISCOUNT CARD</Text></View>
<View style={{marginTop:135,marginLeft:10,position:'absolute',backgroundColor:'red',width:299,height:35}}><Text style={{fontSize:17, color:'white'}}></Text></View>
<View style={{marginTop:90,marginLeft:15,position:'absolute',backgroundColor:'#FCDD00',width:45,height:25,borderRadius:5}}><Text style={{fontSize:17, color:'white'}}></Text></View>
<View style={{marginTop:112,marginLeft:12,position:'absolute',width:299,height:25,borderRadius:5}}><Text style={{fontSize:17}}>XXX XXX XXX 9791</Text></View>
<View style={{marginTop:145,marginLeft:75,position:'absolute',width:299,height:25,borderRadius:5}}><Text style={{fontSize:10, color:'white'}}>EXPIRES END :</Text><View style={{marginLeft:70,marginTop:-18}}><Text>02/22</Text></View></View>
<View style={{marginTop:155,marginLeft:225,position:'absolute',width:299,height:25,borderRadius:5}}><Text style={{fontSize:20, color:'blue',fontWeight:'bold'}}>VISA</Text></View>
<View style={{position:'absolute',backgroundColor:'black',marginTop:240,marginLeft:8,width:299}}><Text>00</Text></View>
<View style={{position:'absolute',marginTop:223,marginLeft:14,width:299}}><Text style={{fontSize:10}}>Refer to Issuer for Conditions of use</Text></View>
<View style={{position:'absolute',marginTop:260,marginLeft:14,width:299}}><Text style={{fontSize:8}}>AUTHORISED SIGNATURE NOT VALID UNLESS SIGNED</Text></View>
<View style={{marginTop:315,marginLeft:15,position:'absolute',backgroundColor:'gray',width:45,height:25,borderRadius:5}}><Text style={{fontSize:17, color:'white'}}></Text></View>
<View style={{marginTop:335,marginLeft:15,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:12, color:'black'}}>XXX XXX XX42</Text></View>
<View style={{marginTop:350,marginLeft:15,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:8, color:'black'}}>Client Identification</Text></View>
<View style={{marginTop:278,marginLeft:235,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:8, color:'black', fontWeight:'bold'}}>Card Enquiries:</Text></View>
<View style={{marginTop:287,marginLeft:177,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}>Card to be returned to UBA Benin if found,</Text></View>
<View style={{marginTop:293,marginLeft:233,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}>Call +229 95631835</Text></View>
<View style={{marginTop:299,marginLeft:201,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}>Email: <EMAIL></Text></View>
<View style={{marginTop:305,marginLeft:187,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}><EMAIL></Text></View>
<View style={{marginTop:311,marginLeft:205,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}><EMAIL></Text></View>
<View style={{marginTop:318,marginLeft:195,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}>+229 21154911 / +229 64269736</Text></View>
<View style={{marginTop:325,marginLeft:141,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}>This card is ussued by United Bank for Africa pursuant</Text></View>
<View style={{marginTop:331,marginLeft:139,position:'absolute',height:25,borderRadius:5}}><Text style={{fontSize:6, color:'black'}}>to a license from Visa International Service Association</Text></View>
<View style={{marginTop:280,marginLeft:15,position:'absolute',height:25,borderRadius:5,backgroundColor:'#FCDD00',width:115}}><Text style={{fontSize:6}}></Text></View>
<View style={{marginTop:283,marginLeft:130,position:'absolute',height:25,borderRadius:5,width:50}}><Text style={{fontSize:6, color:'black',fontSize:12}}>XXX</Text></View>
<View style={{marginTop:353,marginLeft:130,position:'absolute',height:25,borderRadius:5}}><Text style={{color:'red',fontSize:8, fontWeight:'bold'}}>Discount CARD</Text></View>
</ScrollView>
);
}
}
class DepotViewSucess extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View style={{flexDirection:'row',justifyContent:'center',marginTop:50}}><Image id='depot' source={require('../assets/icons/depôt_dpay.png')} style={{width:75,height:75}} resizeMode='contain'/></View>
<View><Text style={{color:'white', marginLeft:10, fontSize:16, marginTop:15}}>Cher(e) client(e), votre dépôt de 350 000 FCFA sur votre compte ce Vendredi 31 Janvier 2020 à 15h02min42s effectué avec succès ! #DPay</Text></View>
</ScrollView>
);
}
}
var styles = StyleSheet.create({
containerDefault:{
backgroundColor:'#CF1111',
flex:1
},
logoPay:{
flexDirection:'row',
justifyContent:'flex-end',
marginBottom:20,
},
headerCompte:{
height:100,
alignItems:'center',
justifyContent:'center',
marginTop:25,
},
OptionsCompteOne:{
alignItems:'center',
justifyContent:'center',
flexDirection:'row',
marginTop:95,
},
OptionsCompteTwo:{
alignItems:'center',
justifyContent:'center',
flexDirection:'row',
marginTop:15,
},
containerCompte:{
color:'white',
marginTop:50,
flexDirection:'row',
justifyContent:'center',
},
montantUser:{
fontSize:25
},
imageLogin:{
alignItems: 'center',
},
iconsContainerCompte:{
width:75,
height:75,
paddingRight:20,
},
inputBox:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
},
containerForm:{
alignItems:'center',
marginTop:35,
},
btnLogin:{
width:150,
marginLeft:100
},
buttons:{
borderRadius:27,
height:60,
borderWidth: 2,
},
avatar:{
alignItems:'center',
marginTop:50,
},
buttons:{
borderRadius:27,
height:50,
marginTop:10,
width:150,
},
idcard:{
marginTop:8,
color:'white',
marginLeft:8,
fontSize:16
},
inputcard:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
marginTop:8,
width:300,
marginLeft:8
},
inputransfertmontant:{
backgroundColor:'white',
borderRadius:27,
marginLeft:8,
width:185,
marginTop:8,
},
inputransfertdesti:{
backgroundColor:'white',
borderRadius:27,
marginLeft:12,
width:145,
marginTop:8,
},
inputcardwithdata:{
backgroundColor:'white',
borderRadius:15,
alignItems:'center',
marginBottom:25,
marginTop:8,
width:300,
height:150,
marginLeft:8,
// position:'absolute'
},
inputdateexpir:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
marginTop:8,
width:95,
marginLeft:8,
flexDirection:'row',
justifyContent:'space-around'
},
inputdepot:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:8,
marginTop:8,
width:300,
marginLeft:8
},
btnAll:{
borderRadius:27,
width:150,
marginRight:-19
},
titleListDepo:{
color:'red',
fontSize:10
},
libelleDepot:{
fontSize:12,
},
priceDepot:{
color:'red',
fontSize:12,
position:'absolute',
width:150,
textAlign:'center'
},
});
const CustomDrawerContentComponent = props => (
<ScrollView>
<SafeAreaView
style={styles.container}
forceInset={{ top: 'always', horizontal: 'never' }}>
<View style={styles.avatar}>
<Avatar source={require('../assets/images/bg_dpay1.png')} size="xlarge" rounded/>
<Button onPress={() => {alert('super');}} buttonStyle={styles.buttons} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} title='Modifiez Profil'></Button>
</View>
<DrawerItems
style={{color:'white',}}
{...props} />
</SafeAreaView>
</ScrollView>
)
const MyAccountStackNavigator = createStackNavigator({
MyAccountHome: {
screen: MyAccountScreen,
navigationOptions:({navigation})=>({
title :'Mon Compte',
}),
},
MyReleveHome: {
screen: ReleveScreen,
navigationOptions:({navigation})=>({
title :'Mon Relevé',
}),
},
MyDepotHome: {
screen: DepotScreen,
navigationOptions:({navigation})=>({
title :'Mes Depôts',
}),
},
MyRechargementHome: {
screen: RechargementScreen,
navigationOptions:({navigation})=>({
title :'Mes Rechargements',
}),
},
MyTransfertHome: {
screen: TransfertScreen,
navigationOptions:({navigation})=>({
title :'Mes Transferts',
}),
},
MyBonusHome: {
screen: BonusScreen,
navigationOptions:({navigation})=>({
title :'Mes Bonus',
}),
},
MyDcardHome: {
screen: DcardScreen,
navigationOptions:({navigation})=>({
title :'Discountcard',
}),
},
MyDcardView: {
screen: DcardViewScreen,
navigationOptions:({navigation})=>({
title :'Ma DiscountCARD',
})
},
MyDepotSucess: {
screen: DepotViewSucess,
navigationOptions:({navigation})=>({
title :'Depôt Effectué',
})
},
});
const DrawerNavigator = createDrawerNavigator({
MyAccount: {
screen: MyAccountStackNavigator,
navigationOptions:({navigation})=>({
title :'Mon Compte',
drawerIcon:<Icon type='antdesign' name='user' rounded reverse color='black'/>,
}),
},
Transaction: {
screen: MyAccountScreen,
navigationOptions:({navigation})=>({
drawerIcon:<Icon type='material-community' name='cash-multiple' rounded reverse color='white'/>,
title:'Transactions',
tintColor:'white',
})
},
Bonus: {
screen: MyAccountScreen,
navigationOptions:({navigation})=>({
title:'Bonus',
drawerIcon:<Icon containerStyle='white' type='material-community' name='sack' rounded reverse color='white'/>
})
},
Parametres: {
screen: MyAccountScreen,
navigationOptions:({navigation})=>({
title:'Paramètres',
drawerIcon:<Icon type='antdesign' name='setting' rounded reverse color='white'/>,
})
},
Deconnexion: {
screen: MyAccountScreen,
navigationOptions:({navigation})=>({
title:'Deconnexion',
drawerIcon:<Icon type='feather' name='power' rounded reverse color='black'/>,
})
},
},
{drawerBackgroundColor:'red',
contentComponent:CustomDrawerContentComponent});
export default createAppContainer(DrawerNavigator);
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React, { Component } from 'react';
import {Button,Text, Input} from 'react-native-elements'
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/FontAwesome';
import {View ,Image,StyleSheet, ImageBackground, TextInput,ScrollView, Picker } from 'react-native';
export default class App extends Component {
// function test(params) {
// }
constructor(props){
super(props);
this.state={
register:{
nom:'',
prenoms:'',
email:'',
password:'',
cf_password:'',
},
fields_not_empty:{
show:false,
}
}
}
render() {
const {register} = this.state;
return (
<ScrollView style={styles.containerDefault}>
<View >
<View style={styles.logoPay}>
<Text h4 style={{color:'white'}}>Discount</Text>
<Text h4 style={{color:'#FCDD00'}}>Pay</Text>
</View>
<View style={styles.imageLogin}>
<Image source={require('../assets/images/register.jpg')} style={{width:250,}} resizeMode='contain'/>
</View>
<View style={styles.containerForm}>
<View style={styles.inputBox}>
<TextInput id="nom" onChangeText={(nom)=>this.setState({...register,nom})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='nom'/>
</View>
<View>
<Text id="error_nom" style={{color:'#FCDD00',marginTop:-22, marginLeft:-125, fontSize:11}}>veuillez renseigner votre nom</Text>
</View>
<View style={styles.inputBox}>
<TextInput id="prenoms" onChangeText={(prenom)=>this.setState({...register,prenom})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='prenoms'/>
</View>
<View>
<Text id="error_prenom" style={{color:'#FCDD00',marginTop:-22, marginLeft:-117, fontSize:11}}>veuillez renseigner votre prénom</Text>
</View>
<View style={styles.inputBox}>
<TextInput id="email" onChangeText={(email)=>{
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var emailtest = re.test(email.toLowerCase());
if(emailtest){
this.setState({...register,email})}
}
} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='email'/>
</View>
<View>
<Text id="error_email" style={{color:'#FCDD00',marginTop:-22, marginLeft:-67, fontSize:11}}>veuillez renseigner une adresse e-mail valide</Text>
</View>
<View style={styles.inputBox}>
<TextInput onChangeText={(password)=>this.setState({...register,password})} secureTextEntry={true} secureTextEntry={true} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='mot de passe'/>
</View>
<View>
<Text id="error_email" style={{color:'#FCDD00',marginTop:-22, marginLeft:-75, fontSize:11}}>veuillez renseigner un mot de passe valide</Text>
</View>
<View style={styles.inputBox}>
<TextInput onChangeText={(cf_password)=>this.setState({...register,cf_password})} secureTextEntry={true} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='confirmer mot de passe'/>
</View>
<View>
<Text id="error_email" style={{color:'#FCDD00',marginTop:-22, marginLeft:-46, fontSize:11}}>les deux mots de passes ne sont pas identiques</Text>
</View>
{/* <View style={[styles.pickerStyle,styles.inputBox]}>
<Picker style={{borderRadius:27, width:300, marginLeft:25}}
selectedValue={this.state.country}
onValueChange={(value,index)=>{
this.setState({country:value})
}}
>
<Picker.Item value='ci' label={'côte d\'ivoire'}/>
<Picker.Item value='bénin' label='bénin'/>
<Picker.Item value='togo' label='togo'/>
<Picker.Item value='cm' label='cameroun'/>
<Picker.Item value='ng' label='nigeria'/>
<Picker.Item value='gh' label='ghana'/>
</Picker>
</View> */}
<View style={styles.btnLogin}>
{/* <Button id="resgister" title='Inscription' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/> */}
<Button onPress={()=>{
if(register.nom.trim() == ""){
}
else{
// fiels_not_empty.error_nom;
}
// alert('veuillez remplir correctement le formulaire');
}
} id="register" title='Inscription' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</View>
</View>
</View>
</ScrollView>
);
}
}
var styles = StyleSheet.create({
containerDefault:{
backgroundColor:'#CF1111',
flex:1
},
logoPay:{
flexDirection:'row',
justifyContent:'flex-end',
marginBottom:20,
},
imageLogin:{
alignItems: 'center',
},
inputBox:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
},
containerForm:{
alignItems:'center',
marginTop:35,
},
btnLogin:{
width:150,
},
buttons:{
borderRadius:27,
height:60,
},
pickerStyle:{
}
});
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React, { Component } from 'react';
import {Button,Text, Input} from 'react-native-elements'
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/FontAwesome';
import {View ,Image,StyleSheet, ImageBackground, TextInput, ScrollView } from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.containerDefault}>
<View style={styles.logoPay}>
<Text h4 style={{color:'white'}}>Discount</Text>
<Text h4 style={{color:'#FCDD00'}}>Pay</Text>
</View>
<ScrollView>
<View style={{alignItems:'center',marginTop:85}}>
<View style={styles.imageLogin}>
<Image source={require('../assets/images/validation_mdp.jpg')} style={{width:250,}} resizeMode='contain'/>
</View>
<View style={styles.containerForm}>
<View style={styles.inputBox}>
<TextInput style={{borderRadius:27, width:300, marginLeft:25}} placeholder='entrez le code'/>
</View>
<View style={styles.btnLogin}>
<Button title='Envoyez' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons} />
</View>
</View>
</View>
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
containerDefault:{
backgroundColor:'#CF1111',
flex:1
},
logoPay:{
flexDirection:'row',
justifyContent:'flex-end',
marginBottom:35,
},
imageLogin:{
alignItems: 'center',
},
inputBox:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
},
containerForm:{
alignItems:'center',
marginTop:35,
},
btnLogin:{
width:150,
},
buttons:{
borderRadius:27,
height:60,
}
});
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React, { Component } from 'react';
import {Button,Text,Icon} from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import {View ,Image,StyleSheet} from 'react-native';
import LoginDC from './pages.DC/Login_DC';
import ConnexionDC from './pages.DC/Register_DC';
import CompteDC from './pages.DC/Compte_DC';
import EditProfilDC from './pages.DC/EditProfil_DC';
import ResetMdpDC from './pages.DC/ResetMdp_DC';
import ValidationMdpDC from './pages.DC/ValidationMdp_DC';
class AppDC extends Component {
constructor(props){
super(props);
}
render() {
return (
<View style={{flex:1,backgroundColor:'#CF1111', alignItems:'center'}}>
<View style={{flexDirection:'row', justifyContent:"flex-end",position:'absolute',right:0}}>
<Text h4 style={{color:'white'}}>Discount</Text>
<Text h4 style={{color:'#FCDD00'}}>Pay.</Text>
</View>
<Image source={require('./assets/images/bg_dpay2.png')} style={{width:250,height:250}} resizeMode='contain'/>
<View style={{flexDirection:'row',justifyContent:"space-around", position:'absolute',bottom:0,marginBottom:250, width:300, zIndex:1}}>
<Button onPress={()=>this.props.navigation.navigate('Login')} title='Connectez-Vous' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
<Button onPress={()=>this.props.navigation.navigate('Connexion')} title='Inscrivez-Vous' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</View>
<View style={{flex:1,justifyContent:'flex-end'}}>
<Image source={require('./assets/images/bg_dpay1.png')} style={{width:380,height:500}} resizeMode='cover'/>
</View>
</View>
);
}
}
var styles = StyleSheet.create({
mainstyle:{
flex: 1,
backgroundColor: 'blue'
},
buttons:{
borderRadius:20,
height:45
}
});
const AppNavigator = createStackNavigator({
Home: {
screen: AppDC,
navigationOptions: {
header: null,
},
},
Login: {
screen: LoginDC,
navigationOptions: {
header: null,
},
},
ResetMdp: {
screen: ResetMdpDC,
navigationOptions: {
header: null,
},
},
ValidationMdp: {
screen: ValidationMdpDC,
navigationOptions: {
header: null,
},
},
Connexion:{
screen:ConnexionDC,
navigationOptions: {
header: null,
}
},
Compte:{
screen:CompteDC,
navigationOptions:({navigation})=>({
headerTransparent:true,
headerLeft:(<View><Icon onPress={()=>navigation.toggleDrawer()} name='menu' color='white' size={45}/></View>)
}),
},
EditProfil:{
screen:EditProfilDC,
navigationsOptions:({navigation})=>({
headerTransparent:true,
// headerLeft:(<View><Icon onPress={()=>navigation.toggleDrawer()} name='menu' color='white' size={45}/></View>)
}),
},
});
export default createAppContainer(AppNavigator);
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React, { Component } from 'react';
import {Button,Text, Input} from 'react-native-elements'
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/FontAwesome';
import {View ,Image,StyleSheet, SafeAreaView,ImageBackground, TextInput,ScrollView, Picker } from 'react-native';
// import { Formik, Form, Field } from 'formik';
// import * as Yup from 'yup';
// const validationSchema = Yup.object().shape({
// name: Yup.string().required()
// });
export default class App extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View >
<View style={styles.logoPay}>
<Text h4 style={{color:'white'}}>Discount</Text>
<Text h4 style={{color:'#FCDD00'}}>Pay</Text>
</View>
<View style={styles.imageLogin}>
<Image source={require('../assets/images/register.jpg')} style={{width:250,}} resizeMode='contain'/>
</View>
<View style={styles.containerForm}>
<View style={styles.inputBox}>
<TextInput id="nom" onChangeText={(value)=> this.setState({nom:value})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='nom'/>
</View>
<View style={styles.inputBox}>
<TextInput id="prenoms" onChangeText={(value)=> this.setState({prenoms:value})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='prenoms'/>
</View>
<View style={styles.inputBox}>
<TextInput id="email" onChangeText={(value)=> this.setState({email:value})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='email'/>
</View>
<View style={styles.inputBox}>
<TextInput id="password" onChangeText={(value)=> this.setState({password:value})} type='password' secureTextEntry={true} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='mot de passe'/>
</View>
<View style={styles.inputBox}>
<TextInput id="cf_password" onChangeText={(value)=> this.setState({cf_password :value})} type='password' secureTextEntry={true} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='confirmer mot de passe'/>
</View>
{/* <View style={[styles.pickerStyle,styles.inputBox]}>
<Picker style={{borderRadius:27, width:300, marginLeft:25}}
selectedValue={this.state.country}
onValueChange={(value,index)=>{
this.setState({country:value})
}}
>
<Picker.Item value='ci' label={'côte d\'ivoire'}/>
<Picker.Item value='bénin' label='bénin'/>
<Picker.Item value='togo' label='togo'/>
<Picker.Item value='cm' label='cameroun'/>
<Picker.Item value='ng' label='nigeria'/>
<Picker.Item value='gh' label='ghana'/>
</Picker>
</View> */}
<View style={styles.btnLogin}>
{/* <Button id="resgister" title='Inscription' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/> */}
{/* <Button onPress={()=>this.validate_form()}
id="register"
title='Inscription'
ViewComponent={LinearGradient}
linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/> */}
</View>
</View>
</View>
</ScrollView>
// <SafeAreaView style={styles.containerDefault}>
// <Formik
// initialValues = {{name:""}}
// onSubmit={(values,actions) =>{
// alert(JSON.stringify(values));
// setTimeout(() => {
// actions.setSubmitting(false);
// }, 1000);
// }}
// validationSchema = {validationSchema}
// >
// {formikProps =>(
// <React.Fragment>
// <View style={styles.inputBox}>
// <TextInput style={{borderRadius:27, width:300, marginLeft:25}} onChangeText={formikProps.handleChange("name")}/>
// <Text style={{color:'#FCDD00'}}>{formikProps.errors.name}</Text>
// </View>
// <View style={styles.btnLogin}>
// <Button id="register" onPress={formikProps.handleSubmit} title='Inscription' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons} />
// </View>
// </React.Fragment>
// )}
// </Formik>
// </SafeAreaView>
)
}
var styles = StyleSheet.create({
containerDefault:{
backgroundColor:'#CF1111',
flex:1
},
logoPay:{
flexDirection:'row',
justifyContent:'flex-end',
marginBottom:20,
},
imageLogin:{
alignItems: 'center',
},
inputBox:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
},
containerForm:{
alignItems:'center',
marginTop:35,
},
btnLogin:{
width:150,
},
buttons:{
borderRadius:27,
height:60,
},
pickerStyle:{
}
});
<file_sep>module.exports = {
" extend ": "standard"
};<file_sep>export default dataDepot =[
{
name: '<NAME>',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
subtitle: '03-02-2020',
rightTitle:'1 350 000 FCFA',
},
{
name: '<NAME>',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
subtitle: '02-02-2020',
rightTitle:'674 000 FCFA',
},
{
name: '<NAME>',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
subtitle: '01-02-2020',
rightTitle:'410 000 FCFA',
},
{
name: '<NAME>',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
subtitle: '31-01-2020',
rightTitle:'3 000 000 FCFA',
},
{
name: '<NAME>',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
subtitle: '30-01-2020',
rightTitle:'647 255 FCFA',
},
]
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React, { Component } from 'react';
import {Button,Text, Input,Avatar, Icon} from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import {View ,Image,StyleSheet, ImageBackground, TextInput,ScrollView,SafeAreaView} from 'react-native';
import { DrawerItems } from 'react-navigation-drawer';
import {createAppContainer} from 'react-navigation'
import {createDrawerNavigator} from 'react-navigation-drawer';
class MyAccount extends Component {
render() {
return (
<ScrollView style={styles.containerDefault}>
<View style={styles.logoPay}>
<Text h4 style={{color:'white'}}>Discount</Text>
<Text h4 style={{color:'#FCDD00'}}>Pay</Text>
</View>
<View style={styles.headerCompte}>
<Text style={{color:'white', fontSize:25}}><NAME></Text>
<Text style={{color:'white', fontSize:20}}>4 325 856 FCFA</Text>
<Icon type='entypo' name='eye-with-line' color='white'/>
</View>
<View style={styles.OptionsCompteOne}>
<Image source={require('../assets/icons/relev_dpay_white.png')} style={styles.iconsContainerCompte} resizeMode='contain'/>
<Image source={require('../assets/icons/depôt_dpay.png')} style={{width:75,height:75}} resizeMode='contain'/>
<Image source={require('../assets/icons/retrait_dpay.png')} style={{width:75,height:75}} resizeMode='contain'/>
</View>
<View style={{flexDirection:'row', justifyContent:'center', margin:5, padding:5,}}>
<Text style={{color:'white', fontSize:15}}>Relevé</Text>
<Text style={{color:'white', fontSize:15}}>Depôt</Text>
<Text style={{color:'white', fontSize:15}}>Retrait</Text>
</View>
<View style={styles.OptionsCompteTwo}>
<Image source={require('../assets/icons/transfert_dpay.png')} style={{width:75,height:75}} resizeMode='contain'/>
<Image source={require('../assets/icons/recompense_dpay.png')} style={{width:75,height:75}} resizeMode='contain'/>
<Image source={require('../assets/icons/card_dpay.png')} style={{width:75,height:75}} resizeMode='contain'/>
</View>
<View style={{flexDirection:'row', justifyContent:'center', margin:5, padding:5,}}>
<Text style={{color:'white', fontSize:15}}>Transfert</Text>
<Text style={{color:'white', fontSize:15}}>Bonus</Text>
<Text style={{color:'white', fontSize:15}}>Dcard</Text>
</View>
</ScrollView>
);
}
}
var styles = StyleSheet.create({
containerDefault:{
backgroundColor:'#CF1111',
flex:1
},
logoPay:{
flexDirection:'row',
justifyContent:'flex-end',
marginBottom:20,
},
headerCompte:{
height:100,
alignItems:'center',
justifyContent:'center',
},
OptionsCompteOne:{
alignItems:'center',
justifyContent:'center',
flexDirection:'row',
marginTop:95,
},
OptionsCompteTwo:{
alignItems:'center',
justifyContent:'center',
flexDirection:'row',
marginTop:15,
},
containerCompte:{
color:'white',
marginTop:50,
flexDirection:'row',
justifyContent:'center',
},
montantUser:{
fontSize:25
},
imageLogin:{
alignItems: 'center',
},
iconsContainerCompte:{
width:75,
height:75,
paddingRight:20,
},
inputBox:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
},
containerForm:{
alignItems:'center',
marginTop:35,
},
btnLogin:{
width:150,
},
buttons:{
borderRadius:27,
height:60,
borderWidth: 2,
},
avatar:{
alignItems:'center',
marginTop:50,
},
buttons:{
borderRadius:27,
height:45,
marginTop:10,
width:150,
},
});
const CustomDrawerContentComponent = props => (
<ScrollView>
<SafeAreaView
style={styles.container}
forceInset={{ top: 'always', horizontal: 'never' }}>
<View style={styles.avatar}>
<Avatar source={require('../assets/images/bg_dpay1.png')} size="xlarge" rounded/>
<Button buttonStyle={styles.buttons} ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} title='Modifiez Profil'></Button>
</View>
<DrawerItems {...props} />
</SafeAreaView>
</ScrollView>
)
const DrawerNavigator = createDrawerNavigator({
MyAccount: {
screen: MyAccount,
navigationOptions:({navigation})=>({
title :'Mon Compte',
drawerIcon:<Icon type='antdesign' name='user' rounded reverse color='black'/>,
})
},
Transaction: {
screen: MyAccount,
navigationOptions:({navigation})=>({
title:'Transactions',
drawerIcon:<Icon type='material-community' name='cash-multiple' rounded reverse color='black'/>,
})
},
// Bonus: {
// screen: MyAccount,
// navigationOptions:({navigation})=>({
// title:'Bonus',
// drawerIcon:<Icon containerStyle='white' type='material-community' name='sack' rounded reverse color='black'/>,
// })
// },
// Parametres: {
// screen: MyAccount,
// navigationOptions:({navigation})=>({
// title:'Paramètres',
// drawerIcon:<Icon type='antdesign' name='setting' rounded reverse color='black'/>,
// })
// },
// Deconnexion: {
// screen: MyAccount,
// navigationOptions:({navigation})=>({
// title:'Deconnexion',
// drawerIcon:<Icon type='feather' name='power' rounded reverse color='black'/>,
// })
// },
},{drawerBackgroundColor:'red',
contentComponent:CustomDrawerContentComponent});
export default createAppContainer(DrawerNavigator);
<file_sep>import React, { Component} from 'react';
import {Button,Text, Input,Avatar, Icon,ListItem,Divider} from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import {View ,Image,StyleSheet,FlatList, ImageBackground, TextInput,ScrollView,SafeAreaView, TouchableOpacity} from 'react-native';
import { DrawerItems } from 'react-navigation-drawer';
import {createAppContainer} from 'react-navigation'
import {createDrawerNavigator} from 'react-navigation-drawer';
import {createStackNavigator} from 'react-navigation-stack';
class depotItem extends React.Component{
render(){
return (
<View style={styleDepot.main_container}>
</View>
)
}
}
const styleDepot = StyleSheet.create({
})
export default depotItem<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
*/
import React, { Component } from 'react';
import {Button,Text, Input} from 'react-native-elements'
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/FontAwesome';
import {View ,Image,StyleSheet, ImageBackground, TextInput,ScrollView, Picker } from 'react-native';
import {Formik} from 'formik';
export default class App extends Component {
constructor(props){
super(props);
this.state={
nom:'',
prenoms:'',
email:'',
password:'',
cf_password:'',
}
}
validate_form=()=>{
const{nom,prenoms,email,password,cf_password} = this.state
if(nom ==""){
alert("rentrez votre nom");
return false;
}
else if (prenoms=="") {
alert("renseigner votre prenom");
}
else if(email==""){
alert("renseigner une adresse e-mail valide");
}
else if(password==""){
alert("renseigner un mot de passe");
}
else if(password != <PASSWORD>){
alert("les mots de passes ne sont pas identiques");
}
}
render() {
return (
<ScrollView style={styles.containerDefault}>
<View >
<View style={styles.logoPay}>
<Text h4 style={{color:'white'}}>Discount</Text>
<Text h4 style={{color:'#FCDD00'}}>Pay</Text>
</View>
<View style={styles.imageLogin}>
<Image source={require('../assets/images/register.jpg')} style={{width:250,}} resizeMode='contain'/>
</View>
<View style={styles.containerForm}>
<View style={styles.inputBox}>
<TextInput id="nom" onChangeText={(value)=> this.setState({nom:value})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='nom'/>
</View>
<View>
<Text id="error_nom" style={{color:'#FCDD00',marginTop:-22,marginLeft:-130, fontSize:11}}>veuillez renseigner votre nom</Text>
</View>
<View style={styles.inputBox}>
<TextInput id="prenoms" onChangeText={(value)=> this.setState({prenoms:value})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='prenoms'/>
</View>
<View>
<Text id="error_prenoms" style={{color:'#FCDD00',marginTop:-22,marginLeft:-115, fontSize:11}}>veuillez renseigner votre prenoms</Text>
</View>
<View style={styles.inputBox}>
<TextInput id="email" onChangeText={(value)=> this.setState({email:value})} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='email'/>
</View>
<View>
<Text id="error_email" style={{color:'#FCDD00',marginTop:-22,marginLeft:-62, fontSize:11}}>veuillez renseigner une adresse e-mail valide</Text>
</View>
<View style={styles.inputBox}>
<TextInput id="password" onChangeText={(value)=> this.setState({password:value})} type='password' secureTextEntry={true} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='mot de passe'/>
</View>
<View>
<Text id="error_pwd" style={{color:'#FCDD00',marginTop:-22,marginLeft:-78, fontSize:11}}>veuillez renseigner votre mot de passe</Text>
</View>
<View style={styles.inputBox}>
<TextInput id="cf_password" onChangeText={(value)=> this.setState({cf_password :value})} type='password' secureTextEntry={true} style={{borderRadius:27, width:300, marginLeft:25}} placeholder='confirmer mot de passe'/>
</View>
<View>
<Text id="error_cf_pwd" style={{color:'#FCDD00',marginTop:-22,marginLeft:-75, fontSize:11}}>veuillez confirmer votre mot de passe</Text>
</View>
<View>
{/* <Text>{"nom ==>"+this.state.nom}</Text>
<Text>{"prénoms ==>"+this.state.prenoms}</Text> */}
</View>
{/* <View style={[styles.pickerStyle,styles.inputBox]}>
<Picker style={{borderRadius:27, width:300, marginLeft:25}}
selectedValue={this.state.country}
onValueChange={(value,index)=>{
this.setState({country:value})
}}
>
<Picker.Item value='ci' label={'côte d\'ivoire'}/>
<Picker.Item value='bénin' label='bénin'/>
<Picker.Item value='togo' label='togo'/>
<Picker.Item value='cm' label='cameroun'/>
<Picker.Item value='ng' label='nigeria'/>
<Picker.Item value='gh' label='ghana'/>
</Picker>
</View> */}
<View style={styles.btnLogin}>
{/* <Button id="resgister" title='Inscription' ViewComponent={LinearGradient} linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/> */}
<Button onPress={()=>this.validate_form()}
id="register"
title='Inscription'
ViewComponent={LinearGradient}
linearGradientProps={{colors:['#fff','#CF1111']}} buttonStyle={styles.buttons}/>
</View>
</View>
</View>
</ScrollView>
);
}
}
var styles = StyleSheet.create({
containerDefault:{
backgroundColor:'#CF1111',
flex:1
},
logoPay:{
flexDirection:'row',
justifyContent:'flex-end',
marginBottom:20,
},
imageLogin:{
alignItems: 'center',
},
inputBox:{
backgroundColor:'white',
borderRadius:27,
alignItems:'center',
marginBottom:25,
},
containerForm:{
alignItems:'center',
marginTop:35,
},
btnLogin:{
width:150,
},
buttons:{
borderRadius:27,
height:60,
},
pickerStyle:{
}
});
|
a26882a20ccbd66732dfa779f0c5e88cade32e36
|
[
"JavaScript"
] | 11
|
JavaScript
|
De-jacques/reactapp
|
22ce78a4966f007d489cd2786d42e89aeb608503
|
87e88acc506923c713bb47aa0902999107e12e6e
|
refs/heads/master
|
<repo_name>nhnifong/breadability<file_sep>/src/breadability/__init__.py
VERSION = '0.1.9'
import client
from scripts import newtest
|
b5a5de5b6343e0d571b5d16caffde494600b9245
|
[
"Python"
] | 1
|
Python
|
nhnifong/breadability
|
bd226ad09336414020ce398b7a73b390ac6d29fc
|
59dc8595c5d1181513d65e47bd7965f7d0ece4a4
|
refs/heads/master
|
<repo_name>bruno-source/skywatch-data-sources<file_sep>/requirements.txt
aspy.yaml==1.3.0
attrs==19.3.0
beautifulsoup4==4.8.1
certifi==2019.9.11
cfgv==2.0.1
chardet==3.0.4
Click==7.0
coverage==4.5.4
identify==1.4.7
idna==2.8
lxml==4.4.2
more-itertools==7.2.0
nodeenv==1.3.3
packaging==19.2
pluggy==0.13.1
pre-commit==1.20.0
py==1.8.0
pyparsing==2.4.5
pytest==5.3.1
pytest-cov==2.8.1
PyYAML==5.1.2
requests==2.22.0
responses==0.10.7
six==1.13.0
soupsieve==1.9.5
tabulate==0.8.6
toml==0.10.0
urllib3==1.25.7
virtualenv==16.7.8
wcwidth==0.1.7
<file_sep>/skywatch_data_sources/cli.py
import click
from tabulate import tabulate
from skywatch_data_sources.sources import get_data_sources
@click.command('list_data_sources')
def list_data_sources():
"""
Parses www.skywatch.com and returns a list of its available data sources
in a pretty-printed tabular data.
"""
sources = get_data_sources()
if sources:
table = tabulate(sources, headers='keys', tablefmt='fancy_grid')
click.echo(click.style(table, fg='green'))
else:
click.echo(click.style('Could not retrieve data sources', fg='red'))
<file_sep>/tests/conftest.py
import pytest
from click.testing import CliRunner
@pytest.fixture
def cli_runner():
return CliRunner()
@pytest.fixture
def xml_data():
xml = """
<urlset>
<url>
<loc>https://www.skywatch.com/data</loc>
<changefreq>daily</changefreq>
<priority>0.75</priority>
<lastmod>2019-06-07</lastmod>
<image:image>
<image:loc>
https://fake.jpg
</image:loc>
<image:title>Sources</image:title>
<image:caption>
Sentinel-2 Provider: ESA / Resolution: 10m / Tech specs
</image:caption>
</image:image>
<image:image>
<image:loc>
https://fake.jpg
</image:loc>
<image:title>Sources</image:title>
<image:caption>
SuperView-1 Provider: SpaceView / Resolution: 50cm / Tech specs
</image:caption>
</image:image>
</url>
</urlset>
""".strip().replace('\n', ' ')
return xml
<file_sep>/skywatch_data_sources/sources.py
from operator import itemgetter
import requests
from bs4 import BeautifulSoup
def get_data_sources():
"""
Parses www.skywatch.com and returns a list of its available data sources
"""
url = 'https://www.skywatch.com/sitemap.xml'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
images = soup.find_all('image:image')
sources = []
for image in images:
if image.find('image:title').get_text() == 'Sources':
source, resolution, _ = image.find(
'image:caption').get_text().split(' / ')
splited_source = source.split(' Provider: ')
data = {
'Source': splited_source[0].strip(),
'Provider': splited_source[1].strip(),
'Resolution': resolution.split(': ')[1].strip(),
}
sources.append(data)
return sorted(sources, key=itemgetter('Provider'))
<file_sep>/tests/skywatch_data_sources/test_sources.py
import responses
from skywatch_data_sources.sources import get_data_sources
@responses.activate
def test_get_data_sources_success(xml_data):
responses.add(
responses.GET,
'https://www.skywatch.com/sitemap.xml',
body=xml_data,
status=200
)
data_sources = get_data_sources()
expected_result = [
{
'Source': 'Sentinel-2',
'Provider': 'ESA',
'Resolution': '10m'
},
{
'Source': 'SuperView-1',
'Provider': 'SpaceView',
'Resolution': '50cm'
}
]
assert data_sources == expected_result
assert len(responses.calls) == 1
@responses.activate
def test_get_data_sources_error(xml_data):
responses.add(
responses.GET,
'https://www.skywatch.com/sitemap.xml',
body='{error}$ 541',
status=404
)
data_sources = get_data_sources()
expected_result = []
assert data_sources == expected_result
assert len(responses.calls) == 1
<file_sep>/pytest.ini
[pytest]
addopts = -v --cov=skywatch_data_sources --cov-report=term-missing
<file_sep>/tests/skywatch_data_sources/test_cli.py
from unittest import mock
from skywatch_data_sources.cli import list_data_sources
@mock.patch('skywatch_data_sources.cli.get_data_sources', autospec=True)
def test_list_data_sources_success(mock_get_data_sources, cli_runner):
data = {'Source': 'Sentinel-42', 'Provider': 'ESA', 'Resolution': '10m'}
mock_get_data_sources.return_value = [data]
result = cli_runner.invoke(list_data_sources)
assert mock_get_data_sources.call_count == 1
assert result.exit_code == 0
assert data['Source'] in result.output
@mock.patch('skywatch_data_sources.cli.get_data_sources', autospec=True)
def test_list_data_sources_empty_list(mock_get_data_sources, cli_runner):
mock_get_data_sources.return_value = []
result = cli_runner.invoke(list_data_sources)
expected_output = 'Could not retrieve data sources\n'
assert mock_get_data_sources.call_count == 1
assert result.exit_code == 0
assert result.output == expected_output
<file_sep>/README.md
# SkyWatch Data Sources
[](https://travis-ci.org/bruno-source/skywatch-data-sources)
[](https://coveralls.io/github/bruno-source/skywatch-data-sources?branch=master)
A simple Command-line interface to list [SkyWatch's](https://www.skywatch.com/) available data sources.
SkyWatch aggregates Earth observation data from many industry-leading sources into a single plataform.

## Instalation
Download and install the latest version from GitHub:
```
$ python -m venv .venv
$ source .venv/bin/activate
$ pip install git+https://github.com/bruno-source/skywatch-data-sources.git@v0.1#egg=skywatch_data_sources
```
## Usage
From the command-line:
```
$ skywatch-data-sources
╒═════════════════════════╤════════════╤══════════════╕
│ Source │ Provider │ Resolution │
╞═════════════════════════╪════════════╪══════════════╡
│ TripleSat Constellation │ 21AT │ 80cm │
├─────────────────────────┼────────────┼──────────────┤
.
.
.
$ skywatch-data-sources --help
Usage: skywatch-data-sources [OPTIONS]
Parses www.skywatch.com and returns a list of its available data sources
in a pretty-printed tabular data.
Options:
--help Show this message and exit.
```
Python console:
```
>>> from skywatch_data_sources.cli import list_data_sources
>>> list_data_sources()
╒═════════════════════════╤════════════╤══════════════╕
│ Source │ Provider │ Resolution │
╞═════════════════════════╪════════════╪══════════════╡
│ TripleSat Constellation │ 21AT │ 80cm │
├─────────────────────────┼────────────┼──────────────┤
.
.
.
```
```
>>> from skywatch_data_sources.sources import get_data_sources
>>> sources = get_data_sources()
>>> sources
[{'Provider': '21AT', 'Resolution': '80cm', 'Source': 'TripleSat Constellation'}
.
.
.
{'Provider': 'Urthecast', 'Resolution': '1m', 'Source': 'Deimos-2'}]
```
## Development and Testing
Clone the project, change directory and choose your favorite way to install
```console
$ git clone https://github.com/bruno-source/skywatch-data-sources
$ cd skywatch-data-sources
```
- With Pipenv:
```console
$ pipenv install --dev
$ pipenv run pytest
```
- With Virtualenv:
```console
$ python -m venv .venv
$ source .venv/bin/activate
$ pip install -r requirements.txt
$ pytest
```
|
7a80167286c7edb2da58f53de44c63f692c57aab
|
[
"Markdown",
"Python",
"Text",
"INI"
] | 8
|
Text
|
bruno-source/skywatch-data-sources
|
b543f4dcb3a383d165f2fff6de0949ed4d7b0f45
|
a7a48727e957d9990994e6c8c12e385a65460fae
|
refs/heads/master
|
<repo_name>oserr/recognizer<file_sep>/my_model_selectors.py
import math
import statistics
import warnings
import numpy as np
from hmmlearn.hmm import GaussianHMM
from sklearn.model_selection import KFold
from asl_utils import combine_sequences
class ModelSelector(object):
'''
base class for model selection (strategy design pattern)
'''
def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,
n_constant=3,
min_n_components=2, max_n_components=10,
random_state=14, verbose=False):
self.words = all_word_sequences
self.hwords = all_word_Xlengths
self.sequences = all_word_sequences[this_word]
self.X, self.lengths = all_word_Xlengths[this_word]
self.this_word = this_word
self.n_constant = n_constant
self.min_n_components = min_n_components
self.max_n_components = max_n_components
self.random_state = random_state
self.verbose = verbose
def select(self):
raise NotImplementedError
def base_model(self, num_states):
# with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
# warnings.filterwarnings("ignore", category=RuntimeWarning)
try:
model = self.compute_model(num_states)
if self.verbose:
fmt = 'model created for {} with {} states'
print(fmt.format(self.this_word, num_states))
return model
except:
if self.verbose:
fmt = 'failure on {} with {} states'
print(fmt.format(self.this_word, num_states))
return None
def compute_model(self, n):
'''Computes a GaussianHMM model.
:param n
The number of components.
'''
return GaussianHMM(
n_components=n,
covariance_type="diag",
n_iter=1000,
random_state=self.random_state,
verbose=False
).fit(self.X, self.lengths)
class SelectorConstant(ModelSelector):
""" select the model with value self.n_constant
"""
def select(self):
""" select based on n_constant value
:return: GaussianHMM object
"""
best_num_components = self.n_constant
return self.base_model(best_num_components)
class SelectorBIC(ModelSelector):
'''Select the model with the lowest Baysian Information Criterion(BIC) score
http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf
Bayesian information criteria: BIC = -2 * logL + p * logN
'''
def select(self):
""" select the best model for self.this_word based on
BIC score for n between self.min_n_components and self.max_n_components
:return: GaussianHMM object
"""
results = self.compute_for_all_n()
if not results:
return None
results = [(self.compute_bic(n,l), m) for n, l, m in results]
_, model = min(results, key=lambda x: x[0])
return model
def compute_for_all_n(self):
'''Computes the model and log likelihood for all combinations of
components.
:return
A list of tuples of the form (n, logL), where n is the number
of components used to train the model, and logL is the log
likelihood for the given model.
'''
warnings.filterwarnings("ignore", category=DeprecationWarning)
results = []
for n in range(self.min_n_components, self.max_n_components+1):
model = self.base_model(n)
if not model: continue
try:
logl = model.score(self.X, self.lengths)
except:
continue
results.append((n, logl, model))
return results
def compute_bic(self, n, logl):
'''Computes the Bayesian Information Criterion (BIC) score given n and
the log likelihood.
'''
return (-2*logl) + (self.compute_free_param(n)*np.log2(n))
def compute_free_param(self, n):
'''Computes the number of free paramters for a model of n components.
:param n
The number of components.
:return
The total number of free parameters.
'''
return n**2 + 2*len(self.X[0])*n - 1
class SelectorDIC(ModelSelector):
'''Select best model based on Discriminative Information Criterion
<NAME>. "A model selection criterion for classification: Application to
hmm topology optimization." Document Analysis and Recognition, 2003.
Proceedings. Seventh International Conference on. IEEE, 2003.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf
DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))
'''
def select(self):
results = self.compute_for_all_n()
if not results:
return None
_, model = max(results, key=lambda x: x[0])
return model
def compute_for_all_n(self):
'''Computes the DIC for all components.
:return
A list of tuples of the form (DIC, model).
'''
warnings.filterwarnings("ignore", category=DeprecationWarning)
results = []
other_words = set(self.hwords.keys())
other_words.remove(self.this_word)
for n in range(self.min_n_components, self.max_n_components+1):
model = self.base_model(n)
if not model: continue
try:
logl = model.score(self.X, self.lengths)
log_other = self.compute_log_other(model, other_words)
if not log_other: continue
except:
continue
results.append((logl-log_other, model))
return results
def compute_log_other(self, model, words):
'''Compute the average log likelihood of the other words.'''
if not model or not words:
return None
total = 0
log_other = 0.0
for w in words:
xo, lo = self.hwords[w]
try:
log_other += model.score(xo, lo)
total += 1
except:
continue
return log_other / total
class SelectorCV(ModelSelector):
'''Select best model based on average log Likelihood of cross-validation
folds.
'''
def select(self):
'''Selects cross-validated model with best log likelihood result.'''
results = self.compute_for_all_n()
if not results:
return None
n, _ = max(results, key=lambda x: x[1])
return self.base_model(n)
def compute_for_all_n(self):
'''Computes the model and log likelihood for all combinations of
components.
:return
A list of tuples of the form (n, logL), where n is the number
of components used to train the model, and logL is the log
likelihood for the given model.
'''
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Save values to restore before returning
cross_n_results = []
len_sequence = len(self.sequences)
if len_sequence <= 1:
for n in range(self.min_n_components, self.max_n_components+1):
list_logl = [] # list of cross validation scores obtained
model = self.base_model(n)
if not model:
continue
try:
logl = model.score(self.X, self.lengths)
except:
continue
list_logl.append(logl)
if list_logl:
avg_logl = np.mean(list_logl)
cross_n_results.append((n, avg_logl))
return cross_n_results
save_x, save_lens = self.X, self.lengths
for n in range(self.min_n_components, self.max_n_components+1):
split_method = KFold(len_sequence if len_sequence<3 else 3)
list_logl = [] # list of cross validation scores obtained
for train_idx, test_idx in split_method.split(self.sequences):
self.X, self.lengths = combine_sequences(train_idx, self.sequences)
model = self.base_model(n)
if not model: continue
test_x, test_len = combine_sequences(test_idx, self.sequences)
try:
logl = model.score(test_x, test_len)
except:
continue
list_logl.append(logl)
if list_logl:
avg_logl = np.mean(list_logl)
cross_n_results.append((n, avg_logl))
# Restore values
self.X, self.lengths = save_x, save_lens
return cross_n_results
|
c6c5bf04b73effeb3c34282b57a9160c1268d926
|
[
"Python"
] | 1
|
Python
|
oserr/recognizer
|
9b23d1f415d393e5a96104df4832d404e1c2b7a1
|
4958d31e260ab04ad5c21eb39b8bc85656a8becf
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Model.model;
import View.View_Pasien;
import sisfopasieninap.Aplikasi;
/**
*
* @author <NAME>
*/
public class controllerHome {
View_Pasien view;
model model;
public controllerHome(model model) {
this.model = model;
view = new View_Pasien();
view.setVisible(true);
}
}
|
a43e6ba111409026a2d3319aa830eac4511cb8ae
|
[
"Java"
] | 1
|
Java
|
faisalfrtz/Tubes_PBO_Kelompok8
|
57ec60d11574e589ad640e371bb2ec1c5f2983f2
|
879639514a89dd875cc853feae34e7b9192ba11c
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.border{
width: 0px;
height:0px;
border:50px solid transparent;
border-left-color: red
}
.txt{
width:400px;
height: 100px;
border: 1px solid;
text-align:left;/*对齐方式*/
line-height: 100px;/*单行文本高度 文本高度=容器高度*/
text-indent: 2em;/*1em=font-size*/
text-decoration: line-through
}
img{
width:200px;
height: 200px;
border:1px solid;
/*margin-left: -6px */
}
</style>
</head>
<body>
<div class="border"></div>
<div class="txt">
单行文本水平垂直居中
</div>
<div>
display显示属性
<p>
行级元素 inline:
内容决定所占的位置;
不能通过css设置宽高;
span a strong em
</p>
<p>
块级元素 block:
独占一行;
可以通过css改变宽高;
div p ul li ol form
</p>
<p>
行级块元素 inline-block:
内容决定所占的位置;
可以通过css改变宽高;
img
</p>
</div>
<div>
<img src="1.jpg" alt=""><img src="1.jpg" alt=""><img src="1.jpg" alt=""><img src="1.jpg" alt="">
</div>
<div>
<img src="1.jpg" alt="">
<img src="1.jpg" alt="">
<img src="1.jpg" alt="">
<img src="1.jpg" alt="">
<br>
图之间有空格,有inline属性的都具有文字特性,img回车后造成有4px的分隔
</div>
</body>
</html><file_sep>export let name="aaaa";
export function getName(){
console.log(name);
}
export function getName1(name1='xxx'){
console.log(name1);
}
class Person {
constructor(age,name) {
this.age =age;
this.name=name;
}
getInfo() {
console.log("name:"+this.name+ " Age:"+this.age);
}
}
export class Student extends Person {
}
export {Person}<file_sep>const fs=require("fs")
const readFile=function(filename){
return new Promise((resolve,reject)=>{
fs.readFile(filename,(err,data)=>{
if(err) reject(err); else resolve(data);
})
})
}
async function fn(){
let f1=await readFile("aaa.txt");
console.log(f1);
let f2=await readFile("bbb.txt");
console.log(f2);
let f3=await readFile("ccc.txt");
console.log(f3);
}
fn()<file_sep>function ajax(method,url,sfn,efn){
var oAjax;
if(window.XMLHttpRequest){
oAjax=new XMLHttpRequest();
}else{
oAjax=new ActiveXObject("Microsoft.XMLHTTP");
}
oAjax.open(method,url,true);
oAjax.send();
oAjax.onreadystatechange=function(){
if(oAjax.readyState==4){
if(oAjax.status==200){
sfn(oAjax.responseText);
}else{
if(efn){
efn(oAjax.status);
}
}
}
}
}<file_sep>console.log('异步加载的js')
function test(){
console.log('测试异步js中的方法')
}<file_sep>function getElementsByClass(obj,sClass){
aEle=obj.getElementsByTagName('*')
var arr=[]
for(var ele of aEle){
if(ele.className==sClass){
arr.push(ele)
}
}
return arr
}
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr]
} else {
return getComputedStyle(obj, false)[attr]
}
}
function startMove(obj, json,fnend) {
clearInterval(obj.timer)
obj.timer = setInterval(function () {
var bstop=true
for(var attr in json){
var speed
var cur=0
if(attr=='opacity'){
cur=parseFloat(getStyle(obj, attr))*100
}else{
cur=parseInt(getStyle(obj, attr))
}
speed= (json[attr] - cur) / 4
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
//if (json[attr] == cur) {
// clearInterval(obj.timer)
// if(fnend) fnend()
//}
if (json[attr] != cur){
bstop=false
}
//else {
if(attr=='opacity'){
obj.style[attr] = (parseFloat(getStyle(obj, attr))*100 + speed )/100
}else
{
obj.style[attr] = parseInt(getStyle(obj, attr)) + speed + 'px'
}
//}
}
if(bstop){
clearInterval(obj.timer)
if(fnend) fnend()
}
}, 30)
}<file_sep>const fs=require("fs")
const readFile=function(filename){
return new Promise((resolve,reject)=>{
fs.readFile(filename,(err,data)=>{
if(err) reject(err); else resolve(data);
})
})
}
readFile("aaa.txt").then(res=>{
console.log(res);
return readFile("bbb.txt");
}).then(
res=>{
console.log(res);
return readFile("ccc.txt");}
).then(res=>{
console.log(res);}
)<file_sep>const fs=require("fs")
const readFile=function(filename){
return new Promise((resolve,reject)=>{
fs.readFile(filename,(err,data)=>{
if(err) reject(err); else resolve(data);
})
})
}
function * gen(){
yield readFile("aaa.txt")
yield readFile("bbb.txt")
yield readFile("ccc.txt")
}
let g1=gen();
g1.next().value.then((res)=>{
console.log(res);
return g1.next().value;
}).then(res=>{
console.log(res);
return g1.next().value;
}).then(res=>{
console.log(res);
})<file_sep>function moveElement(ele){
this.element=ele;
this.style=ele.style;
}
moveElement.prototype.getStyle=function(attr) {
if (this.element.currentStyle) {
return this.element.currentStyle[attr]
} else {
return getComputedStyle(this.element, false)[attr]
}
}
moveElement.prototype.move=function(json,fnend) {
var timer = setInterval( ()=> {
var bstop=true
for(var attr in json){
var speed
var cur=0
if(attr=='opacity'){
cur=parseFloat(this.getStyle(attr))*100
}else{
cur=parseInt(this.getStyle(attr))
}
speed= (json[attr] - cur) / 4
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
//if (json[attr] == cur) {
// clearInterval(obj.timer)
// if(fnend) fnend()
//}
if (json[attr] != cur){
bstop=false
}
//else {
if(attr=='opacity'){
this.style[attr] = (parseFloat(this.getStyle(attr))*100 + speed )/100
}else
{
this.style[attr] = parseInt(this.getStyle(attr)) + speed + 'px'
}
//}
}
if(bstop){
clearInterval(timer)
if(fnend) fnend()
}
}
, 30)
return this;
}<file_sep>
console.log("模块化测试!")
const a=10;
let b=7;
let show=(a,b)=>{
return a+b;
}
export let ss={
a,
b,
show
}<file_sep>function LimitDrag(id){
Drag.call(this,id);
}
for(var i in Drag.prototype){
LimitDrag.prototype[i]=Drag.prototype[i]
}
LimitDrag.prototype.fnmove= function(ev){
var l=ev.clientX-this.disX;
var t=ev.clientY-this.disY;
if(l>800)
l=800
else if(l<200)
l=200
if(t>600)
t=600
else if(t<200)
t=200
this.oDiv.style.left=l+'px';
this.oDiv.style.top=t+'px';
}
|
0417e7dccd8a92384ec72eb5ce40a2c89377ecc3
|
[
"JavaScript",
"HTML"
] | 11
|
HTML
|
zwjsoft/web
|
a0e30ec970f1431e4e57c2092d4b35986a75ac61
|
9f224d13eeab701ddecbde282405240266accf56
|
refs/heads/master
|
<repo_name>hosnimubaraq/C-Programming-Assignment<file_sep>/no2(a).c
float do_it (char a,char b, char c) //header function do_it()
//<NAME> 17/U/3772/PS
<file_sep>/no4.c
/*function addarrays()*/
int c[] = {};
void addarrays(int a[], int b[], int x) {
int i = 0;
while (i < x) {
c[i] = a[i] + b[i];
i++;
}
}
/*Modification to return pointer as well as display the values from the three arrays*/
#include <stdio.h>
#include <stdlib.h>
int c[] = {};
int *addarrays(int a[], int b[], int x);
int main(void) {
int i,x;
printf("Size of the arrays: \n");
scanf("%d",&x);
int a[x], b[x];
printf("First array: \n");
for ( i = 0; i < x; i++) {
scanf("%d", &a[i]);
}
printf("Second array: \n");
for ( i = 0; i < x; i++) {
scanf("%d", &b[i]);
}
int *d;
d = addarrays(a,b, x);
printf("array one: ");
for (i=0; i < x; i++){
printf("%d,", a[i]);
}
printf("\narray two: ");
for (i=0; i < x; i++){
printf("%d,", b[i]);
}
printf("\narray three: ");
for (i=0; i < x; i++){
printf("%d,", d[i]);
}
return 0;
}
int *addarrays(int a[], int b[], int x) {
int i = 0;
for (i = 0; i < x; i++) {
c[i] = a[i] + b[i];
}
int *p;
p = &c;
return p;
}
//<NAME> 17/U/3772/PS
<file_sep>/no3.c
long hm[50];
long hm[49] = 123.456;
for (x = 0; x < 100; x++)//x is 100
for(ctr = 2; ctr < 10; ctr += 3)// the value of ctr is 11
int counter;
int d=1;
while(d<=100){ //while loop to count from 1 to 100 in 3s.
counter =d;
d+=3;
}
for (counter = 1; counter < MAXVALUES; counter++ );
printf("\nCounter = %d", counter); //there is no error with the code unless it was intended to print everytime the for loop is being checked.
<file_sep>/n02(b).h
void print_a_number(int y)// header function print_a_number() which returns nothing.
|
dd7ef33e610a1715721cacb864d6a1992c15bccf
|
[
"C"
] | 4
|
C
|
hosnimubaraq/C-Programming-Assignment
|
7b2d1f50099445d39e6653c29c175e4a94d3c97c
|
5d57bfd87bba3acc711f92c37e1e2e40eb71881e
|
refs/heads/master
|
<repo_name>hardliner66/sleep-rs<file_sep>/README.md
# sleep
## About
Windows has no simple tool or command to wait for a certain amount of time while executing a batch file.
I already have rust installed on all my computers so I thought it would be fitting to create a simple sleep command which can be installed directly through cargo.
## Installation & Update
With cargo:
```bash
cargo install sleep --force
```
## Command Line
```bash
sleep 1.0
Sleep for a given amount of time
USAGE:
sleep <TIME>
FLAGS:
-h, --help Prints help information
-V, --version Prints version information
ARGS:
<TIME> The time to sleep in milliseconds
```
## Examples
Sleep for one second:
```bash
sleep 1000
```<file_sep>/Cargo.toml
[package]
name = "sleep"
version = "1.0.2-alpha.0"
authors = ["hardliner66 <<EMAIL>>"]
edition = "2018"
description = "Create a command from a value of an INI-file and execute it."
license = "MIT OR Apache-2.0"
categories = ["command-line-utilities"]
keywords = ["sleep"]
repository = "https://github.com/hardliner66/sleep-rs"
readme = "README.md"
[dependencies]
clap = "2.33"
<file_sep>/src/main.rs
struct Args {
time: u64,
}
use clap::{App, Arg};
fn get_args() -> Result<Args, Box<dyn std::error::Error>> {
let matches = App::new("sleep")
.version("1.0")
.about("Sleep for a given amount of time")
.arg(
Arg::with_name("time")
.value_name("TIME")
.help("The time to sleep in milliseconds")
.required(true),
)
.get_matches();
let time_string = matches.value_of("time").unwrap();
let time = if let Ok(time) = time_string.parse() {
time
} else {
eprintln!("\"{}\" is not a valid number!", time_string);
std::process::exit(1);
};
Ok(Args {
time
})
}
use std::{
thread,
time::Duration,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = get_args()?;
Ok(thread::sleep(Duration::from_millis(args.time)))
}
|
e05301af4beaa6339c0214ef23c5bf6d26b135e8
|
[
"Markdown",
"TOML",
"Rust"
] | 3
|
Markdown
|
hardliner66/sleep-rs
|
566ba4cf0e8f08884332c6c87277090495241554
|
757eadb3294572118edd5c85992e869a9bf77b85
|
refs/heads/master
|
<file_sep># shopping-cart-service<file_sep>package service
import (
"github.com/google/uuid"
"shopping-cart-service/src/main/dao"
"shopping-cart-service/src/main/domain"
)
var cartDao = dao.CartDao{Carts: make(map[uuid.UUID]domain.Cart)}
func CreateOrUpdate(c *domain.Cart) *domain.Cart {
return cartDao.CreateOrUpdate(c)
}
func GetCart(id uuid.UUID) *domain.Cart{
return cartDao.Get(id)
}
func RetrieveCarts()[]domain.Cart{
return cartDao.RetrieveAll()
}<file_sep>package config
import (
"github.com/gorilla/mux"
"net/http"
"shopping-cart-service/src/main/controller"
)
type Config interface {
Router() http.Handler
}
func New() Config {
a := &controller.Api{}
r := mux.NewRouter()
r.HandleFunc("/carts", a.GetCarts).Methods(http.MethodGet)
r.HandleFunc("/carts", a.CreateCart).Methods(http.MethodPost)
r.HandleFunc("/carts/{id}/items", a.GetItems).Methods(http.MethodGet)
r.HandleFunc("/carts/{id}/items", a.DeleteItems).Methods(http.MethodDelete)
r.HandleFunc("/carts/{id}/items/{itemId}", a.DeleteItem).Methods(http.MethodDelete)
r.HandleFunc("/carts/{id}/items", a.AddItem).Methods(http.MethodPut)
r.HandleFunc("/articles", a.GetArticles).Methods(http.MethodGet)
a.ApiRouter = r
return a
}
<file_sep>package service
import (
"shopping-cart-service/src/main/client"
"shopping-cart-service/src/main/domain"
)
var ArticlesContent = client.Cache
func LoadArticles() map[string]domain.Item {
ArticlesContent.Load()
return ArticlesContent.Articles
}<file_sep>package domain
type Item struct {
Id string `json:"id"`
Title string `json:"title"`
Price string `json:"price"`
Quantity int `json:"quantity"`
}
func (i *Item) Increment() {
i.Quantity++
}
<file_sep>package dao
import (
"github.com/google/uuid"
"shopping-cart-service/src/main/domain"
"sync"
)
type GenericDao interface {
Get(u uuid.UUID) *domain.Cart
CreateOrUpdate(cart *domain.Cart) *domain.Cart
RetrieveAll() []domain.Cart
}
type CartDao struct {
Carts map[uuid.UUID]domain.Cart
mux sync.Mutex
}
func (d *CartDao) Get(id uuid.UUID) *domain.Cart {
elem, _ := d.Carts[id]
return &elem
}
func (d *CartDao) CreateOrUpdate(cart *domain.Cart) *domain.Cart {
if cart.Id == uuid.Nil {
cart.Id, _ = uuid.NewRandom()
}
d.Carts[cart.Id] = *cart
return cart
}
func (d *CartDao) RetrieveAll() []domain.Cart {
var carts = make([]domain.Cart, 0)
for _, value := range d.Carts {
carts = append(carts, value)
}
return carts
}
<file_sep>package main
import (
"bytes"
"encoding/json"
"github.com/google/uuid"
"net/http"
"net/http/httptest"
"os"
"shopping-cart-service/src/main/config"
"shopping-cart-service/src/main/domain"
"shopping-cart-service/src/main/service"
"strconv"
"testing"
)
var s config.Config
func TestMain(m *testing.M) {
s = config.New()
code := m.Run()
os.Exit(code)
}
func TestApi_AddItem(t *testing.T) {
req, err := http.NewRequest("GET", "/carts", nil)
if err != nil {
t.Fatal(err)
}
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
if body := response.Body.String(); body != "[]" {
t.Errorf("Expected an empty array. Got %s", body)
}
}
func TestApi_CreateCart(t *testing.T) {
body := []byte(`{"description":"Test description"}`)
request, _ := http.NewRequest("POST", "/carts", bytes.NewBuffer(body))
response := executeRequest(request)
checkResponseCode(t, http.StatusCreated, response.Code)
var cart domain.Cart
json.Unmarshal(response.Body.Bytes(), &cart)
if cart.Description != "Test description" {
t.Errorf("Expected user name to be 'test user'. Got '%v'", cart.Description)
}
if cart.Id == uuid.Nil {
t.Errorf("Expected product ID to be '1'. Got '%v'", cart.Id)
}
}
func TestApi_DeleteItem(t *testing.T) {
var cart = getCartContent()
service.CreateOrUpdate(&cart)
req, err := http.NewRequest("DELETE", "/carts/"+ cart.Id.String() + "/items/2", nil)
if err != nil {
t.Fatal(err)
}
response := executeRequest(req)
checkResponseCode(t, http.StatusCreated, response.Code)
var cartFromApi domain.Cart
json.Unmarshal(response.Body.Bytes(), &cartFromApi)
if cart.Id != cartFromApi.Id {
t.Errorf("Expected a cart with id %s. Got %s", cart.Id, cartFromApi.Id)
}
if len(cartFromApi.Items) != 1 {
t.Errorf("Expected an item list with size %s. Got %s", "1", strconv.Itoa(len(cartFromApi.Items)))
}
}
func TestApi_DeleteItems(t *testing.T) {
var cart = getCartContent()
service.CreateOrUpdate(&cart)
//type fields struct {
// ApiRouter http.Handler
//}
//type args struct {
// w http.ResponseWriter
// r *http.Request
//}
//tests := []struct {
// name string
// fields fields
// args args
//}{
// // TODO: Add test cases.
//}
//for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// a := &Api{
// ApiRouter: tt.fields.ApiRouter,
// }
// print(a)
// })
//}
}
func TestApi_GetArticles(t *testing.T) {
}
func TestApi_GetCarts(t *testing.T) {
var cart = domain.Cart{Description: "Test description"}
service.CreateOrUpdate(&cart)
req, err := http.NewRequest("GET", "/carts", nil)
if err != nil {
t.Fatal(err)
}
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
var cartList[]domain.Cart
json.Unmarshal(response.Body.Bytes(), &cartList)
if body := response.Body.String(); body == "[]" {
t.Errorf("Expected an array. Got %s", body)
}
if len(cartList) != 1 {
t.Errorf("Expected an array with %s elements. Got %s", "1", strconv.Itoa(len(cartList)))
}
}
func TestApi_GetItems(t *testing.T) {
}
func Test_buildErrorResponse(t *testing.T) {
}
func Test_buildResponse(t *testing.T) {
}
func executeRequest(req *http.Request) *httptest.ResponseRecorder {
rr := httptest.NewRecorder()
s.Router().ServeHTTP(rr, req)
return rr
}
func checkResponseCode(t *testing.T, expected, actual int) {
if expected != actual {
t.Errorf("Expected response code %d. Got %d\n", expected, actual)
}
}
func getCartContent() domain.Cart {
var items = map[string]domain.Item{
"1":{
Id:"1",
Title:"Banana",
Price:"2.50",
Quantity: 1,
},
"2":{
Id:"2",
Title:"Apple",
Price:"3.20",
Quantity: 1,
},
}
var cart = domain.Cart{
Description: "Test cart",
Items: items,
}
return cart
}
<file_sep>package domain
import "github.com/google/uuid"
type Cart struct {
Id uuid.UUID `json:"id"`
Description string `json:"description,omitempty" validate:"nil=false > empty=false" `
Items map[string]Item `json:"item"`
}
<file_sep>package controller
import (
"encoding/json"
"github.com/google/uuid"
"github.com/gorilla/mux"
"net/http"
"shopping-cart-service/src/main/domain"
"shopping-cart-service/src/main/service"
)
type Api struct {
ApiRouter http.Handler
}
func (a *Api) Router() http.Handler {
return a.ApiRouter
}
func (a *Api) GetCarts(w http.ResponseWriter, r *http.Request) {
var content = service.RetrieveCarts()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(content)
}
func (a *Api) GetArticles(w http.ResponseWriter, r *http.Request){
var content = service.LoadArticles()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(content)
}
func (a *Api) CreateCart(w http.ResponseWriter, r *http.Request){
cart := domain.Cart{Items: make(map[string]domain.Item)}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&cart); err != nil {
buildErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
service.CreateOrUpdate(&cart)
buildResponse(w, http.StatusCreated, cart)
}
func (a *Api) AddItem(w http.ResponseWriter, r *http.Request){
service.LoadArticles()
eventID := mux.Vars(r)["id"]
item := domain.Item{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&item); err != nil {
buildErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
var id, _ = uuid.Parse(eventID)
var cart = service.GetCart(id)
var articleInCache = service.ArticlesContent.Articles[item.Id]
if val, ok := cart.Items[articleInCache.Id]; !ok{
cart.Items[articleInCache.Id] = articleInCache
}else{
val.Increment()
cart.Items[articleInCache.Id] = val
}
service.CreateOrUpdate(cart)
buildResponse(w, http.StatusCreated, cart)
}
func (a *Api) GetItems(w http.ResponseWriter, r *http.Request){
cartId, _ := uuid.Parse(mux.Vars(r)["id"])
var cart = service.GetCart(cartId)
buildResponse(w, http.StatusCreated, cart.Items)
}
func (a *Api) DeleteItems(w http.ResponseWriter, r *http.Request){
cartId, _ := uuid.Parse(mux.Vars(r)["id"])
var cart = service.GetCart(cartId)
cart.Items = make(map[string]domain.Item)
service.CreateOrUpdate(cart)
buildResponse(w, http.StatusCreated, cart)
}
func (a *Api) DeleteItem(w http.ResponseWriter, r *http.Request) {
cartId, _ := uuid.Parse(mux.Vars(r)["id"])
itemId, _ := mux.Vars(r)["itemId"]
var cart = service.GetCart(cartId)
delete(cart.Items, itemId)
service.CreateOrUpdate(cart)
buildResponse(w, http.StatusCreated, cart)
}
func buildResponse(w http.ResponseWriter, status int, payload interface{}) {
response, err := json.Marshal(payload)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write([]byte(response))
}
func buildErrorResponse(w http.ResponseWriter, code int, message string) {
buildResponse(w, code, map[string]string{"error": message})
}
func validateCartContent(){
}<file_sep>package client
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"shopping-cart-service/src/main/domain"
)
type ArticlesCache struct {
Articles map[string]domain.Item
Loaded bool
}
type CacheInterface interface {
Load()
}
var Cache = ArticlesCache{Articles: make(map[string]domain.Item)}
func (cache *ArticlesCache)Load(){
var articleList = load()
if !cache.Loaded{
for _, art := range articleList {
cache.Articles[art.Id] = art
}
}
cache.Loaded = true
}
func load() []domain.Item {
var articles []domain.Item
resp, err := http.Get("http://challenge.getsandbox.com/articles")
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
bodyBytes, _ := ioutil.ReadAll(resp.Body)
bodyString := string(bodyBytes)
log.Print("API Response as String:\n" + bodyString)
json.Unmarshal(bodyBytes, &articles)
log.Printf("API Response as struct %+v\n", articles)
return articles
}
|
22dcc5f527b08c95d690dc0f2e6c241878a9dec1
|
[
"Markdown",
"Go"
] | 10
|
Markdown
|
holmergaitan/shopping-cart-service
|
1ecfcb1911ede35bcea127811a3eedbfbfefce88
|
08de4e2ec047776ccb599bb0b9c96f692a86ea3f
|
refs/heads/main
|
<repo_name>ricardopraxedes/nestjs-training<file_sep>/README.md
## Description
Practice with [Nest](https://github.com/nestjs/nest) framework.
<file_sep>/src/players/players.controller.ts
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { CreatePlayerDto } from './dto/create-player.dto';
import { UpdatePlayerDto } from './dto/update-player.dto';
import { PlayersService } from './players.service';
import { Player } from './schema/player.schema';
@Controller('players')
export class PlayersController {
constructor(private readonly playersService: PlayersService) {}
@Post()
async create(@Body() createPlayerDto: CreatePlayerDto): Promise<Player> {
return this.playersService.create(createPlayerDto);
}
@Get()
async findAll(): Promise<Player[]> {
return this.playersService.findAll();
}
@Put(':id')
async update(
@Param('id') id: string,
@Body() updatePlayerDto: UpdatePlayerDto,
): Promise<Player> {
const player = await this.playersService.update(id, updatePlayerDto);
return player;
}
@Delete(':id')
async delete(@Param('id') id: string): Promise<void> {
return this.playersService.delete(id);
}
}
<file_sep>/src/players/players.controller.spec.ts
import { getModelToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { v4 } from 'uuid';
import { CreatePlayerDto } from './dto/create-player.dto';
import { PlayersController } from './players.controller';
import { PlayersService } from './players.service';
import { Player } from './schema/player.schema';
describe('PlayersController', () => {
let controller: PlayersController;
let service: PlayersService;
const playerDTO = new CreatePlayerDto();
const expectedResult = new Player();
const playerId = v4();
Object.assign(playerDTO, {
name: 'Ricardo',
});
Object.assign(expectedResult, {
...playerDTO,
id: v4(),
});
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PlayersController],
providers: [
PlayersService,
{
provide: getModelToken(Player.name),
useValue: {},
},
],
}).compile();
controller = module.get<PlayersController>(PlayersController);
service = module.get<PlayersService>(PlayersService);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
it('create should call service with player data', async () => {
jest.spyOn(service, 'create').mockResolvedValue(expectedResult);
const result = await controller.create(playerDTO);
expect(service.create).toBeCalledWith(playerDTO);
expect(result).toStrictEqual(expectedResult);
});
it('findAll should call service and return all players', async () => {
const expectedResult = new Player();
const playerId = v4();
Object.assign(expectedResult, {
...playerDTO,
id: playerId,
});
jest.spyOn(service, 'findAll').mockResolvedValue([expectedResult]);
const result = await controller.findAll();
expect(service.findAll).toBeCalled();
expect(result).toStrictEqual([expectedResult]);
});
it('update should call service with id and return updated object', async () => {
jest.spyOn(service, 'update').mockResolvedValue(expectedResult);
const result = await controller.update(playerId, playerDTO);
expect(service.update).toBeCalledWith(playerId, playerDTO);
expect(result).toBe(expectedResult);
});
it('delete should call service with id', async () => {
jest.spyOn(service, 'delete').mockImplementation();
await service.delete(playerId);
expect(service.delete).toBeCalledWith(playerId);
});
});
<file_sep>/docker-compose.yml
version: "3.7"
services:
mongodb:
image : mongo
container_name: mongodb
restart: always
environment:
- MONGODB_DATABASE="test"
ports:
- 27017:27017
<file_sep>/src/players/players.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { model, Model } from 'mongoose';
import { CreatePlayerDto } from './dto/create-player.dto';
import { UpdatePlayerDto } from './dto/update-player.dto';
import { Player, PlayerDocument } from './schema/player.schema';
@Injectable()
export class PlayersService {
private logger = new Logger(PlayersService.name);
constructor(
@InjectModel(Player.name)
private readonly playerModel: Model<PlayerDocument>,
) {}
async create(createPlayerDto: CreatePlayerDto): Promise<Player> {
return this.playerModel.create(createPlayerDto);
}
async findAll(): Promise<Player[]> {
return this.playerModel.find().exec();
}
async update(_id: string, updatePlayerDto: UpdatePlayerDto): Promise<Player> {
const player = await this.playerModel
.findOneAndUpdate({ _id }, updatePlayerDto, { new: true })
.exec();
return player;
}
async delete(_id: string): Promise<void> {
await this.playerModel.deleteOne({ _id });
}
}
<file_sep>/src/players/players.service.spec.ts
import { getModelToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { Model } from 'mongoose';
import { v4 } from 'uuid';
import { CreatePlayerDto } from './dto/create-player.dto';
import { Player, PlayerDocument } from './schema/player.schema';
import { PlayersService } from './players.service';
describe('PlayersService', () => {
let service: PlayersService;
let model: Model<PlayerDocument>;
const playerDTO = new CreatePlayerDto();
const playerId = v4();
const expectedResult = new Player();
Object.assign(playerDTO, {
name: 'Ricardo',
});
Object.assign(expectedResult, {
...playerDTO,
id: playerId,
});
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
PlayersService,
{
provide: getModelToken(Player.name),
useValue: {
create: jest.fn(),
find: jest.fn(),
findOneAndUpdate: jest.fn(),
deleteOne: jest.fn(),
},
},
],
}).compile();
model = module.get<Model<PlayerDocument>>(getModelToken(Player.name));
service = module.get<PlayersService>(PlayersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('create on service should call mongodb create', async () => {
const spy = jest
.spyOn(model, 'create')
.mockImplementation(() => expectedResult);
const result = await service.create(playerDTO);
expect(spy).toBeCalledTimes(1);
expect(result).toBe(expectedResult);
});
it('find all should return all players', async () => {
const players = [expectedResult];
const spy = jest.spyOn(model, 'find').mockReturnValue({
exec: jest.fn().mockResolvedValue(players),
} as any);
const result = await service.findAll();
expect(spy).toBeCalledTimes(1);
expect(result).toStrictEqual(players);
});
it('update should return updated object', async () => {
const spy = jest.spyOn(model, 'findOneAndUpdate').mockReturnValue({
exec: jest.fn().mockResolvedValue(expectedResult),
} as any);
const result = await service.update(playerId, playerDTO);
expect(spy).toBeCalledTimes(1);
expect(result).toBe(expectedResult);
});
it('delete should call database delete with id ', async () => {
const spy = jest.spyOn(model, 'deleteOne').mockImplementation();
await service.delete(playerId);
expect(spy).toBeCalledTimes(1);
});
});
|
4898ee328e0bc8f4ef593c651be42658a119899e
|
[
"Markdown",
"TypeScript",
"YAML"
] | 6
|
Markdown
|
ricardopraxedes/nestjs-training
|
d64fc45ab0ed7dde34171b2c236e9620a8ababf1
|
2ac862b0c0f3636fde2f9f9683af97fbb8e6d0df
|
refs/heads/main
|
<file_sep>// Assignment Code
//do you want to use Upper Case characters - var = globally scoped
var upperCase = ['A','B','C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X','Y', 'Z']
//Array of lower case characters - do you want to use Lower Case
var lowerCase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
//do you want to use numbers
var numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
//do you want to use special characters
var symbols = [ '@', '%', '+', '\\', '/', '!', '#', '$', '^', '?', ':', ',', ')', '(', '}', '{', ']', '[', '~', '-', '_', '.']
var generateBtn = document.querySelector("#generate");//id selector = html line 28
function generatePassword(){
//parseInt applied to prompt to convert any string values to numeric value
var passwordLength = parseInt(prompt ("How many characters you would like your password to have?"))
//validating password ie that it is the correct length
//validating password ie that a number not alpha has been used to choose password length
if (Number.isNaN (passwordLength)){
alert("Your entry is invalid, please re-enter a valid number")
return //stops the code being processed beyond this point.
}
if (passwordLength < 8 ){
alert("Your choice is invalid, please enter a number that is greater than 8")
return
}
if (passwordLength > 128 ){
alert("Your choice is invalid, please enter a number that is less than 128")
return
}
var confirmUpCase = confirm ("Would you like to use upper case letters in your password? Press ok to confirm or cancel to ignore");
// confirmUpCase = confirm = "ok", decline = "cancel");
if (confirmUpCase) {
alert ("Upper Case selected");
} else {
alert("Upper Case not Selected");
}
// }
var confirmLowCase = confirm("Would you like to use lower case letters in your password? Press ok to confirm or cancel to ignore");
if (confirmLowCase){
alert ("Lower Case Selected");
} else {
alert ("Lower Case not Selected");
}
var confirmNumbers = confirm("Would you like to use numbers in your password? Press ok to confirm or cancel to ignore");
if (confirmNumbers){
alert ("Numbers Selected");
} else {
alert ("Numbers not Selected");
}
var confirmSymbols = confirm("Would you like to use symbols in your password? Press ok to confirm or cancel to ignore");
if (confirmSymbols){
alert ("Symbols Selected");
} else {
alert ("Symbols not Selected");
}
//for loop allowing the selection of the characters from the array of characters.
//var characters = upperCase.concat(lowerCase, numbers, symbols);
for(var i, i = 0; i < characters.length; i++){
generatePassword += characters.charAt(math.random() * characters.length)
}
};
// var generatePassword = upperCase.concat(lowerCase, numbers, symbols);
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");//id selector = html line 22
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
<file_sep>//Pseudo code: for JS file
//ask how long should the password be
//consider propmts; alerts & confirmations
//give user choices:-
//do you want UCase
//var upperCase = ['A','B','C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X','Y', 'Z']
//do you want LCase
//var lowerCase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
//do you want numbers
//var numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
//do you want special characters
//var specialCharacters = [ '@', '%', '+', '\\', '/', '!', '#', '$', '^', '?', ':', ',', ')', '(', '}', '{', ']', '[', '~', '-', '_', '.']
// combine arrays - concatenation
//my alerts give popup messages to user
//collate and put into 1 group -
//randomly select characters
//link to html<file_sep># password-generator
Using Java Script to create a password generator
## Approach:
* Create pseudo code to map requirements and functions.
* Create variables to cover the scope of the characters that would be used to generate a random password.
* Create a for loop to allow the selection of the characters from the array.
* Create prompt to establish desired password length:
- password length must be more than 8 characters and less than 128 characters.
* Create prompt & alerts to establish & notify the user which characters they would like to use
- character options are:
Upper Case
Lower Case
Numbers
Symbols
* Create alert to notify user if password is less than 8 or more than 128 characters
* Create an alert if the user users an invalid entry for password length
* Link to GitHub: https://github.com/Jacqieq6464/password-generator.git
* Link to Git Pages: https://jacqieq6464.github.io/password-generator/
|
ea22462ddcac2d1c821cee399dd346f3acb13bc5
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Jacqieq6464/password-generator
|
47e26a9fa2d708d8c0eff2704412a8307b79b6e5
|
94d366753ef7084c3998b0c9c302eb7c2ff98764
|
refs/heads/master
|
<repo_name>dlcnd/pathapi<file_sep>/README.md
# pathapi
<file_sep>/pathapi.py
#!usr/bin/env python
#coding:utf8
import sys
import re
def project(path):
"""
경로를 넣으면 project 이름을 반환.
"""
p= re.findall('/prject/(\w+)',path.replace("\\","/"))
if len(p) != 1:
return "", "경로에서 project정보를가져 올 수 없습니다"
return p[0],None
def seq(path):
"""
경로를 넣으면seq 이름을 반환.
"""
p= re.findall('/shot/(\w+)',path.replace("\\","/"))
if len(p) != 1:
return "", "경로에서 seq 정보를가져 올 수 없습니다"
return p[0],None
def shot(path):
"""
경로를 넣으면shot 이름을 반환.
"""
p= re.findall('/shot/\w/(\w+)',path.replace("\\","/"))
if len(p) != 1:
return "", "경로에서 shot 정보를가져 올 수 없습니다"
return p[0],None
def task(path):
"""
경로를 넣으면task 이름을 반환.
"""
p= re.findall('/shot/\w/\w(\w+)',path.replace("\\","/"))
if len(p) != 1:
return "", "경로에서 task 정보를가져 올 수 없습니다"
return p[0],None
def ver(path):
"""
경로를 넣으면version 반환.
"""
p= re.findall('_v(\d+)',path.replace("\\","/"))
if len(p) != 1:
return "", "경로에서 version 정보를가져 올 수 없습니다"
return int(p[0]),None
def seqNum(path):
"""
경로를 넣으면sequence number 반환.
"""
p= re.findall('\.(\d+)\.',path.replace("\\","/"))
if len(p) != -1:
return "", "경로에서 sequence number 정보를가져 올 수 없습니다"
return int(p[0]),None
<file_sep>/pathapi_test.py
#!/usr/bin/env python
#coding:utf8
import unittest
from pathapi import *
class Test_path(unittest.TestCase):
def test_project(self):
self.assertEqual(project("/project/circle"),("circle",None))
self.assertEqual(project("/project/circle/"),("circle",None))
self.assertEqual(project("\\\\10.20.30.40\\project\\circle\\"),("circle",None))
self.assertEqual(project("\\\\10.20.30.40\\server1\\project\\circle\\"),("circle",None))
self.assertEqual(project("/project/circle/shot/FOO/0010/comp/FOO_0010_comp_v001.nk"),("circle",None))
self.assertEqual(project("/server1/project/circle"),("circle",None))
self.assertEqual(project("/server2/project/circle"),("circle",None))
def test_seq(self):
self.assertEqual(project("/project/circle/shot/FOO/0010"),("FOO",None))
self.assertEqual(project("/project/circle/shot/FOO.0010/comp/FOO_0010_comp_v001.nk"),("FOO",None))
self.assertEqual(project("\\\\10.20.30.40\\project\\circle\\shot\\FOO"),("FOO",None))
def test_shot(self):
self.assertEqual(project("/project/circle/shot/FOO/0010"),("0010",None))
self.assertEqual(project("/project/circle/shot/FOO/0032/"),("0032",None))
self.assertEqual(project("\\\\10.20.30.40\\project\\circle\\shot\\FOO\\0010"),("0010",None))
def test_task(self):
self.assertEqual(project("/project/circle/shot/FOO/0010/comp"),("comp",None))
self.assertEqual(project("/project/circle/shot/FOO/0032/comp/"),("comp",None))
self.assertEqual(project("\\\\10.20.30.40\\project\\circle\\shot\\FOO\\0010\\comp"),("comp",None))
def test_ver(self):
self.assertEqual(project("/project/circle/shot/FOO/0010/comp/FOO_0010_comp_v001"),(1,None))
self.assertEqual(project("/project/circle/shot/FOO/0010/comp/FOO_0010_comp_v001/"),(1,None))
self.assertEqual(project("\\\\10.20.30.40\\project\\circle\\shot\\FOO\\0010\\comp\\FOO_comp_v001"),(1,None))
def test_seqNum(self):
self.assertEqual(project("/project/circle/shot/FOO/0010/comp/FOO_0010_comp_v001.1001.nk"),(1001,None))
self.assertEqual(project("\\\\10.20.30.40\\project\\circle\\shot\\FOO\\0010\\comp\\FOO_comp_v001.11.nk"),(11,None))
if __name__ == "__main__":
unittest.main()
|
9409f33072375b5b5e94cb47da40a7bdd3f3ae2a
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
dlcnd/pathapi
|
01daf04a559add9f5ac0ad39049d09c79ba251ba
|
5e3b5c92d5389136e3fa71ac8d99adb789a0ccb3
|
refs/heads/master
|
<file_sep>from sys import argv
adjective, color, noun = argv
prompt = '>'
print(f"I know the teacher is very {adjective}. Sometimes he wears a {color} shirt with {noun} on it.")
print(f"Name an item")
iteam = input(prompt)
print(f"Name a place")
place = input(prompt)
print(f"Name a person")
person = input(prompt)
print(f"I canot find my {iteam} anywhere! It's not even at {place}. While I was at {place}, I saw {person}... maybe they have it.")
Words_Needed = ["Time", "Feeling", "Food", "Vehicle", "Grade level","Funny job", "Thing", "Adjective", "Hard task", "Name", "Verb", "School subject", "Body part", "Facial feature"]
Dictionary = {}
for Word in Words_Needed:
Temp_Word = input(f"Write a(n) {Word}:")
Dictionary[Word] = Temp_Word
print(f"It is the first day of school. NOOOO. I spent {Dictionary['Time']} hours moaning and groaning in bed. I was so {Dictionary['Feeling']} because I had to strat {Dictionary['Grade level']} grade. I ran downstairs to eat {Dictionary['Food']} for breakfast. When I walked outside, the {Dictionary['Vehicle']} had already left.")
print(f"I go to school so I can be a {Dictionary['Funny job']} when I grow up. They do {Dictionary['Hard task']}. Those professionals are very {Dictionary['Adjective']}. I hate other jobs because they use {Dictionary['Thing']}. I completely against that. ")
print(f" Dear {Dictionary['Name']},")
print(f"I still remeber the first time I {Dictionary['Verb']} eyes on you.")
print(f"It was during {Dictionary['School subject']} class, and you canme in to give out teacher a {Dictionary['Thing']}.")
print(f"One day I want to hold your {Dictionary['Body part']} and kiss it")
print(f"Best Wishes <3, oh ans P.S. I LOVE your {Dictionary['Facial feature']}")
Words_Needed = ["Color", "Country", "Article of Clothing", "Verb", "Adjective", "Animal","Name","Food", "Store", "Candy", "Dance type", "Celebrity","Song", "Pronoun", "Verb2","Costume", "Number"]
Dictionary = {}
for Word in Words_Needed:
Temp_Word = input(f"Write a(n) {Word}:")
Dictionary[Word] = Temp_Word
print(f"I went to {Dictionary['Store']} to buy a {Dictionary['Animal']} last friday. I've been needing a friend. I found out that it only eats {Dictionary['Food']}, but I only had {Dictionary['Candy']} with me.I let it eat the {Dictionary['Candy']} and it ....ummmm..... died.")
print(f"I decided to take a {Dictionary['Dance type']} dance class. {Dictionary['Celebrity']} ended up teaching the class using the song {Dictionary['Song']}.")
print(f" Dear parents or guardians of {Dictionary['Name']}, {Dictionary['Name']} has been doing very {Dictionary['Adjective']} this semester. I thought it be very important that you were aware.")
print(f"{Dictionary['Pronoun']} is very rude to his classmates. He is also very intrested in {Dictionary['Verb']}ing. He needs to work on {Dictionary['Verb2']}ing however.")
print(f"My friend hired me to be a {Dictionary['Costume']} for {Dictionary['Number']} dollars. I was the best damn {Dictionary['Costume']} out there. The children were throwing {Dictionary['Candy']} at me. One apple was thrown at me too")
print(f"Today I get to marry {Dictionary['Name']}! It was the happiest day of my life. I wore a {Dictionary['Color']} {Dictionary['Article of Clothing']}. I had my whole family help me pick it out. We got married in {Dictionary['Country']}, also the best place for a honeymoon.")
<file_sep>Words_Needed = ["Adjective", "Adverb", "Body Part", "Color", "Event", "Food", "Fruit", "Liquid", "Material", "Name", "Noun", "Number", "Plural Noun", "Vegetable", "Verb"]
Dictonary = {}
for Word in Words_Needed:
Temp_Word = input(f"Write a(n) {Word}:")
Dictonary[Word] = Temp_Word
print(f"Please excuse {Dictonary['Name']} who is far too {Dictonary['Adjective']} to attend {Dictonary['Noun']} class.")
print(f"{Dictonary['Name']} is sick with {Dictonary['Body Part']} flu. Drink more {Dictonary['Liquid']} and take {Dictonary['Material']} as needed.")
<file_sep>adjective = input("Please select an adjective")
color = input("Please select a color")
noun = input("Please select a noun")
print(f"I know the teacher is very {adjective}. Sometimes he wears a {color} shirt with {noun} on it.")
iteam = input("What is your favorite thing")
place = input("The scariest place on the planet")
person = input("Name a person")
print(f"I canot find my {iteam} anywhere! It's not even at {place}. While I was at {place}, I saw {person}... maybe they have it.")
time = input("Insert a number")
feeling = input("What emotion are you feeling right noun")
food = input("What food do you feel like eating right now")
vehicle = input("Insert a way of transportation")
grade =input("Choose a grade level 1-12")
print(f"It is the first day of school. NOOOO. I spent {time} hours moaning and groaning in bed. I was so {feeling} because I had to strat {grade}grade. I ran downstairs to eat {food} for breakfast. When I walked outside, the {vehicle} had already left")
funny = input("Name a funny job")
thing = input("Name a thing")
describe = input("What is a describing word")
do = input(" A difficult thing to do")
print(f"I go to school so I can be a {funny} when I grow up. They do {do}. Those professionals are very {describe}. I hate other jobs because it uses{thing}. I completely against that. ")
first = input("Your first name")
verb = input("Verb past tense")
school = input("school subject")
body = input("body part")
face = input("facial feature")
print(f" Dear {first},")
print(f"I still remeber the first time I {verb} eyes on you.")
print(f"It was during {school} class, and you canme in to give out teacher a {thing}.")
print(f"One day I want to hold your {body} and kiss it")
print(f"Best Wishes <3, oh ans P.S. I LOVE your {face}")
animal = input("Name a animal")
store = input("Name a store")
candy = input("Name a candy")
print(f"I went to {store} to buy a {animal} last friday. I've been needing a friend. I found out that it only eats {food}, but I only had {candy} with me.I let it eat the {candy} and it ....ummmm..... died.")
dance = input(f"Name a type of dance")
celebrity = input(f"Name a celebrity")
song = input(f"Name a song")
print(f"I decided to take a {dance} dance class. {celebrity} ended up teaching the class using the song {song}.")
name = input("What is your first name")
pro = input("Pronoun")
verb = input("Verb")
verb2 = input("Another verb")
print(f" Dear parents or guardians of {name}, {name} has been doing very {adjective} this semester. I thought it be very important that you were aware.")
print(f"{pro} is very rude to his {noun}. He is also veru intrested in {verb}ing. He needs to work on {verb2}ing however.")
cost = input("Costume")
can = input("Candy")
mon = input("Number")
print(f"My friend hired me to be a {cost} for {mon} dollars. I was the best damn {cost} out there. The children were throwing {can} at me. One candy was thrown at me")
per = ("Name a person")
col = ("A color")
con = ("A country")
dress = ("An article of clothing")
print(f"Today I get to marry {per}! It was the happiest day of my life. I wore a {col} {dress}. I had my whole family help me pick it out. We got married in {con}, also the best place for a honeymoon.")
|
c0d7fb6e0b072be9a722ea1d1f6b8019cb167c70
|
[
"Python"
] | 3
|
Python
|
mekhaabraham03/MadlibProject2
|
6d0e87af4a69d2c80390812a35c57eab6c936652
|
f20094b8f236b4c19c79b4d18ec8e00bdffb9e66
|
refs/heads/master
|
<file_sep>compare_cols_naive <- function(x, y, col, tolerance) {
}
|
a423eaa451e79c77a115824057b2f47a0fa993f7
|
[
"R"
] | 1
|
R
|
ryanbthomas/safelyexample
|
af802a091a0b7a53e9e877b4ed1c993df70d5cd1
|
70bb62088321c2911c19e1f7cf17932388c535b8
|
refs/heads/master
|
<file_sep>Docker image containing PyCharm IDE
<file_sep>FROM ubuntu:16.04
MAINTAINER <NAME> "<EMAIL>"
# Configures operative system dependencies
ENV LANG C.UTF-8
ENV DEBIAN_FRONTEND noninteractive
ENV DEBCONF_NONINTERACTIVE_SEEN true
RUN sed 's/main$/main universe/' -i /etc/apt/sources.list && \
apt-get update -qq && \
echo 'Installing OS dependencies' && \
apt-get install -qq -y --fix-missing sudo software-properties-common git libxext-dev libxrender-dev libxslt1.1 \
libxtst-dev libgtk2.0-0 libcanberra-gtk-module unzip wget && \
echo 'Cleaning up' && \
apt-get clean -qq -y && \
apt-get autoclean -qq -y && \
apt-get autoremove -qq -y && \
rm -rf /var/lib/apt/lists/* && \
rm -rf /tmp/*
RUN echo 'Creating user: developer' && \
mkdir -p /home/developer && \
echo "developer:x:1000:1000:Developer,,,:/home/developer:/bin/bash" >> /etc/passwd && \
echo "developer:x:1000:" >> /etc/group && \
sudo echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer && \
sudo chmod 0440 /etc/sudoers.d/developer && \
sudo chown developer:developer -R /home/developer && \
sudo chown root:root /usr/bin/sudo && \
chmod 4755 /usr/bin/sudo
# Installs java
ENV JAVA_VERSION 8
ENV JAVA_UPDATE 72
ENV JAVA_BUILD 15
ENV JAVA_HOME /usr/lib/jvm/jdk1.${JAVA_VERSION}.0_${JAVA_UPDATE}
RUN apt-get update && apt-get install ca-certificates curl \
gcc libc6-dev libssl-dev make \
-y --no-install-recommends && \
mkdir -p /usr/lib/jvm && \
curl --silent --location --retry 3 --cacert /etc/ssl/certs/GeoTrust_Global_CA.pem \
--header "Cookie: oraclelicense=accept-securebackup-cookie;" \
http://download.oracle.com/otn-pub/java/jdk/"${JAVA_VERSION}"u"${JAVA_UPDATE}"-b"${JAVA_BUILD}"/server-jre-"${JAVA_VERSION}"u"${JAVA_UPDATE}"-linux-x64.tar.gz \
| tar xz -C /usr/lib/jvm && \
apt-get remove --purge --auto-remove -y \
gcc \
libc6-dev \
libssl-dev \
make && \
apt-get autoclean && apt-get --purge -y autoremove && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
ENV PATH $JAVA_HOME/bin:$PATH
ENV PYCHARM /opt/pycharm
RUN mkdir $PYCHARM
RUN wget https://download.jetbrains.com/python/pycharm-professional-2017.1.2.tar.gz -O - | tar xzv --strip-components=1 -C $PYCHARM
ENV PATH $PYCHARM/bin:$PATH
<file_sep>#!/bin/bash
set -e
IMAGE=pycharm
[[ ! -z "$NAME" ]] || NAME=pycharm
IP=$(ifconfig en0 inet | grep inet | awk '{print $2'})
SNAP_DEV=/Users/dev/sparklinedata
open -a XQuartz
xhost + $IP
docker run -it -d \
--name ${NAME} \
-v ${SNAP_DEV}:/home/developer/code \
-v /tmp/.X11-unix:/tmp/.X11-unix \
-e DISPLAY=${IP}:0.0 \
${IMAGE} \
pycharm.sh
echo "Container $NAME of image $IMAGE started"
|
b9733faadd8862678fbf3b73c2772379cab49692
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 3
|
Markdown
|
ali1rathore/pycharm-docker
|
90f1f4ed8b469b479d9a48e2af1cd3357274ff99
|
01a4edac6acb3352e13936333b78335170c1c2b1
|
refs/heads/master
|
<repo_name>tuandat95cbn/LTSS<file_sep>/Code/quicksort.cpp
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
int n;
int a[1000000],*localArr,*reciveArr;
int nold;
MPI_Status status;
int rank;
void readData(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
}
void printArray(int *a,int n,int z){
printf("*****************\n Rank is %d %d The array is %d number\n",rank,z,n);
for(int i=0;i<n-1;i++){
printf("%d ->",a[i]);
}
printf("%d end",a[n-1]);
printf("\n****************\n");
}
void swap(int *x,int *y){
int tmp=*x;
*x=*y;
*y=tmp;
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(int argc, char** argv){
clock_t begin = clock();
freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
double passingTime=0;
double calTime=0;
double allTime=0;
MPI_Init(&argc,&argv);
int numpro;
int size;
int *reArr;
reciveArr= (int *)malloc(1000000*sizeof(int));
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank ( MPI_COMM_WORLD , & rank );
if ( rank == 0 ){
readData();
int subSize=n/size +((n%size==0)?0:1);
printf("sub size is %d %d %d",subSize,n,size);
int *subArr= (int *)malloc(subSize*sizeof(int));
int c=0;
//printf("done read data\n");
for(int i=0;i<size-1;i++){
int nS=0;
//printf("split data\n");
while(nS<subSize){
subArr[nS]=a[c];
nS++;
c++;
}
MPI_Send(&nS,1,MPI_INT,i+1,0,MPI_COMM_WORLD);
MPI_Send(subArr,nS,MPI_INT,i+1,0,MPI_COMM_WORLD);
}
localArr= (int *)calloc(subSize,sizeof(int));
int nS=0;
printf("c is %d\n",c);
while(c<n){
localArr[nS]=a[c];
nS++;
c++;
}
nold=n;
n=nS;
printArray(localArr,n,1);
} else {
MPI_Recv(&n,1,MPI_INT,0,0,MPI_COMM_WORLD,&status);
localArr= (int *)calloc(n,sizeof(int));
MPI_Recv(localArr,n,MPI_INT,0,0,MPI_COMM_WORLD,&status);
printArray(localArr,n,1);
}
//printf("Done \n");
int key;
//MPI_Barrier(MPI_COMM_WORLD);
if(rank==0){
srand(time(NULL));
int r = rand()%nold;
key=a[r];
}
MPI_Bcast(&key, 1, MPI_INT, 0, MPI_COMM_WORLD);
//} else {
// printf("rank is %d start recive key",rank);
//MPI_Recv(&key,1,MPI_INT,0,1,MPI_COMM_WORLD,&status);
//printf("rank is %d key is %d ",rank,key);
//}
//printf("Done2 \n");
int step=size/2;
//for(step>0;step=step>>1){
int e=0;
//printf("local %d\n",rank );
for(int i=0;i<n;i++){
//printf("local %d\n",rank);
if(localArr[i]<key){
swap(&localArr[e],&localArr[i]);
e++;
}
}
//printArray(localArr,e,"partion");
MPI_Request req;
if( (rank / step) % 2 == 0){
int nSend=n-e;
MPI_Send(&nSend,1,MPI_INT,rank+step,step,MPI_COMM_WORLD);
int nRe;
MPI_Recv(&nRe,1,MPI_INT,rank+step,step,MPI_COMM_WORLD,&status);
printf(" resive %d from %d \n",nRe,rank+step);
if(nSend>0){
//printArray(localArr,n,"send to rank+step");
int *subArr= (int *)calloc(nSend,sizeof(int));
for(int i=0;i<nSend;i++) localArr[i]=subArr[i];
MPI_Isend(subArr,nSend,MPI_INT,rank+step,step,MPI_COMM_WORLD,&req);
}
//printf("Rank %d send done\n",rank);
reArr= (int *)calloc(100,sizeof(int));
//printf("malloc %d rank %d\n",nRe+e,rank);
int x=nRe;
if(nRe>0){
printf("Resive %d in rank %d \n",nRe,rank);
MPI_Irecv(&reArr,x,MPI_INT,rank+step,step,MPI_COMM_WORLD,&req);
MPI_Wait(&req, &status);
int number_amount;
MPI_Get_count(&status, MPI_INT, &number_amount);
// Print off the amount of numbers, and also print additional
// information in the status object
printf("1 received %d numbers from 0. Message source = %d, "
"tag = %d\n",
number_amount, status.MPI_SOURCE, status.MPI_TAG);
printf(" resive2 %d in rank %d \n",nRe,rank);
printArray(reArr,x,2);
}
//printf("Rank %d resive done in parter %d \n",rank,step);
for(int i=0;i<e;i++){
//printf("reArr %d ",reArr[nRe-1]);
//printf("local[%d]= %d in rank %d\n",i,localArr[i],rank);
reArr[nRe+i]=localArr[i];
}
printf("Rank %d make new done in partner %d\n ",rank,step);
free((int *) localArr);
localArr=reArr;
n=nRe+e;
printArray(localArr,n,3);
} else {
int nSend=e;
MPI_Send(&nSend,1,MPI_INT,rank-step,step,MPI_COMM_WORLD);
int nRe;
MPI_Recv(&nRe,1,MPI_INT,rank-step,step,MPI_COMM_WORLD,&status);
printf("Resive %d from %d \n",nRe,rank-step);
if(nSend>0){
//printArray(localArr,n,"send to rank-step");
int *subArr= (int *)calloc(nSend,sizeof(int));
for(int i=0;i<nSend;i++) localArr[i]=subArr[i];
MPI_Isend(&localArr,nSend,MPI_INT,rank-step,step,MPI_COMM_WORLD,&req);
//MPI_Wait(&req);
}
printf("Rank %d send done\n",rank);
reArr= (int *)calloc(100,sizeof(int));
int reArr[10000];
//printf("malloc %d rank%d\n",nRe+n-e,rank);
int x=nRe;
if(nRe>0){
printf(" resive %d in rank %d \n",nRe,rank);
MPI_Irecv(&reArr,x,MPI_INT,rank-step,step,MPI_COMM_WORLD,&req);
int number_amount;
MPI_Wait(&req, &status);
MPI_Get_count(&status, MPI_INT, &number_amount);
// Print off the amount of numbers, and also print additional
// information in the status object
printf("1 received %d numbers from 0. Message source = %d, "
"tag = %d\n",
number_amount, status.MPI_SOURCE, status.MPI_TAG);
printf(" resive2 %d in rank %d \n",nRe,rank);
printArray(reArr,x,2);
}
//printf("Rank %d resive done in parter %d \n",rank,step);
for(int i=0;i<n-e;i++){
//printf("reArr %d ",reArr[nRe-1]);
//printf("local[%d]= %d in rank %d",i,localArr[i],rank);
reArr[nRe+i]=localArr[e+i];
}
printf("Rank %d make new done in partner %d\n ",rank,step);
free((int *) localArr);
localArr=reArr;
n=nRe+n-e;
printArray(localArr,n,3);
}
//}
MPI_Finalize ();
fclose(stdin);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f ",time_spent);
}
<file_sep>/Code/Final/Tuantu/quick_sort.c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void swap(int a[],int x,int y) {
int tmp = a[x];
a[x] = a[y];
a[y] = tmp;
}
int partition(int a[],int L,int R,int indexPivot) {
int pivot = a[indexPivot];
swap(a,indexPivot,R);
int storeindex = L;
for(int i = L;i <= R - 1;i++) {
if(a[i] < pivot) {
swap(a,storeindex,i);
storeindex++;
}
}
swap(a,storeindex,R);
return storeindex;
}
void quick_sort(int a[],int L,int R) {
if(L < R) {
int index = (L + R)/2;
index = partition(a,L,R,index);
if(L < index) {
quick_sort(a,L,index - 1);
}
if(index < R) {
quick_sort(a,index + 1,R);
}
}
}
int main(int argc,char** argv) {
// int a[] = {2,5,1,6,3,8,10,11,3,4,21,14,15,16,17};
int *x = NULL;
int n_element = atoi(argv[1]);
FILE *inp = NULL;
FILE *out = NULL;
printf("\nSize is %d\n",n_element);
x = malloc(n_element*sizeof(int));
if(x == NULL) {
printf("\n\n Memory Allocation Failed! \n\n");
exit(EXIT_FAILURE);
}
inp = fopen(argv[2],"r");
if(inp == NULL) {
printf("\nMemory Allocation Failed !\n");
exit(EXIT_FAILURE);
}
printf("\nInput Data is: %s",argv[2]);
for(int i=0;i < n_element - 1;i++) {
int tmp;
fscanf(inp,"%d",&tmp);
x[i] = tmp;
}
fclose(inp);
clock_t begin = clock();
// merge_sort(x,0,n_element-1,n_element);
quick_sort(x,0,n_element - 1);
clock_t end = clock();
printf("\nTime run is: %f\n",(double)(end - begin)/CLOCKS_PER_SEC);
}
<file_sep>/Code/oddeven.cpp
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
int n;
int a[1000000],*localArr,*reciveArr;
int nold;
MPI_Status status;
int oddArr[1000000],evenArr[1000000];
void readData(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
}
void printArray(int *a,int n,char* s){
printf("*****************\n %s The array is %d number\n",s,n);
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n****************");
}
void swap(int *x,int *y){
int tmp=*x;
*x=*y;
*y=tmp;
}
void sortEven(int *a,int n){
int j=0;
while(1){
int xd=0;
int xd2=0;
for(int i=0;i<n-1;i+=2){
if(a[i]>a[i+1]){
swap(&(a[i]),&(a[i+1]));
xd=1;
}
}
for(int i=1;i<n-1;i+=2){
if(a[i]>a[i+1]){
swap(&(a[i]),&(a[i+1]));
xd2=1;
}
}
if((xd==0)&&(xd2==0)) break;
j++;
}
}
int *mergeArr(int *a,int *b,int m,int n){
int i=0;
int j=0;
int c=0;
int *res=(int *)malloc(nold*sizeof(int));;
while(1){
if(i>=m){
while(j<n) {
res[c]=b[j];
c++;
j++;
}
break;
}
if(j>=n){
while(i<m) {
res[c]=a[i];
c++;
i++;
}
break;
}
if(a[i]<b[j]) {
res[c]=a[i];
c++;
i++;
} else {
res[c]=b[j];
c++;
j++;
}
}
return res;
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(int argc, char** argv){
clock_t begin = clock();
freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
double passingTime=0;
double calTime=0;
double allTime=0;
MPI_Init(&argc,&argv);
int numpro,rank;
localArr= (int *)malloc(1000000*sizeof(int));
reciveArr= (int *)malloc(1000000*sizeof(int));
MPI_Comm_rank ( MPI_COMM_WORLD , & rank );
if ( rank == 0 ){
readData();
for(int i=0;i<n-1;i+=2){
oddArr[i/2]=a[i];
evenArr[i/2]=a[i+1];
}
nold=n;
n=n/2;
MPI_Send(&n,1,MPI_INT,1,0,MPI_COMM_WORLD);
MPI_Send(evenArr,n,MPI_INT,1,0,MPI_COMM_WORLD);
localArr=oddArr;
if(nold %2==1){
n=n+1;
localArr[n-1]=a[nold-1];
}
} else {
MPI_Recv(&n,1,MPI_INT,0,0,MPI_COMM_WORLD,&status);
//printf("%d ",n);
MPI_Recv(localArr,n,MPI_INT,0,0,MPI_COMM_WORLD,&status);
//char mess[20];
//sprintf ( mess , " %d " , rank );
}
//printArray(localArr,n,"input is: \n");
sortEven(localArr,n);
//printArray(localArr,n,"sorted done \n");
if(rank==1) {
MPI_Send(localArr,n,MPI_INT,0,0,MPI_COMM_WORLD);
} else {
MPI_Recv(reciveArr,n,MPI_INT,1,0,MPI_COMM_WORLD,&status);
int *b=mergeArr(localArr,reciveArr,(nold%2==0)?nold/2:nold/2+1,n);
/*printArray(b,nold,"done");
qsort (a, nold, sizeof(int), compare);
int u=0;
for (int i=0; i<nold; i++)
if(a[i]!=b[i]) u++;
printArray(a,nold,"qsort");
printf("%d ",u);*/
}
MPI_Finalize ();
//free(localArr);
//free(reciveArr);
fclose(stdin);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f ",time_spent);
}
<file_sep>/Code/Final/Songsong/meger_sort_parallel_2.c
#include <stdio.h>
#include <mpi.h>
#include <stdlib.h>
#define RANK_MASTER 0
FILE *inp;
FILE *out;
void merge(int a[],int L,int M,int R,int size);
void merge_sort(int a[],int L,int R,int size);
void sortCheckers(int size,int a[]);
void mergeParallel(int localeData[],int localeSize,int comm_size,int rank);
int * merge_two(int *v1, int n1, int *v2, int n2)
{
int i,j,k;
int * result;
// printf("n1 is: %d and n2 is: %d",n1,n2);
// printf("\nv1 is: ");
// for(int x = 0;x<n1;x++){
// printf("%d ",v1[x]);
//}
//printf("\nv2 is: ");
//for(int x = 0;x < n2;x++) {
// printf("%d ",v2[x]);
//}
result = (int *)malloc((n1+n2)*sizeof(int));
i=0; j=0; k=0;
while(i<n1 && j<n2)
if(v1[i]<v2[j])
{
result[k] = v1[i];
i++; k++;
}
else
{
result[k] = v2[j];
j++; k++;
}
if(i==n1)
while(j<n2)
{
result[k] = v2[j];
j++; k++;
}
else
while(i<n1)
{
result[k] = v1[i];
i++; k++;
}
return result;
}
int main(int argc,char **argv) {
int rank;
int comm_size;
int *localeData = NULL;
int *x = NULL;
int n_elements = atoi(argv[1]);
MPI_Status status;
// Khoi tao moi truong MPI commutication
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&comm_size);
if(rank == RANK_MASTER) {
printf("Start Agorithm Merge Sort Parallel");
//printf("\nSize is %d\n",n_elements);
x = malloc(n_elements*sizeof(int));
if(x == NULL) {
printf("\nMemory Allocation Failed! \n");
exit(EXIT_FAILURE);
}
inp = fopen(argv[2],"r");
if(inp == NULL) {
printf("\n inp Memory Allocation Failed! \n");
exit(EXIT_FAILURE);
}
printf("\nInput Data is: %s",argv[2]);
for(int i = 0;i < n_elements;i++) {
int tmp;
fscanf(inp,"%d",&tmp);
x[i] = tmp;
}
printf("\nEnd Input !!!");
fclose(inp);
}
double startTimer;
double stopTimer;
if(rank == RANK_MASTER) {
startTimer = MPI_Wtime();
}
if(n_elements < comm_size) {
printf("\n\n SIZE is less than the number of process! \n\n");
exit(EXIT_FAILURE);
}
// Chia array thanh subarray
int localeSize = n_elements/comm_size;
if(rank == comm_size - 1) {
localeSize = n_elements - (comm_size-1)*localeSize;
}
// printf("\n\n n_elements is: %d",n_elements);
//printf("\n\n comm_size is: %d",comm_size);
//printf("\n\n localeSize is: %d",localeSize);
// khoi tao cac subarray cho moi bo su li
localeData = (int*)malloc(localeSize*sizeof(int));
if(localeData == NULL) {
printf("\n localeData Memory Allocation Failed!");
exit(EXIT_FAILURE);
}
// SGui moi subarray cho moi bo xu li
// MPI_Scatter(x,localeSize,MPI_INT,localeData,localeSize,MPI_INT,RANK_MASTER,MPI_COMM_WORLD);
// Thuc hien merger_sort tren moi bo xu li
// printf("aaaa");
if(rank == RANK_MASTER) {
// printf("aa");
for(int i = 0;i < localeSize;i++) {
localeData[i] = x[i];
}
for(int i = 1;i < comm_size;i++) {
// printf("bb");
int index = i*localeSize;
int *loc = NULL;
if(i != comm_size - 1) {
loc = (int*)malloc(localeSize*sizeof(int));
for(int j =0;j < localeSize;j++) {
loc[j] = x[index + j];
}
MPI_Send(loc,localeSize,MPI_INT,i,0,MPI_COMM_WORLD);
}else {
int size = n_elements - (comm_size - 1)*localeSize;
loc = (int*)malloc(size*sizeof(int));
for(int j =0;j < size;j++) {
loc[j] = x[index + j];
}
MPI_Send(loc,size,MPI_INT,i,0,MPI_COMM_WORLD);
}
}
}else {
MPI_Recv(localeData,localeSize,MPI_INT,0,0,MPI_COMM_WORLD,&status);
// printf("\nrank %d is: ",rank);
}
//printf("rank %d localesize : %d\n",rank,localeSize);
//for(int i = 0;i < localeSize-1;i++) {
//printf("%d-> ",localeData[i]);
//}
//printf("%d end\n",localeData[localeSize-1]);
merge_sort(localeData,0,localeSize - 1,localeSize);
// tron subarray da sap xep vao process master
// MPI_Gather(localeData,localeSize,MPI_INT,x,localeSize,MPI_INT, RANK_MASTER, MPI_COMM_WORLD);
//free(localeData);
/*
* meger parallel
*
*/
int step = 1,m;
int* other;
while(step < comm_size) {
if(rank%(2*step) == 0) {
if(rank + step < comm_size) {
MPI_Recv(&m,1,MPI_INT,rank + step,0,MPI_COMM_WORLD,&status);
// printf("m is: %d",m);
other = (int*)malloc(m*sizeof(int));
MPI_Recv(other,m,MPI_INT,rank + step,0,MPI_COMM_WORLD,&status);
localeData = merge_two(localeData,localeSize,other,m);
localeSize = localeSize + m;
}
}else {
int near = rank - step;
MPI_Send(&localeSize,1,MPI_INT,near,0,MPI_COMM_WORLD);
MPI_Send(localeData,localeSize,MPI_INT,near,0,MPI_COMM_WORLD);
break;
}
step = step*2;
}
if(rank == RANK_MASTER) {
// Final sorting
/* printf("\nArray is: ");
for(int i =0 ;i < n_elements;i++) {
printf("%d ",localeData[i]);
}*/
printf("\n");
// merge_sort(x,0,n_elements - 1,n_elements);
stopTimer = MPI_Wtime();
out = fopen(argv[3],"w");
if(out == NULL) {
printf("\n Out Memory Allocation Failed!");
exit(EXIT_FAILURE);
}
// viet thong tin ra file
fprintf(out, "Sorted Data: ");
fprintf(out, "\n\nInput size is: %d",n_elements);
fprintf(out, "\n\nNumber Processes is: %d",comm_size);
fprintf(out, "\n\nWall time is: %.4f",stopTimer - startTimer);
printf("\nWall time is: %.4f",stopTimer - startTimer);
fprintf(out,"\n\n");
for(int i = 0;i < n_elements;i++) {
fprintf(out,"%d ",localeData[i]);
}
// dong file out
fclose(out);
printf("\n\nCheck Sorted");
sortCheckers(n_elements,localeData);
printf("\n\n");
}
if(rank == RANK_MASTER) {
free(x);
}
free(localeData);
MPI_Finalize();
return EXIT_SUCCESS;
}
void sortCheckers(int size, int a[]) {
for(int i = 1;i < size;i++) {
if(a[i-1] > a[i]) {
printf("\n\n Check failed. array not sorted");
break;
}
}
printf("\n\nCheck successfully completed. Array Sorted");
}
/*
void mergeParallel(int localeData,int localeSize,int comm_size,int rank){
if(rank % 2 == 0) {
if(comm_size % 2 == 0) {
MPI_Send(&localeSize,1,MPI_INT,rank + 1,0,MPI_COMM_WORLD);
MPI_Send(localeData,localeSize,MPI_INT,rank + 1,0,MPI_COMM_WORLD);
}else {
if(rank != comm_size - 1) {
MPI_Send(&localeSize,1,MPI_INT,rank + 1,MPI_COMM_WORLD);
MPI_Send(localeData,localeSize,MPI_INT,rank + 1,0,MPI_COMM_WORLD);
}
}
}else {
}
}
*/
void merge(int a[],int L,int M,int R,int size) {
int i = L; // first position of the first list
int j = M + 1; // first position of the second list a[M + 1, ... R]
int TA[size];
for(int k = L; k <= R;k++) {
if(i > M) { // the first list
TA[k] = a[j];
j++;
}else if(j > R) {
TA[k] = a[i];
i++;
}else {
if(a[i] < a[j]) {
TA[k] = a[i];
i++;
}else {
TA[k] = a[j];
j++;
}
}
}
for(int k = L;k <= R;k++) {
a[k] = TA[k];
}
}
void merge_sort(int a[],int L,int R,int size) {
if(L < R) {
int M = (L + R)/2;
merge_sort(a,L,M,size);
merge_sort(a,M + 1,R,size);
merge(a,L,M,R,size);
}
}
<file_sep>/Code/Final/Tuantu/Odd_Event_sort_2.c
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RANK_MASTER 0
FILE* inp;
FILE* out;
void swap(int a[],int x,int y) {
int tmp = a[x];
a[x] = a[y];
a[y] = tmp;
}
int partition(int a[],int L,int R,int indexPivot) {
int pivot = a[indexPivot];
swap(a,indexPivot,R);
int storeindex = L;
for(int i = L;i <= R - 1;i++) {
if(a[i] < pivot) {
swap(a,storeindex,i);
storeindex++;
}
}
swap(a,storeindex,R);
return storeindex;
}
void quick_sort(int a[],int L,int R) {
if(L < R) {
int index = (L + R)/2;
index = partition(a,L,R,index);
if(L < index) {
quick_sort(a,L,index - 1);
}
if(index < R) {
quick_sort(a,index + 1,R);
}
}
}
void MergeSplitLow(int local_A[], int temp_B[], int temp_C[],
int local_n) {
int ai, bi, ci;
ai = 0;
bi = 0;
ci = 0;
while (ci < local_n) {
if (local_A[ai] <= temp_B[bi]) {
temp_C[ci] = local_A[ai];
ci++; ai++;
} else {
temp_C[ci] = temp_B[bi];
ci++; bi++;
}
}
memcpy(local_A, temp_C, local_n*sizeof(int));
}
void MergeSplitHigh(int local_A[], int temp_B[], int temp_C[],
int local_n) {
int ai, bi, ci;
ai = local_n-1;
bi = local_n-1;
ci = local_n-1;
while (ci >= 0) {
if (local_A[ai] >= temp_B[bi]) {
temp_C[ci] = local_A[ai];
ci--; ai--;
} else {
temp_C[ci] = temp_B[bi];
ci--; bi--;
}
}
memcpy(local_A, temp_C, local_n*sizeof(int));
}
void OddEvenIter(int locale_A[],int temp_B[],int temp_C[], int locale_n,int phase,
int even_partner, int odd_partner, int rank,int p,double &timeS,double &timeR) {
MPI_Status status;
if(phase % 2 == 0) { // phase even, odd process -- rank - 1
if(even_partner >= 0) {
double time1 = MPI_Wtime();
MPI_Sendrecv(locale_A,locale_n,MPI_INT,even_partner, 0 , temp_B,
locale_n,MPI_INT,even_partner, 0,MPI_COMM_WORLD,&status);
double time2 = MPI_Wtime();
timeS += time2 - time1;
if(rank % 2 !=0) {
MergeSplitHigh(locale_A,temp_B,temp_C,locale_n);
}else {
MergeSplitLow(locale_A,temp_B,temp_C,locale_n);
}
}
}else {
if(odd_partner >= 0) {
double time1 = MPI_Wtime();
MPI_Sendrecv(locale_A,locale_n,MPI_INT,odd_partner, 0 , temp_B,
locale_n,MPI_INT,odd_partner, 0,MPI_COMM_WORLD,&status);
double time2 = MPI_Wtime();
timeS += time2 - time1;
if(rank % 2 !=0) {
MergeSplitLow(locale_A,temp_B,temp_C,locale_n);
}else {
MergeSplitHigh(locale_A,temp_B,temp_C,locale_n);
}
}
}
}
void Sort(int local_A[],int locale_n,int rank,int p,double &timeS,double &timeR) {
int phase;
int *temp_B, *temp_C;
int even_partner; // phase chan
int odd_partner; // phase le
// bo nho tam dung de luu tru khi merge-split
temp_B = (int*) malloc(locale_n*sizeof(int));
temp_C = (int*) malloc(locale_n*sizeof(int));
if(rank % 2 !=0) {
even_partner = rank - 1;
odd_partner = rank + 1;
if(odd_partner == p) odd_partner = -1;
}else {
even_partner = rank + 1;
if(even_partner == p) even_partner = -1;
odd_partner = rank - 1;
}
quick_sort(local_A,0,locale_n - 1);
for(phase = 0;phase < p;phase++) {
OddEvenIter(local_A,temp_B,temp_C,locale_n,phase,
even_partner,odd_partner,rank,p,timeS,timeR);
}
free(temp_B);
free(temp_C);
}
int main(int argc, char** argv) {
int n_elements;
int rank;
int comm_size;
int *x = NULL;
int *localeData = NULL;
double startTimer,endTimer;
double timeSend = 0,timeRecive = 0;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&comm_size);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
n_elements = atoi(argv[1]);
if(rank == RANK_MASTER) {
printf("\nSize is %d\n",n_elements);
x = (int*)malloc(n_elements*sizeof(int));
if(x == NULL) {
printf("\n\n Memory Allocation Failed ! \n\n");
exit(EXIT_FAILURE);
}
inp = fopen(argv[2],"r");
if(inp == NULL) {
printf("\n\n inp Memory Allocation Failed ! \n\n");
exit(EXIT_FAILURE);
}
printf("\n\nInput Data is: %s \n\n",argv[2]);
for(int i = 0;i < n_elements;i++) {
int tmp;
fscanf(inp,"%d",&tmp);
x[i] = tmp;
}
printf("\n\n End Input!");
fclose(inp);
}
if(rank == RANK_MASTER) {
startTimer = MPI_Wtime();
}
if(n_elements < comm_size) {
printf("\n Size is less than the number of process!\n");
exit(EXIT_FAILURE);
}
// chia thanh cac sub array
int localeSize = n_elements/comm_size;
if(rank == comm_size - 1) {
localeSize = n_elements - (comm_size-1)*localeSize;
}
localeData = (int*)malloc(localeSize*sizeof(int));
if(localeData == NULL) {
printf("\n localeData Memory Allocation Failed!");
exit(EXIT_FAILURE);
}
//MPI_Scatter(x,localeSize,MPI_INT,localeData,localeSize,MPI_INT,RANK_MASTER,MPI_COMM_WORLD);
if(rank == RANK_MASTER) {
// printf("aa");
for(int i = 0;i < localeSize;i++) {
localeData[i] = x[i];
}
double time1 = MPI_Wtime();
for(int i = 1;i < comm_size;i++) {
// printf("bb");
int index = i*localeSize;
int *loc = NULL;
if(i != comm_size - 1) {
loc = (int*)malloc(localeSize*sizeof(int));
for(int j =0;j < localeSize;j++) {
loc[j] = x[index + j];
}
MPI_Send(loc,localeSize,MPI_INT,i,0,MPI_COMM_WORLD);
}else {
int size = n_elements - (comm_size - 1)*localeSize;
loc = (int*)malloc(size*sizeof(int));
for(int j =0;j < size;j++) {
loc[j] = x[index + j];
}
MPI_Send(loc,size,MPI_INT,i,0,MPI_COMM_WORLD);
}
}
double time2 = MPI_Wtime();
timeSend += time2 - time1;
}else {
double time1 = MPI_Wtime();
MPI_Recv(localeData,localeSize,MPI_INT,0,0,MPI_COMM_WORLD,&status);
double time2 = MPI_Wtime();
timeRecive += time2 - time1;
// printf("\nrank %d is: ",rank);
}
Sort(localeData,localeSize,rank,comm_size,timeSend,timeRecive);
double time1 = MPI_Wtime();
MPI_Gather(localeData,localeSize,MPI_INT,x,localeSize,MPI_INT,RANK_MASTER,MPI_COMM_WORLD);
double time2 = MPI_Wtime();
timeRecive += time2 - time1;
if(rank == RANK_MASTER) {
endTimer = MPI_Wtime();
}
// Time Passing
if(rank != RANK_MASTER) {
MPI_Send(&timeSend,1,MPI_DOUBLE,RANK_MASTER,0,MPI_COMM_WORLD);
MPI_Send(&timeRecive,1,MPI_DOUBLE,RANK_MASTER,0,MPI_COMM_WORLD);
}else {
double timePass[comm_size];
for(int i = 0;i < comm_size;i++) {
if(i == 0) {
timePass[i] = timeSend + timeRecive;
}else {
timePass[i] = 0;
}
}
for(int i = 1;i < comm_size;i++) {
double timeS,timeR;
MPI_Recv(&timeS,1,MPI_DOUBLE,i,0,MPI_COMM_WORLD,&status);
MPI_Recv(&timeR,1,MPI_DOUBLE,i,0,MPI_COMM_WORLD,&status);
timePass[i] = timeS + timeR;
}
double timeT = 0;
for(int i = 0;i < comm_size;i++) {
timeT += timePass[i];
}
printf("\n\nTime Passing is: %f\n\n",timeT);
}
free(localeData);
if(rank == RANK_MASTER) {
// endTimer = MPI_Wtime();
out = fopen(argv[3],"w");
if(out == NULL) {
printf("\n Out Memory Allocation Failed!");
exit(EXIT_FAILURE);
}
// viet thong tin ra file
fprintf(out, "Sorted Data: ");
fprintf(out, "\n\nInput size is: %d",n_elements);
fprintf(out, "\n\nNumber Processes is: %d",comm_size);
fprintf(out, "\n\nWall time is: %.4f",endTimer - startTimer);
printf("\nWall time is: %.4f",endTimer - startTimer);
fprintf(out,"\n\n");
for(int i = 0;i < n_elements;i++) {
fprintf(out,"%d ",x[i]);
}
// dong file out
fclose(out);
}
MPI_Finalize();
return EXIT_SUCCESS;
}
<file_sep>/Code/sampleSort.cpp
#include <stdio.h>
#include <mpi.h>
#include <stdlib.h>
#include <time.h>
int rank;
int size;
int n;
int *a;
int nold;
int *localArr;
MPI_Request request;
MPI_Status status;
void readData(){
scanf("%d",&n);
a=(int*) malloc(n*sizeof(int));
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
void printArray(int *a,int n,int z){
printf("*****************\n Rank is %d %d The array is %d number\n",rank,z,n);
for(int i=0;i<n-1;i++){
printf("(%d)->",a[i]);
}
printf("%d end",a[n-1]);
printf("\n****************\n");
}
int main ( int argc , char * argv [] )
{
freopen(argv[1],"r",stdin);
char cRank[10];
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
sprintf (cRank, "%d_stdout.txt", rank);
//freopen(cRank,"w",stdout);
if(rank ==0){
readData();
nold=n;
n=n/size;
}
double timestart=MPI_Wtime();
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
localArr=(int *) malloc(n*sizeof(int));
MPI_Scatter(a,n,MPI_INT,localArr,n,MPI_INT,0,MPI_COMM_WORLD);
qsort (localArr, n, sizeof(int), compare);
int sampl[size-1];
int it=n/(size-1)-1;
for(int i=0;i<size-1;i++){
sampl[i]=localArr[it];
it+=(n/(size-1));
//printf("%d \n",it);
}
int *sampleFull;
if(rank==0) sampleFull=(int *) malloc(size*(size-1)*sizeof(int));
fclose(stdin);
MPI_Gather(sampl,size-1,MPI_INT,sampleFull,size-1,MPI_INT,0,MPI_COMM_WORLD);
if(rank==0)qsort (sampleFull, size*(size-1), sizeof(int), compare);
int bucket[size];
if(rank==0){
it=size-1;
for(int i=0;i<size-1;i++){
bucket[i]=sampleFull[it];
it+=size;
//printf("%d \n",it);
}
}
//free(sampl);
//if(rank==0)
//free(sampleFull);
MPI_Bcast(&bucket,size-1,MPI_INT,0,MPI_COMM_WORLD);
//if(rank==0) printArray(sampleFull,size*(size-1),2);
bucket[size-1]=100000000;
//fclose(stdout);
it=0;
int o=0;
int *seft;
int nSeft=0;
for(int i=0;i<size;i++){
while ((localArr[it]<bucket[i])&&(it<n)) it++;
if(rank==i){
nSeft=it-o;
seft=(int *) malloc((it-o)*sizeof(int));
for(int j=o;j<it;j++)
seft[j-o]=localArr[j];
} else{
int nSend=it-o;
MPI_Isend(&nSend,1,MPI_INT,i,0,MPI_COMM_WORLD,&request);
if(nSend!=0)
MPI_Issend(localArr+o,nSend,MPI_INT,i,2,MPI_COMM_WORLD,&request);
//printArray(localArr+o,nSend,5);
}
o=it;
}
int *res=(int *) malloc((10000000)*sizeof(int));
int nRev=nSeft;
for(int i=0;i<nSeft;i++){
res[i]=seft[i];
}
for(int i=0;i<size;i++)
if(rank!=i){
int nV;
MPI_Recv(&nV,1,MPI_INT,i,0,MPI_COMM_WORLD,&status);
//printf("rank %d rev %d",rank,nV);
int *reArr=(int *) malloc(nV*sizeof(int));
if(nV!=0)
MPI_Recv(reArr,nV,MPI_INT,i,2,MPI_COMM_WORLD,&status);
for(int j=0;j<nV;j++){
res[nRev+j]=reArr[j];
}
nRev+=nV;
free(reArr);
}
/*if(rank==0)
MPI_Issend(&localArr,1,MPI_INT,1,2,MPI_COMM_WORLD,&request);
int *reArr=(int *) malloc(2*sizeof(int));
if(rank==1)
MPI_Recv(reArr,2,MPI_INT,0,2,MPI_COMM_WORLD,&status);
printArray(reArr,2,6);*/
qsort (res, nRev, sizeof(int), compare);
if(rank!=0){
MPI_Isend(&nRev,1,MPI_INT,0,4,MPI_COMM_WORLD,&request);
MPI_Isend(res,nRev,MPI_INT,0,3,MPI_COMM_WORLD,&request);
} else {
int *Arr=(int *) malloc((nold)*sizeof(int));
for(int i=0;i<nRev;i++){
Arr[i]=res[i];
}
int t=nRev;
for(int i=1;i<size;i++){
int rev;
MPI_Recv(&rev,1,MPI_INT,i,4,MPI_COMM_WORLD,&status);
int *revA=(int *) malloc((rev)*sizeof(int));
MPI_Status status2;
MPI_Recv(revA,rev,MPI_INT,i,3,MPI_COMM_WORLD,&status2);
//printArray(revA,rev,5);
for(int i=0;i<rev;i++){
Arr[t+i]=revA[i];
}
t=t+rev;
free(revA);
}
//printArray(Arr,nold,5);
}
double timeend =MPI_Wtime();
if(rank==0){
printf("Time %f",timeend-timestart);
}
MPI_Finalize();
//fclose(stdout);
}
<file_sep>/README.md
# LTSS
Lập trình song song
<file_sep>/Code/hello.cpp
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <mpi.h>
int generateArr(){
freopen("input.txt","w",stdout);
int n=100000;
srand(time(NULL));
int r = rand()%10000;
printf("%d\n",n);
for(int i=0;i<n;i++){
printf("%d ",rand()%10000-rand()%10000);
}
fclose(stdout);
}
int main ( int argc , char * argv [] )
{
generateArr();
return 0;
}
<file_sep>/Code/quicksort4.cpp
#include <stdio.h>
#include <mpi.h>
#include <stdlib.h>
#include <time.h>
int rank;
int size;
int n;
int *a;
int nold;
int *localArr;
void readData(){
scanf("%d",&n);
a=(int*) malloc(n*sizeof(int));
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
}
void printArray(int *a,int n,int z){
printf("*****************\n Rank is %d %d The array is %d number\n",rank,z,n);
for(int i=0;i<n-1;i++){
printf("(%d)->",a[i]);
}
printf("%d end",a[n-1]);
printf("\n****************\n");
}
void swap(int *x,int *y){
int tmp=*x;
*x=*y;
*y=tmp;
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(int argc, char** argv){
clock_t begin = clock();
freopen(argv[1],"r",stdin);
char cRank[10];
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
//sprintf (cRank, "%d_stdout.txt", rank);
//freopen(cRank,"w",stdout);
if(rank ==0){
readData();
nold=n;
n=n/size;
}
double pstime=0;
double timestart=MPI_Wtime();
double timeend =MPI_Wtime();
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
localArr=(int *) malloc(n*sizeof(int));
MPI_Scatter(a,n,MPI_INT,localArr,n,MPI_INT,0,MPI_COMM_WORLD);
int key;
//MPI_Bcast(&key, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Request request;
MPI_Status status;
for(int step=size/2;step>0;step=step>>1){
if(rank%(step*2)==0 ){
srand(time(NULL));
int r = rand()%n;
key=localArr[r];
timeend =MPI_Wtime();
for(int i=1;i<2*step;i++)
MPI_Isend(&key,1,MPI_INT,rank+i,2,MPI_COMM_WORLD,&request);
timeend =MPI_Wtime();
} else {
MPI_Recv(&key,1,MPI_INT,(rank/(step*2))*(2*step),2,MPI_COMM_WORLD,&status);
}
//printf("key is %d\n",key);
int e=0;
for(int i=0;i<n;i++){
if(localArr[i]<key){
swap(&localArr[e],&localArr[i]);
e++;
}
}
int nSend;
int nRev;
if((rank/step)%2==0 ){
nSend=n-e;
MPI_Isend(&nSend,1,MPI_INT,rank+step,0,MPI_COMM_WORLD,&request);
MPI_Recv(&nRev,1,MPI_INT,rank+step,0,MPI_COMM_WORLD,&status);
}else{
nSend=e;
MPI_Isend(&nSend,1,MPI_INT,rank-step,0,MPI_COMM_WORLD,&request);
MPI_Recv(&nRev,1,MPI_INT,rank-step,0,MPI_COMM_WORLD,&status);
}
//printf("rank %d send %d rev %d\n",rank,nSend,nRev);
//printArray(localArr,n,0);
int *revArr= (int *) malloc((n-nSend+nRev)*sizeof(int));
if((rank/step)%2==0 ){
MPI_Isend(localArr+e,nSend,MPI_INT,rank+step,1,MPI_COMM_WORLD,&request);
MPI_Recv(revArr,nRev,MPI_INT,rank+step,1,MPI_COMM_WORLD,&status);
//MPI_Wait(&request, &status);
for(int i=0;i<n-nSend;i++){
revArr[nRev+i]=localArr[i];
}
//printArray(revArr,nRev,3);
} else {
MPI_Isend(localArr,e,MPI_INT,rank-step,1,MPI_COMM_WORLD,&request);
MPI_Recv(revArr,nRev,MPI_INT,rank-step,1,MPI_COMM_WORLD,&status);
//MPI_Wait(&request, &status);
for(int i=0;i<n-nSend;i++){
revArr[nRev+i]=localArr[e+i];
}
//printArray(revArr,nRev,3);
}
//free(localArr);
localArr=revArr;
n=(n-nSend)+nRev;
//printf("N is %d\n",n);
//printArray(localArr,n,3);
}
qsort (localArr, n, sizeof(int), compare);
if(rank!=0){
MPI_Isend(&n,1,MPI_INT,0,4,MPI_COMM_WORLD,&request);
MPI_Isend(localArr,n,MPI_INT,0,3,MPI_COMM_WORLD,&request);
} else {
printf("completed %d 1\n",nold);
int *Arr=(int *) malloc((nold)*sizeof(int));
for(int i=0;i<n;i++){
Arr[i]=localArr[i];
}
int t=n;
for(int i=1;i<size;i++){
int rev;
MPI_Recv(&rev,1,MPI_INT,i,4,MPI_COMM_WORLD,&status);
int *revA=(int *) malloc((rev)*sizeof(int));
MPI_Status status2;
MPI_Recv(revA,rev,MPI_INT,i,3,MPI_COMM_WORLD,&status2);
//printArray(revA,rev,5);
for(int i=0;i<rev;i++){
Arr[t+i]=revA[i];
}
t=t+rev;
printf("completed2\n");
free(revA);
}
//printArray(Arr,nold,5);
}
timeend =MPI_Wtime();
if(rank==0){
printf("Time %f",timeend-timestart);
}
MPI_Finalize();
fclose(stdin);
//clock_t end = clock();
//double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
//printf("%f ",time_spent);
//printf("read Done");
//fclose(stdout);
}
<file_sep>/Code/test.cpp
# include <stdio.h>
# include <mpi.h>
const int SERVER_RANK = 0;
const int MESSAGE_TAG = 0;
void do_server_work( int number_of_processes )
{
const int max_message_length = 256;
char message[ max_message_length ];
int src ;
MPI_Status status ;
for ( src = 0; src < number_of_processes ; src ++ )
{
if ( src != SERVER_RANK )
{
MPI_Recv( message , max_message_length , MPI_CHAR ,src , MESSAGE_TAG , MPI_COMM_WORLD ,&status );
printf ( " Received : %s \n " , message );
}
}
}
void do_client_work( int rank )
{
const int max_message_length = 256;
char message [ max_message_length ];
int message_length ;
message_length =
sprintf ( message , " Greetings from process %d " , rank );
message_length ++;
/* add one for null char */
MPI_Send ( message , message_length , MPI_CHAR ,
SERVER_RANK , MESSAGE_TAG , MPI_COMM_WORLD );
}
int main ( int argc , char * argv[] )
{
int rank , number_of_processes ;
MPI_Init( &argc , &argv );
MPI_Comm_size( MPI_COMM_WORLD , &number_of_processes );
MPI_Comm_rank( MPI_COMM_WORLD , &rank );
if ( rank == SERVER_RANK )
do_server_work( number_of_processes );
else
do_client_work( rank );
MPI_Finalize();
return 0;
}
<file_sep>/Code/sameple.cpp
#include <stdio.h>
#include <mpi.h>
#include <stdlib.h>
#include <time.h>
void readData(){
scanf("%d",&n);
a=(int*) malloc(n*sizeof(int));
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
void printArray(int *a,int n,int z){
printf("*****************\n Rank is %d %d The array is %d number\n",rank,z,n);
for(int i=0;i<n-1;i++){
printf("(%d)->",a[i]);
}
printf("%d end",a[n-1]);
printf("\n****************\n");
}
int maim(int argc,char ** argv){
clock_t begin = clock();
freopen(argv[1],"r",stdin);
char cRank[10];
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
sprintf (cRank, "%d_stdout.txt", rank);
freopen(cRank,"w",stdout);
if(rank ==0){
readData();
nold=n;
n=n/size;
}
double timestart=MPI_Wtime();
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
localArr=(int *) malloc(n*sizeof(int));
MPI_Scatter(a,n,MPI_INT,localArr,n,MPI_INT,0,MPI_COMM_WORLD);
qsort (localArr, n, sizeof(int), compare);
int sampl[size-1];
int it=0;
for(int i=0;i<size-1;i++){
sampl[i]=localArr[it+=(n/size)];
}
printArray(sampl,size-1,1);
}
<file_sep>/Code/Final/Tuantu/oddeven_single.cpp
#include<stdio.h>
#include <time.h>
#include <stdlib.h>
int n;
int *a;
void readData(){
scanf("%d",&n);
a=(int *) malloc(n*sizeof(int));
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
}
void swap(int *x,int *y){
int tmp=*x;
*x=*y;
*y=tmp;
}
void printArray(int *a,int n,int rank){
printf("*****************\n From %d The array is %d number\n",rank,n);
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n****************");
}
void sortEven(int *a,int n){
int j=0;
while(1){
int xd=0;
int xd2=0;
for(int i=0;i<n-1;i+=2){
if(a[i]>a[i+1]){
swap(&(a[i]),&(a[i+1]));
xd=1;
}
}
for(int i=1;i<n-1;i+=2){
if(a[i]>a[i+1]){
swap(&(a[i]),&(a[i+1]));
xd2=1;
}
}
if((xd==0)&&(xd2==0)) break;
j++;
}
}
int main(int argc, char** argv){
printf("Done");
clock_t begin = clock();
freopen(argv[1],"r",stdin);
readData();
sortEven(a,n);
fclose(stdin);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f ",time_spent);
}
<file_sep>/Code/Final/Tuantu/megersort.c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main(int argc,char **argv)
{
/*
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
*/
int *x = NULL;
int n_element = atoi(argv[1]);
FILE *inp = NULL;
FILE *out = NULL;
//printf("\nSize is %d\n",n_element);
x = (int*)malloc(n_element*sizeof(int));
printf("\nSize is %d\n",n_element);
if(x == NULL) {
printf("\n\n Memory Allocation Failed! \n\n");
exit(EXIT_FAILURE);
}
inp = fopen(argv[2],"r");
if(inp == NULL) {
printf("\nMemory Allocation Failed !\n");
exit(EXIT_FAILURE);
}
printf("\nInput Data is: %s",argv[2]);
for(int i=0;i < n_element;i++) {
int tmp;
fscanf(inp,"%d",&tmp);
x[i] = tmp;
}
//printf("\nSize is %d\n",n_element);
fclose(inp);
clock_t begin = clock();
mergeSort(x, 0,n_element - 1);
clock_t end = clock();
printf("\nTime run is: %f\n",(double)(end - begin)/CLOCKS_PER_SEC);
// printArray(x,n_element);
return 0;
}
|
b64c00eb6cbde754be6c83132f76d4ef160a1370
|
[
"Markdown",
"C",
"C++"
] | 13
|
C++
|
tuandat95cbn/LTSS
|
19e2a3b59a4ebdb038012ae1cb3ff973089f9907
|
b64e8d8e64c58993f2a982cb318dfcae8bbe657a
|
refs/heads/master
|
<repo_name>shangzhouye/final-project-numg<file_sep>/README.MD
# Mini Golf
*<NAME>, <NAME>, <NAME> and <NAME>*
## Demo
<p align="center">
<img width="600" height="450" src="https://github.com/shangzhouye/final-project-numg/blob/master/pictures/demo.gif?raw=true">
</p>
For a video of the robot in action, [please watch this video](https://www.youtube.com/watch?v=8vYBKLIraps).
## Overview
The goal of this project was to program a Rethink Sawyer robot to play mini-golf. Given a game space mimicking a putting green, the robot recognizes the ball and the hole, and moves itself into a striking position behind the ball. Then, it actuates its joints to perform a putting motion and hit the ball into the hole.
This repository is our final project of ME495: Embedded Systems in Robotics (ROS), Dec. 2019. The theme is recreational robotics.
## Project Overview
### Operation
Once installed, this package can be operated using two simple commands. To launch all the nodes and prepare to hit, enter in the command line:
```
roslaunch mini_golf launch.launch
```
The robot will then wait for the command to hit the ball. This command is a service that can be called by entering:
```
rosservice call /game_on
```
### Nodes
This project is designed as an interaction of five nodes:
- cv_detect_ball: computer vision; visualizes the game space and finds the ball & hole
- move_group_python_interface: trajectory planning; determines the end-effector motion necessary to a) move the putter behind the ball and b) hit the ball towards the hole
- hit_ball: actuation; plans and sends commands to the joints to move the robot per the planned trajectory
- game_planner: integrator node; brings information from the other four nodes together to achieve the task
- camera_cal2: calibrates the camera space to the physical game space
The function of these nodes will be described in detail later. However, the program generally follows the structure of the flowchart shown here:

### Physical Equipment:
* Acrylic game board (2' x 4') with holes
* Artificial turf putting surface: 8 (1' x 1') pieces
* Golf ball
* 3D printed putter
* Rethink Robotics Sawyer robot
* External USB camera
### Third Party Packages:
* Sawyer_tools
* Sawyer_gazebo
* Sawyer_moveit
* Sawyer_robot
* MoveIt
* OpenCV
### Node Descriptions:
#### Computer Vision
- Objective
- Design and program a Sawyer camera interface that accurately recognizes the game space, including the ball, hole, and the game area itself, and to package and distribute that information in a way that allows other program components to successfully interact with the game space.
- Successes
- The camera consistently and effectively identified the ball and the game space using color-based image segmentation.
- The computer vision node converts the pixel locations of the ball to geometric coordinates based off a set of physical calibration parameters.
- Failures
- We ended up using an external camera to identify the game area, as the Sawyer camera was not sufficient for our needs. Color detection was not ideal and the camera was somewhat fish-eyed, which would have negatively impacted our calculations of distance/angle to the ball and hole.
- We would have liked to perform camera calibration automatically, rather than having to physically move the ball around and calibrate our game space based on those measurements; however, automatic calibration proved inconsistent.
- Future Improvements
- Work on automatic camera calibration.
#### Mapping Frames
- Objective
- Provide setup calibration procedure for translating overhead camera picture coordinates to real world Sawyer frame coordinates.
- Provide a service to the game planner that could convert overhead camera picture coordinates to real world Sawyer frame coordinates.
- Successes
- Established a calibration system and position translation service.
- Failures
- Resolution of service was ~4cm in addition to calibration being a rather long process, taking ~15 minutes.
- Future Improvements
- Successfully implement solvePnP mapping with OpenCV and the provided checkerboard, then using homography to map between the overhead camera frame and Sawyer frame.
- Using April tags such that the overhead frame and Sawyer could locate themselves in space using the transforms provided by perceiving the April tags. This is likely the optimal approach.
#### Moving Behind Ball
- Objective
- Move the putter behind the ball to prepare for hitting. The putter should be positioned behind the ball, collinear with the ball and hole, and facing towards the hole.
- Obstacle avoidance: the putter should not collide with the table, ball, or robot.
- Successes
- Configured MoveIt to work with sawyer; forked moveit_sawyer package for the specific use of this project, and modified joint velocity limits and scaling according to our requirements.
- Completed position and angle calculation using the position of the ball and hole obtained from the CV node.
- Implemented collision avoidance by adding the table, putter, and ball to the motion planning scene. Removed the self-collision check between the putter and the gripper.
- Enhanced the capability to reliably find solutions with inverse kinematics and obstacle avoidance motion planning by requesting the numerical solution multiple times.
- Failures
- Attempted to align Joint 5 with the hitting direction by adding an extra constraint to the motion planner. It turns out that with seven constraints (including six components of the requested pose) and joint limits of the robot, a solution cannot always be found.
- Future Improvements
- The distance behind the ball can be automatically calculated according to the distance between the ball and hole.
#### Hitting Ball
- Objective
- Hit the ball towards the hole using a motion similar to an actual golf swing.
- Align the putter with the direction to the hole right before hitting the ball.
- Use MoveIt to accomplish this task.
- Successes
- Based on the ball's location, completed the putting motion to hit it to the hole successfully.
- Made the putting motion similar to a real golf swing.
- Returned to the home location after each swing to wait for the next shot.
- Failures
- Attempted to use velocity control to hit the ball. Our first attempts at velocity control resulted in pushing the ball along the line to the hole, rather than a swing that contacts the ball at a single time point.
- Did not always successfully align the putter in the same direction as the hole right before the hit, causing the ball to not move directly towards the hole.
- Future Improvements
- Velocity control can be implemented to see if it is possible to hit the ball without checking which area the ball is in.
- The putter can be aligned perfectly right before the hit.
### Role Breakdown
* Josh </br>
Mechanical - Assist in prototyping </br>
Integration - Create services to communicate between nodes and build control interface </br> </br>
* Yigitcan </br>
Operation of joints - Make the joints move according to the trajectory that is planned </br></br>
* Shangzhou </br>
Distance/angle calculation - Calculate the distance and the angles to the hole according to the location of the ball </br>
Motion planning in task space - Plan a path according to the location of the ball in the task space </br> </br>
* Riley </br>
Mechanical - Design of putter/game space; fabrication of game space </br>
Computer Vision - Identification of ball, hole, and game space
<file_sep>/nodes/hit_ball
#!/usr/bin/env python
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
from math import pi
from std_msgs.msg import String
from moveit_commander.conversions import pose_to_list
import numpy as np
import math
import numpy as np
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from mini_golf.srv import HitBall, HitBallResponse
"""
This node checks the current location of the end effector. Then it makes the sawyer robot hit the ball with a specific joint motion according to the end effector location. After the hitting motion, it returns back to sawyer's home configuration. This whole motion is then turned into a service
SERVICE:
--> hit_ball: The node creates the hit_ball service to be called in the game planner node. The service takes nothing and also returns nothing.
"""
class HitTheBall(object):
def __init__(self):
self.robot = moveit_commander.RobotCommander()
self.scene = moveit_commander.PlanningSceneInterface()
self.group_name = "right_arm"
self.move_group = moveit_commander.MoveGroupCommander(self.group_name)
### Finding the x-y coordinates for the forward motion ###
def ball_pos_to_sawyer(self,ball_pos):
ball_pose = [0.7,0.355,-0.43]
hole_pose = [0.736,0.432,-0.44]
ball_x = ball_pose[0]
ball_y = ball_pose[1]
hole_x = hole_pose[0]
hole_y = hole_pose[1]
self.wpose = self.move_group.get_current_pose().pose
ef_x = self.wpose.position.x
ef_y = self.wpose.position.y
dir_x = hole_x-ball_x
dir_y = hole_y -ball_y
hit_direction = [dir_x,dir_y]
return hit_direction
### checks the current state of the robot ###
def current_state(self):
current_state = self.robot.get_current_state()
return current_state
### returns to the home configuration ###
def return_home(self):
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]=0.0
joint_goal[1]=0.0
joint_goal[2]=0.0
joint_goal[3]=np.pi/2
joint_goal[4]=0.0
joint_goal[5]=0.0
joint_goal[6] = -np.pi/2
self.move_group.go(joint_goal, wait=True)
self.move_group.stop()
### checks the location of the end effector makes the putting motion according to that location#
def my_putter(self,req):
self.waypoints = []
self.wpose = self.move_group.get_current_pose().pose
joint_goal = self.move_group.get_current_joint_values()
## AREA 1 ##
if self.wpose.position.y > 0.3 and self.wpose.position.x<=0.7:
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0]
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5] + np.pi/2
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0]
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5] - np.pi
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
## AREA 2 ##
elif 0< self.wpose.position.y <= 0.3 and self.wpose.position.x<=0.7:
joint_goal[0]= joint_goal[0]
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3] + np.pi/12
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0]
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3] - np.pi/4
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
## AREA 2.5 ##
elif -0.3<= self.wpose.position.y <= 0 and self.wpose.position.x<=0.7:
joint_goal[0]= joint_goal[0] - np.pi/3
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0] + np.pi/2
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
## AREA 3 ##
if self.wpose.position.y < -0.3 and self.wpose.position.x<=0.7:
joint_goal[0]= joint_goal[0] -np.pi/4
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0] + np.pi/2
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
## AREA 4 ##
elif self.wpose.position.y < -0.3 and self.wpose.position.x>0.7:
joint_goal[0]= joint_goal[0] -np.pi/6
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0] + np.pi/3
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
## AREA 5##
elif -0.3<= self.wpose.position.y <= 0.3 and self.wpose.position.x>0.7:
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0] -np.pi/5
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0] + np.pi/4
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5]
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
## AREA 6##
elif self.wpose.position.y > 0.3 and self.wpose.position.x>0.7:
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]= joint_goal[0]
joint_goal[1]= joint_goal[1]
joint_goal[2]= joint_goal[2]
joint_goal[3]= joint_goal[3]
joint_goal[4]= joint_goal[4]
joint_goal[5]= joint_goal[5] - np.pi/2
joint_goal[6] = joint_goal[6]
self.move_group.go(joint_goal, wait=True)
rospy.sleep(5)
self.return_home()
return HitBallResponse()
if __name__ == '__main__':
moveit_commander.roscpp_initialize(sys.argv)
rospy.init_node('hit_ball', anonymous=True, log_level=rospy.DEBUG)
my_put = HitTheBall()
rospy.loginfo(my_put.current_state())
hit_service = rospy.Service('hit_ball', HitBall, my_put.my_putter)
rospy.spin()
<file_sep>/nodes/tiger_woods
#!/usr/bin/env python
import intera_interface
import argparse
import rospy
from mini_golf.srv import DisplayPicture, DisplayPictureResponse
"""
This node display different pictures of Tiger_woods according to the message recieved from the game planner. This action is done under the picture_display service. Pictures can be found under the pictures folder.
SERVICE:
+ picture_display: this service displays different pictures of Tiger Woods depending on the status of the robot. It takes int64 integers from the game planner and returns nothing.
"""
def display_picture(req):
if req.result == 1:
file_arg = "~/msr/fall2019/embedded/final/ws/src/mini_golf/pictures/celebration.png"
head_display = intera_interface.HeadDisplay()
picture = head_display.display_image(file_arg)#args.file, args.loop, args.rate)
return DisplayPictureResponse()
elif req.result == 0:
file_arg = "~/msr/fall2019/embedded/final/ws/src/mini_golf/pictures/hitting.png"
head_display = intera_interface.HeadDisplay()
picture = head_display.display_image(file_arg)
return DisplayPictureResponse()
elif req.result == 2:
file_arg = "~/msr/fall2019/embedded/final/ws/src/mini_golf/pictures/upset.png"
head_display = intera_interface.HeadDisplay()
picture = head_display.display_image(file_arg)
return DisplayPictureResponse()
def picture_server():
rospy.init_node("tiger_woods", anonymous=True)
service = rospy.Service('picture_display', DisplayPicture,display_picture)
rospy.spin()
if __name__ == '__main__':
picture_server()
<file_sep>/sawyer_setup.bash
export ROS_MASTER_URI=http://10.42.0.2:11311
export ROS_IP=10.42.0.1<file_sep>/nodes/game_planner
#!/usr/bin/env python
import rospy
from mini_golf.srv import CV_POIs, CV_POIsResponse, GetPhysical, GetPhysicalResponse, HitBall, HitBallResponse, InitRobot, InitRobotResponse, MoveBehindBall, MoveBehindBallResponse, DisplayPicture, DisplayPictureResponse, GameOn, GameOnResponse
from geometry_msgs.msg import Transform, Pose, Point
import numpy as np
from tf.transformations import quaternion_matrix
def se3_inv(matrix):
"""
Calculates the inverse of an se(3) transformation matrix.
"""
R = matrix[0:3,0:3] #roation matrix
p = matrix[0:3,-1] #translation vector
RT = np.transpose(R) #transpose rotation matrix
inv_p = -np.matmul(RT, p) #invert translation vector
g = np.zeros((4,4))
g[0:3,0:3] = RT
g[0:3,-1] = inv_p
g[-1,-1] = 1
return g #output transformation matrix
class GamePlanner(object):
def __init__(self):
#establish game on service for user to call
rospy.Service('/game_on', GameOn, self.game_on)
#wait for services
rospy.wait_for_service('/get_pois')
rospy.wait_for_service('/init_robot')
rospy.wait_for_service('/get_physical')
rospy.wait_for_service('/move_behind_ball')
rospy.wait_for_service('/hit_ball')
#establish service proxies
self.get_physical = rospy.ServiceProxy('/get_physical', GetPhysical)
self.get_POIs = rospy.ServiceProxy('/get_pois', CV_POIs)
self.init_robot = rospy.ServiceProxy('/init_robot', InitRobot)
self.move_behind_ball = rospy.ServiceProxy('/move_behind_ball', MoveBehindBall)
self.hit_ball = rospy.ServiceProxy('/hit_ball', HitBall)
self.display_picture = rospy.ServiceProxy('/picture_display', DisplayPicture)
self.setup_robot()
print("initializing robot...")
rospy.sleep(3) #sleep for 3 seconds to let things chill out
self.loop()
def game_on(self, req):
#gets ball and hole positions in sawyer frame
ball_pose, hole_pose = self.get_positions()
#tell sawyer to move behind ball in sawyer frame coordinates
# self.display_picture(1)
self.move(ball_pose, hole_pose)
print("setting up to hit wait for it....")
rospy.sleep(5) #dumb sleep for 10 seconds while we get behind ball
self.hit_ball()
# self.display_picture(0)
return GameOnResponse()
def setup_robot(self):
#figure out x,y origin of gamespace in sawyer frame
#either drag cuff or use our extrinsic camera callibration
self.init_robot()
def get_positions(self):
resp = self.get_POIs()
ball_pose_camera = resp.ball_pose
hole_pose_camera = resp.hole_pose
ball_pose_sawyer = self.get_physical(ball_pose_camera)
hole_pose_sawyer = self.get_physical(hole_pose_camera)
print("ball:")
print((ball_pose_sawyer.sawyer_frame.position.x,ball_pose_sawyer.sawyer_frame.position.y))
print("hole:")
print((hole_pose_sawyer.sawyer_frame.position.x,hole_pose_sawyer.sawyer_frame.position.y))
return ball_pose_sawyer, hole_pose_sawyer
def move(self, ball_pose, hole_pose):
print("ball pose is:")
print(ball_pose.sawyer_frame)
print("hole pose is:")
print(hole_pose)
hole_pose.sawyer_frame.position.x = 0.9536
hole_pose.sawyer_frame.position.y = 0.5726
self.move_behind_ball(hole_pose.sawyer_frame, ball_pose.sawyer_frame, False)
def loop(self):
rate = rospy.Rate(2)
while not rospy.is_shutdown():
#get ball position in overhead camera frame coordinate
# self.get_positions()
rate.sleep()
if __name__ == '__main__':
rospy.init_node("game_planner")
GamePlanner()
<file_sep>/nodes/camera_cal2
#!/usr/bin/env python
import rospy
import numpy as np
import cv2
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
from geometry_msgs.msg import Transform, Quaternion, Vector3
from tf.transformations import quaternion_from_matrix
from mini_golf.srv import GetPhysical, GetPhysicalResponse, CV_POIs, CV_POIsResponse
class CameraCallib(object):
def __init__(self):
#where we see the pixel coords of the ball from cv detect
self.callibration_pixel_pts = np.array([[516,362],
[286,365],
[51,374],
[46,146],
[277,141],
[514,139],
[281,251]])
#physical mapping from sawyer frame
self.physical_pts = np.array([[0.45,-0.4544],
[0.45,.1543],
[0.45,.708],
[1.0597,.708],
[1.0597,.1543],
[1.086,-0.4544],
[.7549,.1543]])
self.num_pts = len(self.callibration_pixel_pts)
rospy.Service('get_physical', GetPhysical, self.get_physical)
self.loop()
def get_physical(self, req):
print("fielding request")
p_balls = np.zeros((self.num_pts,2))
R = np.array([[0,1],[-1,0]])
for i in range(self.num_pts):
p_balls[i] = np.copy([req.pixel_frame.position.x,req.pixel_frame.position.y])
# print(p_balls)
p_balls[i][0] = - p_balls[i][0]
p_balls[i] = np.matmul(R,p_balls[i])
#here's where the unique per callubration point stuff start
off_set = self.callibration_pixel_pts[i]
off_set[0] = -off_set[0]
off_set = np.matmul(R,off_set)
p_balls[i] = p_balls[i] - off_set
p_balls[i] = p_balls[i] * 0.0023
p_balls[i] = p_balls[i] - self.physical_pts[i]
p_balls[i] = -p_balls[i]
x_phys = np.average(p_balls[:,0])
y_phys = np.average(p_balls[:,1])
resp = GetPhysicalResponse()
resp.sawyer_frame.position.x = x_phys
resp.sawyer_frame.position.y = y_phys
return resp
def loop(self):
rate = rospy.Rate(10)
while not rospy.is_shutdown():
rate.sleep()
if __name__ == '__main__':
rospy.init_node("camera_callibrator")
CameraCallib()<file_sep>/nodes/cv_detect_ball
#!/usr/bin/env python
#necessary imports
from __future__ import print_function
import rospy
import numpy as np
from sensor_msgs.msg import Image
from geometry_msgs.msg import Pose
from cv_bridge import CvBridge #CvBridgeError
from mini_golf.srv import CV_POIs, CV_POIsResponse
import cv2
class DetectBall(object):
"""
Detects a ball in the visual field. Currently uses HSV color segmentation
"""
def __init__(self):
"""
Initialization function. Creates variables, image converter, and publisher/subscriber
"""
self.rows = 0 #image height placeholder
self.cols = 0 #image width placeholder
self.hole_X = 0 #placeholders for hole locator circle
self.hole_Y = 0
self.hole_rad = 0
self.ball_pose = Pose() #ball position
self.hole_pose = Pose() #hole position
#colorspaces found using script from:
#https://github.com/opencv/opencv/blob/3.4/samples/cpp/tutorial_code/ImgProc/Threshold_inRange.cpp
#HSV-space ranges for ball color (blue)
self.ball_H_range = (100, 115)
self.ball_S_range = (130, 255)
self.ball_V_range = (100, 255)
#HSV ranges for turf (green)
self.turf_H_range = (20, 45)
self.turf_S_range = (100, 255)
self.turf_V_range = (0, 200)
rospy.loginfo("HSV filters set.")
self.bridge = CvBridge() #converts between ROS and cv2 image
self.capture = cv2.VideoCapture(2) #capture from webcam
'''
IMPORTANT!!!
On Riley's computer, use argument 0 for attached camera, use 2 for laptop webcam.
I don't know why this is but roll with it. Might be different on other people's computers,
if the image isn't showing up in ImageViewer try using the other argument.
'''
#initialize publishers
self.image_pub = rospy.Publisher('/overhead_image_out', Image, queue_size=1)
self.ball_pose_pub = rospy.Publisher('/ball_pose', Pose, queue_size=10)
self.hole_pose_pub = rospy.Publisher('/hole_pose', Pose, queue_size=10)
rospy.loginfo("Publishers initialized.")
#call hole-locating function
self.find_hole()
#initialize subscriber
# rospy.Subscriber('/io/internal_camera/head_camera/image_rect_color', Image,
# self.detect_ball)
# rospy.loginfo("Subscriber initialized.")
#initialize service
self.serv = rospy.Service('get_pois', CV_POIs, self.serv_callback)
def serv_callback(self, req):
resp = CV_POIsResponse()
resp.ball_pose = self.ball_pose
resp.hole_pose = self.hole_pose
return resp
def find_hole(self):
"""
Finds the hole in the putting green
"""
#read webcam image
ret, hole_img_in = self.capture.read()
#convert image to HSV
hole_hsv = cv2.cvtColor(hole_img_in, cv2.COLOR_BGR2HSV)
#color thresholding - turf (green)
turf_threshold = cv2.inRange(hole_hsv, (self.turf_H_range[0], self.turf_S_range[0],
self.turf_V_range[0]),
(self.turf_H_range[1], self.turf_S_range[1],
self.turf_V_range[1]))
#Gaussian blur
turf_blur = cv2.GaussianBlur(turf_threshold, (5, 5), 0)
#erode & dilate image to remove noise
turf_erode = cv2.erode(turf_blur, np.ones((5, 5)), iterations=1)
turf_dilate = cv2.dilate(turf_erode, np.ones((5, 5)), iterations=2)
#find contours in image
image, contours, hierarchy = cv2.findContours(turf_dilate, cv2.RETR_LIST,
cv2.CHAIN_APPROX_NONE)
#find contours based on size
for cont in contours: #for all contours
area = cv2.contourArea(cont) #determine contour area
if area > 600 and area < 800: #if contour is correct size
#if using smaller webcam: threshold is 1250:1750
(x, y), radius = cv2.minEnclosingCircle(cont) #find smallest circle enclosing it
self.hole_X = int(x) #hole center x-coordinate
self.hole_Y = int(y) #hole center y-coordinate
self.hole_rad = int(radius + 3) #hole radius
#set hole coordinates to publish
self.hole_pose.position.x = self.hole_X
self.hole_pose.position.y = self.hole_Y
#publish hole position
self.hole_pose_pub.publish(self.hole_pose)
def detect_ball(self):
"""
Detects the ball using color thresholding
"""
#read webcam image
ret, img_in = self.capture.read()
#convert to HSV colorspace
img_hsv = cv2.cvtColor(img_in, cv2.COLOR_BGR2HSV)
#color thresholding
img_threshold = cv2.inRange(img_hsv,
(self.ball_H_range[0], self.ball_S_range[0],
self.ball_V_range[0]),
(self.ball_H_range[1], self.ball_S_range[1],
self.ball_V_range[1]))
#Gaussian blur
blur = cv2.GaussianBlur(img_threshold, (5, 5), 0)
#find contours in blurred image
image, contours, hierarchy = cv2.findContours(blur, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
#isolate largest contour (should be the ball)
if len(contours) > 0:
biggest_contour = max(contours, key=cv2.contourArea)
#find smallest circles enclosing biggest contour
(x, y), radius = cv2.minEnclosingCircle(biggest_contour) #smallest enclosing circle
centerX = int(x) #center X coordinate
centerY = int(y) #center Y coordinate
radius = int(radius) #radius
#draw circles on image at ball and hole locations
img_circle = cv2.circle(img_in, (centerX, centerY), radius, (0, 0, 255), 2)
img_circle = cv2.circle(img_in, (self.hole_X, self.hole_Y), self.hole_rad,
(51, 255, 255), 2)
#ball x- and y- coordinates
self.ball_pose.position.x = centerX
self.ball_pose.position.y = centerY
print("pixel ideation")
print("x:{}\ty:{}".format(centerX,centerY))
q = np.array([centerX,centerY])
off_set_to_game_orig = np.array([507,341])
q = q + off_set_to_game_orig
q[0] = -q[0] #flip handedness
R = np.array([[0,1],[-1,0]]) #-90 degree rotation matrix
q = np.matmul(R,q)
q = q * 0.0023
q[0] = q[0] + 0.455
q[1] = q[1] + -0.494
print("positional ideation")
print("x:{}\ty:{}".format(q[0],q[1]))
# T = np.array([[0,-1,0,0.715],[-1,0,0,-0.0174],[0,0,-1,1.65],[0,0,0,1]])
# b = np.array([centerX * 0.002,centerY * 0.002,1,1])
# a = np.matmul(T,b)
# print("x:{}\ty:{}".format(a[0],a[1]))
#publish ball position
self.ball_pose_pub.publish(self.ball_pose)
elif len(contours) == 0:
img_circle = cv2.circle(img_in, (self.hole_X, self.hole_Y), self.hole_rad,
(51, 255, 255), 2)
#convert cv2 image to ROS image
img_out = self.bridge.cv2_to_imgmsg(img_circle, "bgr8")
#publish image for display
self.image_pub.publish(img_out)
def main():
"""
Main function; initializes the node and calls the DetectBall class
"""
rospy.loginfo("Beginning Ball Detection...") #console output message
det = DetectBall()
while not rospy.is_shutdown():
det.detect_ball()
if __name__ == '__main__':
rospy.init_node('cv_detect_ball') #initialize node
rospy.loginfo("CV Node Initialized") #console output message
try:
main()
except rospy.ROSInterruptException:
pass
<file_sep>/nodes/camera_cal
#!/usr/bin/env python
import rospy
import numpy as np
import cv2
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
from geometry_msgs.msg import Transform, Quaternion, Vector3
from tf.transformations import quaternion_from_matrix
from mini_golf.srv import CamCal, CamCalResponse, CV_POIs, CV_POIsResponse
#bringing this in for debug purposes
def se3_inv(matrix):
"""
Calculates the inverse of an se(3) transformation matrix.
"""
R = matrix[0:3,0:3] #roation matrix
p = matrix[0:3,-1] #translation vector
RT = np.transpose(R) #transpose rotation matrix
inv_p = -np.matmul(RT, p) #invert translation vector
g = np.zeros((4,4))
g[0:3,0:3] = RT
g[0:3,-1] = inv_p
g[-1,-1] = 1
return g #output transformation matrix
class CameraCallib(object):
def __init__(self):
rospy.loginfo("hello world")
self.sawyer_cam_matrix = np.reshape(np.asarray(rospy.get_param("/sawyer_cam/camera_matrix/data")), (3, 3))
self.overhead_cam_matrix = np.reshape(np.asarray(rospy.get_param("/overhead_cam/camera_matrix/data")), (3, 3))
self.sawyer_cam_distortion = np.reshape(np.asarray(rospy.get_param("/sawyer_cam/distortion_coefficients/data")), (5, 1))
self.overhead_cam_distortion = np.reshape(np.asarray(rospy.get_param("/overhead_cam/distortion_coefficients/data")), (5, 1))
self.killa = 0
self.killb = 0
rospy.Subscriber("/overhead_image_out", Image, self.overhead_cal_callback)
rospy.Subscriber("/io/internal_camera/head_camera/image_raw", Image, self.sawyer_cal_callback)
#bringing this in for debug purposes
self.get_pois = rospy.ServiceProxy('/get_pois', CV_POIs)
self.T_saw = np.zeros((4,4))
self.T_over = np.zeros((4,4))
self.bridge = CvBridge()
self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, .001)
self.sawyer_transform = Transform()
self.overhead_transform = Transform()
rospy.Service('/get_camera_cal', CamCal, self.set_camera_cal)
self.main()
def set_camera_cal(self, req):
rospy.loginfo("got request for transforms")
resp = CamCalResponse()
print(self.sawyer_transform)
print(self.overhead_transform)
resp.sawyer_transform = self.sawyer_transform
resp.overhead_transform = self.overhead_transform
return resp
def construct_obj_pts(self):
objpts = np.zeros((48, 1, 3))
for i in range(48):
objpts[i][0] = np.array([.0254*i % (6 * 0.0254), 0.0254*np.floor(i/6), 0])
return objpts
def overhead_cal_callback(self, data):
img = self.bridge.imgmsg_to_cv2(data, "bgr8")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret_val, corners = cv2.findChessboardCorners(gray, (6, 8), None)
# print(ret_val)
if ret_val == True and not self.killa:
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), self.criteria)
overhead_objpts = self.construct_obj_pts()
#print(overhead_objpts)
rguess = np.array([[0,1,0 ],[1,0,0],[0,0,-1]])
ret, rvec, tvec, inliers = cv2.solvePnPRansac(overhead_objpts,
corners2,
self.overhead_cam_matrix,
self.overhead_cam_distortion,
useExtrinsicGuess = True
)
# print(corners2.shape)
# cv2.drawChessboardCorners(gray, (6,8), corners2[0][0], ret)
# cv2.imshow("eggs",gray)
# cv2.waitKey()
R = cv2.Rodrigues(rvec)
print(R)
T = np.zeros((4, 4))
T[0:3, 0:3] = R[0]
T[-1, :] = np.array([0, 0, 0, 1])
# print(T)
q = quaternion_from_matrix(T)
T[0:3,-1] = tvec[:,0]
# print(tvec)
self.overhead_transform.rotation = Quaternion(q[0], q[1], q[2], q[3])
self.overhead_transform.translation = Vector3(tvec[0][0], tvec[1][0], tvec[2][0])
self.T_over = T
# print("Overhead Trans")
# # print(self.overhead_transform)\
# print(T)
self.killa = 1
def sawyer_cal_callback(self, data):
img = self.bridge.imgmsg_to_cv2(data, "bgr8")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret_val, corners = cv2.findChessboardCorners(gray, (6, 8), None)
if ret_val == True and not self.killb:
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), self.criteria)
sawyer_objpts = self.construct_obj_pts()
ret, rvec, tvec, inliers = cv2.solvePnPRansac(sawyer_objpts,
corners2,
self.sawyer_cam_matrix,
self.sawyer_cam_distortion,
useExtrinsicGuess = True)
R = cv2.Rodrigues(rvec)
print(R)
T = np.zeros((4, 4))
T[0:3, 0:3] = R[0]
T[-1, :] = np.array([0, 0, 0, 1])
# print(T)
q = quaternion_from_matrix(T)
T[0:3,-1] = tvec[:,0]
self.sawyer_transform.rotation = Quaternion(q[0], q[1], q[2], q[3])
self.sawyer_transform.translation = Vector3(tvec[0][0], tvec[1][0], tvec[2][0])
self.T_saw = T
# print("Sawyer Trans")
# print(T)
self.killb = 1
def main(self):
rate = rospy.Rate(0.5)
# while not rospy.is_shutdown() and not (self.killa and self.killb):
while not rospy.is_shutdown():
resp = self.get_pois()
ball_pos_o = np.array([resp.ball_pose.position.x, resp.ball_pose.position.y, resp.ball_pose.position.z, 1])
hole_pos_o = np.array([resp.hole_pose.position.x, resp.hole_pose.position.y, resp.hole_pose.position.z, 1])
#transform to ball and hole positions in game frame
ball_pos_g = np.matmul(se3_inv(self.T_over),ball_pos_o)
hole_pos_g = np.matmul(se3_inv(self.T_over),hole_pos_o)
# ball_pos_g_s = np.matmul(se3_inv(self.T_saw),ball_pos)
# hole_pos_g_s = np.matmul()
# rospy.loginfo("hole pos game space:\n{}".format(hole_pos_g))
# rospy.loginfo("ball pos game space:\n{}".format(ball_pos_g))
#transform to ball and hole positions in sawyer frame
ball_pos_s = np.matmul(self.T_saw, ball_pos_g) * 0.002
hole_pos_s = np.matmul(self.T_saw, hole_pos_g) * 0.002
#rospy.loginfo("hole pos saw camera space:\n{}".format(hole_pos_s))
rospy.loginfo("ball pos saw camera space:\n{}".format(ball_pos_s))
rate.sleep()
if __name__ == '__main__':
rospy.init_node("camera_cal")
CameraCallib()
<file_sep>/nodes/move_group_python_interface
#!/usr/bin/env python
''' This node provides a python interface to achieve following functions
based on the move_it python interface.
- getting robot current state
- planning to a pose goal
- calculate a starting pose before hitting
- add table and putter into planning scene
- add a constrait on joint 6
PUBLISHERS:
/move_group/display_planned_path (moveit_msgs.msg.DisplayTrajectory)
~ a DisplayTrajectory publisher which is used to display trajectories in Rviz
'''
from __future__ import division
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
from math import pi
import math
from std_msgs.msg import String
from moveit_commander.conversions import pose_to_list
import numpy as np
from tf.transformations import quaternion_from_euler
from moveit_msgs.msg import RobotState, Constraints, JointConstraint
import intera_interface
from mini_golf.srv import InitRobot, InitRobotRequest, InitRobotResponse
from mini_golf.srv import MoveBehindBall,MoveBehindBallRequest, MoveBehindBallResponse
class MoveGroupPythonInterface(object):
''' Integrate the functions we need for the mini-golf project '''
def __init__(self):
''' Initialize RobotCommander, PlanningSceneInterface and MoveGroupCommander objects respectively '''
self.robot = moveit_commander.RobotCommander()
self.scene = moveit_commander.PlanningSceneInterface()
self.group_name = "right_arm"
self.move_group = moveit_commander.MoveGroupCommander(self.group_name)
self.display_trajectory_publisher = rospy.Publisher('/move_group/display_planned_path',
moveit_msgs.msg.DisplayTrajectory,
queue_size=20)
# get the end effector link name it is controlling
self.eef_link = self.move_group.get_end_effector_link()
rospy.logdebug('End effector link: %s', self.eef_link)
# for not detecting collision between the putter and the following links
self.gripper_links = ['right_gripper_base',\
'right_electric_gripper_base',\
'right_gripper_tip',\
'right_hand',\
'right_connector_plate_base',\
'right_gripper_l_finger',\
'right_gripper_l_finger_tip',\
'right_gripper_r_finger',\
'right_gripper_r_finger_tip',\
'right_hand_camera',\
'right_wrist']
# used for sawyer python api
self.limb = intera_interface.Limb('right')
def current_state(self):
''' Get the current state of the robot
Returns:
current_state : current state of the robot
'''
current_state = self.robot.get_current_state()
return current_state
def go_to_pose(self, position, orientation):
''' Make the end effector go to a pose in task space
Args:
position (1*3 list e.g. [0.4,0.1,0.4]) : x, y, z coordinates of goal position
orientation (1*4 list e.g. [0,0,0,1]) : x, y, z, w (quaternion) of a orientation
'''
pose_goal = geometry_msgs.msg.Pose()
pose_goal.position.x = position[0]
pose_goal.position.y = position[1]
pose_goal.position.z = position[2]
pose_goal.orientation.x = orientation[0]
pose_goal.orientation.y = orientation[1]
pose_goal.orientation.z = orientation[2]
pose_goal.orientation.w = orientation[3]
self.move_group.set_pose_target(pose_goal)
# change the max velocity and acceleratin factor before execution
self.move_group.set_max_velocity_scaling_factor(1.0)
self.move_group.set_max_acceleration_scaling_factor(1.0)
# try to find the solution for several times
for i in range(5):
plan = self.move_group.go(wait=True)
if plan == True:
self.move_group.stop()
self.move_group.clear_pose_targets()
return True
else:
rospy.logdebug('Fail to find solution: trial %s', i+1)
return False
def get_start_pose(self, pos_hole, pos_ball, distance = 0.05):
''' Calculate the starting pose give the position of the hole and the ball
Args:
pos_hole (e.g.[0.68,0.27,0.07]): The 3D position (x,y,z) of the hole in the world frame
pos_ball (e.g.[0.63,-0.34,0.07]): The 3D position (x,y,z) of the ball in the world frame
Returns:
position (1*3 list e.g. [0.4,0.1,0.4]) : x, y, z coordinates of the position
orientation (1*4 list e.g. [0,0,0,1]) : x, y, z, w (quaternion) of the orientation
'''
#### Position ####
# x_s, y_s, z_s denotes the starting position of the center of the putter
# default distance between the starting position of the putter and the ball is 5cm
# z_s is same as the height of the ball
z_s = pos_ball[2]
# get the vector pointing from the hole to the ball
v_h2b = (np.array(pos_ball) - np.array(pos_hole))[:2]
# normalize the vector
v_h2b_norm = np.linalg.norm(v_h2b)
v_h2b = v_h2b / v_h2b_norm
# compute x_s, y_s
x_s = pos_ball[0] + (v_h2b * distance)[0]
y_s = pos_ball[1] + (v_h2b * distance)[1]
position = [x_s, y_s, z_s]
#### Orientation ####
# get the angle in xy plane from the vector
# v_h2b is point from the hole to the ball
# we need the vector pointing from the ball to the hole
angle_xy_plane = math.atan2(-v_h2b[1], -v_h2b[0])
# convert it to euler angle
euler_yaw = angle_xy_plane
euler_pitch = pi
euler_roll = 0
# convert it to quaternion
quaternion = quaternion_from_euler(euler_roll, euler_pitch, euler_yaw)
orientation = [quaternion[0],quaternion[1],quaternion[2],quaternion[3]]
return position, orientation
def add_table(self, x_offset=0.6, z_height=-0.5):
''' Add table to the planning scene
Args:
x_offset (m) : the distance from center of the table to world frame in x direction
z_height (m) : the height of the table (upper surface)
'''
table_pose = geometry_msgs.msg.PoseStamped()
table_pose.header.frame_id = "world"
table_pose.pose.orientation.w = 1.0
table_pose.pose.position.x = x_offset
table_pose.pose.position.z = z_height - 0.025
table_name = "table"
table_size = (0.6096, 1.2192, 0.05)
self.scene.add_box(table_name, table_pose, size=table_size)
if not self.wait_object_update(table_name):
rospy.logdebug('Attach table failed.')
def add_putter(self):
''' Add putter to the planning scene and attach it to the gripper '''
putter_pose = geometry_msgs.msg.PoseStamped()
putter_pose.header.frame_id = "right_gripper_tip"
putter_pose.pose.orientation.w = 1.0
putter_pose.pose.position.z = -0.0325
putter_name = "putter"
putter_size = (0.018, 0.0625, 0.087)
self.scene.add_box(putter_name, putter_pose, size=putter_size)
if self.wait_object_update(putter_name):
self.scene.attach_box(self.eef_link, putter_name, touch_links=self.gripper_links)
else:
rospy.logdebug('Attach putter failed.')
def add_ball(self, ball_position):
''' Add ball to the planning scene
Args:
ball_position (e.g.[0.63,-0.34,0.07]): The 3D position (x,y,z) of the ball in the world frame
'''
ball_pose = geometry_msgs.msg.PoseStamped()
ball_pose.header.frame_id = "world"
ball_pose.pose.orientation.w = 1.0
ball_pose.pose.position.x = ball_position[0]
ball_pose.pose.position.y = ball_position[1]
ball_pose.pose.position.z = -0.43
ball_name = "ball"
self.scene.add_sphere(ball_name, ball_pose, radius=0.02)
if not self.wait_object_update(ball_name):
rospy.logdebug('Attach ball failed.')
def wait_object_update(self, object_name, timeout=4):
''' Wait for the collision update to be completed
Args:
object_name : The name of the object to be checked
timeout (s) : timeout in seconds
'''
start = rospy.get_time()
seconds = rospy.get_time()
while (seconds - start < timeout) and not rospy.is_shutdown():
is_known = object_name in self.scene.get_known_object_names()
if is_known:
return True
rospy.sleep(0.1)
seconds = rospy.get_time()
return False
def init_path_constraints(self):
''' Add the joint 6 constraint to align joint 5 with the hitting direction '''
self.constraints = Constraints()
joint_constraint = JointConstraint()
self.constraints.name = "align_joint5"
joint_constraint.position = 3.14/2
joint_constraint.tolerance_above = 0.1
joint_constraint.tolerance_below = 0.3
joint_constraint.weight = 1
joint_constraint.joint_name = "right_j6"
self.constraints.joint_constraints.append(joint_constraint)
self.move_group.set_path_constraints(self.constraints)
def hit_it(self):
''' Hit the ball by rotating joint 5 '''
rospy.sleep(3)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[5] += pi/6
self.move_group.go(joint_goal, wait=True)
self.move_group.stop()
rospy.sleep(3)
joint_goal = self.move_group.get_current_joint_values()
joint_goal[5] -= pi/3
self.move_group.go(joint_goal, wait=True)
self.move_group.stop()
def return_home(self):
''' Go to the defined home position '''
joint_goal = self.move_group.get_current_joint_values()
joint_goal[0]=0.0
joint_goal[1]=0.0
joint_goal[2]=0.0
joint_goal[3]=np.pi/2
joint_goal[4]=0.0
joint_goal[5]=0.0
joint_goal[6] = -np.pi/2
self.move_group.go(joint_goal, wait=True)
self.move_group.stop()
##### Wrapping functions #####
def initialize_robot_pipline(self,req):
''' Initialize the robot, add collision detection '''
# add the table and putter to the planning scene
self.add_table()
self.add_putter()
return InitRobotResponse()
def move_to_start_position_pipline(self,req):
''' Complete the pipline of moving end effector to the starting pose '''
hole_position = [req.hole_position.position.x,req.hole_position.position.y,-0.43]
ball_position = [req.ball_position.position.x,req.ball_position.position.y,-0.43]
self.add_ball(ball_position)
self.return_home()
# setup the constraint
if req.if_add_constraint:
self.init_path_constraints()
# calculate starting pose
# position, orientation = self.get_start_pose([0.736,0.432,-0.43],[0.5,0.305,-0.43])
position, orientation = self.get_start_pose(hole_position,ball_position)
# go to starting pose
if_success = self.go_to_pose(position,orientation)
self.scene.remove_world_object('ball')
return MoveBehindBallResponse()
if __name__ == '__main__':
moveit_commander.roscpp_initialize(sys.argv)
rospy.init_node('move_group_python_interface', anonymous=True, log_level=rospy.DEBUG)
# initialize move group commander
my_sawyer = MoveGroupPythonInterface()
# get current state
rospy.logdebug(my_sawyer.current_state())
# Create service
s1 = rospy.Service('init_robot', InitRobot, my_sawyer.initialize_robot_pipline)
s2 = rospy.Service('move_behind_ball', MoveBehindBall, my_sawyer.move_to_start_position_pipline)
rospy.spin()
<file_sep>/tests/hit_ball_test
#!/usr/bin/env python
import unittest
import rospy
from mini_golf.srv import HitBall,DisplayPicture
class TestingNode(unittest.TestCase):
def __init__(self,*args):
super(TestingNode,self).__init__(*args)
rospy.init_node("test_client")
def test_display_picture(self):
rospy.wait_for_service("picture_display")
disp_pic = rospy.ServiceProxy("picture_display",DisplayPicture)
response = disp_pic(2)
self.assertTrue(response,None)
def test_hit_ball(self):
rospy.wait_for_service("hit_ball")
hit_the_ball = rospy.ServiceProxy("hit_ball",HitBall)
response = hit_the_ball()
self.assertTrue(response,None)
if __name__ == "__main__":
import rostest
rostest.rosrun('mini_golf', "testing_node", TestingNode)
<file_sep>/scripts/callibration_mapper.py
import numpy as np
callibration_pixel_pts = np.array([[507,341],[57,361],[49,144],[503,129]])
to_use = np.copy(callibration_pixel_pts)
physical_pts = np.array([[0.455,-0.494],[0.455,0.725],[1.064,0.725],[1.064,-0.494]])
num_pts = len(callibration_pixel_pts)
virtual_pts = np.zeros((num_pts,2))
err = np.zeros(num_pts)
def callibration(x_pix,y_pix,its):
print("Running")
p_balls = np.zeros((num_pts,2))
R = np.array([[0,1],[-1,0]])
for i in range(num_pts):
p_balls[i] = np.copy([x_pix,y_pix])
# print(p_balls)
p_balls[i][0] = - p_balls[i][0]
p_balls[i] = np.matmul(R,p_balls[i])
#here's where the unique per callubration point stuff start
off_set = callibration_pixel_pts[i]
off_set[0] = -off_set[0]
off_set = np.matmul(R,off_set)
p_balls[i] = p_balls[i] - off_set
p_balls[i] = p_balls[i] * 0.0023
p_balls[i] = p_balls[i] - physical_pts[i]
p_balls[i] = -p_balls[i]
x_phys = np.average(p_balls[:,0])
y_phys = np.average(p_balls[:,1])
x_actual = physical_pts[its][0]
y_actual = physical_pts[its][1]
# print("from pix: {}, {}\ngot phys: {}, {}\nreal phys:{}, {}".format(x_pix,y_pix,x_phys,y_phys,x_actual,y_actual))
err = np.sqrt(np.square(x_phys-x_actual)+np.square(y_phys-y_actual))
return x_phys,y_phys,err
if __name__ == '__main__':
for i in range(num_pts):
x = to_use[i][0]
y = to_use[i][1]
print((x,y))
phys_guess_x,phys_guess_x,err = callibration(x,y,i)
print(err)
|
9892ea32dafa863ef97899ff2ea00f8538dabb46
|
[
"Markdown",
"Python",
"Shell"
] | 11
|
Markdown
|
shangzhouye/final-project-numg
|
710ce352d21ac474b64052b0f20951a4ff5ae408
|
9678244b7c6c738eb0bcef89d68af7f8c2c7594e
|
refs/heads/master
|
<file_sep>
function limpa_formulario_cep() {
//Limpa valores do formulário de cep.
document.getElementById('rua').value = ("");
document.getElementById('bairro').value = ("");
document.getElementById('cidade').value = ("");
document.getElementById('estado').value = ("");
}
function meu_callback(conteudo) {
if (!("erro" in conteudo)) {
//Atualiza os campos com os valores.
document.getElementById('rua').value = (conteudo.logradouro);
document.getElementById('bairro').value = (conteudo.bairro);
document.getElementById('cidade').value = (conteudo.localidade);
document.getElementById('estado').value = (conteudo.uf);
} //end if.
else {
//CEP não Encontrado.
limpa_formulario_cep();
alert("CEP não encontrado.");
document.getElementById('cep').value = ("");
}
}
function pesquisacep(valor) {
//Nova variável "cep" somente com dígitos.
var cep = valor.replace(/\D/g, '');
//Verifica se campo cep possui valor informado.
if (cep !== "") {
//Expressão regular para validar o CEP.
var validacep = /^[0-9]{8}$/;
//Valida o formato do CEP.
if (validacep.test(cep)) {
//Preenche os campos com "..." enquanto consulta webservice.
document.getElementById('rua').value = "...";
document.getElementById('bairro').value = "...";
document.getElementById('cidade').value = "...";
document.getElementById('estado').value = "...";
//Cria um elemento javascript.
var script = document.createElement('script');
//Sincroniza com o callback.
script.src = '//viacep.com.br/ws/' + cep + '/json/?callback=meu_callback';
//Insere script no documento e carrega o conteúdo.
document.body.appendChild(script);
} //end if.
else {
//cep é inválido.
limpa_formulario_cep();
alert("Formato de CEP inválido.");
}
} //end if.
else {
//cep sem valor, limpa formulário.
limpa_formulario_cep();
}
}
function formatar(mascara, documento) {
var i = documento.value.length;
var saida = mascara.substring(0, 1);
var texto = mascara.substring(i);
if (texto.substring(0, 1) !== saida) {
documento.value += texto.substring(0, 1);
}
}
function exibe(i) {
document.getElementById(i).readOnly = true;
}
function desabilita(i) {
document.getElementById(i).disabled = true;
}
function habilita(i) {
document.getElementById(i).disabled = false;
}
function desabilitaPF() {
if ((document.getElementById('cpf').disabled == true) && (document.getElementById('NomePF').disabled == true)) {
document.getElementById('cpf').disabled = false;
document.getElementById('NomePF').disabled = false;
document.getElementById('cnpj').disabled = true;
document.getElementById('NomeEmp').disabled = true;
document.getElementById('NomeFants').disabled = true;
}
}
function desabilitaPJ() {
if ((document.getElementById('cnpj').disabled == true) && (document.getElementById('NomeEmp').disabled == true)) {
document.getElementById('cpf').disabled = true;
document.getElementById('NomePF').disabled = true;
document.getElementById('NomeEmp').disabled = false;
document.getElementById('cnpj').disabled = false;
document.getElementById('NomeFants').disabled = false;
}
}
function validaSenha() {
NovaSenha = document.getElementById('password1').value;
CNovaSenha = document.getElementById('password2').value;
if (NovaSenha != CNovaSenha) {
alert("As senhas devem ser iguais.");
} else {
document.FormSenha.submit();
}
}
function verificaServico(){
tipo = document.getElementById('tipo').value;
if(tipo == 1){
document.getElementById('tpServico').disabled = false;
}
else {
document.getElementById('tpServico').disabled = true;
}
}
|
e997a500e36103f80ab2893a781abb7a09d6d0a1
|
[
"JavaScript"
] | 1
|
JavaScript
|
furstsoo/PI3
|
12fc2c0eb684aaad6a1e5f718441d476e893b03a
|
04b8a23a84063e2abc9da4cb7e7cc50170b4d32f
|
refs/heads/master
|
<repo_name>dmignosa/CS399<file_sep>/searchingProject/src/searchingProject/heapSort.java
package searchingProject;
public class heapSort {
public heapSort(){
}
//main heapsort method, builds the heap from the completely unsorted list
//then sorts it by swapping the top of the heap with the last value and finding the
//next largest value, which will become the top of the heap after the heapify method finishes running
public void hSort(int[] a){
int heapsize = a.length;
buildHeap(a, heapsize);
for (int i = a.length - 1; i >= 0; i--){
swap(a, 0, i);//swap the largest value with the value being accessed
heapsize--; //heapsize goes down as we do not want to further access the element moved in the last step
//as it is already sorted
heapify(a, 0, heapsize);
}
}
//builds the heap from an unsorted list by calling heapify on the elements in the first half of the list
public void buildHeap(int[] a, int heapsize){
for (int i = Math.floorDiv(a.length -1 , 2); i >= 0; i--){
heapify(a, i, heapsize);
}
}
//ensures that the child elements of the parent element this method is called on are smaller than the parent element
//(the heap property is maintained). Runs recursively on the child elements if a swap is made to ensure
//that the heap property is maintained at all levels
public void heapify(int[] a, int i, int heapsize){
int left = (2*i) + 1;
int right = (2*i) + 2;
int largest = -1;
if (left < heapsize && a[left] > a[i]){
largest = left;
}
else{
largest = i;
}
if (right < heapsize && a[right] > a[largest]){
largest = right;
}
if (largest != i){
swap(a, i, largest);
heapify(a, largest, heapsize);
}
}
//swaps the values of the array passed in at the locations specified
public void swap(int[] a, int b, int c){
int temp = a[b];
a[b] = a[c];
a[c] = temp;
}
}
<file_sep>/HuffmanCode/src/huffman.java
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.PriorityQueue;
public class huffman {
public static void main(String[] args){
//will keep track of the counts of each of the variables
int aCount = 0;
int cCount = 0;
int gCount = 0;
int tCount = 0;
int totalCount = 0;
//ecoli.txt MUST be located in the same location as this class
URL path = ClassLoader.getSystemResource("ecoli.txt");
//creates file object, which file reader will access
File ecoli = null;
try {
ecoli = new File(path.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//accesses file with file reader
FileReader fr = new FileReader(ecoli);
int i;
while ((i = fr.read()) != -1) //gets input from text file character by character
{
char ch = (char) i;
//checks character, increments a character count according to what character is read
//increments total count with each incrememted character count
if (ch == 'A'){
aCount++;
totalCount++;
}
if (ch == 'C'){
cCount++;
totalCount++;
}
if (ch == 'G'){
gCount++;
totalCount++;
}
if (ch == 'T'){
tCount++;
totalCount++;
}
}
fr.close();
}
catch (IOException e) {
e.printStackTrace();
}
//calls the method to build the tree based on character frequencies
//the root node of the tree is returned
//the codes will be found by traversing the tree from the root node
Node root = buildTree(aCount, cCount, gCount, tCount);
String[] codeStrings = new String[4];
//calls the method to traverse the tree to get the code of the tree
//starts from the root node and recursively calls self on child nodes
//when it gets to a node with no child it checks the value of the node
//and stores it to the appropriate location in an array
getCode(codeStrings, root, "");
String aCode = codeStrings[0];
String cCode = codeStrings[1];
String gCode = codeStrings[2];
String tCode = codeStrings[3];
//formats and prints all of the hoffman code information
//also gets the percentage of the character compared to the total number of characters
System.out.println("Huffman Code:");
System.out.println("Alphabet Frequency Code");
float totalFloat = (float) totalCount;
System.out.print("A ");
float aPct = (aCount / totalFloat) * 100;
System.out.printf("%.0f/100 ", aPct);
System.out.print(aCode);
System.out.println();
System.out.print("C ");
float cPct = (cCount / totalFloat) * 100;
System.out.printf("%.0f/100 ", cPct);
System.out.print(cCode);
System.out.println();
System.out.print("G ");
float gPct = (gCount / totalFloat) * 100;
System.out.printf("%.0f/100 ", gPct);
System.out.print(gCode);
System.out.println();
System.out.print("T ");
float tPct = (tCount / totalFloat) * 100;
System.out.printf("%.0f/100 ", tPct);
System.out.print(tCode);
}
//class for Node objects, which will have a character, a frequency, and possibly child nodes
public static class Node implements Comparable<Node> {
char ch;
int freq;
Node left;
Node right;
//constructor for nodes
Node(char chIn, int frequency, Node hLeft, Node hRight) {
ch = chIn;
freq = frequency;
left = hLeft;
right = hRight;
}
// checks if node is a leaf by checking if it has any children
public boolean isLeaf() {
assert ((left == null) && (right == null)) || ((left != null) && (right != null));
return (left == null) && (right == null);
}
//instantiation of comparator for nodes, which compares frequencies of the calling node to another node
public int compareTo(Node n) {
return this.freq - n.freq;
}
}
//Builds a tree based on character frequencies
//the root node of the tree is returned
public static Node buildTree(int aFreq, int cFreq, int gFreq, int tFreq){
Node root = null;
//pririty queue which will make up the tree
PriorityQueue<Node> tree= new PriorityQueue<Node>();
//creates leaf nodes for all character nodes if they occur
//adds them to priority queue
if (aFreq > 0){
Node nodeA = new Node('A', aFreq, null, null);
tree.add(nodeA);
}
if (cFreq > 0){
Node nodeC = new Node('C', cFreq, null, null);
tree.add(nodeC);
}
if (gFreq > 0){
Node nodeG = new Node('G', gFreq, null, null);
tree.add(nodeG);
}
if (aFreq > 0){
Node nodeT = new Node('T', aFreq, null, null);
tree.add(nodeT);
}
//gets (and removes) 2 nodes with the smallest value from the priority queue
//creates a new node with the input nodes as its children and a frequency
//equal to the sum of the two frequencies
//adds this new node to the priority queue. Stops once there is only one node, which is the root
while (tree.size() > 1){
Node l = tree.poll();
Node r = tree.poll();
Node parent = new Node(' ', (l.freq + r.freq), l, r);
tree.add(parent);
}
//gets and returns the root node from the priority queue
root = tree.poll();
return root;
}
// method to traverse the tree to get the code of the tree
//starts from the root node and recursively calls self on child nodes
//when it gets to a node with no child it checks the value of the node
//and stores it to the appropriate location in an array
public static void getCode(String[] st, Node x, String s) {
//if the node has children then calls self recursivly on the child nodes
//creates a string which records the traversal (adds a 0 if goes left, 1 if right)
if (!x.isLeaf()) {
getCode(st, x.left, s + '0');
getCode(st, x.right, s + '1');
}
//if the node is a leaf, g
else {
if (x.ch == 'A'){
st[0] = s;
}
if (x.ch == 'C'){
st[1] = s;
}
if (x.ch == 'G'){
st[2] = s;
}
if (x.ch == 'T'){
st[3] = s;
}
}
}
}
<file_sep>/BubbleSortHW/src/SmartBubbleSort.java
import java.util.Random;
/*
* By: <NAME>
* CS399
* HW2-2
* Implement Bubble Sort - Optimized Version
*/
public class SmartBubbleSort {
public static void main(String[] args){
int testArray[] = new int[10];//creates an array of length 10 for testing purposes
randomArray(testArray);//initializes the array with random integers
System.out.print("Unsorted: ");
toString(testArray);//prints the unsorted array
sort(testArray);//calls the bubble sort method
System.out.print("Sorted: ");
toString(testArray);//prints the newly sorted array
}
public static void sort(int[] n)
{
int temp;
boolean swap = true;
for (int i = n.length - 1; i >= 1&& swap; i--) //if the algorithm is in order (no swaps are made), then the sorting will stop
{
swap = false; //sets swap to false, so if no swap is made then it will be known that the array is sorted
for (int j = 1; j <= i; j++ )
{
if (n[j-1] > n[j])
{
temp = n[j];
n[j] = n[j-1];
n[j-1] = temp;
swap = true;//sets swap to true if a swap is made, marking the sorting as incomplete
}
}
}
}
public static void toString(int[] n)//prints the array
{
for(int i=0; i<n.length; i++){
System.out.print(n[i] + " ");
}
System.out.println();
}
public static void randomArray(int[] n)//fills the array with random numbers
{
Random random = new Random();
for (int i = 0; i < n.length; i++)
{
int randomInt = random.nextInt(100);
n[i] = randomInt;
}
}
}
|
d6c0772a69365a6685d6b361bdfd3cca9625c6cc
|
[
"Java"
] | 3
|
Java
|
dmignosa/CS399
|
058cc6ef634b7483b4183163119c0876baa39ca5
|
29d10629316ef3a8517b7d34e7e7d3a8af01903f
|
refs/heads/master
|
<repo_name>Amit-singh311/EmployeeApp<file_sep>/src/actions/types.js
export const EMAIL_CHANGED = 'email_changed';
export const PASSWORD_CHANGED = '<PASSWORD>';
export const USER_LOGIN_SUCCESS = 'user_login_success';
export const USER_LOGIN_FAIL = 'user_login_fail';
export const USER_LOGIN = 'user_login';
export const EMPLOYEE_UPDATE = 'employee_update';
|
797017bb55688e124dba365794daf936f6632774
|
[
"JavaScript"
] | 1
|
JavaScript
|
Amit-singh311/EmployeeApp
|
4f37b3f5dc837d26c2ae6b3de4b95b9a0d5b2890
|
14f64140c4c1e82e1fd44340d551e77f720dfe0f
|
refs/heads/master
|
<repo_name>ValentynKurylo/python2<file_sep>/main.py
list=[{'name': 'mouse', 'price': 200}, {'name': 'table', 'price': 400}, {'name': 'phone', 'price': 4000}]
bought_thing = []
n = 100
while n != 0:
print("1 - Create notice" )
print("2 - Show all notices")
print("3 - To buy something by name of notice")
print("4 - Show bought thing")
print("5 - Show general price")
print("6 - The most expensive thing")
print("0 - go out")
n = int(input("Enter number: "))
if n == 1:
name = input("Enter name: ")
price = int(input("Enter price: "))
list.append({'name': name, 'price': price})
if n == 2:
for i in range(len(list)):
print(i, list[i])
if n == 3:
find = input('Enter name ')
for i in list:
if i['name'] == find:
bought_thing.append(i)
if n == 4:
for i in range(len(bought_thing)):
print(bought_thing[i])
if n == 5:
sum = 0
for i in bought_thing:
sum += i['price']
print(sum)
if n == 6:
expensive = 0
expensive_thing = []
for i in bought_thing:
if i['price'] >= expensive:
expensive = i['price']
expensive_thing = i
print(expensive_thing)
|
3d266f3acd31e88ac817b2a49d44bef17980664e
|
[
"Python"
] | 1
|
Python
|
ValentynKurylo/python2
|
f7659d3d03e57dd394cdf62c3f998da3e7ea6882
|
bf98422858f43edde882b7016ceff0698308e19b
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int z = AddTwoNumbers(6, 4);
Restaurant mcDonalds = new Restaurant("McDonald's");
mcDonalds.ChangeName();
}
static int AddTwoNumbers(int x, int y)
{
return x + y;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sandbox;
namespace SandboxTests
{
[TestClass]
public class StoreTests
{
[TestMethod]
public void SellLemons_PlayerHasMoney_LemonCountIncreases()
{
// arrange
Store store = new Store();
Player player = new Player();
int expected = 5;
int actual;
// act
store.SellLemons(5, player);
actual = player.inventory.lemonCount;
// assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void SellLemons_PlayerDoesNotHaveMoney_LemonCountDoesNotIncrease()
{
// arrange
Store store = new Store();
Player player = new Player();
player.inventory.wallet = 0;
int expected = 0;
int actual;
// act
store.SellLemons(5, player);
actual = player.inventory.lemonCount;
// assert
Assert.AreEqual(expected, actual);
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sandbox;
namespace SandboxTests
{
[TestClass]
public class WeatherTests
{
[TestMethod]
public void SetCondition_RandomNumberIsZero_ConditionIsSunny()
{
// arrange
Weather weather = new Weather();
string expected = "Sunny";
string actual;
// act
weather.SetCondition(0);
actual = weather.condition;
// assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void SetCondition_RandomNumberIsOne_ConditionIsCloudy()
{
// arrange
Weather weather = new Weather();
string expected = "Cloudy";
string actual;
// act
weather.SetCondition(1);
actual = weather.condition;
// assert
Assert.AreEqual(expected, actual);
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sandbox;
using System.Collections.Generic;
using System.Collections;
namespace CustomListTests
{
[TestClass]
public class CustomListTests
{
[TestMethod]
public void Add_Numbers_ToList()
{
CustomList<int> testList = new CustomList<int>();
int expected = 2;
int actual;
testList.Add(2);
testList.Add(3);
actual = testList[0];
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_AddToEmptyList_ItemGoesToIndexZero()
{
// arrange
CustomList<int> testList = new CustomList<int>();
int expected = 12;
int actual;
// act
testList.Add(12);
actual = testList[0];
// assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_ToEmptyList_WhatsInTheSecondIndex()
{
CustomList<int> testList = new CustomList<int>();
int expected = 12;
int actual;
testList.Add(10);
testList.Add(13);
testList.Add(12);
actual = testList[2];
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_ToEmptyList_Items_WhatsInTheFifthIndex()
{
CustomList<int> testList = new CustomList<int>();
int expected = 22;
int actual;
testList.Add(2);
testList.Add(1);
testList.Add(3);
testList.Add(10);
testList.Add(11);
testList.Add(22);
actual = testList[5];
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_ToEmptyList_Items_WhatsInTheSixthIndex()
{
CustomList<int> testList = new CustomList<int>();
int expected = 33;
int actual;
testList.Add(2);
testList.Add(1);
testList.Add(3);
testList.Add(10);
testList.Add(11);
testList.Add(22);
testList.Add(33);
actual = testList[6];
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Whats_InThe_third_Index()
{
CustomList<int> testList = new CustomList<int>() { 1, 2, 3, 4 };
int expected = 4;
int actual = testList[3];
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_Two_NumbersToA_ListOfNumbersFind_IndexFive()
{
CustomList<int> testList = new CustomList<int>() { 1, 2, 3, 4 };
testList.Add(5);
testList.Add(6);
int expected = 6;
int actual = testList[5];
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_ToEmptyList_Items_WhatsInTheFourthIndex()
{
CustomList<int> testList = new CustomList<int>();
int expected = 11;
int actual;
testList.Add(2);
testList.Add(1);
testList.Add(3);
testList.Add(10);
testList.Add(11);
testList.Add(22);
testList.Add(33);
actual = testList[4];
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_AddItemToList_CountIncrements()
{
//arrange
CustomList<int> testList = new CustomList<int>();
int expected = 1;
int actual;
//act
testList.Add(234);
actual = testList.Count;
//assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_Mulitple_Numbers_ToList_GetCount()
{
// arrange
CustomList<int> testList = new CustomList<int>();
int expected = 2;
int actual;
// act
testList.Add(2);
testList.Add(3);
actual = testList.Count;
// assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_Ten_Numbers_ToList_GetCount()
{
// arrange
CustomList<int> testList = new CustomList<int>();
int expected = 10;
int actual;
// act
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList.Add(4);
testList.Add(5);
testList.Add(6);
testList.Add(7);
testList.Add(8);
testList.Add(9);
testList.Add(10);
actual = testList.Count;
// assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_Five_NumbersToList_GetCount()
{
// arrange
CustomList<int> testList = new CustomList<int>();
int expected = 5;
int actual;
// act
testList.Add(2);
testList.Add(3);
testList.Add(4);
testList.Add(5);
testList.Add(6);
actual = testList.Count;
// assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_Mulitple_Twelve_ToList_GetCount()
{
// arrange
CustomList<int> testList = new CustomList<int>();
int expected = 12;
int actual;
// act
testList.Add(2); testList.Add(6); testList.Add(6); testList.Add(6);
testList.Add(3); testList.Add(6); testList.Add(6); testList.Add(6);
testList.Add(4); testList.Add(6); testList.Add(6); testList.Add(6);
actual = testList.Count;
// assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Capacity_Full_So_AddToCapacity()
{
CustomList<int> testList = new CustomList<int>();
int expected = 8;
int actual;
//act
testList.Add(2);
testList.Add(4);
testList.Add(6);
testList.Add(8);
testList.Add(10);
actual = testList.Capacity;
//assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void MakingCapacity_ToSixteen()
{
CustomList<int> testList = new CustomList<int>();
int expected = 16;
int actual;
//act
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList.Add(4);
testList.Add(5);
testList.Add(6);
testList.Add(7);
testList.Add(8);
testList.Add(9);
actual = testList.Capacity;
//assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Capacity_Testing_MakingItThirty_Two()
{
CustomList<int> testList = new CustomList<int>();
int expected = 32;
int actual;
//act
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList.Add(4);
testList.Add(5);
testList.Add(6);
testList.Add(7);
testList.Add(8);
testList.Add(9);
testList.Add(10);
testList.Add(11);
testList.Add(12);
testList.Add(13);
testList.Add(14);
testList.Add(15);
testList.Add(16);
testList.Add(17);
actual = testList.Capacity;
//assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Removing_Object_FromArray()
{
//Arrange
CustomList<int> testList = new CustomList<int>();
int expected = 1;
int actual;
//Act
testList.Add(1);
testList.Add(2);
testList.Remove(1);
actual = testList.Count;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Removing_Muiltple_NumbersFromList()
{
//Arrange
CustomList<int> testList = new CustomList<int>();
int expected = 1;
int actual;
//Act
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList.Remove(1);
testList.Remove(2);
actual = testList.Count;
//Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Make_ListInto_String()
{
//Arrange
CustomList<int> testList = new CustomList<int>();
string expected = "[1, 3, 5]";
//Act
testList.Add(1);
testList.Add(3);
testList.Add(5);
string actual = testList.ToString();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Add_ThreeNumbers_And_MakeIntoAString()
{
CustomList<int> testList = new CustomList<int>();
string expected = "[1, 4, 6, 5, 4, 6]";
testList.Add(1);
testList.Add(4);
testList.Add(6);
testList.Add(5);
testList.Add(4);
testList.Add(6);
string actual = testList.ToString();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void AddToList_RemoveFromList_MakeIntoAString()
{
CustomList<int> testList = new CustomList<int>();
string expected = "[10, 12, 30]";
testList.Add(10);
testList.Add(12);
testList.Add(30);
testList.Add(5);
testList.Add(6);
testList.Remove(5);
testList.Remove(6);
string actual = testList.ToString();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Adding_strings_IntoList()
{
CustomList<string> testList = new CustomList<string>();
string expected = "[S, A, V, E, , F, E, R, R, I, S]";
testList.Add("S");
testList.Add("A");
testList.Add("V");
testList.Add("E");
testList.Add(" ");
testList.Add("F");
testList.Add("E");
testList.Add("R");
testList.Add("R");
testList.Add("I");
testList.Add("S");
string actual = testList.ToString();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ZipTwoClass_Instances_Together()
{
CustomList<int> odd = new CustomList<int>() { 1, 3, 5 };
CustomList<int> even = new CustomList<int>() { 2, 4, 6 };
CustomList<int> expected = new CustomList<int>() { 1, 2, 3, 4, 5, 6 };
odd.Remove(3);
odd.Remove(5);
even.Remove(2);
even.Remove(4);
even.Remove(6);
odd.Add(2);
odd.Add(3);
even.Add(4);
even.Add(5);
even.Add(6);
CustomList<int> actual = odd + even;
for (int i = 0; i < expected.Count; i++)
Assert.AreEqual(expected[i], actual[i]);
}
[TestMethod]
public void Adding_TwoList()
{
CustomList<int> testList = new CustomList<int>();
CustomList<int> testList2 = new CustomList<int>();
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList2.Add(4);
testList2.Add(5);
testList2.Add(6);
CustomList<int> actual = testList + testList2;
CustomList<int> expected = new CustomList<int>();
expected.Add(1);
expected.Add(2);
expected.Add(3);
expected.Add(4);
expected.Add(5);
expected.Add(6);
for(int i = 0; i < expected.Count; i++)
Assert.AreEqual(expected[i], actual[i]);
}
[TestMethod]
public void Removing_FromTwoList()
{
CustomList<int> testList = new CustomList<int>();
CustomList<int> testList2 = new CustomList<int>();
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList2.Add(4);
testList2.Add(5);
testList2.Add(6);
testList.Remove(1);
testList.Remove(2);
testList2.Remove(4);
testList2.Remove(6);
CustomList<int> actual = testList - testList2;
CustomList<int> expected = new CustomList<int>();
expected.Add(3);
expected.Add(5);
for (int i = 0; i < expected.Count; i++)
Assert.AreEqual(expected[i], actual[i]);
}
[TestMethod]
public void OverLoad_Operator_AddTwo_Instances()
{
CustomList<int> one = new CustomList<int>() { 1, 3, 5 };
CustomList<int> two = new CustomList<int>() { 2, 4, 6 };
CustomList<int> expected = new CustomList<int> { 1, 3, 5, 2, 4, 6 };
CustomList<int> actual;
actual = one + two;
for(int i = 0;i < expected.Count; i++)
Assert.AreEqual(expected[i], actual[i]);
}
[TestMethod]
public void Overload_Operator_AddTwoIntances_ThatHaveSix_Integers()
{
CustomList<int> one = new CustomList<int>() { 1, 3, 5, 4, 3, 2 };
CustomList<int> two = new CustomList<int>() { 2, 4, 6, 4, 3, 2 };
CustomList<int> expected = new CustomList<int> { 1, 3, 5, 4, 3, 2, 2, 4, 6, 4, 3, 2 };
CustomList<int> actual;
actual = one + two;
for (int i = 0; i < expected.Count; i++)
Assert.AreEqual(expected[i], actual[i]);
}
[TestMethod]
public void Overload_Operator_That_SubtractsOne_Instance()
{
CustomList<int> one = new CustomList<int>() { 1, 3, 5 };
CustomList<int> two = new CustomList<int>() { 2, 1, 6 };
CustomList<int> expected = new CustomList<int> { 3, 5 };
CustomList<int> actual;
one.Remove(1);
two.Remove(2);
two.Remove(1);
two.Remove(6);
actual = one - two;
for(int i = 0; i < expected.Count; i++)
Assert.AreEqual(expected[i], actual[i]);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Employee
{
// member variables
// constructor
public Employee()
{
}
// member methods
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Restaurant
{
// member variables (HAS A)
public string name;
public List<string> foodOptions;
public List<Employee> staffMembers;
// constructor (SPAWNER)
public Restaurant(string name)
{
this.name = name;
foodOptions = new List<string>();
staffMembers = new List<Employee>();
}
// member methods (CAN DO)
public void ChangeName()
{
Console.WriteLine("What would you like to change the name to?");
string newName = Console.ReadLine();
name = newName;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Sandbox
{
public class CustomList<T> : IEnumerable
{
private T[] items;
public int Size { get; private set; }
private int count;
private int word;
public int Word
{
get { return word; }
set { count = value; }
}
public int Count
{
get { return count; }
// set { value = count; }
}
private int capacity;
public int Capacity
{
get { return capacity; }
set { capacity = value; }
}
public T this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
public CustomList()
{
items = new T[4];
count = 0;
capacity = 4;
}
public void Add(T itemToAdd)
{
if (capacity == count)
{
capacity = (2 * capacity);
T[] newItems = new T[capacity];
for (int i = 0; i < count; i++)
{
newItems[i] = items[i];
}
items = newItems;
}
items[count] = itemToAdd;
count += 1;
}
public void Remove(T itemToRemove)
{
for (int i = 0; i < count; i++)
{
if (itemToRemove.Equals(items[i]))
{
count -= 1;
for (int j = i; j < (count + 1); j++)
{
items[j] = items[j + 1];
}
}
else
{
items[i] = items[i];
}
}
}
public override string ToString()
{
string itemsWord = "[";
for (int i = 0; i < count; i++)
{
string word = items[i].ToString();
if (i == count - 1)
{
itemsWord += word + "]";
break;
}
itemsWord += word + ", ";
}
return itemsWord;
}
public static CustomList<T> operator +(CustomList<T> firstList, CustomList<T> secondList)
{
CustomList<T> item = new CustomList<T>();
for (int i = 0; i < firstList.count; i++)
{
item.Add(firstList[i]);
}
for (int j = 0; j < secondList.count; j++)
{
item.Add(secondList[j]);
}
return item;
}
public static CustomList<T> operator -(CustomList<T> firstList, CustomList<T> secondList)
{
CustomList<T> item = new CustomList<T>();
for (int i = 0; i < firstList.count; i++)
{
item.Add(firstList[i]);
}
for (int j = 0; j < secondList.count; j++)
{
item.Add(secondList[j]);
}
return item;
}
public IEnumerator GetEnumerator()
{
for(int i = 0; i < items.Length; i++)
{
yield return items[i];
}
}
}
}
|
c7e688e85546703a5c75c9279f9140ca09435e31
|
[
"C#"
] | 7
|
C#
|
krntranslation/UserStoryTest
|
4a9171511a89698dcc12e5fd5106d7d17c583e03
|
8df898e85142d594f23c1fe7bfcd31f0cbddaa6a
|
refs/heads/master
|
<repo_name>lazargal/maman-13<file_sep>/Maman13Q1/src/MenuFileReader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class MenuFileReader
{
private ArrayList<MenuItem> m_menuItmeArray = new ArrayList<MenuItem>();
public MenuFileReader(String strFilePath) throws FileNotFoundException, IllegalFileFormat
{
strFilePath.trim();
Scanner inputFile = new Scanner(new File(strFilePath));
readFileData(inputFile);
inputFile.close();
}
private void readFileData(Scanner inputFile) throws IllegalFileFormat
{
String strTempItemName;
float fTempItemPrice = 0;
String strTemp;
int nLineNumber = 0;
MenuItem.ItemType tempType = MenuItem.ItemType.APPETIZER;
while(inputFile.hasNext())
{
strTempItemName = inputFile.nextLine();
nLineNumber++;
strTempItemName.trim();
if(strTempItemName.isEmpty() )
throw new IllegalFileFormat("item name may not be empty. Line number = " + nLineNumber);
if(!inputFile.hasNext())
throw new IllegalFileFormat("next line is not compatible with the wanted file format . Last line number = " + nLineNumber);
strTemp = inputFile.nextLine();
nLineNumber++;
strTemp.trim();
if(strTemp.isEmpty() )
throw new IllegalFileFormat("item type may not be empty. Line number = " + nLineNumber);
if(!inputFile.hasNextFloat())
throw new IllegalFileFormat("next line is not compatible with the wanted file format . Last line number = " + nLineNumber);
switch(strTemp)
{
case"APPETIZER":
tempType = MenuItem.ItemType.APPETIZER;
break;
case"MAIN":
tempType = MenuItem.ItemType.MAIN;
break;
case"DESSERT":
tempType = MenuItem.ItemType.DESSERT;
break;
case"DRINK":
tempType = MenuItem.ItemType.DRINK;
break;
}
fTempItemPrice = inputFile.nextFloat();
if(inputFile.hasNextLine())
inputFile.nextLine();
nLineNumber++;
m_menuItmeArray.add(new MenuItem(strTempItemName, tempType, fTempItemPrice));
}
}
@SuppressWarnings("unchecked")
public ArrayList<MenuItem> getMenuItemArray()
{
ArrayList<MenuItem> res = (ArrayList<MenuItem>) m_menuItmeArray.clone();
return res;
}
}
<file_sep>/README.md
# maman-13
<file_sep>/Maman13Q1/src/MenuPanel.java
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Formatter;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
public class MenuPanel extends JPanel implements ActionListener
{
private ArrayList<MenuItem> m_menuList = null;
private ArrayList<MenuPanelItem> m_menuItemList = new ArrayList<MenuPanelItem>();
private int m_nNumOfMenuTypes = MenuItem.ItemType.values().length;
private boolean[] m_bItemTypesArray = new boolean[m_nNumOfMenuTypes];
@SuppressWarnings("unchecked")
public MenuPanel(ArrayList<MenuItem> menuList)
{
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS) );
setAlignmentX(Component.LEFT_ALIGNMENT);
m_menuList = (ArrayList<MenuItem>) menuList.clone();
for(MenuItem tempMenuItem : m_menuList)
{
if(!m_bItemTypesArray[tempMenuItem.getItemType().getPos()])
{
add(new JLabel(tempMenuItem.getItemType().toString()));
m_bItemTypesArray[tempMenuItem.getItemType().getPos()] = true;
}
MenuPanelItem tempMenuPanelItem = new MenuPanelItem(tempMenuItem);
m_menuItemList.add(tempMenuPanelItem);
tempMenuPanelItem.setLayout(new FlowLayout(FlowLayout.LEFT));
tempMenuPanelItem.setAlignmentX(Component.LEFT_ALIGNMENT);
add(tempMenuPanelItem);
}
}
public void resetMenuState()
{
for(MenuPanelItem tempMenuItem : m_menuItemList)
{
tempMenuItem.resetContent();
}
}
public float getTotalOrderPrice()
{
float fTemp = 0;
for(MenuPanelItem tempMenuItem : m_menuItemList)
{
fTemp += tempMenuItem.getTotalPrice();
}
return fTemp;
}
@Override
public void actionPerformed(ActionEvent event)
{
StringBuilder myBuilder = new StringBuilder();
for(MenuPanelItem tempMenuItem : m_menuItemList)
{
if(tempMenuItem.getIsChecked())
myBuilder.append(tempMenuItem.toString() + "\r\n");
}
myBuilder.append("Total order cost = " + getTotalOrderPrice());
Object[] options = {"Confirm" , "Update" , "Cancel"};
int nSelection = JOptionPane.showOptionDialog(this, myBuilder.toString(), "Confirm Order", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
switch(nSelection)
{
case JOptionPane.YES_OPTION:
saveOrderToFile(myBuilder.toString());
resetMenuState();
break;
case JOptionPane.NO_OPTION:
// do nothing for now
break;
case JOptionPane.CANCEL_OPTION:
resetMenuState();
break;
}
}
public void saveOrderToFile(String orderInfo)
{
String strUserInput = JOptionPane.showInputDialog("Enter name and ID");
if(strUserInput == null)
return;
strUserInput.trim();
if(strUserInput.isEmpty())
return;
try
{
strUserInput += ".txt";
Formatter output = new Formatter(strUserInput);
output.format(orderInfo, (Object[]) null);
output.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
<file_sep>/Maman13Q1/src/MenuPanelItem.java
import java.awt.Checkbox;
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MenuPanelItem extends JPanel
{
private Integer[] m_comboOption = {1,2,3,4,5,6,7,8,9,10};
private MenuItem m_myMenuItem = null;
private Checkbox m_chekBox = new Checkbox();
private JComboBox m_comboBox = new JComboBox(m_comboOption);
public MenuPanelItem(MenuItem menuItem)
{
super();
try
{
m_myMenuItem = (MenuItem)menuItem.clone();
}
catch (CloneNotSupportedException e)
{
m_myMenuItem = new MenuItem("Empty Menu Item" , MenuItem.ItemType.APPETIZER , 0);
e.printStackTrace();
}
add(m_chekBox);
add(new JLabel(m_myMenuItem.toString()));
add(m_comboBox);
}
public void resetContent()
{
m_chekBox.setState(false);
m_comboBox.setSelectedIndex(0);
}
public boolean getIsChecked()
{
return m_chekBox.getState();
}
public int getComboSelectionIndex()
{
return m_comboBox.getSelectedIndex();
}
public float getTotalPrice()
{
float fTemp;
if(getIsChecked())
fTemp = (getComboSelectionIndex()+1) * m_myMenuItem.getItemPrice();
else
fTemp = 0;
return fTemp;
}
@Override
public String toString()
{
String strRes;
if(getIsChecked())
{
strRes = m_myMenuItem.toString() + " X " + (getComboSelectionIndex()+1) + " = " + getTotalPrice();
}
else
strRes = "Item not Selected";
return strRes;
}
}
|
c03dc8f3857c3ebfa3448aa20f6794cd3fd40e93
|
[
"Markdown",
"Java"
] | 4
|
Java
|
lazargal/maman-13
|
b1929829d3ba820009c5f00f42e52b180c2acaa3
|
a55a904c41e067e0fc304098c5ec1c8c2f90ec56
|
refs/heads/master
|
<repo_name>Skill-Zozo/AmazonCHALLENGE<file_sep>/Host.java
/* Author: <NAME>
* Date: 15/10/2014
* Description: Object class to keep the host details
*/
public class Host
{
private String id;
private InstanceType type;
private int totalSlot;
private int emptySlot;
private int usedSlot;
private int i = 0;
public Host(String id, InstanceType type, int n) {
this.id = id;
this.type = type;
totalSlot = n;
usedSlot = 0;
emptySlot = 0;
}
public String getID() {
return id;
}
public void addEmptySlot() {
emptySlot++;
i++;
if(emptySlot==totalSlot) type.hostIsEmpty();
else if(i==totalSlot) type.countAsMostFilled(emptySlot);
}
public void addUsedSlot() {
usedSlot++;
i++;
if(usedSlot==totalSlot) type.hostIsFull();
else if(i==totalSlot) type.countAsMostFilled(emptySlot);
}
}
|
1305d79c5f2f2ad2bebe315b0e7e953604c91f61
|
[
"Java"
] | 1
|
Java
|
Skill-Zozo/AmazonCHALLENGE
|
b2a6cda3cac1cea3163d65f566f08ee56dd93f2c
|
6120d81953478eb3d963f41c0ad6c54645a394a3
|
refs/heads/master
|
<repo_name>swcunba/Algorithms<file_sep>/2839(3&5_미완).cpp
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
int N, sack;
cin >> N;
if (N % 5 == 0)
{
sack = N / 5;
printf("%d", sack);
}
if (N % 5 == 1)
{
if (N != 1)
{
sack = N / 5 + 1;
printf("%d", sack);
}
else if (N == 1)
{
sack = -1;
printf("%d", sack);
}
}
if (N % 5 == 2)
{
if (N != 2 || N != 7)
{
sack = N / 5 + 2;
printf("%d", sack);
}
else if (N == 2 || N==7)
{
sack = -1;
printf("%d", sack);
}
}
if (N % 5 == 3)
{
sack = N / 5 + 1;
printf("%d", sack);
}
if (N % 5 == 4)
{
if (N != 4)
{
sack = N / 5 + 2;
printf("%d", sack);
}
else if (N == 4)
{
sack = -1;
printf("%d", sack);
}
}
return 0;
}<file_sep>/Greedy/1700(멀티탭_이해못함).cpp
/*n개 공간, k번 사용, 전기용품 이름이 숫자로 주어짐
플러그를 최소한으로 뽑는 횟수
처음 n개 만큼의 전기용품이 꽂힌 채로 시작해야함.
최소한으로 뽑으려면 나중에 또 쓰일 전기용품을 뽑지 말아야함
*/
#include <iostream>
using namespace std;
int tools[100];
int plugged[100];//꽂혀있는 전기용품
int main(void) {
int n, k;
cin >> n >> k;
for (int i = 0; i < k; i++) {
cin >> tools[i];
}
int result = 0;
for (int i = 0; i < k; i++) {
bool plug = false;
for (int j = 0; j < n; j++)
if (plugged[j] == tools[i]) {
plug = true;//꽂혀있으면 true
break;
}
if (plug) continue;//꽂혀있으면 패스
for (int j = 0; j < n; j++) {
if (!plugged[j]) {//빈 값(구멍)있다면
plugged[j] = tools[i];//다음 기기 꽂아주고
plug = true;
break;
}
//가장 나중 혹은 사용되지 않는 기기 찾기
int idx, deviceidx = -1;
for (int j = 0; j < n; j++) {
int lastidx = 0;
for (int K = i + 1; K < k; K++) {
if (plugged[j] == tools[K]) break;
lastidx++;
}
if (lastidx > deviceidx) {
idx = j;
deviceidx = lastidx;
}
}
result++;
plugged[idx] = tools[i];//기기 바꿔 꽂음
}
}
cout << result << '\n';
return 0;
}<file_sep>/수학/11720(숫자의 합).py
n = int(input())
num_list = []
num = input(str())
for i in range(0, n):
num_list.append(int(num[i]))
result = 0
for i in range(0, n):
result += int(num_list[i])
print(result)
<file_sep>/Greedy/1700(멀티탭).cpp
/*n개 공간, k번 사용, 전기용품 이름이 숫자로 주어짐
플러그를 최소한으로 뽑는 횟수
처음 n개 만큼의 전기용품이 꽂힌 채로 시작해야함.
최소한으로 뽑으려면 나중에 또 쓰일 전기용품을 뽑지 말아야함
*/
#include <iostream>
using namespace std;
int tools[100];
int plugged[100];//꽂혀있는 전기용품
int main(void) {
int n, k;
cin >> n >> k;
for (int i = 0; i < k; i++) {
cin >> tools[i];
}
for (int i = 0; i < n; i++) {
plugged[i] = tools[i];//처음에 꽂혀있는 기구
}
int result = 0, count = 0;
//뒤에 또 쓰이는 애들을 어떻게 골라낼까, 원소 개수 카운트?
//뽑는 횟수 = k - n - 처음부터 꽂은거 중에서 쓰는 기구 개수
for (int i = 0; i < n; i++) {
for (int j = n; j < k; j++) {
if (tools[j] == plugged[i]) count++;
}
}
result = k - n - count;
cout << result;
return 0;
}<file_sep>/수학/2739(반복문 기초).py
#!/usr/bin/env python
# coding: utf-8
# In[10]:
N = int(input(""))
# In[14]:
for i in range (1, 10): ##끝부분 숫자 -1만큼 i값 들어감
print(N, "*", i, "=", N*i)
# In[ ]:
<file_sep>/Greedy/1946(신입사원).cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//유의사항: 성적이 아니라 순위이다.
vector<pair <int, int> > score;
int main(void) {
int n, t;
cin >> t;
for (int i = 0; i < t; i++) {//테스트 케이스만큼 반복
cin >> n;
score.clear();//초기화
int x, y;
for (int j = 0; j < n; j++) {
cin >> x >> y;
score.push_back(make_pair(x, y));//페어 자료형에 각 전형 점수 입력받음
}
sort(score.begin(), score.end());//서류 오름차순 정렬
int temp = score[0].second, result = 1;//서류 1등 면접 등수, 서류 1등은 무조건 합격이라 1로 시작.
for (int j = 0; j < n; j++) {
//서류 1등은 무조건 합격
//서류 2등은 서류 1등보다 면접 등수 높아야함
//서류 3등은 서류 2등보다 면접 등수 높아야함...과정 반복
if (temp > score[j].second) {//서류 1등 면접 등수보다 높다면,
temp = score[j].second;//결과값에 1을 추가하고, 합격할 수 있는 면접 등수 기준 갱신.
result += 1;
}
}
cout << result << "\n";
}
return 0;
}
<file_sep>/수학/5554(심부름).cpp
#include <iostream>
int main(void){
int sec[4];
int sec_sum = 0;
for(int i = 0; i < 4; i++){
scanf("%d", &sec[i]);
sec_sum += sec[i];
}
int minute = sec_sum / 60;
int second = sec_sum % 60;
printf("%d\n%d\n", minute, second);
return 0;
}
<file_sep>/2292(벌집).cpp
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
int range = 1, barrier = 1, tmp = 1, N;
cin >> N;
while (1) {
if (range >= N)
break;
tmp = 6 * (barrier++); //방 개수가 6의 배수로 늘어나므로 더해줄 변수를 이렇게 설정함.
range += tmp;
}//range(숫자 범위)가 N을 넘지 않는 선에서
//숫자를 6의 배수만큼 계속 늘려줌.
//barrier(겹겹이 쌓인 층 개수)가 곧 답임.
cout << barrier;
return 0;
}<file_sep>/그래프 탐색/1260(DFS&BFS구현).cpp
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int c[10000];//방문한 노드 컨테이너(dfs)
int d[10000]; //방문한 노드 컨테이너(bfs)
vector<int> a[10000];//정점 그래프 담을 컨테이너
vector<int> b[10000];
queue<int> q;
void dfs(int x) {
if (c[x]) return;//방문한 노드라면 함수를 끝내버림
c[x] = true;
cout << x << ' ';
for (int i = 0; i < a[x].size(); i++) {
int y = a[x][i];//인접 노드 하나씩 방문, 벡터 배열 안에는 여러 개의 값 들어감(예를 들어 a[1]에는 연결된 정점 2, 3 등이 들어갈 수 있음)
dfs(y);//재귀함수가 스택 구조로 구현되므로(인접 노드인 y가 다시 dfs 함수에 인수로 들어가 방문한 노드들의 배열인 c에 들어가는 과정 반복)
}
}
void bfs(int start) {//큐에서 하나의 노드 꺼내고, 꺼낸 노드와 인접한 노드 중 방문하지 않은 노드를 방문한 뒤 큐에 삽입. 그리고 다시 큐에서 노드 꺼내는 과정 반복
q.push(start);//시작점을 인수로 받고 방문한 노드 배열에 삽입
d[start] = true;//시작점은 방문한 것으로 시작
while (!q.empty()) {//큐가 빌 때까지
int x = q.front();//큐에서 가장 위에 있는 노드 꺼냄
q.pop();
cout << x << ' ';
for (int i = 0; i < a[x].size(); i++) {
int y = a[x][i];//인접한 노드들 방문
if (!d[y]) {//방문 상태가 아니라면
q.push(y);//큐에 담아줌
d[y] = true;//담아준 뒤엔 방문한 것으로 처리
}
}
}
}
int main(void) {
int n, m, v;//간선 개수와 시작할 정점
cin >> n >> m >> v;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
a[x].push_back(y);
a[y].push_back(x);
b[x].push_back(y);
b[y].push_back(x);
sort(a[x].begin(), a[x].end());
sort(b[x].begin(), b[x].end());
sort(a[y].begin(), a[y].end());
sort(b[y].begin(), b[y].end());//인접한 노드 중 가까운 정점 먼저 방문하게
//하기 위해서 오름차순 정렬시킴
}
dfs(v);//1이라는 노드에서부터 탐색 시작
cout << '\n';
bfs(v);
return 0;
}<file_sep>/기능개발(큐).cpp
#include <string>
#include <vector>
#include <queue>
using namespace std;
vector<int> solution(vector<int> progresses, vector<int> speeds) {
vector<int> answer;
queue<int> q;
for(int i = 0; i < progresses.size(); i++){
int remain;
if((100 - progresses[i]) % speeds[i] != 0){
remain = (100 - progresses[i]) / speeds[i] + 1;
}
else remain = (100 - progresses[i]) / speeds[i];
q.push(remain);
}
int cnt = 0;
int cur = q.front();
while(!q.empty()){
q.pop();
cnt++;
if(cur < q.front() || q.empty()){
//앞 작업 완성시기가 뒷 작업보다 빠른 경우 다른 날 배포.
//(answer 배열에 값을 넣어주고 기준이 되는 완성시간 교체)
//(answer[100]과 같이 메모리 직접 할당한 배열 아니라 인덱스 접근 x)
answer.push_back(cnt);
cnt = 0;
cur = q.front();
}
}
return answer;
}
<file_sep>/1010(다리놓기_조합).py
from math import factorial
t = int(input())
for i in range(0, t):
n, m = map(int, input().split())
result = factorial(m)/(factorial(n)*factorial(m-n))
print(int(result))
<file_sep>/디스크 컨트롤러(우선순위 큐 구조체 활용).cpp
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
//연산자 오버로딩
//오버로딩이란 같은 일을 처리하는 함수, 연산자 등의 매개변수의 형식을 조금씩 달리하여,
//하나의 이름으로 작성할 수 있게 해주는 것
struct cmp {
bool operator()(vector<int> a, vector<int> b) {
return a.at(1) > b.at(1);
//at()은 배열 범위 벗어나면 예외 던져줌. 최소힙 만들기 위한 연산자 클래스.
}
};
int solution(vector<vector<int>> jobs) {
int answer = 0, idx = 0, t = 0;
priority_queue<vector<int>, vector<vector<int>>, cmp> pq; //cmp를 통해 두번째 원소 기준으로 최소힙 형성.
sort(jobs.begin(), jobs.end());//요청시점 기준 오름차순 정렬.
while(idx < jobs.size() || !pq.empty()){
if (jobs.size() > idx && t >= jobs[idx][0]) {
//작업 남아있고 요청시점이 지나있다면 최소힙에 작업 추가.
pq.push(jobs[idx++]);
continue;
}
if (!pq.empty()) {
//대기 중인 작업이 있는 경우.
t += pq.top()[1];//현재 작업 완료시점으로 이동(작업시간만큼 추가).
answer += t - pq.top()[0];//완료시점 - 요청시점 더해서 대기시간 반영.
pq.pop();//작업 완료.
}
else //큐가 비어있다면 다음작업 시간으로 넘김
t = jobs[idx][0];
}
answer /= jobs.size();
return answer;
}
<file_sep>/가장 큰 수(문자열 정렬).py
def solution(numbers):
answer = ''
#맨 앞자릿수가 큰 수를 앞으로 보낸다.
#문자열은 앞 자릿수를 기준으로 정렬한다. 그 다음으로는 길이 기준.
#오름차순이면 앞 자릿수 작은게 앞으로, 앞 자릿수 같으면 바로 뒷자리 수가 더 작거나 길이 짧은게 앞으로.
#내림차순이면 앞 자릿수 큰게 앞으로, 앞 자릿수 같으면 바로 뒷자리 수 더 큰거
#30, 3 있으면 30이 뒤로 가야함. 그대로 두면 30이 앞으로 오지만 문자열 곱셈 통해 303030 333와 같이 되면 333이 앞으로 옴.
#최대 4자리. 문자열 4번 곱해주면 앞 자릿수로만 비교 가능
numbers = sorted(list(map(str, numbers)), key = lambda x : x*3, reverse = True)
return str(int(''.join(numbers)))
<file_sep>/그래프 탐색/1916(최소비용_다익스트라).cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int number = 6;
int INF = 1000000000;
int n, m;
vector < pair<int, int> > tree[1001];//간선 정보, a[시작 정점](인접 정점, 비용)
int d[1001]; //최소 비용 정보 담을 배열
void dijkstra(int start) {
d[start] = 0; //자기 자신으로 가는 비용은 0
priority_queue<pair<int, int> > pq;//우선 순위 큐 사용해서 힙 형성(최대힙, 큰 값을 기준으로 최상단 노드 형성)
pq.push(make_pair(start, 0));//시작 정점, 비용 큐에 삽입
while (!pq.empty()) {
int current = pq.top().first;//현재 노드를 큐의 최상단 노드라고 설정
int distance = -pq.top().second;//작은 값이 최상단에 오도록 음수화했었으므로 다시 -붙여줌.
//printf("current = %d", current);
pq.pop();//큐에서 최상단 꺼냄
if (d[current] < distance) continue;//최단 거리 아닌 경우 스킵
for (int i = 0; i < tree[current].size(); i++) {//인접 노드 하나씩 확인
//선택된 노드의 인접 노드
int next = tree[current][i].first;
//printf("next = %d ", next);
//선택된 노드 거쳐서 인접 노드로 가는 총 비용(선택된 노드까지 드는 최소 비용 + 인접된 노드까지 가는 비용)
int nextDistance = distance + tree[current][i].second;
//기존 최소 비용보다 값이 더 작다면 최솟값을 교체
if (nextDistance < d[next]) {
d[next] = nextDistance;
pq.push(make_pair(next, -nextDistance));//작은 값 우선되도록 음수화
}
}
}
}
int main(void){
scanf("%d", &n);
scanf("%d", &m);
for(int i = 1; i <= n; i++){
d[i] = INF;
}
for(int i = 0; i < m; i++){
int s, d, c;
scanf("%d %d %d", &s, &d, &c);
tree[s].push_back(make_pair(d, c));
}
int start, destination;
scanf("%d %d", &start, &destination);
dijkstra(start);
printf("%d\n", d[destination]);
return 0;
}
<file_sep>/그래프 탐색/2178(미로 탐색).cpp
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
int row, col;
bool map[100][100];//0과 1.
int check[100][100];//지나온 길(거쳐간 경로의 수) 기록할 배열.
int move[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};//움직이는 경우의 수(위, 아래, 오른쪽, 왼쪽).
bool isInMap(int y, int x){//미로 안에 있는 값인지 판단해주는 함수.
return (y >= 0 && y < row) && (x >= 0 && x < col);
}
int bfs(){
queue<pair<int, int> >q;//큐 선언.
int current_x = 0, current_y = 0;//시작점 설정.
q.push(pair<int, int>(current_y, current_x));//시작점 큐에 삽입.
check[current_y][current_x] = 1;//시작점 방문 처리(1로 시작함).
while(!q.empty()){
current_y = q.front().first;
current_x = q.front().second;//직교 좌표에 빗대어 위치 표현.
q.pop();
if(current_y == row - 1 && current_x == col - 1) break;//도착하면 반복 중단.
for(int i = 0; i < 4; i++){
int next_x = current_x + move[i][1];
int next_y = current_y + move[i][0];//다음 위치 탐색.
if(isInMap(next_y, next_x) && check[next_y][next_x] == 0 && map[next_y][next_x]){//미로 안에 있는 지점이며, 방문한 적 없고 1인 구역이라면,
check[next_y][next_x] = check[current_y][current_x] + 1;//방문 표시.
q.push(pair<int, int>(next_y, next_x));//방문한 곳 큐에 삽입.
}
}
}
return check[row-1][col-1];
}
int main(void){
scanf("%d %d", &row, &col);
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
int value;
scanf("%1d", &value);
if(value == 1) map[i][j] = true;//값이 1이면 true표시해둠.
}
}
printf("%d\n", bfs());
return 0;
}
<file_sep>/10773(제로_스택 이용).cpp
#include <stdio.h>
#include <vector>
#include <stack>
using namespace std;
stack <int> s;
int main(void){
int k, result = 0;
scanf("%d", &k);
for(int i = 0; i < k; i++){
int x;
scanf("%d", &x);
if(x == 0) s.pop();
else s.push(x);
}
while(!s.empty()){
result += s.top();
s.pop();
}
printf("%d\n", result);
return 0;
}
<file_sep>/우선순위 큐 활용_라면공장.cpp
#include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(int stock, vector<int> dates, vector<int> supplies, int k) {
int answer = 0;
priority_queue<int> q;
int idx = 0;
for(int i = 0; i < k; i++){//i: 현재 시점.
if(i == dates[idx]){//날짜는 오름차순으로 주어짐. 현시점과 일치하는 공급일 있다면,
q.push(supplies[idx]);//우선순위 큐에 해당 일자 공급량 삽입.
idx++;
}
if(stock == 0){
stock += q.top();
q.pop();
answer++;
}
stock--;
}
return answer;
}
<file_sep>/Greedy/2828(사과담기).cpp
/*N칸의 공간, M칸의 바구니, j개의 사과
최소한의 움직임으로 사과를 바구니에 넣으려면 바구니의 끝부분이
사과가 떨어지는 위치에 오게 하면 된다.
바구니의 끝부분만 저장*/
#include <iostream>
using namespace std;
int apple[21];
int basket[2];
int main(void) {
int N, M, j, i, distance = 0;
cin >> N >> M;//공간 크기, 바구니 크기
cin >> j;//사과 개수
for (i = 0; i < j; i++) {
cin >> apple[i];//사과 낙하위치
}
//바구니의 범위
basket[0] = 1;//바구니 왼쪽 끝
basket[1] = M;//바구니 오른쪽 끝
for (i = 0; i < j; i++) {
int move = 0;
if (apple[i] > basket[1]) {//오른쪽 끝보다 더 오른쪽이면
distance += (apple[i] - basket[1]);
basket[0] += (apple[i] - basket[1]);
basket[1] += (apple[i] - basket[1]);
move += 1;
//cout << distance << endl;
}
else if (apple[i] < basket[0] && move == 0) {//왼쪽 끝보다 더 왼쪽이면
distance += (basket[0] - apple[i]);
basket[1] -= (basket[0] - apple[i]);
basket[0] -= (basket[0] - apple[i]);
//cout << distance << endl;
}
else if(apple[i] == basket[0] || apple[i] == basket[1] && move == 0){
//cout << distance << endl;
continue;
}
}
cout << distance;
return 0;
}<file_sep>/DP/1003(피보나치_함수).cpp
//0과 1이 나오는 횟수 카운트하면 된다.
//하향식?
#include <iostream>
int result_0[41];
int result_1[41];
int n;
void dp(int k){
if(k > n) return;
result_0[k] = result_0[k-1] + result_0[k-2];
result_1[k] = result_1[k-1] + result_1[k-2];
dp(k+1);
}
int main(void){
int t;
result_0[0] = 1;
result_0[1] = 0;
result_0[2] = 1;
result_1[0] = 0;
result_1[1] = 1;
result_1[2] = 1;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
if(n > 2){
dp(2);
}
printf("%d %d\n", result_0[n], result_1[n]);
}
return 0;
}
<file_sep>/Greedy/1781(컵라면).cpp
/*
Milk Scheduling 문제와 동일한 조건
목표값도 동일. 같은 알고리즘 사용 가능할듯 -> 시간 초과.
*/
#include <iostream>
#include <queue>
using namespace std;
int n, result = 0;
bool schedule[200001] = { false, };
priority_queue<pair<int, int> >q;
int scheduling(){
while(!q.empty()){
int ramyeon = q.top().first;
int time_limit = -q.top().second;
q.pop();
if(schedule[time_limit]){//이미 풀 문제가 정해진 시점이면,
for(int i = time_limit-1; i > 0; i--){
if(!schedule[i]){//해당 작업 데드라인 이전 시점 중 가장 늦은 시점에 배치.
schedule[i] = true;
result += ramyeon;
break;
}
}
}
else{
schedule[time_limit] = true;
result += ramyeon;
}
}
return result;
}
int main(void){
scanf("%d", &n);
for(int i = 0; i < n; i++){
int deadline, reward;
scanf("%d %d", &deadline, &reward);
q.push(pair<int, int>(reward, -deadline));//데드라인도 빠른 순으로 정렬해야 시간초과 x.
}
printf("%d\n", scheduling());
return 0;
}
<file_sep>/2675(문자열 반복).py
t = int(input())
while(t):
reps, s = input().split()
txt = ''
for i in s:
txt += int(reps)*i
print(txt)
t -= 1
<file_sep>/11052(카드 구매).cpp
/*
1. n의 약수 카드팩 사는 경우.(i * n/i)
2. i번째 + n-i번쨰 카드팩 사는 경우.(인덱스 합 n)
3. 1과 나머지 카드 수 채우는 카드팩 섞어사는 경우
*/
#include <iostream>
#include <algorithm>
#define MAX 1001
using namespace std;
int cardpacks[MAX];
int price[MAX];
int main(void){
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%d", &cardpacks[i]);
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
price[i] = max(price[i], price[i-j] + cardpacks[j]);//인덱스의 합 i되는 모든 경우 탐색.
}
}
printf("%d\n", price[n]);
return 0;
}
<file_sep>/DP/2579(계단 오르기_dp).cpp
/*
계단마다 점수가 있고, 계단은 연속해서 3개를 오르거나, 3칸 이상 건너뛸 수 없음.
마지막 계단은 꼭 밟아야 함.
n개의 계단(300이하의 자연수)
계단의 각 점수는 10,000이하 자연수.
점수의 최댓값 산출.
마지막 칸을 꼭 밟아야하니 마지막 칸에서부터 수식을 완성해보자.
문제의 예제를 기준으로 생각해보면,
마지막 층에서의 선택지는 10 혹은 25이다.
10을 선택하면 15와 20을 선택하거나 15와 10을 선택해야한다.
각 45와 35이다. 시작값인 20을 포함하면 65, 55.
25를 선택하면 15와 10을 선택하거나 20과 10을 선택해야한다.
각 50과 55이다. 시작값인 20을 포함하면 70, 75.
따라서 최댓값인 75이다.
경우의 수를 꼭대기 계단(n번째 계단)에서부터 크게 나눠서 보자면 n-1번째 계단을 선택하는 경우와 n-2번째 계단을 선택하는 경우로 나눠볼 수 있다.
*/
#include <stdio.h>
#include <iostream>
#include <algorithm>
#define MAX 10001
using namespace std;
int stairs[MAX];//계단 점수 정보.
int values[MAX];//인덱스가 계단의 칸 수 - 1. 경우의 수는 항상 2개 중 하나.
int n;
int main(void){
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &stairs[i]);
}//계단 갯수와 각 계단의 점수 입력.
values[0] = stairs[0];//1칸 오르기.
values[1] = max(stairs[0] + stairs[1], stairs[1]);//1칸씩 둘 다 오르기 vs 2칸 오르기.
values[2] = max(stairs[0] + stairs[2], stairs[1] + stairs[2]);//1칸 오르고 2칸 오르기 vs 2칸 오르고 1칸 오르기.
for(int i = 3; i < n; i++){
values[i] = max(values[i-2] + stairs[i], values[i-3] + stairs[i-1] + stairs[i]);
}
//엑셀로 생각해보면 보인다.
//매번 i+1번째 계단의 최댓값의 경우의 수는 2가지이다. 2칸 전까지의 경로 + 마지막 계단 or 3칸 전까지의 경로 + i-1계단 + 마지막 계단.
//이 두 가지 중 3칸 전까지의 경로 + i-1계단 + 마지막 계단의 경우는 마지막에 2개의 연속된 계단을 오른 것이므로 반드시 i-3까지의 경로로부터 연산을 해주는 것이다.
printf("%d\n", values[n-1]);
return 0;
}
<file_sep>/단어 변환(문자열 dfs).cpp
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//한글자만 다른 단어들끼리 노드 연결.
//target까지 이동횟수 반환.
//트리의 깊이가 곧 답.
bool check[51] = { false, };
int answer = 51;
//디폴트 매개변수: 사용자가 값 안넣으면 해당 값을 기본값으로 메소드 수행.
void dfs(string begin, string target, vector<string> words, int depth = 0){
for(int i = 0; i < words.size(); i++){
int cnt = 0;
for(int j = 0; j < words[i].length(); j++){
if(!check[i] && begin[j] != words[i][j]) cnt++;//글자 다른 부분 찾기.
}
if(cnt == 1){
//한 곳만 다르다면(변환이 가능하다면)
if(target == words[i] && answer > depth + 1){
answer = depth + 1;
return;
}
//방문 표시해준뒤 재귀, 재귀 끝나면(트리 형성이 끝나면) 다시 방문 표시 해제.
check[i] = true;
dfs(words[i], target, words, depth + 1);
check[i] = false;
}
}
}
int solution(string begin, string target, vector<string> words) {
dfs(begin, target, words);
if(answer == 51) return 0;
return answer;
}
<file_sep>/DP/9095(1, 2, 3 더하기).cpp
/*연산의 종류는 1, 2, 3으로 3가지이다. 주어진 n 값을 넘지 않는 선에서 1~3가지 경우의 수 중 하나를 선택해 나간다.
저번 dp문제처럼 역으로 결과를 만들어나가는 방법을 생각해보자. 주어진 n을 1, 2, 3으로 쪼갠다고 생각해보자.
데이터의 크기가 작아서 재귀함수를 이용해봐도 괜찮을 거 같다.
경우의 수들은 n이 3인 순간부터 연산의 종류가 3가지이므로 처음에 3갈래로 나뉜다.
n은
1일 때 1가지.
2일 때 2가지.
3일 때 4가지.까지를 기본 값으로 해서 이후로는 n의 경우의 수는 n-1, n-2, n-3 경우의 수의 합이다.
4일 때 7가지.
5일 때 13가지.
...
n = n -1, n - 2, n - 3으로 구성되므로 선입선출 방식이 적용되는 큐를 통해 구현하면 될 거 같다.
*/
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
queue <int> q;
int result, n, count, temp = 0;
void spliter(int target){//n이 목표값임. 4 이상인 값부터 들어오게 만들었음. 스택에 n값까지 값 쌓아주다가 3개 꺼내고 그 값 모두 합할 거임.
int one = 1, two = 2, three = 4;
q.push(one);
q.push(two);
q.push(three);
temp = one + two + three;
q.push(temp);
//큐에 1, 2, 3, 4의 값까지 들어감. 이후 5 = 4+3+2, 6 = 5+4+3...쌓아나가야 함.
while(n != count){
if(n == 4){
break;
}
else{
q.pop(); //먼저 들어온 1, 2, 3 순으로 사라짐.
//큐에 남아있는 3개의 원소들의 합을 다시 큐에 삽입해주면 된다.
for(int i = 0; i < 3; i++){
if(i == 0) one = q.front();
if(i == 1) two = q.front();//다시 큐에 삽입할 n - 2의 값 저장.
if(i == 2) three = q.front();//다시 큐에 삽입할 n - 3의 값 저장.
q.pop();
}
temp = one + two + three;
q.push(one);
q.push(two);
q.push(three);
q.push(temp);
count++;
}
}
//printf("%d %d %d ", one, two, three);
for(int i = 0; i < 4; i++){
q.pop();//큐 초기화.
}
result = temp;
}
int main(void){
int t;
scanf("%d", &t);
while(t--){
n = 0, count = 4, temp = 0;
result = 0;
scanf("%d", &n);
if(n == 1){
result = 1;
printf("%d\n", result);
continue;
}
if(n == 2){
result = 2;
printf("%d\n", result);
continue;
}
if(n == 3){
result = 4;
printf("%d\n", result);
continue;
}
else spliter(n);
printf("%d\n", result);
}
return 0;
}
<file_sep>/1436(666찾기_미완).cpp
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(0);
cin.tie(0);//cin 입력 속도 개선, 단 stdio.h에서 제공하는 함수 사용 불가
int N;
cin >> N; // 몇번째 번호 출력하게 할건지 입력
int num = 666; //첫 번째 종말의 숫자
int turn = 1; //출력할 번호
while (1)//완전 탐색
{
if (turn == N)//해당 숫자를 찾았다면
break;
num++; //666에서 시작해 1씩 증가시킴
int copyNum = num;//해당 숫자를 저장하고
string s; //문자열 변수 s 선언
while (copyNum)
{
s += (copyNum % 10 + '0');//666에서부터 1씩 증가 되는 수의 1의 자리수에 0을 합침
copyNum /= 10;
}
copyNum = stoi(s); //문자열을 다시 정수 형태로 변환(string to int)
int six = 0;
while (copyNum)//6이 연속으로 세개 있는지 확인
{
int temp = copyNum % 10;//1의 자리수부터 한 자리수씩 까면서 확인
if (temp == 6)
six++;// 6의 개수 세기
else if (six < 3) //6의 개수가 3개보다 적으면
six = 0; // 6개수 초기화
copyNum /= 10; //
}
if (six >= 3)//조건을 만족한다면
turn++; //출력할 번호 1증가
}
cout << num << "\n";
return 0;
}<file_sep>/그래프 탐색/6118(숨바꼭질).cpp
/*
1번부터 탐색.
N개의 정점, M개의 경로.
입력에 따라 트리 생성하고, 다익스트라 알고리즘으로 1부터 모든 정점 최소 비용 산출.
제일 큰 값의 정점 번호 출력, 같은 비용 정점 번호 개수 카운트.
*/
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector < pair <int, int> > farm [20001];
int d[20001];
int n, m;
int INF = 987654321;
void dijkstra(int start){
d[start] = 0;
priority_queue<pair<int, int> > pq;//출발 정점, 비용을 담을 우선순위 큐 선언.
pq.push(make_pair(start, 0));//시작 정점, 비용 큐에 삽입
while (!pq.empty()) {
int current = pq.top().first;//현재 정점.
int distance = -pq.top().second;//현재 정점에서 가장 작은 비용으로 갈 수 있는 정점으로
pq.pop();
if (d[current] < distance) continue;//최단 거리 아닌 경우 스킵
for (int i = 0; i < farm[current].size(); i++) {//현재 정점의 인접 정점 하나씩 확인
int next = farm[current][i].first;//인접 정점.
int nextDistance = distance + farm[current][i].second;//현재 정점을 거쳐서 next로 가는 총 비용(현재 노드까지 드는 최소 비용 + next까지 가는 비용)
//기존 최소 비용보다 값이 더 작다면 최솟값을 교체
if (nextDistance < d[next]) {
d[next] = nextDistance;
pq.push(make_pair(next, -nextDistance));//작은 값 우선되도록 음수화
}
}
}
}
int main(void){
int cnt = 1;
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++) d[i] = INF;
for(int i = 0; i < m; i++){
int x, y;
scanf("%d %d", &x, &y);
farm[x].push_back(make_pair(y, 1));//비용 = 지나친 길의 개수이므로.
farm[y].push_back(make_pair(x, 1));
}
dijkstra(1);
int result = d[1];
int idx = 1;
for(int i = 1; i <= n; i++){
if(result < d[i]){
result = d[i];
cnt = 1;
idx = i;
}
else if(result == d[i]) cnt++;
}
printf("%d %d %d\n", idx, result, cnt);
return 0;
}
<file_sep>/수학/3052(나머지).cpp
#include <iostream>
int main(void){
int num[10];
for(int i = 0; i < 10; i ++){
scanf("%d", &num[i]);
num[i] %= 42;
}
int result = 10;
for(int i = 0; i < 10; i++){
for(int j = i+1; j < 10; j++){
if(num[i] == num[j]){
result--;
break;
}
}
}
printf("%d\n", result);
return 0;
}
<file_sep>/DP/2133(타일 채우기).cpp
/*
마지막 타일에 올 수 있는 경우의 수는 다음과 같다.
1. 가로 2칸 패턴 -> 3종류.
2. 가로 4칸 패턴 -> 2종류.
3. 가로 6칸 패턴 -> 2종류.
n-2칸 or n-4칸, n-6칸 채우는 경우의 수 각각에 *3, *2, *2.
2칸 채우는 경우의 수는 3개.
4칸 채우는 경우의 수는 11개.
6칸 채우는 경우의 수는 41개.
4칸 채우는 경우의 수 중 2칸 채우는 경우 2개를 사용한 경우는 9개.
즉, 순수히 4칸 채우는 경우는 2가지.
6칸 채우는 경우의 수 중 2칸 채우는 경우 3개를 사용한 경우 27개.
4칸 채우는 경우 1개와 2칸 채우는 경우 1개를 사용한 경우 12개.
즉, 순수히 6칸 채우는 경우는 2가지.
6칸 채우는 경우를 다시 생각해보면
2칸 채우는 경우 3 * 4칸 채우는 경우 11 = 33
4칸 채우는 경우 2 * 2칸 채우는 경우 3 = 6
6칸 채우는 경우 = 2
dp[6] = dp[2]*dp[4] + 2*dp[2] + 2.
dp[4] = dp[2]*dp[2] + 2.
dp[n] = dp[n-4]*dp[n-2] + 2*dp[n-4]
*/
#include <iostream>
int dp[31];
int main(void){
int n;
scanf("%d", &n);
dp[0] = 1;
dp[1] = 0;
dp[2] = 3;
for(int i = 4; i <= n; i += 2) {
dp[i] = 3*dp[i-2] + 2;//마지막 2칸 채우는 경우 3가지이므로 *3, 추가되는 새로운 경우의 수 2.
for(int j = i-4; j > 0; j -= 2) {
dp[i] += 2*dp[j];//마지막 4칸 채우는 경우
}
}
printf("%d\n", dp[n]);
return 0;
}
<file_sep>/DP/11726(동적 프로그래밍 기초, 타일링).cpp
/*2 x N 크기의 직사각형을 1 x 2, 2 x 1 타일로 채우는
방법의 수를 구하는 프로그램
타일을 채우는 방법의 수를 10,007로 나눈 나머지를 출력
동적 프로그래밍의 핵심은 규칙성 파악을 통한 점화식 도출이다.
이번 문제의 경우 가장 마지막에 오는 타일을 기준으로
2가지 경우로 나눌 수 있다. 맨 마지막에 2x1타일이 오는 경우와
1x2타일이 오는 경우이다.
따라서 점화식을 세워보면 D[i] = D[i-1]+D[i-2}가 된다.
*/
#include<iostream>
using namespace std;
int d[1001];
int dp(int x) {
if (x == 1) return 1;//초기값 설정 및 종료 시점
if (x == 2) return 2;
if (d[x] != 0) return d[x];//값이 있다면(이미 계산이 되었다면) 그대로 반환(연산하지 마라)
return d[x] = (dp(x - 1) + dp(x - 2)) % 10007;
}//점화식에 따라 dp함수가 재귀적으로 수행
//ex) dp(5) = dp(4) + dp(3) = dp(3) + dp(2) + dp(3) + dp(2)...꼴로 수행되어 연산됨.
int main(void) {
int x;
cin >> x;
cout << dp(x);
return 0;
}
<file_sep>/정수 삼각형(DP).cpp
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int dp[501][501];
int solution(vector<vector<int>> triangle) {
dp[0][0] = triangle[0][0];
for(int i = 1; i < triangle.size(); i++){
for(int j = 0; j <= i; j++){
if(j == 0) dp[i][j] = dp[i-1][j] + triangle[i][j];//맨 왼쪽 것만 합산.
else if(i == j) dp[i][j] = dp[i-1][i-1] + triangle[i][j];//맨 오른쪽 것만 합산.
else dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j];//중간은 최댓값 찾아서 합산.
}
}
int answer = dp[triangle.size()-1][0];
for(int i = 1; i < triangle[triangle.size()-1].size(); i++){
if(answer < dp[triangle.size()-1][i]) answer = dp[triangle.size()-1][i];
}
return answer;
}
<file_sep>/DP/2163(초콜릿 자르기).cpp
/*
길이가 짝수면 반갈.
홀수면 짝수와 홀수 길이로 쪼갬.
1x1크기가 될 때까지 쪼갠다.
ex)
1x1 -> 0
1x2 -> 1
1x3 -> 2
1x4 -> 3
...
2x2 -> 3
2x3 -> 5
2x4 -> 7
3x3 -> 8
3x4 -> 2+9 = 11
4x4 -> 3+12 = 15
0 1 2 3 =>1씩 증가.
1 3 5 7 =>2씩 증가.
2 5 8 11 =>3씩 증가.
3 7 11 15
4 9 14 19
=> (n-1)+n*(m-1) = n-1 + nm - n.
=> n*m-1 점화식 나옴.
*/
#include <iostream>
int n, m;
int main(void){
scanf("%d %d", &n, &m);
printf("%d\n", n*m-1);
return 0;
}
<file_sep>/수학/2588(곱셈).cpp
#include <iostream>
int main(void){
int a, b;
scanf("%d", &a);
scanf("%d", &b);
int b_arr[4];
b_arr[0] = b % 10;
b_arr[1] = (b % 100) / 10 ;
b_arr[2] = b / 100;
b_arr[3] = b;
for(int i = 0; i < 4; i++){
printf("%d\n", a*b_arr[i]);
}
return 0;
}
<file_sep>/부분합.cpp
#include <iostream>
using namespace std;
int A;
int partial_sum(void)
{
int n = 1;
while (1)
{
int copy = n;
int sum = n;
while (copy)
{
sum += copy % 10; //10으로 나눴을 때 나머지 값 더해주는 것 반복(맨 끝자리서부터 더해짐)
copy /= 10;//일의 자리수부터 하나씩 떼어냄
}
if (n == A || sum == A)
break;
n++;
}
return n;
}
int main(void)
{
int result = 0;
cin >> A;
result = partial_sum();
if (result == A)
cout << 0 << endl;
else
cout << result << endl;
return 0;
}
<file_sep>/그래프 탐색/5567(결혼식).cpp
/*
인접 리스트 활용해서 1과 친구인 애들 찾기.
*/
#include <iostream>
#include <vector>
using namespace std;
vector<int> tree[501];
bool friends[501] = { false, };//친구면 true.
int main(void){
int n, m, result = 0;
scanf("%d", &n);
scanf("%d", &m);
for(int i = 0; i < m; i++){
int a, b;
scanf("%d %d", &a, &b);
tree[a].push_back(b);
tree[b].push_back(a);//트리는 방향 그래프를 제외하고 항상 상호 연결시킬것.
}
//tree[1]에 있는 원소들은 일단 초대함.
//tree[1]의 원소들의 친구 인원 수 찾으면 된다.
for(int i = 0; i < tree[1].size(); i++){
int link = tree[1][i];
friends[link] = true;
}
for(int i = 0; i < tree[1].size(); i++){
int link = tree[1][i];
for(int j = 0; j < tree[link].size(); j++){
if(!friends[tree[link][j]]){//친구의 친구.
friends[tree[link][j]] = true;
}
}
}
for(int i = 2; i <= n; i++){
if(friends[i]) result++;
}
printf("%d\n", result);
return 0;
}
<file_sep>/11727(2xn타일링2).cpp
/*
2*n 크기의 직사각형의 1s2, 2x1, 2x2 타일로 채우는 방법의 수
결과값은 10,007로 나눈 나머지 값 출력.
마지막 칸이 2x1 오는 경우와 2x2 or 1x2 오는 경우로 나눌 수 있음.
2x1이 마지막에 온다면 2x(n-1)칸을 채워넣는 경우의 수를 찾으면 되고,
2x2나 1x2가 마지막에 온다면 2x(n-2)칸을 채워넣는 경우의 수*2 값을 찾으면 된다.
*/
#include <iostream>
int dp[1001];
int tiling(int x){
if(x==1) return 1;
if(x==2) return 3;
if(dp[x]!=0) return dp[x];
return dp[x] = (tiling(x-1) + tiling(x-2)*2) % 10007;
}
int main(void){
int n;
scanf("%d", &n);
printf("%d\n", tiling(n));
return 0;
}
<file_sep>/13458(시험 감독).cpp
#include <iostream>
#define MAX 1000001
using namespace std;
int people[MAX];//응시자.
int main(void){
int n, a, b;//a: 총감독관이 관리 가능한 응시생 수, b: 부감독관 관리 가능치.
long long result = 0;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &people[i]);
}
scanf("%d %d", &a, &b);
for(int i = 0; i < n; i++){
people[i] -= a;
result++;//총 감독관은 무조건 한 명 들어가니까 +1.
if(people[i] > 0){
if(people[i] % b == 0){
result += people[i] / b;
}
else{
result += people[i] / b + 1;
}
}
}
printf("%lli\n", result);
return 0;
}//처음에 음수 되는 경우 고려안해서 틀렸음.
<file_sep>/DP/2156(포도주시식_dp).cpp
/*
계단 오르기 문제와 유사하다.
3개 연속되면 안된다는 규칙만 존재한다.
몇 개를 지나치든 상관없고, 마지막거 무시해도 괜찮다.
*/
#include <iostream>
#include <algorithm>
#define MAX 10003
using namespace std;
int wine[MAX] = { 0, };//각 잔에 들어있는 포도주의 양.
int values[MAX] = { 0, };//선택 결과들. 인덱스 - 1 = 지나친 잔의 개수.
int main(void){
int n;
scanf("%d", &n);
for(int i = 3; i < n+3; i++){
scanf("%d", &wine[i]);
}
//values[0] = wine[0];
//values[1] = wine[0] + wine[1];
//values[2] = max(wine[0] + wine[2], wine[1]);
for(int i = 3; i < n+3; i++){
values[i] = max(values[i-2] + wine[i], values[i-3] + wine[i-1] + wine[i]);//2번 연속 패스하는 경우 고려x.
values[i] = max(values[i-1], values[i]);//2번 연속 안먹는 경우가 더 클 수 있음.
printf("%d ", values[i]);
}
//printf("%d\n", values[n+2]);
return 0;
}
<file_sep>/Greedy/1138(한 줄 세우기).cpp
/*N명의 사람들이 줄을 선다. 사람들은 자기보다 큰 사람이 왼쪽에 몇
명 있었는지만 기억한다. 사람들의 키는 1~N까지이고 모두 다르다.
input) N을 입력받고, 키가 1인 사람부터 왼쪽에 자기보다 큰 사람 몇 명인지
입력 받음.
output) 줄을 선 순서대로 '키'를 출력.
단순하게 1~N까지의 사람들을 입력받은 왼쪽에 자기보다 큰 사람 수에
맞춰서 자기가 들어갈 자리로 들어가면 될 거 같다.
모든 사람이 왼쪽부터 하나씩 탐색하며 자신이 들어갈 위치 고름.
*/
#include <iostream>
using namespace std;
int N;
int people[11];
int main(void) {
cin >> N;
for (int i = 1; i <= N; i++) {
int comp;
cin >> comp;//왼쪽에 자기보다 큰 사람 수 입력(0~N-1)
int count = 0; //왼쪽에 자기보다 큰 사람 수 카운트
for (int j = 1; j <= N; j++) {
if (count == comp && people[j] == 0) {//왼쪽에 자기보다 큰 사람 수가 입력받은 값과 일치하고, 원소의 값이 0이면
people[j] = i;//원소의 값을 NULL에서 번호 부여
break;
}
if (people[j] == 0) count++;//위 조건문 충족 안되고 값만 0이라면 count 증가, c++에서 0은 NULL 값이기도 함.
}
}
for (int i = 1; i <= N; i++) {
cout << people[i] << " ";//출력 시 공백 안만들어주면 오답 처리함
}
return 0;
}<file_sep>/Greedy/1758(long long 중요성).cpp
/*뒤로 갈수록 -금액 커지므로 최댓값을 얻으려면
팁 많이 주는 사람을 앞으로 보내야한다.
따라서 팁 정렬한 후 팁 최댓값 계산*/
#include <iostream>
#include <algorithm>
using namespace std;
int p[100001];
int main(void) {
int n;
cin >> n;//사람 수
for (int i = 0; i < n; i++) {
cin >> p[i];//주려는 팁
}
sort(p, p + n);//팁 오름차순 정렬(많이 주는 사람 맨 뒤에)
int minus = 0, temp = 0;//결과, 차감 금액
long long result = 0;//스택 오버플로우 방지 위함(이거 안해서 틀렸음)
for (int i = n - 1; i >= 0; i--) {//맨 뒤부터
temp = p[i] - minus;
if (temp < 0) temp = 0;
result += temp;
minus++;
}
cout << result << '\n';
return 0;
}<file_sep>/Greedy/1181(문자열 정렬).cpp
/*알파벳 소문자로 이루어진 N개의 단어가 들어오면 다음의 조건따라
정렬하기
1. 길이가 짧은 것
2. 길이가 같으면 사전 순
3. 같은 단어는 한 번만 출력
길이 짧은 순은 알겠는데 사전 순 정렬은 어쩌지*/
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string a[20000];
int n;
bool compare(string a, string b) {
//길이 짧은 단어 먼저
if (a.length() < b.length())
return 1;//우선순위 높임
else if (a.length() > b.length())
return 0;//우선순위 낮춤
//길이 같으면 사전 순
else
return a < b;//비교 연산자 넣으면 자동으로 사전 순으로 정렬해줌
}
int main(void) {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n, compare);
for (int i = 0; i < n; i++) {
//동일 단어는 패스
if (i > 0 && a[i] == a[i - 1]) {
continue;
}
else {
cout << a[i] << '\n';
}
}
return 0;
}<file_sep>/DP/1463(1만들기).cpp
#include <stdio.h>
int Dp[1000001];
int min(int a, int b){
return a > b ? b : a;
}
int main(void){
int N;
scanf("%d", &N);
Dp[1] = 0;//1을 1로 만드는 최소 횟수는 0.
for (int i = 2; i <= N; i++)
{
Dp[i] = Dp[i - 1] + 1;
if (i % 2 == 0)
Dp[i] = min(Dp[i], Dp[i / 2] + 1);
if (i % 3 == 0)
Dp[i] = min(Dp[i], Dp[i / 3] + 1);
printf("%d ", Dp[i]);
}
printf("%d\n", Dp[N]);
return 0;
}
/*주어진 수(N)을 1로 만드는 최소 횟수는 = 'N-1을 1로 만드는 최소 횟수 + 1번' 또는 'N/2를 1로 만드는 최소 횟수 +1번' 또는 'N/3을 1로 만드는 최소 횟수 + 1번'
ex) N = 4, 1로 만드는 최소 횟수는 3을 1로 만드는 최소 횟수 + 1번 = 2, 2를 1로 만드는 최소 횟수 + 1번 = 2...
N = 15, 14를 1로 만드는 최소 횟수 + 1번, 5를 1로 만드는 최소 횟수 +1...이런 과정으로 수를 쪼개다보면 더 못쪼개는 지점에 이름. 여기서부터 상향식으로 문제를 해결.
*/
<file_sep>/10828(스택_미완).cpp
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
int N;
string s;
scanf("%d", &N);
while (N)
{
scanf("%s", &s);
if (s ) //문자열에 조건문 붙이기?
}
}<file_sep>/타겟넘버(dfs).cpp
#include <string>
#include <vector>
using namespace std;
int answer=0;
//재귀로 dfs 구현, 입력으로 주어지는 데이터와 연산 통해 나온 값과 계산한 개수 인자로 받음.
void dfs(vector<int> numbers, int target, int sum, int cnt){
if(cnt >= numbers.size()){
if(sum == target) answer++;
return ;
}
//+, - 가능한 연산 모두 해봄.
dfs(numbers, target, sum+numbers[cnt], cnt+1);
dfs(numbers, target, sum-numbers[cnt], cnt+1);
}
int solution(vector<int> numbers, int target) {
dfs(numbers, target, 0, 0);
return answer;
}
//출처: https://chozzza-diary.tistory.com/85
<file_sep>/Greedy/1398(동전 문제).cpp
#include <iostream>
long coins[23];
int main(void){
int t;
coins[0] = 1;
coins[1] = 10;
coins[2] = 25;
for(int i = 3; i < 23; i++){
if(i%3 == 2 && i <= 20){
coins[i] = coins[i-2]*25;
}
else if(i%3 == 0){
coins[i] = coins[i-2]*10;
}
else{
coins[i] = coins[i-1]*10;
}
}
scanf("%d", &t);
//1 25 100 1000 2500 10000 100000 250000... 인덱스 3단위로 100씩 곱해짐. 100보다 큰 수가 주어지면 100이하의 수가 될 때까지 100으로 나누어볼까..
//ex) 3072 -> 원래대로면 2500, 100*5, 72 => 72의 최솟값에다가 3000은 그냥 큰 단위로 쪼개버리면 된다. 100으로 나누었을 때 나머지만 생각하자.
while(t--){
long p;
int result = 0;
scanf("%ld", &p);
for(int i = 22; i >= 0; i--){
if(p >= coins[i]){
if(p <= 100){
if(coins[i] == 25 && p % 10 < 5){
result += p / coins[i-1];
p -= coins[i-1]*(p / coins[i-1]);
}
else{
result += p / coins[i];
p -= coins[i]*(p/coins[i]);
}
}
else{
result += p/coins[i];
p -= coins[i]*(p/coins[i]);
}
}
}
printf("%d\n", result);
}
return 0;
}
<file_sep>/Greedy/2217(로프_알고리즘은 맞으나 원인불명 오답).cpp
/*로프의 개수를 k, 중량을 w라 할 때, 각 로프에 걸리는 중량은 w/k.
로프마다 버틸 수 있는 중량 한계가 존재.
k개의 로프를 모두 사용하는 경우부터 적은 중량을 들 수 있는 로프부터
소거해나가면서 중량 버틸 수 있는지 확인하는 과정 반복.
오름차순으로 정렬해두면 앞에서부터 약한 로프 소거 가능.*/
#include <stdio.h>
#include <algorithm>
int N;
int ropes[10001];
int main(void) {
scanf("%d\n", &N);
for (int i = 0; i < N; i++) {
scanf("%d\n", &ropes[i]);
}
std::sort(ropes, ropes + N);//약한 로프 순으로 정렬
int max = 0;//최대 중량은 사용하는 로프 수 * 가장 약한 줄이 들 수 있는 무게
for(int i = 0; i < N; i++) {
if(max < ropes[i]*(N-i)) max = ropes[i] * (N - i);
}
printf("%d", max);
return 0;
}<file_sep>/2750(선택정렬_사용).cpp
//시간제한 관련 tip: 1초에 1억번 정도의 연산
//선택정렬(오름차순 정렬하는 문제)
#include <stdio.h>
int array[1001];//1~1000까지지만 대개 1 여유둠.
int main(void) {
int number, i, j, min, index, temp;
scanf("%d", &number);//입력받을 수의 개수 입력
for (i = 0; i < number; i++) {//N 개수만큼 입력받아 배열에 저장
scanf("%d", &array[i]);
}
for (i = 0; i < number; i++) {
min = 1001;//최솟값을 일부러 최솟값이 될 수 없는 수로 잡음
for (j = i; j < number; j++) {
if (min > array[j]) {//그럼 배열의 첫번째 원소가 min이 될 것이고,
min = array[j];//그보다 작은 값이 나올 때마다 min 값을 교체
index = j;//최솟값의 배열 인덱스 저장
}
}
temp = array[i];
array[i] = array[index];
array[index] = temp;//임시변수 이용해 최솟값과 array[i]위치 변경
}
for (i = 0; i < number; i++) {
printf("%d\n", array[i]);
}
}//큰 반복문의 i 값 1씩 증가하니까 자연스럽게 살펴보는 원소 하나씩 줄어듦<file_sep>/수학/10869번(사칙연산).cpp
#include <iostream>
int main(void){
int a, b;
printf("%d\n", a+b);
printf("%d\n", a-b);
printf("%d\n", a*b);
printf("%d\n", a/b);
printf("%d\n", a%b);
return 0;
}
<file_sep>/DP/2139(이친수).py
n = int(input())
if n == 1:
print(1)
elif n == 2:
print(1)
elif n == 3:
print(2)
else:
#(n-3) + (n-1자리 이친수 개수)
num_list = [1, 1]
for i in range(2, n):
temp = num_list[i-2] + num_list[i-1]
num_list.append(temp)
print(num_list[n-1])
<file_sep>/2차원 배열 활용.cpp
#include <stdio.h>
int T, k, n, i, j, p[15][15];
int main(void)
{
//층과 방이라는 변수 2개 -> 2차원 배열 사용
for (i = 1; i < 15; i++) p[0][i] = i;//0층 사람 수
for (i = 1; i < 15; i++)
{
for (j = 1; j < 15; j++)
p[i][j] = p[i - 1][j] + p[i][j - 1]; //점화식에 따라 값 설정
}
scanf("%d", &T);
for (i=1; i<=T; i++) {
scanf("%d %d", &k, &n);
printf("%d\n", p[k][n]);
}
return 0;
}<file_sep>/14501(퇴사).cpp
/*
dp로 푸는게 맞는거 같다.
점화식: k일까지 얻은 이익 + n-k일자에 시작하는 작업으로 얻는 이익.(조건 충족하는)
*/
#include <iostream>
#include <algorithm>
using namespace std;
int credit[17];//credit[i] = i일자에 받는 수익.
int time[17];
int price[17];
int main(void){
int n, t, p, result = 0;
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%d %d", &time[i], &price[i]);
}
for(int i=1; i<=n; i++){
if(i+time[i] <=n+1){//i일의 상담 수행한 경우(n+1일 이전에 끝난다는 전제 하).
credit[i+time[i]] = max(credit[i+time[i]], credit[i] + price[i]);
result = max(result, credit[i+time[i]]);
}
credit[i+1] = max(credit[i+1], credit[i]);//i일의 상담 포기한 경우.
result = max(result, credit[i+1]);//i일자 상담 수행한 경우와 포기한 경우 중 최댓값 선택.
}
printf("%d\n", result);
return 0;
}
<file_sep>/Greedy/1541(잃어버린괄호).cpp
/*5자리보다 큰 수는 없고, +와 -만 있는 길이가 최대 50인 식에서
괄호를 적절히 쳐서 최솟값을 만들어라.
-이후에 괄호를 쳐버리면 되지 않을까?*/
#include <iostream>
#include <string>
using namespace std;
string str;
int minResult(void)
{
int result = 0;
string temp = "";
bool minus = false;//마이너스 플래그 변수 선언
for (int i = 0; i <= str.size(); i++)
{
//연산자일 경우
if (str[i] == '+' || str[i] == '-' || str[i] == '\0')
{
if (minus)//-가 나오면
result -= stoi(temp);//문자열 정수로 바꿔서 -연산
else
result += stoi(temp);//+연산
temp = ""; //초기화
if (str[i] == '-')//-가 나오면
minus = true;//플래그 값 바꿔주고
continue;//루프의 끝으로 이동
}
//피연산자일 경우
temp += str[i];//계속 이어붙여줌
}
return result;
}
int main(void)
{
cin >> str;
cout << minResult() << endl;
return 0;
}<file_sep>/2188(축사배정_이분매칭).cpp
/*
m개의 칸을 가진 축사.
한 칸에 최대 한 마리의 소만 들어갈 수 있음.
n마리의 소가 있고, 각 소는 희망하는 0~m개의 칸이 있다.
*/
#include <stdio.h>
#include <vector>
#define MAX 201
using namespace std;
int n, m, s;
vector <int> cows[MAX];//소가 희망하는 축사 칸 정보.
int select[MAX];//~칸에 들어간 소가 몇 번 소인지.
bool check[MAX];//확인 여부.
bool dfs(int x){//1번 소부터 n번 소 혹은 칸의 번호가 인수. 들어갈 수 있으면 true, 아니면 false.
//연결된 모든 노드에 대해서 들어갈 수 있는 시도.
for(int i = 0; i < cows[x].size(); i++){//소들의 정보(인접 리스트) 모두 살피기.
int t = cows[x][i];//살펴보고 있는 소가 갈 수 있는 축사 칸 중 하나(노드).
if(check[t]) continue;//이미 처리한 칸은 더 이상 볼 필요가 없음.
check[t] = true;//살펴본 소는 true.
//선택되지 않은 칸이거나(==0), 점유 노드에 더 들어갈 공간이 있는 경우(또 다른 곳에 배정될 수 있으면 true를 반환하므로).
if(select[t] == 0 || dfs(select[t])){//선택을 못받아 0이거나 해당 소가 다른 곳과 매칭 가능한지 확인. //dfs(select(t))함으로써 다른 칸 갈 수 있는지 확인.
select[t] = x;//소를 축사 칸에 배정함.
return true; //소가 칸에 배정되면 true를 반환.
}
}
return false;
}
int main(void){
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){
scanf("%d", &s);
for(int j = 1; j <= s; j++){
int k;
scanf("%d", &k);
cows[i].push_back(k);
}
}
int count = 0;
for(int i = 1; i <= n; i++){
fill(check, check + MAX, false);//check 배열을 false로 다 채워넣고.
if(dfs(i)) count++;//dfs 함수가 true를 반환한다면(소가 들어갈 수 있다면), 카운트++.
}
printf("%d\n", count);//배정될 수 있는 소가 몇 마리인지 출력된다.
return 0;
}
<file_sep>/Greedy/1049(기타줄).cpp
/*기타줄을 사는 선택지는 6개 패키지, 낱개 두 가지이다.
낱개로 살 때 가장 싼 가격과 6개 패키지 중 가장 싼
값을 파악하면 될 거 같다.*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int single[100], bundle[100];//낱개 가격과 세트 가격 담을 컨테이너
int main(void) {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> bundle[i] >> single[i];
//기타줄 가격 입력
}
//세트 가격 기준으로 오름차순 정렬
sort(single, single + m);
sort(bundle, bundle + m);
int b_cheap = bundle[0], s_cheap = single[0], charge = 0;//b_cheap: 패키지 중 가장 싼 가격, s_cheap: 낱개 중 가장 싼 가격
//페어 자료형으로 선언하고 정렬하니 왜인지는 모르겠으나 오름차순 정렬이 되지 않음
//cout << s_cheap << b_cheap << '\n';
//패키지 가장 싼 가격과 낱개 가장 싼 가격 선정.
//n%6 == 0이고, 패키지가 더 싸다면 패키지로 모두 구매
if (b_cheap < s_cheap * 6 && n % 6 == 0) {
charge = b_cheap * n / 6;
}
/*패키지가 낱개보다 싸더라도
끊어진 기타줄의 수가 6으로 나누어떨어지지 않고,
6으로 나눈 나머지만큼 낱개로 산 가격이 패키지 값보다 작다면
패키지와 낱개 섞어 사야함.*/
else if (b_cheap < s_cheap * 6 && n % 6 != 0 && (n % 6) * s_cheap <= b_cheap) {
charge = (n / 6) * b_cheap + (n % 6) * s_cheap;
}
/*기타줄의 수가 6으로 나누어떨어지지 않고 패키지 가격이 더 싼데
n%6만큼 낱개로 산 가격이 패키지 값보다 크다면 패키지로만 사면 된다.*/
else if (b_cheap < s_cheap * 6 && n % 6 != 0 && (n % 6) * s_cheap > b_cheap) {
charge = (n / 6) * b_cheap + b_cheap;
}
//낱개로 사는게 가장 싼 경우 그냥 낱개로 사면 됨
else{
charge = s_cheap*n;
}
cout << charge;
return 0;
}<file_sep>/수학/4344(평균은넘겠지).cpp
//자료형에 따른 연산 연습해보는 문제.
#include <iostream>
int main(void){
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
int students[1001];
int sum = 0;
for(int i = 0; i < n; i++){
scanf("%d", &students[i]);
sum += students[i];
}
double mean = (double)sum / n;
int over_mean = 0;
for(int i = 0; i < n; i++){
if(students[i] > mean){
over_mean++;
//printf("%d ", students[i]);
}
}
printf("%.3f%%\n", (double)over_mean / n * 100);//%%는 반올림 연산자.
}
return 0;
}
<file_sep>/Greedy/2875(대회or인턴).cpp
/*2명의 여학생과 1명의 남학생으로 대회 팀을 구성해야함
N명의 여학생 M명의 남학생이 있고 이 중 K명은 인턴쉽에 참가해야함
인턴쉽 참가하면 대회엔 참가 불가
시간 제한 1초, 데이터 크기는 400, 연산 좀 많아져도 괜찮을거 같다.
N, M, K가 주어질 때 만들 수 있는 '최대 팀의 수'
인턴을 보내는 학생을 고르는 기준을 정하는게 핵심
여학생의 수가 남학생보다 2배 이상 많은 경우는 남학생 수에 의해
팀의 수 결정되고 이외의 경우는 n/2로 팀의 수가 정해진다.
따라서 전자의 경우는 여학생을 인턴 보내고 후자의 경우 남자를
인턴 보낸다.*/
#include <iostream>
using namespace std;
int main(void) {
int n, m, k;
cin >> n >> m >> k;
int team = 0;
while (k) {
if (n >= 2 * m) {
n--;
k--;
}
else {
m--;
k--;
}
if (k == 0) {
if (n >= 2 * m) team = m;
else team = n / 2;
}
}
cout << team;
return 0;
}
//오답이다(이유는 모르겠다)
/*해답은 다음과 같다.*/
#include <iostream>
using namespace std;
int main() {
int N, M, K;
cin >> N >> M >> K;
int max = 0;
while (N >= 2 && M >= 1) {//팀을 만들 최소한의 인원이 있다면
N -= 2;
M--;
max++;//팀 만들고 팀 최대수 1증가
}
while (N + M < K) {//학생의 수가 k보다 작다면
N += 2;
M++;
max--;//팀을 해체시키고 여학생 2명 남학생 1명씩 돌려받음
}
cout << max << endl;
return 0;
}<file_sep>/그래프 탐색/2667(단지번호_DFS).cpp
/*
BFS와 DFS 모두 사용 가능한 문제이다.
DFS를 구현 많이 안해봤으니 DFS로 해보자.
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool map[25][25] = { false, };//탐색 여부 확인(미로).
int dx[4] = { 0, 1, 0, -1};
int dy[4] = { -1, 0, 1, 0};
string arr[25];//문자열 배열은 원소의 각 자릿수 인덱스로 접근 가능. 결과적으로 2차원 배열과 동일해짐.
vector <int> ans;
int n, cnt;
void dfs(int i, int j){//방문할 곳 인수로 받음.
map[i][j] =true;//방문 처리.
cnt++;
int k;
for(k = 0; k < 4; k++){
int next_y = i + dy[k];
int next_x = j + dx[k];
if (0 <= next_x && next_x < n && 0 <= next_y && next_y < n)
if(arr[next_y][next_x] == '1' && !map[next_y][next_x]) dfs(next_y, next_x);
}
}
int main(void){
int i, j;
//scanf("%d", &n);
cin >> n;//cin으로 입력하면 띄어쓰기 없이 입력된 수들을 '하나의' 수로 인식함. scanf를 사용하면서 하나의 수로 인식하게 하려면 "%1d"를 넣어주면 된다.
for(i = 0; i < n; i++) cin >> arr[i];
//scanf("%d", &arr[i]);
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
if(arr[i][j] == '1' && !map[i][j]){//아직 방문하지 않은 1이라면,
cnt = 0;//cnt 0으로 초기화하고,
dfs(i, j);//dfs수행한 후,
ans.push_back(cnt);//cnt를 정답 저장하는 배열에 저장.
}
}
}
sort(ans.begin(), ans.end());//오름차순 정렬.
//printf("%d\n", ans.size()); //단지 개수 출력.
cout << ans.size() << '\n';
for(i = 0; i < ans.size(); i++) cout << ans[i] << '\n';
//printf("%d\n", ans[i]);
return 0;
}
<file_sep>/이중우선순위 큐.cpp
#include <string>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
//최소힙, 최대힙 사용 -> 최댓값 삭제 최대힙에서 수행, 최솟값 삭제는 최소힙에서 수행.
//최댓값과 최솟값만 return하면 됌.
priority_queue<int> min_q;
priority_queue<int> max_q;
vector<int> solution(vector<string> operations) {
vector<int> answer(2);
int cnt = 0;
for(string op : operations){
if(!cnt){
//cnt = 0 -> 이중우선순위 큐가 비었다는 의미.
while(!max_q.empty()) max_q.pop();
while(!min_q.empty()) min_q.pop();
}
if(op[0] == 'I'){
//삽입.
int num = stoi(op.substr(2));
min_q.push(-num);
max_q.push(num);
cnt++;
}
else if(op[0] == 'D'){
//삭제.
if(!cnt) continue;
if(op[2] == '-') min_q.pop();
else max_q.pop();
cnt--;
}
if(cnt){
answer[0] = max_q.top();
answer[1] = -min_q.top();
}
}
return answer;
}
<file_sep>/블랙잭.cpp
#include <iostream>
using namespace std;
int main()
{
int N, M;
int A[100];
cin >> N >> M; //앞서 선언한 두 개의 변수 값 입력
int result = 0;
for (int i = 0; i < N; i++) cin >> A[i]; //A배열에 순차적으로 ~
for (int i = 0; i < N - 2; i++) //A배열 끝에서 3번째까지 ~A[i]
{
for (int j = i + 1; j < N - 1; j++) //A배열 끝에서 2번째까지 ~A[j]
{
for (int k = j + 1; k < N; k++) //A배열 끝 값까지 ~A[k]
{
if (A[i] + A[j] + A[k] <= M && M - (A[i] + A[j] + A[k]) < M - result) //배열에서 가져온 값들의 합이 M이하이면서 M-값들의 합이 M-result보다 작다면
{
result = A[i] + A[j] + A[k];// result 갱신.
}
}
}
}
cout << result;
}
<file_sep>/2751(퀵정렬).cpp
#include <stdio.h>
int number, data[1000001];
//시간 제한 1초이므로 1억번 연산까지 가능
//N*log N 복잡도 이용해야함. 즉 병합정렬이나 퀵정렬 사용해야함
void quickSort(int* data, int start, int end) {
if (start <= end) {//원소가 1개라면 그대로 둠
return;
}
int key = start; //키 값(피벗)은 첫번째 원소로 둠
int i = start + 1, j = end, temp;//i값을 시작값의 한 칸 옆으로 둠
while (i <= j) {//i값이 j보다 작거나 같을 때까지(엇갈릴 때까지)
while (data[i] <= data[key]) {//키 값보다 큰 값 만날 때까지
i++;//시작점에서부터 끝방향으로 원소 탐색
}
while (data[j] >= data[key] && j > start) {//키 값보다 작은 값 만날 때까지
j--;//끝에서부터 처음 방향으로 원소 탐색
}
if (i > j) {//엇갈렸다면
temp = data[j];
data[j] = data[key];
data[j] = temp;//키 값을 교체
data[key] = temp;
} else {//엇갈리지 않았다면
temp = data[i];
data[i] = data[j];
data[j] = temp;//i와 j 교체
}
}
quickSort(data, start, j - 1);//프로세스 한 사이클 돌고나면 피벗 값 기준으로 왼쪽과 오른쪽 정렬됨
quickSort(data, j + 1, end);//따라서 왼쪽 오른쪽 각각 한 번 더 정렬시킴
}
int main(void) {
scanf("%d", &number);
for (int i = 0; i < number; i++) {
scanf("%d", &data[i]);
}
quickSort(data, 0, number - 1);//배열의 시작과 끝 원소 넣어줌
for (int i = 0; i < number; i++) {
printf("%d\n", data[i]);
}
return 0;
}//테스트 케이스가 추가되서 퀵 정렬로 안풀림. 최악의 경우 O(N^2)가 나옴
//따라서, C++에서 제공하는 알고리즘 STL라이브러리를 사용하여 해결
#include <stdio.h>
#include <algorithm>
int number, data[1000001];
int main(void) {
scanf("%d", &number);
for (int i = 0; i < number; i++) {
scanf("%d", &data[i]);
}
std::sort(data, data + number);
for (int i = 0; i < number; i++) {
printf("%d\n", data[i]);
}
return 0;
}<file_sep>/Greedy/5585(그리디알고리즘, 거스름돈).cpp
#include <iostream>
using namespace std;
int main(void) {
int price, change, result = 0;
int coins[6] = { 500, 100, 50, 10, 5, 1 };
cin >> price;
change = 1000 - price;
for (int i = 0; i < 6; i++) {
if (coins[i] <= change) {
result += change / coins[i];
change -= coins[i]*(change/coins[i]);
}
}
cout << result;
return 0;
}<file_sep>/10817(조건문 활용).py
#!/usr/bin/env python
# coding: utf-8
# In[13]:
a, b, c = map(int, input().split()) ##맵 함수 사용하여 전부 int 적용, 공백을 기준으로 나눔.
# In[14]:
if a > b and a > c:
if b > c:
print(b)
elif b < c:
print(c)
else:
print (b)
if a < b and a < c:
if b > c:
print(c)
elif b < c:
print (b)
else:
print(b)
elif a == b or a == c:
print(a)
elif a > b and a < c:
print(a)
elif a < b and a > c:
print(a)
# In[ ]:
<file_sep>/1912(연속합).cpp
/*
주어지는 수의 배열에서 위치상으로 연속되는 수만 뽑아서 최댓값 만들기
모든 수가 음수인 경우 가장 작은 수 하나만 선택.
정렬은 이용할 수 없을거 같다.
주어진 수들 다 더한 후 원소 하나씩 양 끝에서 빼나가는 방식?
데이터 크기 100,000이고 시간제한 1초. O(log n) 알고리즘 써야함.
양수인 경우 당연히 선택하고,
음수인 경우 해당 음수 나오기 이전까지의 누적합이 해당 음수보다 크고, 뒤에 더해질 양수들의 합이 해당 음수보다 커야함.
*/
#include <iostream>
#define MAX 100001
using namespace std;
int numbers[MAX];
int values[MAX];
int main(void){
int n, sum = 0;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &numbers[i]);
}//수열 입력.
for(int i = 0; i < n; i++){
if(numbers[i] > 0){
}
}
}
<file_sep>/소수 찾기.cpp
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool primeNumberChecker(int n) {
//에라토스테네스의 체 알고리즘에 따라 2부터 해당 숫자의 제곱근까지만 약수 여부 판별.
if (n < 2) return false;
for (int i = 2; i*i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
int solution(string numbers) {
int answer = 0;
vector<int> v;
for (int i = 0; i < numbers.size(); i++) {
//string number을 바로 int 배열에 넣으면 아스키코드 값으로 들어감.
//-'0' 해주면 의도한 숫자가 들어감.
v.push_back(numbers[i] - '0');
}
sort(v.begin(), v.end());
vector<int> ans;
// 모든 경우의 수 찾기
do {
for (int i = 0; i <= v.size(); i++) {
int tmp = 0;
for (int j = 0; j < i; j++) {
tmp = (tmp * 10) + v[j];
ans.push_back(tmp);
}
}
//next_permutation: 추가적으로 조합 생성 가능하면 true, 아닌 경우 false 반환.
} while(next_permutation(v.begin(), v.end()));
// 중복된 vector값 제외
// unique는 연속된 중복 원소를 vector의 제일 뒷부분으로 쓰레기값으로 보내므로 정렬 후 사용.
sort(ans.begin(), ans.end());
ans.erase(unique(ans.begin(), ans.end()), ans.end());
for (int i = 0; i < ans.size(); i++) {
if (primeNumberChecker(ans[i])) answer++;
}
return answer;
}
<file_sep>/그래프 탐색/1012(유기농 배추).cpp
/*
섬 개수 문제와 유사.
상하좌우로 뭉쳐있는 배추 밀집 지역 개수를 파악하면 된다.
*/
#include <iostream>
#include <cstring>
int map[50][50];
bool check[50][50];
int m, n, k;//m:가로, n:세로, k:배추 개수.
int move[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
bool isInMap(int y, int x){
return ((y >= 0 && y < n) && (x >= 0 && x < m));
}
void dfs(int y, int x){
check[y][x] = true; //해당 지점 방문 표시
for (int i = 0; i < 4; i++)
{
int newY = y + move[i][0];
int newX = x + move[i][1];//다음 좌표 이동.
//다음 좌표의 값이 지도 안에 있으며 방문한 적이 없고, 값이 1인 지점이면 재귀적으로 dfs 수행.
if(isInMap(newY, newX) && !check[newY][newX] && map[newY][newX]) dfs(newY, newX);
}
}
int main(void){
int t;
scanf("%d", &t);
while(t--){
scanf("%d %d %d", &m, &n, &k);
memset(check, false, sizeof(check));
memset(map, 0, sizeof(map));
for(int i = 0; i < k; i++){
int c, r;
scanf("%d %d", &c, &r);
map[r][c] = 1;
}
int cnt = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!check[i][j] && map[i][j]){
dfs(i, j);//지도에서 1을 찾으면 dfs 시작.
cnt++;//dfs 시작 횟수가 곧 배추의 밀집 지역 개수.
}
}
}
printf("%d\n", cnt);
}
return 0;
}
<file_sep>/1978(소수찾기).cpp
#include <stdio.h>
int main(void)
{
int N, cnt = 0, prime = 0, div = 1;
scanf("%d", &N);
int *nums = new int[N];
for (int i = 0; i < N; i++)
scanf("%d", &nums[i]);
for (int i = 0; i < N; i++)
{
for (div = 1; div <= nums[i]; div++)
{
if (nums[i] % div == 0)
cnt++;
if (div == nums[i] && cnt == 2)
{
prime++;
cnt = 0;
}
else if (div == nums[i])
cnt = 0;
}
}
printf("%d", prime);
return 0;
}<file_sep>/그래프 탐색/1697(숨바꼭질).cpp
/*
최단경로 문제. bfs 사용.
*/
#include <iostream>
#include <cstdio>//컴파일 에러 때문에 추가한 헤더 파일.
#include <queue>
#define MAX 100001//인덱스가 0에서 시작하는 것 때문에 1 추가.
using namespace std;
bool check[MAX];//방문 여부 확인.
int loc[MAX];//경로 확인.
int move[3] = {-1, 1, 2};
int n, k;
bool isInMap(int x){//범위 안에 있는 값인지 판단해주는 함수.
return (x >= 0 && x < MAX);
}
int bfs(int start){
queue<int> q;
q.push(start);
check[start] = true;
int current = start;
int next;
while(!q.empty()){
if(current == k) break;
current = q.front();
q.pop();
for(int i = 0; i < 3; i++){
if(i == 2) next = current * move[i];
else next = current + move[i];
if(isInMap(next) && !check[next]){//범위 안에 있는 지점이며, 방문한 적 없다면,
check[next] = true;//방문 표시.
q.push(next);//방문한 곳 큐에 삽입.
loc[next] = loc[current] + 1;
}
}
}
return loc[k];
}
int main(void){
scanf("%d %d", &n, &k);
printf("%d\n", bfs(n));
return 0;
}
<file_sep>/Greedy/1092(배).cpp
/*
n개의 크레인, 작업 단위 시간 1.
각 크레인에는 무게 제한 존재. 박스는 한 번에 하나씩만 이동가능.
모든 크레인은 동시에 움직임. 즉, 1 단위 시간에 최대 n개의 박스 옮길 수 있음.
가능하다면 모든 크레인을 이용할 수 있도록 하면 답이다.
박스의 개수 m.
박스 옮기는데 걸리는 시간의 최솟값.
옮길 수 없으면 -1 출력.
그냥 떠오르는 생각으로는 크레인의 무게 제한과 박스 무게의 차를 최소화하여
옮기면 되지 않을까 싶다.
우선순위 큐 사용시 중복된 원소 사용하면 무한루프 발생하는 문제 깨달음.
*/
#include <iostream>
#include <algorithm>
using namespace std;
int box[10001];
int crane[51];
int check[10001];
int n, m;
int desc(int x, int y){
return (x > y);
}
int main(void){
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &crane[i]);
scanf("%d", &m);
for(int i = 0; i < m; i++) scanf("%d", &box[i]);
sort(crane, crane + n, desc);
sort(box, box + m);
int result = 0;
if(crane[0] < box[m-1]){
printf("-1");
return 0;
}
while(m){
int idx = 0;
for(int j = m-1; j >= 0; j--){
if(box[j] <= crane[idx]){
idx++;
m--;
break;
}
if(idx == n) break;
}
result++;
}
printf("%d\n", result);
return 0;
}
<file_sep>/1436번(666변태).cpp
//#include<iostream>
using namespace std;
int N, ord = 0;
int num_checker(int N)
{
int tmp = 1;
while (1)
{
if (tmp % 1000 == 666)
{
ord++;
if (ord == N)
break;
}
else if (tmp > 10)
tmp /= 10;
tmp++;
}
return tmp;
}
int main()
{
cin >> N;
num_checker(N);
return 0;
}
<file_sep>/2562(최댓값).cpp
#include <iostream>
int main(void){
int num[9];
for(int i = 0; i < 9; i++){
scanf("%d", &num[i]);
}
int maximum = num[0];
int idx = 1;
for(int i = 0; i < 9; i++){
if(maximum < num[i]){
maximum = num[i];
idx = i+1;
}
}
printf("%d\n%d\n", maximum, idx);
return 0;
}
<file_sep>/Webhacking.kr No.6.py
#!/usr/bin/env python
# coding: utf-8
# In[9]:
import base64
import sys #파이썬에서 제공하는 변수&함수 직접 제어할 수 있게 해주는 모듈(예: 경로설정)
val_id = "admin"
val_pw = "<PASSWORD>"
# In[10]:
val_id = val_id.encode("utf-8") #유니코드로 전환시켜서 이상한 문장 나오지 않도록 함
val_pw = val_pw.encode("utf-8")
i = 0
for i in range(20):#소스에 나와있는대로 20번 base64 인코딩(문자 코드를 기준으로 문자를 코드로 변환)
val_id = base64.b64encode(val_id)
j = 0
for j in range(20):
val_pw = base64.b64encode(val_pw)
val_id = val_id.decode() ##base64로 인코딩된 것 디코딩(코드 다시 문자로 변환)
val_pw = val_pw.decode()
val_id.replace("1", "!") #소스의 규칙대로 디코딩된 id와 pw 특수문자로 변환
val_id.replace("2", "@")
val_id.replace("3", "$")
val_id.replace("4", "^")
val_id.replace("5", "&")
val_id.replace("6", "*")
val_id.replace("7", "(")
val_id.replace("8", ")")
val_pw.replace("1", "!")
val_pw.replace("2", "@")
val_pw.replace("3", "$")
val_pw.replace("4", "^")
val_pw.replace("5", "&")
val_pw.replace("6", "*")
val_pw.replace("7", "(")
val_pw.replace("8", ")")
print("id:" + val_id)
print("pw:" + val_pw)
# In[ ]:
<file_sep>/1193(분수찾기_미완).cpp
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
int X, i;
cin >> X;
float *fraction = new float[X];
for (i = 1; i <= X; i++)
{
fraction[i] = ;
} //입력받은만큼 배열 생성(방 개수 생성)
}<file_sep>/2252(줄 세우기_위상정렬).cpp
/*N명의 학생을 키 순서대로 줄 세우려고 함. 비교해서 정렬 시도할건데 매번 2명씩 비교하고 두 학생의 순서가 결정됨.
줄을 세운 결과를 출력해야함(여러 방법으로 세울 수 있으면 아무거나 출력)
즉 순서를 결정해주는 알고리즘 문제.
위상정렬 사용(순서가 정해져 있는 그래프의 순서를 정해주는 알고리즘. 1을 수행해야 2를 수행할 수 있는 구조의 그래프).
큐를 통해 구현.
비교한 학생들끼리 연결.*/
#include <stdio.h>
#include <vector>
#include <queue>
#define MAX 32001//학생 수 범위 1부터 32000.
using namespace std;
int n, inDegree[MAX];//inDegree: 진입 차수 정보.
vector<int> a[MAX];//그래프 구현할 인접 리스트.
//학생들을 세운 줄을 그래프로 표현 ex) 1 -> 2 -> 3.
void topologySort(){
int result[MAX];
queue <int> q;
//진입 차수가 0인 노드를 큐에 삽입.
for(int i = 1; i <= n; i++){
if(inDegree[i] == 0) q.push(i);
}
//정렬이 완전히 수행되려면 정확히 n개의 노드를 방문해야함.
for(int i = 1; i<=n; i++){
//n개를 방문하기 전에 큐가 비어버리면 사이클이 발생한 것.
int x = q.front();//x에 큐의 가장 앞 원소 저장하고
q.pop();//삭제. (연결된 모든 간선 제거 과정).
result[i] = x;
for(int j =0; j < a[x].size(); j++){
int y = a[x][j];
//새롭게 진입차수가 0이 된 정점을 큐에 삽입.
if(--inDegree[y]==0) q.push(y);//--는 간선 제거하였으므로 진입차수 줄여주기 위함.
}
}
for (int i = 1; i <=n; i++){
printf("%d ", result[i]);
}
}
//진입차수: 해당 노드에 들어갈 수 있는 경로의 수(이산수학에서 배움).
int main(void){
int m;
scanf("%d %d", &n, &m);
for(int i = 0; i < m; i++){
int x, y;
scanf("%d %d", &x, &y);
a[x].push_back(y);
inDegree[y]++;//진입차수 1씩 증가시켜줌.
}//비교하는 학생 입력.
topologySort();
}
<file_sep>/P_주식가격.cpp
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// prices_len은 배열 prices의 길이입니다.
int prices[5] = { 1, 2, 3, 2, 3};
int prices_len = 5;
int* solution(int prices[], size_t prices_len) {
// return 값은 malloc 등 동적 할당을 사용해주세요. 할당 길이는 상황에 맞게 변경해주세요.
int* answer = (int*)malloc(sizeof(int)*prices_len);
int cnt = 0;
for(int i = 0; i < prices_len; i++){
int stock = prices[i];
for(int j = cnt; j < prices_len; j++){
if(stock >= prices[j]){
answer[cnt]++;
}
else{
break;
}
}
cnt++;
}
return answer;
}
int main(void){
printf("%d ", solution(prices, prices_len));
return 0;
}
<file_sep>/DP/2167(2차원 배열의 합).cpp
#include <iostream>
int arr[300][300];
int n, m, k;
int r, c, x, y;
int main(void){
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
scanf("%d ", &arr[i][j]);
}
"\n";
}
scanf("%d", &k);
for(int i = 0; i < k; i++){
scanf("%d %d %d %d", &r, &c, &x, &y);
int result = 0;
for(int j = r-1; j < x; j++){
for(int l = c-1; l < y; l++){
result += arr[j][l];
}
}
printf("%d\n", result);
}
return 0;
}
<file_sep>/수학/1037(약수).cpp
/*
약수는 대칭성을 갖는 특징이 있다.
예) 8의 약수 = 1, 2, 4, 8 -> 1 * 8 = 8, 2 * 4 = 8
33의 약수 = 1, 3, 11, 33
*/
#include <iostream>
#include <algorithm>
using namespace std;
int dividers[51];
int main(void){
int n, idx;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", ÷rs[i]);
}
sort(dividers, dividers + n);
int result = dividers[0]*dividers[n-1];
printf("%d\n", result);
}
<file_sep>/Greedy/9869(젖소).cpp
/*
스케줄링 문제 -> 종료 시점이 빠른 것 우선탐색
우유 추출 시간은 모두 동일하게 1.
따라서, 데드라인이 빠른 젖소 먼저 확인.
데드라인 빠른 젖소 중에서도 가중치(우유 양)가 높은 젖소 우선 선택.
우선 순위 큐를 페어 자료형으로 선언. 데드라인 같다면 우유 양 많은 게 상단으로 옴.
<데드라인, 우유 양>으로 두고, 데드라인에 - 붙여서 데드라인 빠른 애들 위로.
시간은 0에서부터 시작.
--------------------------------------------------------------------------틀림
앞에 젖소들을 포기하는게 이득인 경우가 고려 되지 않았음.
가중치 큰 순으로 정렬하고,
데드라인 데드라인에 딱 맞게 작업 배치 시작.
다음 소의 데드라인이 같다면 그 앞에 배치
*/
#include <iostream>
#include <queue>
using namespace std;
int n, result = 0;
bool schedule[10001];
priority_queue<pair<int, int> >q;
int optimalMilking(){
while(!q.empty()){
int time_limit = q.top().second;
int milking = q.top().first;
q.pop();
if(schedule[time_limit]){//이미 배치된 작업이 있다면,
for(int i = time_limit-1; i > 0; i--){//앞에 작업할 수 있는 시간이 있나 탐색.
if(!schedule[i]){//아직 배치 안된 지점이면,
schedule[i] = true;
result += milking;
break;
}
}
}
else{
schedule[time_limit] = true;
result += milking;
}
}
return result;
}
int main(void){
scanf("%d", &n);
for(int i =0; i < n; i++){
int milk, deadline;
scanf("%d %d", &milk, &deadline);
q.push(pair<int, int>(milk, deadline));//데드라인에 -붙여서 가장 참을성 없는 젖소 우선순위 큐의 상단으로 보냄.
}
printf("%d\n", optimalMilking());
return 0;
}
<file_sep>/Greedy/1202(우선순위 큐).cpp
/*n개 보석, k개 가방, 가방에는 무게 한도 존재
보석에는 무게와 가격이라는 정보
보석 가격 최대 합
일단 가격을 기준으로 오름차순 정렬하고 용량이 안넘치는 선에서 선택
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int bag[300001];
vector<pair <int, int> > jewel;
priority_queue<int> q;//max_heap 사용으로 시간 복잡도 낮출 수 있음. heap은 이진 트리를 오름or내림차순으로 구성한 형태를 말한다.
//큐는 선입선출이지만 우선순위 큐는 값이 큰 걸 우선순위를 높게
//잡아서 큰 값을 먼저 내보냄. 즉, 알아서 내림차순 정렬을 함
int main(void) {
int n, k, x, y;
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> x >> y;
jewel.push_back(make_pair(x, y));
}
sort(jewel.begin(), jewel.end());//보석 무게 기준 오름차순 정렬
for (int i = 0; i < k; i++) {
cin >> bag[i];
}
sort(bag, bag+k);//가방 무게 오름차순 정렬(작은거 먼저 쓰도록)
long long result = 0;
int idx = 0;
for (int i = 0; i < k; i++) {
while (idx < n && jewel[idx].first <= bag[i]) {
//무게 기준 충족하는 보석 다 넣음(무게 작은거부터 들어감)
q.push(jewel[idx++].second);//큐에는 가격 정보만 넣음
}
//가격을 우선순위 큐에 넣었으니 가장 위에 가장 비싼 보석
if (!q.empty()) {
result += q.top();
q.pop();//맨 앞의 원소 삭제(꺼냄), 담았으니까 고려 안하기 위해서
}
}
cout << result;
return 0;
}//시간 초과, 값을 없애주는게 아니라 더이상 안봐도 되게 만들어야함
<file_sep>/DP/1149(RGB거리).cpp
#include <iostream>
#include <algorithm>
using namespace std;
int numbers[1001][3];
int ans[1001][3];
int main(void){
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++){
for(int j = 0; j < 3; j++) scanf("%d", &numbers[i][j]);
}
ans[0][0] = numbers[0][0];
ans[0][1] = numbers[0][1];
ans[0][2] = numbers[0][2];
for(int i = 1; i < n; i++){
ans[i][0] = min(ans[i-1][1], ans[i-1][2]) + numbers[i][0];
ans[i][1] = min(ans[i-1][0], ans[i-1][2]) + numbers[i][1];
ans[i][2] = min(ans[i-1][0], ans[i-1][1]) + numbers[i][2];
}
int result = 987654321;//엄청 큰 값으로 상정해두어야 정답 처리된다. 이유는 모르겠음.
for(int i = 0; i < 3; i++){
if(result > ans[n-1][i]) result = ans[n-1][i];
}
printf("%d\n", result);
return 0;
}
<file_sep>/Greedy/2012(등수 매기기).cpp
#include <iostream>
#include <algorithm>
#define MAX 500001
using namespace std;
int pre[MAX];
int real[MAX];
int main(void){
int n;
long long result = 0;//데이터 크기.
scanf("%d", &n);
for(int i =0; i < n; i++){
scanf("%d", &pre[i]);
real[i] = i+1;
}
sort(pre, pre + n);
//예상 등수 겹치면 실제 등수에 공백 생김.
//공백 생긴 실제 등수 - 예상 등수의 합이 답.
for(int i = 0; i < n; i++){
if(real[i] - pre[i] > 0) result += real[i] - pre[i];
else result += -(real[i] - pre[i]);
}
printf("%ld\n", result);
return 0;
}
<file_sep>/그래프 탐색/1753(다익스트라).cpp
/*입력: 정점 개수 v와 간선의 개수 e가 주어짐. 모든 정점에는 1부터 v까지의 번호
가 매겨진다. 둘째 줄에는 시작 정점의 번호가 주어짐. 셋째 줄부터 e개의 줄에 걸쳐
각 간선을 나타내는 세 개의 정수(시작 노드, 도착 노드, 비용) 주어짐.
서로 다른 두 정점 사이에 여러 개의 간선 존재할 수 있다.
출력: v개의 줄에 걸쳐 시작점으로부터 각 i번 정점으로의 최단 경로값을 출력
경로 없다면 INF 출력.
사용할 알고리즘: 다익스트라 알고리즘
구현 방법: 우선순위 큐를 통해 트리를 구현하고, 배열에 최소 비용 정보 담을 것.
우선 순위 큐를 사용할 때 pair 형이라면 <1, 2>중 1을 먼저 비교하므로 결과로 도출해야 하는 값을 1에 두어야 시간 제한에 걸리지 않을 수 있다.
*/
#include <stdio.h>
#include <queue>
#include <vector>
using namespace std;
#define INF 987654321
#define MAX_V 20004
vector < pair<int, int> > e_info[MAX_V];//간선 정보 담을 컨테이너. 원소 인덱스가 시작 정점, <비용, 도착점> 으로 구성.
int result[MAX_V];//최단 경로 비용 담을 배열.
void dijkstra(int start){//인수로 시작 정점을 받는다.
result[start] = 0;//자기 자신으로 가는 비용은 0.
priority_queue<pair<int, int> > pq;//우선 순위 큐 사용해서 힙 형성(최대힙, 큰 값을 기준으로 최상단 노드 형성)
pq.push(make_pair(0, start));//비용, 시작점 큐에 삽입
while (!pq.empty()) {
int current = pq.top().second;//현재 노드를 큐의 최상단 노드라고 설정. 시작점 먼저.
int distance = -pq.top().first;//비용이 작은 값이 최상단에 오도록 음수화(-붙이기 전에는 큰 값들이 위에 있음. -붙이면 절댓값 큰 애들이 작아지므로 밑으로 내려감).
pq.pop();//큐에서 최상단 꺼냄.
if (result[current] < distance) continue;//최단 거리 아닌 경우 스킵.
for (int i = 0; i < e_info[current].size(); i++) {//인접 노드 하나씩 확인.
//선택된 노드의 인접 노드
int next = e_info[current][i].second;
//선택된 노드 거쳐서 인접 노드로 가는 총 비용(선택된 노드까지 드는 최소 비용 + 인접된 노드까지 가는 비용)
int nextDistance = distance + e_info[current][i].first;
//기존 최소 비용보다 값이 더 작다면 최솟값을 교체
if (nextDistance < result[next]) {
result[next] = nextDistance;
pq.push(make_pair(-nextDistance, next));//작은 값 우선되도록 음수화
}
}
}
}
int main(void){
int v, e, s;//정점 개수, 간선 개수, 시작점.
int u, d, w;//시작 정점, 도착 정점, 비용.
scanf("%d %d %d", &v, &e, &s);//정점 개수와 간선 개수 입력.//시작 정점 입력.
for(int i = 1; i <= v; i++){
result[i] = INF;//연결된 거 없으면 INF.
}
for(int i = 0; i < e; i++){
scanf("%d %d %d", &u, &d, &w);
e_info[u].push_back(make_pair(w, d));//출발점, 도착점, 비용 정보 입력
}
dijkstra(s);
for(int i = 1; i <= v; i++){
if (result[i] == INF){
printf("%s\n", "INF");
}
else printf("%d\n", result[i]);
}
return 0;
}
<file_sep>/Greedy/11399(그리디_ATM).cpp
/*인출하는데 시간이 적게 걸리는 사람을 앞으로 보내면 최솟값이 나옴
따라서, 소요시간을 오름차순으로 정렬시키고 합을 구하게 하면 되겠다.*/
#include <stdio.h>
#include <algorithm>
int N, time[1001];
int main(void) {
scanf("%d", &N);//사람 수 입력
for (int i = 0; i < N; i++) {
scanf("%d", &time[i]);//사람 수만큼 각 소요시간 입력
}
std::sort(time, time + N);//소요시간 오름차순 정렬
int result = 0;
for (int i = 1; i < N; i++) {
time[i] += time[i-1];//소요시간 앞사람 거랑 합침
}
for (int i = 0; i < N; i++) {
result += time[i];
}
printf("%d", result);
return 0;
}
<file_sep>/수학/11021(A+B, 문자열 섞어 출력).cpp
#include <iostream>
int main(void){
int t;
scanf("%d", &t);
for(int i = 1; i <= t; i++){
int x, y;
scanf("%d %d", &x, &y);
printf("Case #%d: %d + %d = %d\n", i, x, y, x+y);
}
return 0;
}
<file_sep>/1011(이동거리_미완).cpp
#include <stdio.h>
int d = 0, jump = 0;
int d_cal(int x, int y)
{
int m_dist = 1;
jump = 0;
d = y - x - 1; //마지막 점프는 1로 제한되므로 처음부터 -1
while (1)
{
if (d > 0)
{
d -= m_dist;
m_dist++;
jump++;
}
else
break;
}
jump += 1;
return jump;
}
int main(void)
{
int T, x, y, result;
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &x, &y);
result = d_cal(x, y);
printf("%d\n", result);
}
return 0;
}<file_sep>/11047(동전최솟값_미완).cpp
#include <stdio.h>
#include <iostream>
using namespace std;
int N[10], K, i;
int m = 0;
int coin_num(void)
{
for (i = 9; i <= 0; i--)
{
m += K / N[i]; //정수형으로 나누면 정수로만 값 나오는 특성 이용
K %= N[i];
}
return m;
}
int main(void)
{
cin >> K;
int result;
for (i = 0; i < 10; i++)
{
N[0] = 1;
if (i != 0)
{
if (i % 2 != 0)
N[i] = 5 * N[i - 1];
else
N[i] = 2 * N[i - 1];
}
//printf("%d\n", N[i]);
}
coin_num();
printf("%d", m);
return 0;
}<file_sep>/Greedy/1931(회의실 배정).cpp
/*N개의 회의, 회의 끝과 동시에 시작 가능. 할 수 있는 회의 수
최댓값.
회의를 최대로 하려면 회의의 끝과 시간 간의 간격 최소화 해야함
빨리 끝나는 회의들만 보면 어떨까*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<pair<int, int> >meeting;
int mBegin[100000], mEnd[100000];//회의 시작, 끝 시간
int main(void) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> mBegin[i] >> mEnd[i];
//회의 시작과 끝 시간 입력
}
for (int i = 0; i < n; i++) {
meeting.push_back(make_pair(mEnd[i], mBegin[i]));//끝나는 시간을 오름차순 정렬하기 위해 앞에 끝나는 시간을 둠
}
int earliest = 0, selected = 0;//earliest는 다음 회의 시작 가능한 가장 빠른 시간, selected는 선택된 회의 수
sort(meeting.begin(), meeting.end());//오름차순 정렬
for (int i = 0; i < n; i++) {
int meetingBegin = meeting[i].second, meetingEnd = meeting[i].first;
if (earliest <= meetingBegin) {//earliest가 회의 시작 시간보다 이르거나 같으면
earliest = meetingEnd;//earliest를 회의가 끝나는 시간으로 갱신
selected++;
}
}
cout << selected;
return 0;
}<file_sep>/2581(소수합_미완).cpp
#include <stdio.h>
int main(void)
{
int M, N, cnt;
scanf("%d %d", &M, &N);
cnt = N - M;
int *nums = new int[];
int *div = new int[];
for (int i = cnt; i <= M; i--) nums[i] = i;
for (int i = 0; i <= N; i++) div[i] = i;
return 0;
}<file_sep>/Greedy/2036(수열의 점수_그리디).cpp
//음수는 음수와 묶어서 곱으로 제거.
#include <iostream>
#include <algorithm>
#define MAX 100001
using namespace std;
long long arr[MAX];//1,000,000까지 수가 주어지므로 곱셈 연산하려면 long long.
int main(void){
int n;
long long result = 0;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%lld", &arr[i]);
}
sort(arr, arr + n);
//음수인 경우, 다음 원소와의 곱이 0이상이면 진행. 0미만이면 해당 음수 더해주고 끝.
for(int i = 0; i < n; i++){
if(arr[i] > 0) break;
if(i+1 == n){
result += arr[i];
break;
}
else if(arr[i] * arr[i+1] >= 0){
result += arr[i]*arr[i+1];
i++;
continue;
}
else result += arr[i];
}
for(int j = n-1; j >= 0; j--){
if(arr[j] < 0) break;
else if(arr[j]*arr[j-1] > 0 && arr[j]*arr[j-1] > arr[j]+arr[j-1]){
result += arr[j]*arr[j-1];
j--;
continue;
}
else result += arr[j];
}
printf("%lld\n", result);
return 0;
}
<file_sep>/1920(수 찾기_이분 탐색).cpp
/*n개의 정수가 배열 a로 주어짐.
b배열의 원소가 a배열에도 존재하면 1출력, 아닌 경우 0출력.*/
#include <iostream>
#include <algorithm>
#define MAX 100001
using namespace std;
int a[MAX];//A배열.
int b[MAX];//A배열과 비교할 배열.
void search(int start, int end, int target){//탐색 시작 인덱스, 끝 인덱스, 찾고자 하는 값.
if(start > end){
printf("0\n");
return;
//시작점이 끝 인덱스보다 크다면 해당 원소 존재하지 않는다는 의미.
}
int mid = (start + end) / 2;//이분 탐색 위해 중간 인덱스 산출.
if(a[mid] == target){
printf("1\n");
return;
//찾으려는 값이 중간 원소였다면 바로 반환시키고 종료.
}
else if(a[mid] > target) return search(start, mid - 1, target);//찾으려는 값보다 탐색범위 중간에 위치한 값이 더 크면 탐색 범위를 중간 인덱스 - 1 부분까지로 줄임.
else return search(mid+1, end, target);//중간보다 찾으려는 값이 멀리 있으면 중간 + 1 범위부터 끝까지만 탐색.
}
int main(void){
int n, m;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
scanf("%d", &m);
for(int i = 0; i < m; i++){
scanf("%d", &b[i]);
}//배열의 원소 입력.
sort(a, a+n);
//이분 탐색을 위해 오름차순 정렬.
for(int i = 0; i < m; i++){
search(0, n-1, b[i]);
}
return 0;
}
<file_sep>/그래프 탐색/11404(플로이드_와샬).cpp
#include <iostream>
#include <algorithm>
using namespace std;
int INF = 987654321;
int cost[101][101];
int n, m;
void floydWarshall(){
//결과 그래프 초기화.
int d[n+1][n+1];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
d[i][j] = cost[i][j];//처음엔 기존 경로 비용 정보와 동일하게 시작.
}
}
//k는 거쳐가는 노드를 나타낸다.
for(int k = 0; k < n; k++){
//i는 출발노드.
for(int i = 0; i < n; i++){
//j는 도착노드.
for(int j = 0; j < n; j++){
if(d[i][k] + d[k][j] < d[i][j]){//k를 거쳐가는 경우의 비용이 더 작다면 결과 그래프 값 바꿔줌.
d[i][j] = d[i][k] + d[k][j];
}
}
}
}
//결과 출력.
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
printf("%d ", d[i][j]);
}
printf("\n");
}
}
int main(void){
scanf("%d", &n);
scanf("%d", &m);
for(int i = 0; i < m; i++){
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
if(cost[x][y]) cost[x][y] = min(cost[x][y], z);
else cost[x][y] = z;
}
floydWarshall();
return 0;
}
<file_sep>/수학/10039(평균점수).cpp
#include <stdio.h>
int scores[5];//학생들 점수.
int main(void){
int average = 0;
for(int i = 0; i < 5; i++){
scanf("%d", &scores[i]);
if(scores[i] < 40) scores[i] = 40;
average += scores[i];
}
average /= 5;
printf("%d\n", average);
return 0;
}
<file_sep>/그래프 탐색/4963(섬의 개수).cpp
/*
섬의 개수 = 1이 인접해 있는 것들의 개수 = 그래프의 연결요소 개수.
*/
#include <iostream>
#include <cstring>
using namespace std;
int w, h;//w: 열 개수, h: 행 개수.
bool check[50][50];
int map[50][50];
int move[8][2] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}};
bool isInMap(int y, int x){
return ((y >= 0 && y < h) && (x >= 0 && x < w));
}
void dfs(int y, int x){
if (!map[y][x] || check[y][x])
return;
check[y][x] = true; //해당 지점 방문 표시
for (int i = 0; i < 8; i++)
{
int newY = y + move[i][0];
int newX = x + move[i][1];
//범위 안에 움직일 수 있고 방문하지 않은 지점일 경우에만 돌아다닌다
if (isInMap(newY, newX))
dfs(newY, newX);
}
}
int main(void){
while(1){
cin >> w >> h;
if(w == 0 && h == 0) break;
memset(check, false, sizeof(check));
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
cin >> map[i][j];
}
}
int cnt = 0;
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
if(!check[i][j] && map[i][j]){
dfs(i, j);
cnt++;
}
}
}
cout << cnt << "\n";
}
return 0;
}
<file_sep>/수학/5543(상근날드).cpp
#include <iostream>
#include <algorithm>
using namespace std;
int burgers[3];
int beverage[2];
int main(void){
for(int i = 0; i < 3; i++){
scanf("%d", &burgers[i]);
}
for(int i = 0; i <2; i++){
scanf("%d", &beverage[i]);
}
sort(burgers, burgers+3);
sort(beverage, beverage+2);
printf("%d\n", burgers[0] + beverage[0] - 50);
}
<file_sep>/Greedy/11047(동전최솟값).cpp
#include <iostream>
#include <vector> //배열 크기를 변수로 받기 위함
using namespace std;
int main(void) {
int N, K, i, result = 0;
cin >> N >> K;
vector<int> coins;
for (i = 0; i < N; i++) {
int x;
cin >> x;
coins.push_back(x);//x에 동전 크기 입력 받아서 컨테이너에 추가
}
for (i = coins.size() - 1; i >= 0; i--) {//사이즈 함수로 안나타내면 에러 발생(이유 모르겠음)
if (K >= coins[i]) {
result += K / coins[i];
K -= coins[i] * (K / coins[i]); //괄호 안쓰면 약분되서 계산 오류남
}
}
cout << result;
return 0;
}<file_sep>/Greedy/1092(배_정답코드).cpp
//내가 제출한 코드와의 차이점: 옮긴 박스에 대해서 check를 통한 추가적인 연산을 수행하지 않아도 되도록 짜여져있다.
//그리고 옮긴 박스를 자료구조에서 아예 삭제시켜버린다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int m, n; //m은 크레인 개수, n은 상자 갯수
int num; //각 벡터의 요소
int cnt = 0; //몇 분만에 옮겼는지
vector<int> v1, v2; //v1은 크레인 정보, v2는 상자 정보
//크래인 정보 입력
cin >> m;
for (int i = 0; i < m; i++) {
cin >> num;
v1.push_back(num);
}
//박스 정보 입력
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
v2.push_back(num);
}
//내림차순으로 정렬
sort(v1.begin(), v1.end(), greater<int>());
sort(v2.begin(), v2.end(), greater<int>());
if (v2[0] > v1[0]) { //들 수 있는 최대 무게보다 무거운 상자가 있는 경우
cout << -1;
}
else { //그 외의 경우
while (v2.size()) { //상자의 갯수가 0이 되기 전까지 반복
int index = 0; //크레인의 순서
for (int i = 0; i < v2.size(); i++) { //박스를 반복하며 탐색
if (index == v1.size()) { //크레인을 다 순회하여 박스를 담을 수 없는 경우
break; //탈출
}
if (v1[index] >= v2[i]) { //크레인이 들 수 있는 무게의 박스이면,
index++; //해당 크레인에 박스를 할당하고, 크레인의 순서를 증가
v2.erase(v2.begin() + i); //크레인으로 옮긴 상자를 삭제
i = i - 1; //사라진 자리로 다음 상자가 이동하니까 인덱스를 하나 줄여야 인덱스 값 유지된다.
}
}
cnt++; //옮긴 시간
}
cout << cnt;
}
}
<file_sep>/1100(하얀 칸).cpp
//문자는 작은 따옴표로 지정해야 에러 발생 안함. 문자열은 큰 따옴표.
//조건 묶어놨더니 이상한 값 출력된다.
//입력받을 때 %c앞에 스페이스를 넣었더니 해결되었다. 이유는 모르겠다.
//scanf안에 공백을 넣으면 개행문자를 무시하게 된다.
//따라서 입력에 공백이나 엔터가 들어간 경우엔 공백을 넣어 의도한 인덱스에 값이 들어가도록 해야한다.
#include <iostream>
char board[8][8];
int result = 0;
int main(void){
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
scanf(" %c", &board[i][j]);
}
"\n";
}
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if((i+j)%2==0 && board[i][j] == 'F'){
//printf("%d %d\n", i, j);
result++;
}
}
}
printf("%d\n", result);
return 0;
}
<file_sep>/1068(트리 구현과 bfs사용).cpp
/*그래프 입력으로 주어졌을 때 입력으로 주어지는 지워지는 노드에
따라 리프 노드의 개수 출력
트리를 구현하는 것에 집중해보자
트리 구현에는 인접 리스트가 자주 사용된다.
bfs탐색을 통해 트리를 탐색하며 리프 노드를 세보자*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> tree[51];//벡터 배열 선언, 인접 리스트는 각 인덱스에 여러 값을 저장할 수 있으므로 트리 구현에 적절하다.
int root_node, result = 0;
int num;
bool check[51];//방문 여부 표시할 곳
void bfs(int start) {
check[start] = true;//시작점 방문 표시
queue<int> q;//bfs는 큐로 구현됨(선입선출 방식)
q.push(start);//큐에 방문한 노드(시작) 삽입
while (!q.empty()) {//큐가 빌 때까지 반복, 큐가 비면 1반환 하니까 !q.empty()는 큐가 빌 때 0 반환, 반복 중단 된다.
int node = q.front();//큐에서 가장 먼저 들어온 애
q.pop();//큐에서 가장 먼저 들어온 애 꺼냄
int child_cnt = 0;//자식 노드 셀 변수
for (int i = 0; i < tree[node].size(); i++) {//tree[node]: 큐에서 꺼내서 탐색하고 있는 애
int next = tree[node][i];//인접 리스트에서 성분 접근은 이차원 배열과 동일
if (!check[next]) {//예: 만약 1이라는 노드에 2, 3, 4노드 연결되어 있다면
child_cnt++;//[1][0]은 2, [1][1]은 3 이런 식이다.
check[next] = true;
q.push(next);//큐에 방문한 노드 삽입
}
}//check[next]가 미방문 상태이거나 존재하지 않는다면 false일 것이므로 !붙여서 앞서 말한 상황이면 실행되는 조건문
if (child_cnt == 0) result++;//자식 노드 없으면 리프 노드 추가
}
}
int main(void) {
int n, k;//n: 노드 개수, k: 지울 노드 번호
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
if (num != -1) {//루트 노드가 아니라면
tree[num].push_back(i);
tree[i].push_back(num);//인접 리스트로 연결된 것 표현
}
else {
root_node = i;
}
}
cin >> k;//지울 노드 번호 입력
check[k] = true;//지울거니깐 방문처리해서 탐색에서 배제함
if (!check[root_node]) bfs(root_node);//루트 노드를 지운게 아니면 탐색 시작
cout << result;
return 0;
}<file_sep>/Greedy/10871(x보다 작은수).cpp
#include <iostream>
using namespace std;
int num[10001];
int main(void) {
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) {
cin >> num[i];
}
for (int i = 0; i < n; i++) {
if (num[i] < x) {
cout << num[i] << ' ';
}
}
return 0;
}
|
320fe4fbbdbc695cb5bbeab253ac0abc0b6380ee
|
[
"Python",
"C++"
] | 98
|
C++
|
swcunba/Algorithms
|
7e9e89738fbc573156c0bb8aae080856b7fecdfc
|
2d97ab825edab07498cf6a94c6d6245318304a43
|
refs/heads/master
|
<file_sep>/**
* @author <NAME> <<EMAIL>>
* @description Get notified
* @version 20181207
*/
'use strict';
// --- configuration --- //
// apiUrl: api url to test every x secondes (eg: https//test.com/api/example/)
// timer: in milliseconds (eg: 5000 for 5 seconds)
// --------------------- //
const apiUrl = ''
const timer = 5000
var notificationNumber = 0;
function issueCheck() {
fetch(apiUrl).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
if(res.data.data.length !== 0) {
res.data.data.forEach(function(element) {
notificationNumber++
chrome.notifications.create(element.id, {
type: 'basic',
iconUrl: 'icon.png',
title: 'Notification: Hey! Something happened!',
message: 'Issue numéro: ' + element.id
}, function(notificationId) {});
});
issueBadge(notificationNumber)
}
}));
}
function issueBadge(i) {
var num = i.toString();
chrome.browserAction.setBadgeText({text: num});
}
// On click, deleting notifications
chrome.browserAction.onClicked.addListener(function (tab) {
issueBadge(0)
notificationNumber = 0;
});
setInterval(issueCheck, timer);<file_sep># Chrome Extension Notification
### Check regulary the desired api and add a chrome notification when the value of the api changed
> Author: <NAME>
*Licence: None. Do what you want ;)*<file_sep>$("#btnClearNotifs").click(function(){
chrome.browserAction.setBadgeText({text: '0'});
});
|
a467562ccfb882a7cb7ef6d44bf449744933767a
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
btronquo/chrome-extension_notification
|
3e54a0ee5fb4b3ec0e881f9ae65c0f34411ef2ee
|
fe255d4f67fff231bfcad195ebda2705201ec6cc
|
refs/heads/master
|
<repo_name>mgprathik27/Foodrunner<file_sep>/client/src/app/models/foodQuant.ts
import {Food} from './food';
export class FoodQuant{
_id : string
food : Food;
quantity : number;
};<file_sep>/config/database.js
var mongoose = require('mongoose');
module.exports = {
database : "mongodb://localhost:27017/foodrunnerDB",
secret : "yoursecret"
};<file_sep>/client/src/app/services/food.service.ts
import { Injectable } from '@angular/core';
import {Http, Headers, ResponseContentType} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class FoodService {
food : String;
constructor(private http : Http) { }
getFoods(type, q){
if(q == null){
q = 'all';
}
if (type == null) {
type = 'all';
}
var url = 'http://localhost:3000/api/food/'+type+'/'+q;
console.log(url);
return this.http.get(url)
.map(res =>res.json());
}
getAvailableFood(fid){
var url = 'http://localhost:3000/api/food/'+fid;
console.log(url);
return this.http.get(url)
.map(res =>res.json());
}
addNewItem(newItem){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/food',newItem,{headers:headers})
.map(res =>res.json());
}
addToCart(fid,uid){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/cart/'+ uid +'/'+ fid,{headers:headers})
.map(res =>res.json());
}
deleteItem(fid){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.delete('http://localhost:3000/api/food/'+ fid,{headers:headers})
.map(res =>res.json());
}
editItem(editedItem){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.put('http://localhost:3000/api/food/'+ editedItem._id,editedItem,{headers:headers})
.map(res =>res.json());
}
getCart(uid){
return this.http.get('http://localhost:3000/api/cart/'+ uid)
.map(res =>res.json());
}
deleteCart(uid){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.delete('http://localhost:3000/api/cart/'+ uid,{headers:headers})
.map(res =>res.json());
}
updateCart(cart,uid){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
console.log("sending updatecart request ");
console.log(cart);
return this.http.put('http://localhost:3000/api/cart/'+ uid , JSON.stringify(cart),{headers:headers})
.map(res =>res.json());
}
confirmOrder(uid){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/order/'+ uid,{headers:headers})
.map(res =>res.json());
}
getHistory(uid){
console.log(uid);
return this.http.get('http://localhost:3000/api/order/'+ uid)
.map(res =>res.json());
}
fetchImage(name){
console.log(name);
return this.http.get('http://localhost:3000/uploads/'+ name,{ responseType: ResponseContentType.Blob })
.map((res) => res.blob())
}
}
<file_sep>/client/src/app/components/edit-food/edit-food.component.ts
import { Component, OnInit } from '@angular/core';
import {FoodService} from '../../services/food.service'
import {Food} from '../../models/food'
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router,ActivatedRoute} from '@angular/router';
import { BsModalRef, BsModalService } from 'ngx-bootstrap';
@Component({
selector: 'app-edit-food',
templateUrl: './edit-food.component.html',
styleUrls: ['./edit-food.component.css']
})
export class EditFoodComponent implements OnInit {
image : any;
food : Food;
name : string;
type : string;
price : number;
fid : string;
modalRef: BsModalRef;
constructor(private foodService : FoodService ,
private flashMessages : FlashMessagesService,
private router : Router,
private route : ActivatedRoute,
private modalService : BsModalService) { }
ngOnInit() {
this.route.params.subscribe(params =>{
console.log(params['id']);
this.fid = params['id'];
this.foodService.getAvailableFood(this.fid).subscribe(info=>{
this.food = info.food;
this.foodService.fetchImage(info.food.image).subscribe(data => {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.image = reader.result;
}, false);
if (data) {
reader.readAsDataURL(data);
}
}, error => {
console.log(error);
});
})
});
}
onUploadFinished(event) {
this.food.image = JSON.parse(event.serverResponse._body).filename;
}
showDelete(template) {
this.modalRef = this.modalService.show(template);
}
deleteItem(){
this.foodService.deleteItem(this.food._id).subscribe(info=>{
if(info.success == true){
this.modalRef.hide();
this.flashMessages.show("Successfully deleted Item ",{cssClass : "alert-success", timeout: 2000});
this.router.navigate(['/menu']);
}else{
this.flashMessages.show("Something went wrong",{cssClass : "alert-danger", timeout: 2000});
}
})
}
editItem(){
this.foodService.editItem(this.food).subscribe(info=>{
if(info.success == true){
this.flashMessages.show("Successfully Updated Item ",{cssClass : "alert-success", timeout: 2000});
this.router.navigate(['/menu']);
}else{
this.flashMessages.show("Something went wrong",{cssClass : "alert-danger", timeout: 2000});
}
})
}
}
<file_sep>/client/src/app/components/navbar/navbar.component.ts
import { Component, OnInit } from '@angular/core';
import {AuthenticationService} from '../../services/authentication.service';
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router} from '@angular/router';
import { Globals } from '../../global';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css'],
providers : [AuthenticationService]
})
export class NavbarComponent implements OnInit {
isCollapsed : Boolean;
constructor(private authenticationService : AuthenticationService,
private flashMessages : FlashMessagesService,
private router : Router, private globals : Globals
) { }
ngOnInit() {
this.setGlobals();
this.isCollapsed = true;
}
setGlobals(){
console.log("comes here");
if(this.authenticationService.loggedIn()){
if(this.globals.admin == undefined || this.globals.admin == null){
this.authenticationService.getProfile().subscribe(user =>{
this.authenticationService.user = user.user;
console.log(user.user.type);
if(user.user.type == "A"){
this.globals.admin = true;
this.onLogin();
}
else{
this.globals.admin = false;
}
},
err =>{
console.log("not logged in "+err);
this.flashMessages.show("User not logged in",{cssClass : "alert-danger", timeout: 1000});
this.router.navigate(['']);
})
}
console.log("its coming here with" + this.globals.admin);
}
}
onLogoutClick(){
this.onClickMenuItem()
this.globals.admin = null;
this.authenticationService.logout();
this.flashMessages.show("Successfully Logged Out ",{cssClass : "alert-success", timeout : 3000});
$(".navbar").removeClass("bg-primary");
$(".navbar").addClass("bg-success");
this.router.navigate(['/']);
}
onLogin(){
$(".navbar").removeClass("bg-success");
$(".navbar").addClass("bg-primary");
}
onClickMenuItem(){
this.isCollapsed = true;
}
}<file_sep>/routes/route.js
const express = require("express");
var app = express();
const router = express.Router();
var user = require("./user");
var food = require("./food");
var cart = require("./cart");
var order = require("./order");
//retrieve data
router.use("/user",user);
router.use("/food",food);
router.use("/cart",cart);
router.use("/order",order);
router.get("/",(req,res)=>{
res.send("in Routes");
});
module.exports = router;<file_sep>/client/src/app/models/cart.ts
import {FoodQuant} from './foodQuant';
export class Cart{
_id : string
email : string;
totalAmt : number;
foods : FoodQuant[];
};<file_sep>/client/src/app/components/register/register.component.ts
import { Component, OnInit } from '@angular/core';
import {AuthenticationService} from '../../services/authentication.service';
import {Info} from '../../models/info';
import {FlashMessagesService} from 'angular2-flash-messages'
import {Router} from '@angular/router';
import * as $ from 'jquery';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css'],
providers : [AuthenticationService ]
})
export class RegisterComponent implements OnInit {
email : string;
password : string;
name : string;
info : Info;
constructor(
private authenticationService : AuthenticationService,
private flashMessage : FlashMessagesService,
private router : Router
) { }
ngOnInit() {
}
register(){
if(this.email == undefined || this.email == null||this.email == ""
|| this.password == undefined || this.password == null||this.password == ""
|| this.name == undefined || this.name == null||this.name == "" ){
if (this.name == undefined || this.name == null||this.name == "") {
$("#nameDisp").append("<span class = 'text-primary '>User name field is mandaory</span>");
}
if (this.email == undefined || this.email == null||this.email == "") {
$("#emailDisp").append("<span class = 'text-primary'>Email field is mandaory</span>");
}
if (this.password == undefined || this.password == null||this.password == "") {
$("#passwordDisp").append("<span class = 'text-primary'>Password field is m<PASSWORD></span>");
}
}else{
const regExp = new RegExp(/^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[\d])(?=.*?[\W]).{8,35}$/);
if(this.password.length<8 || this.password.length >35)
this.flashMessage.show("Password must be at least 8 characters but no more than 35", {cssClass : 'alert-danger', timeout : 3000})
else
if(regExp.test(this.password)) {
console.log(this.email);
const userInfo = {
email : this.email,
password : <PASSWORD>,
name : this.name,
type : "N"
}
console.log(userInfo.name);
this.authenticationService.register(userInfo)
.subscribe(info => {
console.log("Hello there");
if(info.success == true){
this.authenticationService.sendmail(userInfo).subscribe(info => {
if(info.success == true){
this.flashMessage.show("You are now registered. Verification mail has been sent to the email given. Please Verify.", {cssClass : 'alert-success', timeout : 4000})
}
})
this.router.navigate(['/login']);
}else{
this.flashMessage.show(info.message, {cssClass : 'alert-danger', timeout : 3000})
this.router.navigate(['/register']);
}
})
}else{
this.flashMessage.show("Valid password must have at least one uppercase, lowercase, special character, and number", {cssClass : 'alert-danger', timeout : 3000})
}
}
}
dispClear(){
$("#nameDisp").empty();
$("#emailDisp").empty();
$("#passwordDisp").empty();
}
}
<file_sep>/client/src/app/components/menu/menu.component.ts
import { Component, OnInit } from '@angular/core';
import {FoodService} from '../../services/food.service';
import {AuthenticationService} from '../../services/authentication.service';
import {FlashMessagesService} from 'angular2-flash-messages'
import {Food} from '../../models/food';
import { Globals } from '../../global';
import * as $ from 'jquery';
import {CartComponent} from '../cart/cart.component';
import { BsModalRef, BsModalService } from 'ngx-bootstrap';
import {Router} from '@angular/router'
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css'],
providers : [CartComponent]
})
export class MenuComponent implements OnInit {
q :string;
type : string;
foods : Food[];
curPagefoods : Food[];
curPage : number;
pageLength :number;
uid : string;
imageToShow: any;
isImageLoading : boolean;
totalPages : number;
modalRef: BsModalRef;
itemToBeDeleted : string;
dispfoods : Food[];
todayDate: Date;
constructor(private foodService: FoodService,
private authenticationService: AuthenticationService,
private flashMessages : FlashMessagesService, private globals : Globals,
private cartComponent : CartComponent,
private modalService : BsModalService,
private router : Router
) { }
ngOnInit() {
this.type = null;
this.q = "";
this.pageLength =12;
console.log("here");
this.fetchFoods();
console.log(this.foods);
this.cartComponent.ngOnInit();
}
fetchFoods(){
var q = this.q;
if(this.q == ""){
q = "all";
}
var loopIdx = 0;
console.log("q "+ this.q + " type "+ this.type);
this.foodService.getFoods(this.type,q).subscribe(foods =>{
this.dispfoods = [];
this.foods = [];
console.log("before "+ foods);
console.log("before " +this.foods);
if(foods ==""){
console.log("inside "+ foods);
this.foods =null;
this.dispfoods = null;
$(".pagination").empty();
}
foods.forEach((food,idx) =>{
var newFood = {
_id : food._id,
name : food.name,
type : food.type,
price : food.price,
available : food.available,
image : null
}
var imageid = "#"+ food._id;
console.log(imageid);
$(imageid).click(function(){
console.log("hover on "+ food._id);
})
//this.isImageLoading = true;
this.foodService.fetchImage(food.image).subscribe(data => {
let reader = new FileReader();
reader.addEventListener("load", () => {
newFood.image = reader.result;
}, false);
if (data) {
reader.readAsDataURL(data);
}
//this.isImageLoading = false;
}, error => {
// this.isImageLoading = false;
console.log(error);
});
this.foods.push(newFood);
this.dispfoods.push(newFood);
loopIdx = idx;
var parent = this;
if(loopIdx == foods.length-1){
this.getFoodsPage(1);
this.buildPagination();
}
})
})
}
getFoodsPage(pageNum){
$(".page-item").removeClass("active");
switch(pageNum){
case 1 : {
$("#1").parent().addClass("active");
break;
}
case 2 : {
$("#2").parent().addClass("active");
break;
}
case 3 : {
$("#3").parent().addClass("active");
break;
}
case 4 : {
$("#4").parent().addClass("active");
break;
}
case 5 : {
$("#5").parent().addClass("active");
break;
}
}
this.curPage = pageNum;
this.curPagefoods = [];
for(var i = (pageNum-1)*this.pageLength; i<pageNum*this.pageLength && i<this.dispfoods.length ;i++){
console.log("in loop "+i);
this.curPagefoods.push(this.dispfoods[i]);
}
}
buildPagination(){
var parent = this;
this.totalPages = Math.ceil(this.dispfoods.length / this.pageLength);
$(".pagination").empty();
$(".pagination").append('<li _ngcontent-c2 class="page-item "><a _ngcontent-c2 class="page-link" id = "prevPage" (click) = "prevPage()">«</a></li>');
$("#prevPage").click(function(event){
parent.prevPage();
});
for(var i=1;i<=this.totalPages;i++){
if(i==1){
$(".pagination").append('<li _ngcontent-c2 class="page-item active"><a _ngcontent-c2 class="page-link" id = "'+i+'" >'+i+'</a></li>');
}else{
$(".pagination").append('<li _ngcontent-c2 class="page-item "><a _ngcontent-c2 class="page-link" id = "'+i+'" >'+i+'</a></li>');
}
$("#"+i).click(function(event){
parent.getFoodsPage(parseInt(event.currentTarget.id));
});
}
$(".pagination").append('<li _ngcontent-c2 class="page-item"><a _ngcontent-c2 class="page-link" id = "nextPage" (click) = "nextPage()">»</a></li>');
$("#nextPage").click(function(event){
parent.nextPage();
});
}
prevPage(){
if(this.curPage == 1){
return;
}else{
this.getFoodsPage(this.curPage-1);
}
}
nextPage(){
if(this.curPage == this.totalPages){
return;
}
else{
this.getFoodsPage(this.curPage+1);
}
}
addToCart(fid){
console.log("clicked cart" + fid);
this.authenticationService.getProfile().subscribe(user =>{
console.log(user.user.email);
this.uid = user.user._id;
console.log("clicked cart " +fid +"for user "+this.uid);
this.foodService.addToCart(fid,this.uid).subscribe(info=>{
if (info.success){
console.log(info.message);
this.flashMessages.show("Successfully added to cart",{cssClass : "alert-success", timeout: 1000});
this.cartComponent.ngOnInit();
}else{
this.flashMessages.show("Failed to insert to cart",{cssClass : "alert-danger", timeout: 2500});
}
})
},
err =>{
console.log("not looged in "+err);
this.flashMessages.show("Failed to insert to cart",{cssClass : "alert-danger", timeout: 1000});
})
}
mouseEnter(fid){
$("#"+fid).fadeTo( "fast" , 0.4, function() {
});
$("#"+fid).next().show( "fast");
}
mouseLeave(fid){
$("#"+fid).fadeTo( "fast" , 1, function() {
});
$("#"+fid).next().hide( "fast");
}
onqChange(){
if(this.type == null || this.type == "all")
this.dispfoods= this.foods.filter(x => (x.name.includes(this.q.toLowerCase())));
else
this.dispfoods= this.foods.filter(x => (x.name.includes(this.q.toLowerCase()) && (x.type == this.type)));
this.getFoodsPage(1);
this.buildPagination();
}
showConfirmOrder(template){
console.log(this.cartComponent.cart);
this.todayDate = new Date();
this.modalRef = this.modalService.show(template);
}
confirmOrder(){
this.modalRef.hide();
this.cartComponent.confirmOrder();
}
}
<file_sep>/client/src/app/components/home/home.component.html
<div class = "jumbotron container">
<h1><i class="fa fa-cutlery"></i> Foodrunner - The Food delivery App</h1>
<hr>
<h3>Satisfy your cravings</h3>
<p>Experience a world of food, with your favorite restaurant at your fingertips.</p>
<a *ngIf = "!authenticationService.loggedIn()" [routerLink] = "['/login']" class ="btn btn-primary btn-lg">Login</a>
<a *ngIf = "!authenticationService.loggedIn()" [routerLink] = "['/register']" class ="btn btn-primary btn-lg">Register</a>
</div><file_sep>/models/cart.js
const mongoose = require('mongoose'); // Node Tool for MongoDB
const Schema = mongoose.Schema; // Import Schema from Mongoose
// User Model Definition
const cartSchema = new Schema({
email: { type: String, required: true, lowercase: true },
totalAmt: { type: Number },
foods : [ {
food :
{
type: mongoose.Schema.Types.ObjectId,
ref: "Food"
},
quantity : { type : Number ,default : 0}
}
]
},{
usePushEach: true
});
module.exports = mongoose.model('Cart', cartSchema);<file_sep>/client/src/app/gaurds/admin.gaurd.ts
import { Injectable } from '@angular/core';
import {Router, CanActivate} from "@angular/router"
import {AuthenticationService} from '../services/authentication.service';
import {Globals} from '../global';
@Injectable()
export class AdminGuard implements CanActivate{
constructor(private authenticationService : AuthenticationService,
private router : Router, private globals : Globals
) { }
canActivate(){
console.log(this.globals.admin);
if(this.authenticationService.loggedIn() && this.globals.admin){
return true;
}else{
this.router.navigate(['/']);
return false;
}
}
}
<file_sep>/client/src/app/components/profile/profile.component.ts
import { Component, OnInit,TemplateRef } from '@angular/core';
import {AuthenticationService} from '../../services/authentication.service';
import {FoodService} from '../../services/food.service';
import {FlashMessagesService} from 'angular2-flash-messages'
import {Router} from '@angular/router';
import { BsModalRef, BsModalService } from 'ngx-bootstrap';
import {Order} from '../../models/order';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css'],
providers : [AuthenticationService, FoodService,DatePipe]
})
export class ProfileComponent implements OnInit {
user : Object;
uid : string;
history : [Order];
modalError: string;
modalRef: BsModalRef;
selectedOrder: Order;
constructor(private authenticationService : AuthenticationService,
private foodservice : FoodService,
private flashMessages : FlashMessagesService,
private router : Router,
private modalService: BsModalService
) { }
ngOnInit() {
this.authenticationService.getProfile().subscribe(user =>{
this.uid = user.user._id;
this.user = user.user;
this.foodservice.getHistory(this.uid).subscribe(history =>{
console.log(history);
var temp = history;
temp.sort(function(a,b){
if(a.orderDate > b.orderDate)
return -1;
else if(a.orderDate < b.orderDate)
return 1;
else
return 0;
})
this.history = temp;
console.log(history);
})
},
err =>{
console.log("not looged in "+err);
this.flashMessages.show("User not logged in",{cssClass : "alert-danger", timeout: 1000});
this.router.navigate(['']);
})
}
showOrders(template, orderId) {
this.history.forEach((order)=>{
if(order._id == orderId){
this.selectedOrder = order;
}
});
this.modalRef = this.modalService.show(template);
}
}
<file_sep>/routes/user.js
const express = require("express");
const router = express.Router();
const passport = require("passport");
const jwt = require("jsonwebtoken");
var User = require("../models/user");
var config = require("../config/database");
var nodemailer = require("nodemailer");
router.get("/",(req,res)=>{
res.send("user route works");
});
//retrieve data
router.post("/login",(req,res,next)=>{
console.log("trying to login");
User.findOne({email : req.body.email},(err,user)=>{
console.log("user "+user);
if(user == null){
console.log("user "+user);
console.log("user does not exist");
res.json({ success: false, message: 'User does not exist. Please register' });
}else{
if(user.active==false){
res.json({ success: false, message: 'Email not verified' });
}else{
var password = <PASSWORD>;
console.log(password);
//console.log(user.comparePassword(password));
if(user.comparePassword(password)){
var userinfo ={
_id : user._id,
email : user.email,
password : <PASSWORD>
}
const token = jwt.sign(userinfo, config.secret,{
expiresIn: 60488
});
console.log("tokem created "+ token);
res.json({
success: true,
token : token,
user : {
id: user._id,
email : user.email
}
});
}else{
res.json({ success: false, message: 'Password invalid' });
}}
}
//res.json(user);
});
})
//add User
router.post("/register",(req,res,next)=>{
console.log("hedfgrer name" + req.body.name);
var rand=Math.floor((Math.random() * 100) + 54);
let newUser = new User({
name : req.body.name,
email: req.body.email,
password: <PASSWORD>,
type : req.body.type,
active : false,
rand : rand
});
User.findOne({email : req.body.email},(err,user)=>{
if(user == null){
console.log("going to register " + newUser);
newUser.save((err,user)=>{
if(err){
res.json({ success: false, message: ""+err });
}
else{
res.json({ success: true, message: 'registered successfully' });
}
});
}
else{
res.json({ success: false, message: 'Provided email has already been registered. Please try the login screen instead' });
}
});
})
//email verification
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "<EMAIL>",
pass: "<PASSWORD>"
},
tls: { rejectUnauthorized: false }
});
router.post("/sendmail",(req,res,next)=>{
User.findOne({email : req.body.email},(err,user)=>{
var userInfo = {};
userInfo.email = req.body.email;
userInfo.expiry = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var token = jwt.sign(userInfo, config.secret,{
expiresIn: 604888
});
console.log(token);
host=req.get('host');
link="http://"+host+"/api/user/verify?id="+token;
mailOptions={
to : req.body.email,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your foodrunner account.<br><a href="+link+">Click here to verify</a>"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.json({ success: false, message: 'email not sent' });
}else{
console.log("Message sent: " + response.message);
res.json({ success: true, message: 'email sent successful' });
}
});
});
});
router.get('/verify',function(req,res){
console.log(req.protocol+":/"+req.get('host'));
//if((req.protocol+"://"+req.get('host'))==("http://"+host))
{
console.log("Domain is matched. Information is from Authentic email");
if( req.query.id != null)
{
jwt.verify(req.query.id, config.secret, function(err,decoded){
console.log(decoded);
console.log(new Date().getTime() );
User.findOneAndUpdate({email : decoded.email} ,{ $set: { active : true }}, { new: true },(err,resp)=>{
if(!err)
res.send("<h2 style = 'color : green'>"+decoded.email + " has been verified</h2>");
})
})
}
else
{
console.log("email is not verified");
res.end("<h1>Bad Request</h1>");
}
}
// else
// {
// res.end("<h1>Request is from unknown source");
// }
});
router.get("/profile",passport.authenticate('jwt',{session:false}) ,(req,res,next) =>{
res.json({user: req.user});
})
module.exports = router;<file_sep>/client/src/app/services/authentication.service.ts
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
//import {Contact} from './contact';
import 'rxjs/add/operator/map';
import {tokenNotExpired} from 'angular2-jwt';
import { Globals } from '../global';
@Injectable()
export class AuthenticationService {
authToken : any;
user : any;
constructor(private http: Http, private globals : Globals) { }
login(userInfo){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/user/login',userInfo,{headers:headers})
.map(res =>res.json());
}
sendmail(userInfo){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/user/sendmail',userInfo,{headers:headers})
.map(res =>res.json());
}
register(userInfo){
var headers = new Headers();
console.log(userInfo.name);
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/user/register',userInfo,{headers:headers})
.map(res =>res.json());
}
storeUserData(user, token){
localStorage.setItem('id_token',token);
localStorage.setItem('user',JSON.stringify(user));
this.authToken = token;
this.user = user;
if(user.type == "A"){
this.globals.admin = true;
}
else{
this.globals.admin = false;
}
}
logout(){
this.authToken = null;
this.user = null;
localStorage.clear();
this.globals.admin = null;
}
getProfile(){
var headers = new Headers();
this.loadToken();
this.authToken = "Bearer "+ this.authToken;
headers.append("Authorization", this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/api/user/profile',{headers:headers})
.map(res =>res.json());
}
loadToken(){
this.authToken = localStorage.getItem("id_token");
}
loggedIn(){
return tokenNotExpired("id_token");
}
}
<file_sep>/routes/food.js
const express = require("express");
const router = express.Router();
var Food = require("../models/food");
router.get("/",(req,res)=>{
res.send("food route works");
});
router.get("/:fid",(req,res)=>{
Food.findById(req.params.fid,(err,food)=>{
if(food == null){
res.json({ success: false, food : req.params.fid, message: 'Food not available' });
}else
if(food.available == "N"){
res.json({ success: false, food : req.params.fid, message: 'Food not available' });
}else {
res.json({ success: true, food : food, message: 'Food available' });
}
});
});
router.put("/:fid",(req,res)=>{
console.log("adsdaaqweqwe");
var fid = req.params.fid;
Food.findByIdAndUpdate(fid,{ $set: {name : req.body.name, type : req.body.type,
price : req.body.price, image : req.body.image }}, { new: true },(err,resp)=>{
if (err){
console.log("something went wrong "+err);
res.json({ success: false, message: 'Could not update food' + err});
}else{
console.log("Successfully Updated food");
res.json({ success: true, message: 'Successfully update food' });
}
})
});
router.get("/:type/:q",(req,res)=>{
console.log("trying to get foods data for type "+ req.params.type+ " q " + req.params.q);
var q;
if(req.params.q=="all"){
q="";
}else{
q=req.params.q.toLowerCase();
}
if(req.params.type == "all"){
Food.find({name: new RegExp(q, "i"), available : "Y"},(err,foods)=>{
console.log(foods+err);
res.json(foods);
});
}else{
Food.find({type : req.params.type.toLowerCase(), name: new RegExp(q, "i"), available : "Y"},(err,foods)=>{
res.json(foods);
});
}
});
router.post("/",(req,res,next)=>{
var imagename = null;
if(req.body.image == null)
imagename = "7645c6effb10cb82cd152ee3c06b543d";
else
imagename = req.body.image;
let newFood = new Food({
name: req.body.name.toLowerCase(),
type: req.body.type.toLowerCase(),
price: req.body.price,
available: "Y" ,
image : imagename
});
console.log("going to add "+newFood);
Food.findOne({name : req.body.name},(err,food)=>{
if(food == null){
newFood.save((err,food)=>{
if(err){
res.json({ success: false, message: 'Could not add' });
}
else{
res.json({ success: true, message: 'Added successfully' });
}
});
}
else{
if(food.available == "N"){
Food.findByIdAndUpdate(food._id,{ $set: { available : "Y" , price : req.body.price, type : req.body.type.toLowerCase(),image : req.body.image}}, { new: true },(err,resp)=>{
if (err){
console.log("something went wrong "+err);
res.json({ success: false, message: 'Could not delete from cart' + err});
}else{
res.json({ success: true, message: 'Successfully added food' });
}
})
}else{
res.json({ success: false, message: 'Food already available' });
}
}
});
})
router.delete("/:fid",(req,res,next)=>{
var fid = req.params.fid;
Food.findByIdAndUpdate(fid,{ $set: { available : "N" }}, { new: true },(err,resp)=>{
if (err){
console.log("something went wrong "+err);
res.json({ success: false, message: 'Could not delete food' + err});
}else{
console.log("Successfully Deleted food");
res.json({ success: true, message: 'Successfully Deleted food' });
}
})
})
module.exports = router;<file_sep>/client/src/app/models/order.ts
import {FoodQuant} from './foodQuant';
export class Order{
_id : string
email : string;
totalAmt : number;
foods : FoodQuant[];
orderDate : Date;
};<file_sep>/client/src/app/components/food/food.component.ts
import { Component, OnInit } from '@angular/core';
import {FoodService} from '../../services/food.service'
import {Food} from '../../models/food'
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router} from '@angular/router'
@Component({
selector: 'app-food',
templateUrl: './food.component.html',
styleUrls: ['./food.component.css'],
providers : [FoodService]
})
export class FoodComponent implements OnInit {
image : string;
food : Food;
name : string;
type : string;
price : number;
constructor(private foodService : FoodService ,
private flashMessages : FlashMessagesService,
private router : Router) { }
ngOnInit() {
}
addNewItem(){
console.log("Here");
console.log(this.image) ;
if (this.image == undefined)
this.image = null;
var newItem = {
name : this.name,
type : this.type,
price : this.price,
image : this.image
};
console.log(newItem);
this.foodService.addNewItem(newItem).subscribe(info=>{
if (info.success){
console.log(info.message);
this.flashMessages.show("Successfully added to cart",{cssClass : "alert-success", timeout: 500});
this.router.navigate(['/menu']);
}else{
this.flashMessages.show("Failed to add item "+ info.message ,{cssClass : "alert-danger", timeout: 500});
}
})
}
onUploadFinished(event) {
this.image = JSON.parse(event.serverResponse._body).filename;
}
}
<file_sep>/client/src/app/components/cart/cart.component.ts
import { Component, OnInit } from '@angular/core';
import {AuthenticationService} from '../../services/authentication.service';
import {FlashMessagesService} from 'angular2-flash-messages';
import {FoodService} from '../../services/food.service';
import {Cart} from '../../models/cart';
import {Router} from '@angular/router';
import { BsModalRef, BsModalService } from 'ngx-bootstrap';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
uid : string;
cart : Cart;
todayDate : Date;
modalRef: BsModalRef;
constructor(private foodService: FoodService,
private authenticationService: AuthenticationService,
private flashMessages : FlashMessagesService,
private modalService : BsModalService,
private router : Router) { }
ngOnInit() {
this.authenticationService.getProfile().subscribe(user =>{
console.log(user.user.email);
this.uid = user.user._id;
this.foodService.getCart(this.uid).subscribe(cart=>{
this.cart = cart;
console.log(this.cart);
})
},
err =>{
console.log("Error in cart "+err);
this.flashMessages.show("Failed to retreive cart",{cssClass : "alert-danger", timeout: 1000});
})
}
deleteCart(fid){
var newAmount =0;
var cartFoods = [];
var deleteIdx;
console.log(this.cart.foods.length);
this.cart.foods.forEach((food, idx)=>{
console.log(food._id);
console.log(fid);
if(food._id == fid){
deleteIdx = idx;
}else{
newAmount = this.precisionRound(newAmount + this.precisionRound(food.quantity*food.food.price,2),2);
var foods = {quantity : food.quantity, _id : food._id, food : food.food._id};
cartFoods.push(foods);
}
});
this.cart.foods.splice(deleteIdx,1);
console.log(cartFoods);
this.cart.totalAmt = newAmount;
var cart = {_id : this.cart._id, email : this.cart.email, foods : cartFoods, totalAmt : newAmount};
if(cartFoods.length == 0){
this.foodService.deleteCart(this.uid).subscribe(info=>{
if (info.success){
console.log(info.message);
this.flashMessages.show("Successfully deleted from cart",{cssClass : "alert-success", timeout: 1000});
}else{
this.flashMessages.show("Failed to delete from cart",{cssClass : "alert-danger", timeout: 2500});
}
},
err =>{
console.log("Failed to delete from cart "+err);
this.flashMessages.show("Failed to delete cart",{cssClass : "alert-danger", timeout: 2500});
})
}else{
this.foodService.updateCart(cart,this.uid).subscribe(info=>{
if (info.success){
console.log(info.message);
this.flashMessages.show("Successfully deleted from cart",{cssClass : "alert-success", timeout: 1000});
}else{
this.flashMessages.show("Failed to delete from cart",{cssClass : "alert-danger", timeout: 2500});
}
},
err =>{
console.log("Failed to delete from cart "+err);
this.flashMessages.show("Failed to delete cart",{cssClass : "alert-danger", timeout: 2500});
})
}
}
precisionRound(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
onChange(fid){
var newAmount =0;
var cartFoods = [];
console.log("here1");
this.cart.foods.forEach((food)=>{
if(food.quantity == null)
food.quantity = 1;
console.log("food.quantity "+this.precisionRound(food.quantity*food.food.price,2));
console.log("food.food.price "+food.food.price);
newAmount = this.precisionRound(newAmount + (this.precisionRound(food.quantity*food.food.price,2)),2);
console.log("newAmount "+newAmount);
var foods = {quantity : food.quantity, _id : food._id, food : food.food._id};
cartFoods.push(foods);
});
console.log(cartFoods);
this.cart.totalAmt = newAmount;
var cart = {_id : this.cart._id, email : this.cart.email, foods : cartFoods, totalAmt : newAmount};
this.foodService.updateCart(cart,this.uid).subscribe(info=>{
if (info.success){
console.log(info.message);
this.flashMessages.show("Successfully updated cart",{cssClass : "alert-success", timeout: 500});
}else{
this.flashMessages.show("Failed to update cart",{cssClass : "alert-danger", timeout: 500});
}
},
err =>{
console.log("Failed to update cart "+err);
this.flashMessages.show("Failed to update cart",{cssClass : "alert-danger", timeout: 1000});
})
}
confirmOrder(){
var count=0;
this.cart.foods.forEach((foods)=>{
this.foodService.getAvailableFood(foods.food._id).subscribe(info=>{
if(info.success == false){
this.flashMessages.show(foods.food.name + " is not available anymore. Please delete it from cart",{cssClass : "alert-danger", timeout: 3000});
return false;
}else {
count++;
if(count == this.cart.foods.length){
console.log("adasd");
this.foodService.confirmOrder(this.uid).subscribe(info=>{
if (info.success){
console.log(info.message);
this.cart = null;
this.modalRef.hide();
this.flashMessages.show("Ordered Successfully",{cssClass : "alert-success", timeout: 2500});
this.router.navigate(['/menu']);
}else{
this.flashMessages.show("Failed to order",{cssClass : "alert-danger", timeout: 2500});
}
},
err =>{
console.log("Failed to order "+err);
this.flashMessages.show("Failed to order",{cssClass : "alert-danger", timeout: 2500});
})
}
}
})
})
}
incQuantity(fid){
console.log(fid);
var idx = this.cart.foods.findIndex(x => x._id == fid);
console.log(idx);
this.cart.foods[idx].quantity++;
console.log(idx+this.cart.foods[idx].quantity);
this.onChange(fid)
}
decQuantity(fid){
var idx = this.cart.foods.findIndex(x => x._id == fid);
if(this.cart.foods[idx].quantity!=1){
this.cart.foods[idx].quantity--;
}else{
return;
}
console.log(idx+this.cart.foods[idx].quantity);
this.onChange(fid)
}
showConfirmOrder(template){
this.todayDate = new Date();
this.modalRef = this.modalService.show(template);
}
}
<file_sep>/routes/cart.js
const express = require("express");
const router = express.Router();
var Cart = require("../models/cart");
var User = require("../models/user");
var Food = require("../models/food");
router.get("/",(req,res)=>{
res.send("cart route works");
});
router.get("/:uid",(req,res)=>{
console.log("trying to get cart data");
User.findById(req.params.uid,(err,user)=>{
Cart.findById(user.cart).populate("foods.food").exec((err,carts)=>{
console.log(carts+err);
res.json(carts);
});
})
});
function precisionRound(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
router.post("/:uid/:fid",(req,res,next)=>{
User.findById(req.params.uid,(err,user)=>{
console.log(user+err);
var fid = req.params.fid;
console.log(fid);
Food.findById(req.params.fid,(err,food)=>{
console.log("user.cart " + user.cart);
if (user.cart == undefined || user.cart == null){
let newCart = new Cart({
email: user.email.toLowerCase(),
totalAmt: food.price,
foods :[{food:fid, quantity: 1}]
});
newCart.save((err,resp)=>{
if (err){
console.log("something went wrong" + err);
res.json({ success: false, message: 'Could not add to cart ' + err });
}
var cid = resp._id;
User.findByIdAndUpdate(req.params.uid,{ $set: { cart : cid }}, { new: true },(err,resp)=>{
if (err){
console.log("something went wrong");
res.json({ success: false, message: 'Could not add to cart' + err });
}else{
res.json({ success: true, message: 'Added successfully to cart' });
}
});
});
}else{
var cartid = user.cart;
var flag = true;
console.log(cartid);
Cart.findById(cartid,(err,cart)=>{
console.log(cart);
cart.totalAmt = cart.totalAmt + food.price ;
cart.totalAmt = precisionRound(cart.totalAmt,2);
console.log(cart.totalAmt);
cart.foods.forEach((food, idx,foods)=>{
console.log(idx);
if(food.food == fid){
flag = false;
console.log("incrementing");
food.quantity = food.quantity +1;
cart.save((err,resp)=>{
if (err){
console.log("something went wrong");
res.json({ success: false, message: 'Could not add to cart' + err});
}else{
res.json({ success: true, message: 'Added successfully to cart' });
}
});
}else
if(idx == foods.length-1 && flag == true){
console.log("pushing");
cart.foods.push({food: fid,quantity : 1});
cart.save((err,resp)=>{
if (err){
console.log("something went wrong");
res.json({ success: false, message: 'Could not add to cart' + err});
}else{
res.json({ success: true, message: 'Added successfully to cart' });
}
})
}
})
})
}
});
});
})
router.delete("/:uid",(req,res,next)=>{
var uid = req.params.uid;
User.findByIdAndUpdate(uid,{$set : {cart : null}},{new : true},(err,resp)=>{
if (err){
console.log("something went wrong "+err);
res.json({ success: false, message: 'Could not delete' + err});
}else{
res.json({ success: true, message: 'Successfully deleted cart' });
}
})
})
router.put("/:uid", (req,res,next)=>{
console.log("In put for cart");
console.log(req.body.foods);
Cart.findByIdAndUpdate(req.body._id,{ $set: { totalAmt : req.body.totalAmt , foods : req.body.foods}}, { new: true },(err,resp)=>{
if (err){
console.log("something went wrong "+err);
res.json({ success: false, message: 'Could not update' + err});
}else{
res.json({ success: true, message: 'Successfully updated cart' });
}
})
})
module.exports = router;<file_sep>/client/src/app/components/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import {AuthenticationService} from '../../services/authentication.service';
import {Info} from '../../models/info';
import {FlashMessagesService} from 'angular2-flash-messages';
import {Router} from '@angular/router';
import {NavbarComponent} from '../navbar/navbar.component'
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [AuthenticationService,NavbarComponent]
})
export class LoginComponent implements OnInit {
email : string;
password : string;
info : Info;
constructor(private authenticationService : AuthenticationService,
private flashMessages : FlashMessagesService,
private router : Router,
private navbarComponent : NavbarComponent
) { }
ngOnInit() {
}
login(){
const userInfo = {
email : this.email,
password : <PASSWORD>
}
this.authenticationService.login(userInfo)
.subscribe(info => {
if(info.success == true){
//get full user info
this.authenticationService.storeUserData(info.user,info.token);
this.authenticationService.getProfile().subscribe(user =>{
this.authenticationService.storeUserData(user.user,info.token);
if(user.user.type == "A"){
this.navbarComponent.onLogin();
}
this.flashMessages.show("You are now logged in. Enjoy ordering", {cssClass : 'alert-success', timeout : 3000})
this.router.navigate(['menu']);
},
err =>{
console.log("not looged in "+err);
this.flashMessages.show("User not logged in",{cssClass : "alert-danger", timeout: 1000});
this.router.navigate(['']);
})
}else{
this.flashMessages.show("Log in Falied "+ info.message, {cssClass : 'alert-danger', timeout : 3000})
this.router.navigate(['login']);
}
})
}
}
|
e1583d2d0af34d8cf1c57578d7caa43d0934356a
|
[
"JavaScript",
"TypeScript",
"HTML"
] | 21
|
TypeScript
|
mgprathik27/Foodrunner
|
407de276e13ef0dad7a7dc3c91959b015d548cfa
|
8d8164743e96342b83dc8590c0a5d1c049d65e0f
|
refs/heads/master
|
<file_sep>const boxes = document.querySelectorAll('.box');
window.addEventListener('scroll',checkBoxes)
checkBoxes()
function checkBoxes(){
const triggerBottom = window.innerHeight/5*4;
boxes.forEach(box => {
const boxTop = box.getBoundingClientRect().top
console.log(boxTop,triggerBottom)
if(boxTop < triggerBottom) {
box.classList.add('show')
} else {
box.classList.remove('show')
}
})
}
// get the window height and do window.innerHeight/5*4 and save in one
// variable and get top lenght of box using getBoundingClientRect() md compare both
// and while scrolling down show class is trigerred and scrolling up remove show is triggered
// this fn will execute for each box and decide the place of the box.
|
56d67afb11fd59d4b652fd67c0629b9af11a2f23
|
[
"JavaScript"
] | 1
|
JavaScript
|
karthig-eng/Blurry-Loading
|
335f9d0e8f47732e23bac3ad8002d1f94df59a33
|
c786c76612aaf67870a439f02fb6e484d538a678
|
refs/heads/main
|
<file_sep>---
layout: post
title: "Getting Started with Ngrok"
date: 2020-06-05
categories: energize
---
I started working with ngrok in the last two days to set up my Alexa Skill
testing. I installed ngrok using Chocolatey and watched a [Flask-ask + ngrok
start guide]. I followed the guide to connect a basic Python script to Alexa.
However, I received the error
`There was a problem with the requested skill's response` again. ngrok
displayed `POST / 500 INTERNAL SERVER ERROR`. I'm too tired to work this out
tonight; I'll take a look tomorrow.
[Flask-ask + ngrok start guide]: https://www.youtube.com/watch?v=eC2zi4WIFX0
<file_sep>source "https://rubygems.org"
gem "jekyll"
gem "jekyll-paginate"
gem "jekyll-sitemap"
gem "jekyll-feed"
gem "jekyll-seo-tag"
gem "jekyll-sass-converter", "~> 2.0"
gem "webrick"
<file_sep>---
layout: post
title: "$HOME Sweet $HOME"
date: 2020-06-27
categories: energize
---
Setting up a new project has never felt this good. After the hell that was
working on Windows, Python 3.6 dependency installation going off without a
hitch on Linux was a great relief for me.
The only thing I needed to change was the import statement format. Reading
[this Stack Overflow answer] helped me understand the differences between
Python 2 and Python 3 imports.
[this Stack Overflow answer]: https://stackoverflow.com/a/12173406
<file_sep>---
layout: post
title: "Legacy Blog"
date: 2020-05-01
categories: energize
---
Posts prior to May 2020 can be found on my old site, [energize-fs.weebly.com].
[energize-fs.weebly.com]: https://energize-fs.weebly.com/
<file_sep>---
layout: post
title: "ECIS Project Setup"
date: 2020-07-10
categories: ecis
---
I had chosen to use `virtualenv` for my last Python project
because all the guides that I had found for Alexa development used it.
Since I feel more comfortable working with virtual environments now,
I felt that this was a good chance to explore a new tool that I had head about.
Called [Poetry](https://python-poetry.org/),
it offered an intuitive CLI for managing project dependencies, building,
and publishing to PyPI.
Reading Poetry's [basic usage commands](https://python-poetry.org/docs/basic-usage/),
I was amazed by its ease of use;
I installed it and used it to set up my project.
I also set up PyCharm on my freshly-installed Manjaro system.
However, I ran into a strange issue: I couldn't open .md or .rst files.
Looking up the error message, I found
[this article](https://medium.com/@julianvargkim/how-to-fix-tried-to-user-preview-panel-provider-javafx-webview-error-on-linux-manjaro-ac5b6326ee1a)
that had my exact problem.
Following its advice, I built PyCharm with a bundled JRE from the AUR,
and it worked.
<file_sep>---
layout: post
title: "A New Data Model for Pokésummary"
date: 2022-05-29
---
This past week, I made significant technical changes to [Pokésummary](https://github.com/pyjamafish/pokesummary),
my command-line Python program.
In this blog post, I'll recount the process of redesigning the data model.
## Some background
Pokésummary version 1 consisted of three modules:
`__main__.py`, which contained the logic for reading Pokémon data into memory and handled the command-line interface;
`displaying.py`, which handled displaying Pokémon summaries;
and `parsing.py`, which contained a utility function for reading `csv` files into dictionaries.
I was unsatisfied with this structure--I didn't like how `__main__.py`
violated the single responsibility principle.
Additionally, with the way I stored Pokémon data into memory,
it was hard to reason about my program.
In `__main__.py`, I had the following code to get the data of every Pokémon:
```python
data_dictionary = parsing.csv_to_nested_dict(
"pokesummary.data",
"pokemon_modified.csv",
"pokemon_name"
)
```
This gave me a 2D dictionary: the outer dictionary mapped Pokémon names to stats,
and the inner dictionaries (the stats) mapped specific attributes (e.g. "attack_stat") to values (e.g. 49).
The problem was that my code didn't explicitly define which attributes the stats should have.
The attributes were given by my *dataset*,
so my code in `displaying.py` had to know the column names of my dataset to access attributes.
For example, here is how I accessed a Pokémon's classification:
```python
pokemon_stats['classification']
```
Since the column name for Pokémon classifications in the dataset is
"classification", I had to use that string as my dictionary key.
Surely there was a better way.
## The model-view-controller design pattern
I remembered someone had once told me about the model-view-controller design pattern.
The idea is to separate your program into three components:
the model manages the program's data,
the view displays the data,
and the controller responds to user input.
It seemed like this could work well for Pokésummary.
I had the view already, `displaying.py`.
I also had the controller, `__main__.py`.
I just needed a model for Pokémon stats.
Creating this model would explicitly define which attributes were available,
and separating out the logic that read data into it from the controller
would satisfy the single responsibility principle.
## Data Classes
Since my Pokémon stats model would store data,
I implemented it using Data Classes.
With normal classes, you need to write an `__init__()` method (the constructor).
Data Classes make things simpler by automatically generating it;
all you need to do is define the class's attributes and their types[^1].
I made a `Pokemon` class, which contains a `PokemonBaseStats`--here is the code:
```python
@dataclass(frozen=True)
class BaseStats:
hp: int
attack: int
defense: int
special_attack: int
special_defense: int
speed: int
@dataclass(frozen=True)
class Pokemon:
name: str
classification: str
height: float
weight: float
primary_type: str
secondary_type: str
base_stats: BaseStats
```
Now, with Data Classes, the available attributes are explicitly defined.
I can also now use dot notation,
which is much cleaner than using key lookup:
```python
pokemon.classification
```
## Inheriting from UserDict
Next, I needed a way to read my dataset into a collection of `Pokemon` objects.
I thought it'd be nice to create my own class that mapped strings to `Pokemon`;
the class could encapsulate reading from my dataset.
Maybe inherit from `dict`?
But, reading an [article](https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/) on this,
I saw that inheriting from `dict` had some unexpected behavior.
So, I followed the article's advice and inherited from `UserDict` instead.
`UserDict` is a wrapper around a dictionary object,
but it is implemented such that values can be accessed just like a dictionary.
The `UserDict` constructor allowed me to give the internal dictionary some initial data.
So, to implement `PokemonDict`,
I created a static method to read my dataset into a dictionary,
and I passed the output of this method into the constructor.
```python
class PokemonDict(UserDict):
def __init__(self):
pokemon_dictionary = self.read_dataset_to_dictionary()
UserDict.__init__(self, pokemon_dictionary)
@staticmethod
def read_dataset_to_dictionary():
with resources.open_text(data, "pokemon_modified.csv") as f:
csv_iterator = csv.DictReader(f)
dataset_dict = {
csv_row["pokemon_name"]: Pokemon(
name=csv_row["pokemon_name"],
classification=csv_row["classification"],
height=float(csv_row["pokemon_height"]),
weight=float(csv_row["pokemon_weight"]),
primary_type=csv_row["primary_type"],
secondary_type=csv_row["secondary_type"],
base_stats=BaseStats(
hp=int(csv_row["health_stat"]),
attack=int(csv_row["attack_stat"]),
defense=int(csv_row["defense_stat"]),
special_attack=int(csv_row["special_attack_stat"]),
special_defense=int(csv_row["special_defense_stat"]),
speed=int(csv_row["speed_stat"]),
)
)
for csv_row in csv_iterator
}
return dataset_dict
```
Although this dictionary comprehension isn't too pretty,
it's much more explicit than before.
Each attribute of the `Pokemon` class is mapped to a value from the current row.
And with this, I was able to replace the complicated `csv_to_nested_dict` call with one line:
```python
pokemon_dict = PokemonDict()
```
The logic of reading Pokémon data is no longer in the controller part of the program,
thus satisfying the single responsibility principle.
With both of my problems solved,
I could finally rest easy--wait no, who am I kidding?
As always, I wanted to do more.
## Enums
There was one thing in particular that was bothering me:
I had stored Pokémon types as strings, but it would be better to represent them using enum members
since there's a small set of Pokémon types.
Enums are great in cases like these because they clearly document the possible values
and prevent errors caused by using invalid ones[^2].
I created an enum, `PokemonType`:
```python
@unique
class PokemonType(Enum):
NORMAL = "Normal"
FIRE = "Fire"
# ... [rest of the types omitted for brevity]
```
Now, in the `Pokemon` class, I could write:
```python
primary_type: PokemonType
```
and in `PokemonDict`:
```python
primary_type=PokemonType(csv_row["primary_type"]),
```
But, what about secondary type?
A Pokémon might not have two types; in that case, `csv_row["secondary_type"]` would be an empty string.
With enums, I initially thought I'd have a `NO_TYPE = ""` member.
However, it didn't make sense for `NO_TYPE` to show up when you iterated through the enum members.
Looking this up, it seemed like the [consensus](https://stackoverflow.com/a/1795662)
was that it's better to use a nullable: a variable set to `None` in the absence of a value.
My initial code for this was probably the worst Python I've ever written.
```python
secondary_type=PokemonType(s) if (s := csv_row["secondary_type"]) else None
```
Since this was in the dictionary comprehension,
I needed to use an assignment expression (`:=`), which isn't supported in Python 3.7.
A clear no-go.
I ended up learning about class methods[^3],
which are commonly used to provide multiple ways to instantiate a class.
I wrote a class method with the same functionality as the above code block:
```python
@classmethod
def optional_pokemon_type(cls, s: str):
if s == "":
return None
return cls(s)
```
With this, I could write:
```python
secondary_type=PokemonType.optional_pokemon_type(csv_row["secondary_type"])
```
Still pretty long, but much easier to understand.
## The grid of type defenses
With `PokemonType` as an enum, I could use its members as the keys of a dictionary.
So, I rewrote the code for the grid of type defenses to use `PokemonType`.
First, I defined `TypeDefenses` as an alias for `Dict[PokemonType, float]`.
Then, I wrote the `TypeDefensesDict` class; although similar to `PokemonDict`, it caused me a fair amount of pain to write.
Here is its `_read_dataset_to_dict()` method:
```python
@staticmethod
def _read_dataset_to_dict() -> Dict[PokemonType, TypeDefenses]:
with resources.open_text(data, "type_defenses_modified.csv") as f:
data_iterator = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
# Gets the column names as a list of PokemonType members.
attacking_types = [
PokemonType(s)
for s in data_iterator.__next__()[1:]
]
all_type_defenses = {
PokemonType(row[0]): dict(
zip(attacking_types, cast(List[float], row[1:]))
)
for row in data_iterator
}
return all_type_defenses
```
I found that you could read numbers directly as floats using `quoting=csv.QUOTE_NONNUMERIC`,
but the problem was, Python couldn't know that each `row` contained all floats besides the first element.
Mypy kept giving me errors, thinking that the elements of each `row` were all supposed to be strings.
I came up with some ideas to resolve this,
but they didn't work,
so I ended up using the `cast` function from `typing` to make mypy happy.
## Addendum: Why not use namedtuples?
I experimented with using namedtuples to store Pokémon data instead of Data Classes.
From a purely practical standpoint, namedtuples are better--they are slightly faster,
reducing the time to print two summaries by around 10ms.
They also use less memory; when I left `pokesummary -i` open,
the version with Data Classes used 11MB of memory,
while the version with namedtuples used 10MB of memory.
However, using namedtuples makes less sense than using Data Classes from a design standpoint.
From my understanding, namedtuples should only be used as a replacement for tuples[^4];
they keep all the functionality of tuples.
So, namedtuples are iterable, and they can be unpacked.
This kind of functionality doesn't make sense for Pokémon objects.
[^1]: Data Classes also generate `__repr__()`, `__eq__()`, and `__hash__()`, but these aren't relevant in Pokésummary.
[^2]: See [here](https://stackoverflow.com/a/4709224) for a general explanation of enums, and [here](https://stackoverflow.com/a/37601645) for a Python-specific one.
[^3]: See [this article](https://realpython.com/python-multiple-constructors/#providing-multiple-constructors-with-classmethod-in-python) for a more thorough explanation of class methods.
[^4]: I gathered this from reading this [thread](https://news.ycombinator.com/item?id=15132670) on Hacker News.<file_sep>---
layout: post
title: "Zappa Setup and Confusion"
date: 2020-05-30
categories: energize
---
I continued the guide today. I created an IAM User for zappa-deploy on AWS,
configured the credentials locally, deployed the Skill with Zappa, and
configured the skill in the Alexa developer console.
Testing the skill showed an error though,
`There was a problem with the requested skill's response`. I replaced my Python
code with a simple one-line response in case the problem is version
incompatibility, but I still received the same error. This is really strange
because I followed the guide pretty well; the only exception is that I'm using
Python 3 (flask-ask and Zappa currently support it).
<file_sep>---
layout: post
title: "Success, Finally"
date: 2020-06-23
categories: energize
---
With everything working on GalliumOS, development proceeded with full steam. In
the past weeks, I set up the temperature functions for individual rooms and
wing averages. I also successfully tested my code by running it with Ngrok.
In the next week, I hope to migrate my code from Python 2 to Python 3.
<file_sep># Fisher's Blog
[](https://app.netlify.com/sites/fishersblog/deploys)
My programming blog. I should really update it more...
<file_sep>---
layout: post
title: "A Different Approach: Cookiecutter"
date: 2020-06-04
categories: energize
---
I didn't make any progress with Zappa in the last few days, so today I tried a
different approach. I researched [Cookiecutter], a CLI utility that creates
projects from templates. I found [this flask-ask template] for Cookiecutter
that should be helpful.
I switched to PyCharm on Windows (because I miss GUI) and set up the project
structure with the template. However, I ran into a problem installing certain
dependencies. Installing cffi raises `IndexError: list index out of range`.
Installing cryptography also failed. I saw that newer versions were already
installed, so I changed the condition in `requirements.txt` from `==` to `>=`.
This seemed to fix the issues.
I also researched Python virtual environments. Here are articles and
discussions that I read:
- [Pipenv & Virtual Environments]
- [What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?]
- [Should I use pipenv or virtualenv?]
- [Pipenv vs virtualenv vs conda environment]
From my reading, it seems that there is no clear consensus on the recommended
Python virtual environment currently. `venv` is part of the Python standard
library, but it has less features than the other options. `pipenv` is a higher
level, third party tool. However, it's not as reliable. `virtualenv`is also a
third party tool, but it's lower level than `pipenv`. I chose `virtualenv`
because it's recommended for beginners.
[Cookiecutter]: https://cookiecutter.readthedocs.io/en/1.7.2/README.html
[this flask-ask template]: https://github.com/chrisvoncsefalvay/cookiecutter-flask-ask
[Pipenv & Virtual Environments]: https://docs.python-guide.org/dev/virtualenvs/
[What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?]: https://stackoverflow.com/questions/41573587/what-is-the-difference-between-venv-pyvenv-pyenv-virtualenv-virtualenvwrappe
[Should I use pipenv or virtualenv?]: https://www.reddit.com/r/learnpython/comments/9lrcee/should_i_use_pipenv_or_virtualenv/
[Pipenv vs virtualenv vs conda environment]: https://medium.com/@krishnaregmi/pipenv-vs-virtualenv-vs-conda-environment-3dde3f6869ed
<file_sep>---
layout: post
title: "Refactoring"
date: 2020-07-13
categories: ecis
---
Today, I joined a Python-focused Discord server for code review.
My algorithm used a nested loop to iterate within the range of years
and my new list of lists.
This didn't feel very elegant, so I wanted some feedback.
```python
column_names = ["P_ID"]
# Iterate through year intervals
for current_year in range(earliest_year, latest_year + 1, 2):
column_names.append(
str(current_year) + "–" + str(current_year + 1)
if current_year != latest_year
else str(latest_year)
)
for row in rows:
...
```
We discussed ways that it could be refactored.
One member brought up using a Cartesian product using
[itertools.product()](https://docs.python.org/3/library/itertools.html#itertools.product).
This sounded smart, but what is a Cartesian product?
It turned out to just be the set of all pairs whose first element is from the first
set and second element is from the second set.
For example, here is the Cartesian product of {x,y,z}×{1,2,3}.
<a title="Quartl, CC BY-SA 3.0 <https://creativecommons.org/licenses/by-sa/3.0>, via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Cartesian_Product_qtl1.svg">
<img width="512" alt="Cartesian Product qtl1" src="/assets/img/cartesian.png" class="centered-image">
</a>
If I replaced my nested loop using `itertools.product()`, it would look like this:
```python
product = itertools.product(range(earliest_year, latest_year + 1, 2), rows)
for year, row in product:
...
```
But, there wasn't a good method to get the column names this way.
I then thought that I might as well create a DataFrame before the loop and append rows to it,
but I read through the documentation of `DataFrame.append()`
and saw that this was not recommended.
The Notes section reads,
> Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate.
A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.
The better solution was essentially what I had before,
so I decided to leave it for now.
One other suggestion that I received was to use formatted string literals.
Reading this [article](https://realpython.com/python-f-strings/),
I learned that formatted string literals, or f-strings for short,
are an easier way to include the value of expressions inside strings.
This interested me, and I added them to my code. Here are some before and afters:
```python
str(current_year) + "–" + str(current_year + 1) # Before 1.
f"{current_year}–{current_year + 1}" # After 1.
"Done! Processed data saved to " + file_output # Before 2.
f"Done! Processed data saved to {file_output}" # After 2.
```
These weren't big changes,
but using f-strings felt much better than adding strings together.
Finally, I read about type annotations from
[this article](https://dev.to/dstarner/using-pythons-type-annotations-4cfe),
and I added them to my code. These just helped me remember how things worked
a little easier.
<file_sep>---
layout: post
title: "First Steps Again"
date: 2020-05-29
categories: energize
---
Today, I started following the Flask-Ask + Zappa guide. I'm using Ubuntu 18 on
Windows Subsystem for Linux (WSL) to hopefully ease development.
I had an issue where I couldn't install virtualenv with pip. This was fixed by
passing the `--user` argument. With this fixed, I created my virtual
environment to install my dependencies, but I ran into another error: I
couldn't install flask-ask. I received
`ModuleNotFoundError: No module named 'pip.req'`. Looking this up, I found this
related issue: [Flask-ask using Python 3.7 image]. I realized that the guide is
written for Python 2.7; I could run into more issues later if I continue to use
Python 3.x. However, I really don't want to use 2.7 because it's not supported
anymore.
I found the solution in [this Stack Overflow question]. Downgrading pip to 9.x
with `pip install --upgrade "pip<10"` fixed my issue.
[Flask-ask using Python 3.7 image]: https://github.com/tiangolo/uwsgi-nginx-flask-docker/issues/133
[this Stack Overflow question]: https://stackoverflow.com/questions/51273969/virtutalenv-command-python-setup-py-egg-info-failed-with-error-code-1
<file_sep>---
layout: post
title: "Working on Windows Makes Me Sad"
date: 2020-06-06
categories: energize
---
Troubleshooting yesterday's error, I found [this Github issue]. On it, a
contributor recommended to test the connection by running ngrok without a
service. I tried this, and ngrok reported a connection successfully
established. The contributor and this [Stack Overflow answer] then recommended
to downgrade cryptography \< 2.2.
However, downgrading cryptography \< 2.2 resulted in an error,
`Failed building wheel for cryptography`. I couldn't find anything helpful for
this, so I suspected that it was due to using Python 3. I then tried switching
to Python 2. I installed Python 2, but somehow `pip` and `python` commands
didn't work. They just opened the Windows Store page for Python. Looking this
up, I found [a relevant Stack Overflow question]. I followed both answers,
adding Python to PATH on re-installation and removing aliases, but they still
didn't work.
I felt that it wasn't worth this headache to continue using Windows. I switched
to my Chromebook (that I had installed GalliumOS on) to get both library
compatibility and PyCharm. I had not previously used it for development because
its CPU and RAM were weaker than my Windows laptop, but I'm getting desperate.
I just want things to work.
During setup, I had an issue installing cryptography, but I was successful
after just [installing a few dependencies].
[this Github issue]: https://github.com/3SpheresRoboticsProject/flask_ask_ros/issues/3
[Stack Overflow answer]: https://stackoverflow.com/a/49466811
[a relevant Stack Overflow question]: https://stackoverflow.com/questions/58754860/cmd-opens-window-store-when-i-type-python
[installing a few dependencies]: https://stackoverflow.com/a/22210069
<file_sep>---
layout: post
title: "Linux for Windows Users"
date: 2021-01-07
categories: energize
---
In the past month,
I invited a few computer science students to join the Energize Andover club.
Most of them used Windows.
Remembering how frustrating development had been for me on Windows,
I shuddered at the thought of returning to that hell with them
if I were to guide them through working with pandas.
I needed to find a way for them to access a Linux environment on Windows.
I had used (and currently use) Windows Subsystem for Linux,
and it works quite well.
However, the installation process is fairly time-consuming,
and installing an entire distribution (about 2G of disk space) seemed like overkill
for students who were unsure about joining.
I then remembered that my trial AWS EC2 server is still running,
and Windows has the OpenSSH Client installed by default.
I created an "energize" user on the server,
and I modified the server's configuration to allow password login for that user[^1].
Students could now access a Linux environment by simply running a command in Command Prompt—
no installation required.
This was quite convenient,
and there were also some added bonuses.
They would have quick access to any dev tools I install
because they wouldn't need to also go through the installation processes themselves.
And, any issues that come up should be easier to investigate
because I can access the exact files or software in which they occur.
However, on the first meeting that we tried using the server,
we came across two big problems.
First, everything was very slow.
Resolving the dependencies of a Python project using Poetry,
a process that took under 30 seconds locally,
took over 8 minutes on the server.
Even connecting to the server and sending commands seemed slow.
Second, installing pandas didn't even work.
The server had Python 3.6.9 running;
this was supposed to be supported.
But, trying to install pandas in a virtual environment failed due to version incompatibilities.
To solve the first problem, I viewed the server's running processes.
I found that I had left some services running from when I was trying out EC2 for the first time,
so I stopped them and uninstalled them.
This made the server much faster.
To fix the second problem, I tried installing [pyenv](https://github.com/pyenv/pyenv).
This is a tool that Dan recommended me;
it helps install and switch between multiple Python versions.
I read [this article](https://realpython.com/intro-to-pyenv/)
to refresh my knowledge on pyenv and its commands.
Then, I used pyenv to install the latest version of Python (3.9.1).
Installing pandas in Python 3.9.1 worked!
To switch from the system Python to Python 3.9.1, I can use:
```bash
pyenv shell 3.9.1
```
This will only change my shell's Python;
other people logged in are not affected.
Now I can create a project in 3.9.1 (named demo1 in this example) using Poetry:
```bash
poetry new demo1
cd demo1
poetry add pandas
poetry install
```
To switch back to the system Python, I can use:
```bash
pyenv shell --unset
```
With the performance and compatibility problems taken care of,
the server is ready for our new members to try pandas!
[^1]: I realize that passwords are much less secure than keys, but I don't understand keys well enough right now to explain how they work or how to add one to a server. For now, I've made the password strong, but I'll definitely learn more about SSH keys in the future.
<file_sep>---
layout: page
title: About
permalink: /about
---
## About the Author
Hey, I'm Fisher!
I'm a CS student at Washington University in St. Louis.
## About this Blog
In this blog,
I plan to document projects I work on, issues I encounter, and things I learn.
The text of this blog (not including code excerpts) is licensed under
[Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/).
The website is built from Lagrange by <NAME>,
which uses the MIT License.
My modifications to Lagrange also use the MIT License.
<file_sep>---
layout: post
title: "List Comprehensions and Vectorization"
date: 2020-07-12
categories: ecis
---
Today, I applied my plan from yesterday.
To format the items in each cell, I learned about
[list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions),
an elegant and efficient way to create lists in Python.
For each cell,
I used a list comprehension
to create a list of all the diagnoses within the year interval.
Then, I merged the elements together with `join()`.
During my research on how to combine the diagnoses together,
I came across
[a very informative write-up](https://stackoverflow.com/a/55557758/14106506)
that warned against iteration. The author writes,
"[i]teration in Pandas is an anti-pattern
and is something you should only do when you have exhausted every other option".
That shocked me!
I remember that I and fellow Energize Andover members had often used
`iterrows()` in our code.
Reading on, I learned that iterating through `DataFrame`s is much slower than
the other options that Pandas provides for multi-element operations.
One option is using vectorized functions.
In contrast to iteration, where single elements are processed repeatedly,
vectorization is where multiple elements are processed
with a single operation simultaneously.
This leads to great improvements in performance for large datasets.
Here is the post's benchmark of different methods that add two columns together.
As you can see, the vectorized implementation `vec` really outperforms
the other implementations at a large number of elements `N`.
<img src="/assets/img/benchmark.png" alt="Benchmark" class="centered-image">
I feel enlightened with this new understanding of Pandas.
I hope to gain some experience working with vectorized functions
and hopefully rewrite my old Energize Andover code to use them instead of
`iterrows()`.
<file_sep>---
layout: post
title: "Towards Python 3 and More Windows Issues"
date: 2020-06-26
categories: energize
---
Since moving to Python 3 meant setting up my project again, I thought that I
might as well give Windows a try again. Little did I know the horrors I would
face!
The first problem, although frustrating, was not Windows' fault. Trying to
install Flask-ask in my Python 3.8 virtual environment gave me an error:
`ModuleNotFoundError: No module named 'pip.req'`. After some searching, I found
[a Stack Overflow question with my exact problem]. It turns out, this issue was
on Flask-Ask's side, and it was fixed two years ago. However, the patch was
never released to PyPi. To resolve it, I needed to install Flask-Ask from
Github.
When I installed Flask-Ask from Github, I received the message,
`error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio"`.
I found the Build Tools [here], under All Downloads: Tools for Visual
Studio 2019. This was a 4GB download! I was quite baffled that I needed to
download something so large just to get my Python libraries working.
I installed the Build Tools for Visual Studio and tried again. This time, I
received the message,
`fatal error C1083: Cannot open include file: 'openssl/opensslv.h': No such file or directory'`.
I checked [cryptography's docs]. I found that because I'm using Windows, I
needed to set the LIB and INCLUDE environment variables.
I set the environment variables and tried again. This time, I received hundreds
of error messages that repeated
`_openssl.obj : error LNK2001: unresolved external symbol` with slight
variations. I searched for some time, but the only relevant article or
discussion I found for this issue was [this unanswered Stack Overflow
question]. The original poster solved the problem by downgrading their Python
to 3.4. This isn't something I'm interested in trying because 3.4 is not
supported anymore, so using it would have made moving from Python 2 pointless.
The alternative would be trying to build OpenSSL from source, but at this point
I've gotten too tired of working on Windows. I really miss the smooth
installation processes of libraries for Linux; I'm not going to leave Linux
again.
[a Stack Overflow question with my exact problem]: https://stackoverflow.com/questions/60284354/pip-installing-flask-ask-raises-modulenotfound-pip-req
[here]: https://visualstudio.microsoft.com/downloads/#
[cryptography's docs]: https://cryptography.io/en/latest/installation.html#building-cryptography-on-windows
[this unanswered Stack Overflow question]: https://stackoverflow.com/questions/30159358/pip-install-cryptography-error-failed-with-exit-status-1120
<file_sep>---
layout: page
title: Contact
permalink: /contact
---
Feel free to contact me if you want to discuss programming!
My email is <EMAIL>.
<file_sep>---
layout: post
title: "Data Input"
date: 2020-07-11
categories: ecis
---
I read about the `.json` format from this
[series on Tutorialspoint](https://www.tutorialspoint.com/json/json_overview.htm).
Looking at the test data (`STC_dx.json`) that I've been given,
`"data"` is an array of objects.
Each object represents a single diagnosis,
containing a diagnosis code, date, patient id, and diagnosis name.
Here are an example 2 objects (out of 9):
```json
{
"data": [
{
"DX_CODE": "427.31",
"DIAG_DATE": "2012/03/25 00:00:00.000000000",
"P_ID": "Z324563",
"DX_NM": "Atrial fibrillation (CMS/HCC)",
"P_MRN_ID": "000167426",
"E_ID": null
},
{
"DX_CODE": "725",
"DIAG_DATE": "2011/11/10 00:00:00.000000000",
"P_ID": "Z273652",
"DX_NM": "Polymyalgia rheumatica (CMS/HCC)",
"P_MRN_ID": "000256352",
"E_ID": 12256152437
}
]
}
```
My first task is to convert this data into `DataFrame` format, with the rows
representing each patient and the columns representing 2-year intervals.
So, each cell should contain a patient's diagnoses for a 2-year interval.
Here is a table I made to visualize the general form:
| | YYYY–YYYY+1 | YYYY+2–YYYY+3 |
|-------|----------------------------------|----------------------------------|
| P_IDA | DX_CODE1—DX_NM1; DX_CODE2—DX_NM2 | DX_CODE3—DX_NM3; DX_CODE4—DX_NM4 |
| P_IDB | DX_CODE5—DX_NM5; DX_CODE6—DX_NM6 | DX_CODE7—DX_NM7; DX_CODE8—DX_NM8 |
I began by simply reading the `.json` file with `pd.read_json(json_file)`.
The resulting DataFrame looked like this:
```
diagnosis
0 {'DX_CODE': '427.31', 'DIAG_DATE': '2012/03/25...
1 {'DX_CODE': 'H53.9', 'DIAG_DATE': '2014/07/17 ...
2 {'DX_CODE': '725', 'DIAG_DATE': '2009/11/10 00...
3 {'DX_CODE': '725', 'DIAG_DATE': '2011/08/11 00...
4 {'DX_CODE': None, 'DIAG_DATE': '2004/10/15 00:...
5 {'DX_CODE': '272.0', 'DIAG_DATE': '2006/09/21 ...
6 {'DX_CODE': '729.81', 'DIAG_DATE': '2012/11/10...
7 {'DX_CODE': '446.5', 'DIAG_DATE': '2010/07/11 ...
8 {'DX_CODE': '725', 'DIAG_DATE': '2011/11/10 00...
```
All the data was stored in one column;
I needed to distribute it to take advantage of Pandas' functions.
Following [this Stack Overflow answer](https://stackoverflow.com/a/53967353/14106506),
I added code to flatten the object, and I dropped the unnecessary columns.
Here is the resulting DataFrame:
```
DX_CODE DIAG_DATE P_ID DX_NM
0 427.31 2012-03-25 Z324563 Atrial fibrillation (CMS/HCC)
1 H53.9 2014-07-17 Z324563 Visual disturbance
2 725 2009-11-10 Z324563 Polymyalgia rheumatica (CMS/HCC)
3 725 2011-08-11 Z324563 Polymyalgia rheumatica (CMS/HCC)
4 None 2004-10-15 Z273652 Disorder of bone and cartilage
5 272.0 2006-09-21 Z273652 Pure hypercholesterolemia
6 729.81 2012-11-10 Z273652 Swelling of limb
7 446.5 2010-07-11 Z273652 Giant cell arteritis (CMS/HCC)
8 725 2011-11-10 Z273652 Polymyalgia rheumatica (CMS/HCC)
```
Now we're talking. My plan now to transform the data is:
1. Get the earliest and latest years.
2. Create a list of lists for rows.
3. Iterate through the year ranges to fill in the sublists.
4. Create a new `DataFrame` from the list of lists.
I will implement these steps tomorrow.
<file_sep>---
layout: post
title: A Noble Cause
date: '2020-07-10'
categories: ecis
---
Today, I was introduced to a project called Etiologic Classification for
Ischemic Stroke (ECIS) through Electronic Health Record-based Natural Language
Processing. Lead by Dr. <NAME>, a professor at the University of
Massachusetts Medical School, this project aims to develop software that
automatically classifies the causes of ischemic stroke (IS).
Here is some background information that I learned:
- Stroke is a major issue in today's world, as it is the 5th leading cause of
death in the US and 2nd leading cause of death globally.
- The majority of the burden of stroke is attributed to IS.
- Etiologic subtype classification (identifying the causes) of IS is critical
for treatment management and outcome prediction.
- However, classification is currently performed through manual chart review,
a time-consuming, error-prone process.
- By developing a deep learning-based NLP system for automatic
classification, the project hopes to overcome these limitations.
I was assigned to work on the pre-processing software; my program would use
Pandas to manipulate the Electronic Health Record (EHR) data into a NLP
system-usable format. I'm eager to contribute to a project that can potentially
help improve the treatment of stroke victims, and I'm grateful for the chance
to improve my work with <NAME> using the new Pandas knowledge that I
learn.
<file_sep>---
layout: post
title: "A New Hope"
date: 2020-05-28
categories: energize
---
Trying to figure out serverless has been fruitless in the last few weeks. I've
asked Mr. Navkal and fellow Energize Andover members about my issue, but we
haven't found any success.
Today, I researched some alternatives for deploying code. [Zappa] is a Python
specific tool for building and deploying event-drive software on AWS Lambda.
However, it's less popular than serverless. [Flask-Ask] is a framework that
makes it easier to develop Skills with Python. I found [this guide] for getting
started with it. Also, I found [this guide][1] for using it in conjunction with
Zappa.
I decided on using the Flask-Ask + Zappa guide for this project. It should
spare me some headache, hopefully.
[Zappa]: https://github.com/Miserlou/Zappa
[Flask-Ask]: https://flask-ask.readthedocs.io/en/latest/index.html
[this guide]: https://developer.amazon.com/blogs/post/Tx14R0IYYGH3SKT/Flask-Ask-A-New-Python-Framework-for-Rapid-Alexa-Skills-Kit-Development
[1]: https://developer.amazon.com/blogs/alexa/post/8e8ad73a-99e9-4c0f-a7b3-60f92287b0bf/new-alexa-tutorial-deploy-flask-ask-skills-to-aws-lambda-with-zappa
|
92ac84ea93f27034f2a5ef932eea93d4a397b996
|
[
"Markdown",
"Ruby"
] | 21
|
Markdown
|
tactlessfish/tactlessfish.github.io
|
19e8ca1865b49cdd885638dc9a15dba7d0ad7af3
|
5d240c55b8c3b8ad808bd8b2cb7ac82090a8b313
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// DAy8iOS
//
// Created by MacStudent on 2019-03-12.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.readInformationPlist()
// Do any additional setup after loading the view, typically from a nib.
}
func readInformationPlist() {
if let bundlePath = Bundle.main.path(forResource: "employee", ofType: "plist") {
let dictionary = NSMutableDictionary(contentsOfFile: bundlePath)
print(dictionary!.description)
let countryList=dictionary!["countries"] as! NSArray
for i in countryList{
print(i)
}
print("**********************\nEmployee Details\n**********************\n////////////////////////////////")
let employeeList=dictionary!["employees"] as! NSArray
for e in employeeList{
let ed=e as! NSDictionary
print("Employee ID: \(ed["eid"]!)")
print("Employee name: \(ed["ename"]!)")
print("Salary: \(ed["salary"]!)")
print("////////////////////////////////")
}
}
}
}
|
d64adc8d4b7c7489328b359fa6a934f6ffc551ee
|
[
"Swift"
] | 1
|
Swift
|
emilabz/DAy8iOS
|
c258b0e88c639794e32c9851f2882b256b13b22a
|
6e78551c49aa9717c2fee05cedcea38a21d65699
|
refs/heads/master
|
<file_sep>import { resolvePackage } from '@shared/resolvePackage';
import babelCore from 'babel-core';
import * as t from 'babel-types';
import fs from 'fs-extra';
import * as path from 'path';
import File from './File';
export interface IModule {
sourcePath: string;
destDir: string;
destinationDirName?: string;
cwd: string;
target: string;
}
export default class Module extends File {
private cwd: string;
private code: string;
private target: string;
private destDir: string;
private sourcePath: string;
private destinationPath: string;
private destinationDir: string;
private destinationDirName: string;
constructor({
sourcePath,
destinationDirName = 'npm',
cwd,
target,
destDir
}: IModule) {
super();
this.cwd = cwd;
this.destDir = destDir;
this.target = target;
this.sourcePath = sourcePath;
this.destinationDirName = destinationDirName;
}
public getSourcePath() {
return this.sourcePath;
}
public async process() {
this.setDestinationPath();
await this.loadCode();
await this.build();
await this.write({
destinationPath: this.destinationPath,
type: 'write',
content: this.code
});
this.reset();
}
public reset() {
this.code = '';
}
public async unlink() {
if (await fs.pathExists(this.getDestinationPath())) {
await fs.remove(this.getDestinationPath());
}
}
public getDestinationPath() {
return this.destinationPath;
}
private async loadCode() {
this.code = await fs.readFile(this.sourcePath, 'utf8');
}
private getDestinationDir() {
if (!this.destinationDir) {
this.destinationDir = path.parse(this.destinationPath).dir;
}
return this.destinationDir;
}
private setDestinationPath() {
const relativePathToNodeModules = path.relative(
path.resolve(this.cwd, 'node_modules'),
this.sourcePath
);
this.destinationDir = path.resolve(this.destDir, this.destinationDirName);
this.destinationPath = path.resolve(
this.destinationDir,
relativePathToNodeModules
);
}
private async build() {
this.code = babelCore.transform(this.code, {
babelrc: false,
plugins: [
() => {
return {
visitor: {
CallExpression: (astPath: any) => {
if (astPath.node.callee.name === 'require') {
const id = astPath.node.arguments[0].value;
if (!id.startsWith('./')) {
const realPath = resolvePackage(id, this.cwd, this.target);
const relativePathFromNodeModules = path.relative(
path.resolve(this.cwd, 'node_modules'),
path.resolve(realPath)
);
const distPath = path.relative(
this.getDestinationPath(),
path.resolve(
this.getDestinationDir(),
relativePathFromNodeModules
)
);
astPath.node.arguments[0].value = distPath;
}
}
},
ImportDeclaration: (astPath: any) => {
const id = astPath.node.source.value;
if (!id.startsWith('./')) {
const realPath = resolvePackage(
id,
path.parse(this.getSourcePath()).dir,
this.target
);
const relativePathFromNodeModules = path.relative(
path.resolve(this.cwd, 'node_modules'),
path.resolve(realPath)
);
const distPath = path.relative(
path.parse(this.getDestinationPath()).dir,
path.resolve(
this.getDestinationDir(),
relativePathFromNodeModules
)
);
astPath.node.source.value = distPath;
}
},
MemberExpression: (astPath: any) => {
if (
t.isMemberExpression(astPath.node) &&
astPath.node.property.name === 'NODE_ENV'
) {
if (
t.isMemberExpression(astPath.node.object) &&
astPath.node.object.property.name === 'env'
) {
if (
t.isIdentifier(astPath.node.object.object) &&
astPath.node.object.object.name === 'process'
) {
astPath.replaceWith(t.stringLiteral('production'));
}
}
}
}
}
};
}
]
}).code;
}
}
<file_sep>const rollupPluginBabel = require('rollup-plugin-babel');
const less = require('rollup-plugin-less');
const sass = require('rollup-plugin-sass');
const rollupPluginNodeResolve = require('rollup-plugin-node-resolve');
const rollupPluginCommonjs = require('rollup-plugin-commonjs');
export default {
input: 'src/app.js',
plugins: [
rollupPluginBabel({
plugins: [
require('@babel/plugin-proposal-class-properties'),
[
require('@babel/plugin-transform-react-jsx'),
{
pragma: 'h'
}
]
],
presets: [
[
require('@babel/preset-env'),
{
targets: {
node: 6
}
}
]
]
}),
less({
// less 不需要输出到文件
output: () => ''
}),
sass(),
rollupPluginNodeResolve(),
rollupPluginCommonjs({})
]
};
<file_sep>import LogService from '@services/Log';
import customizedReactFileNames from '@shared/customizedReactFileNames';
import targetExtensions from '@shared/targetExtensions';
import axios from 'axios';
import chalk from 'chalk';
import chokidar from 'chokidar';
import * as fs from 'fs-extra';
import * as path from 'path';
import rollup from 'rollup';
import AppEntry from './AppEntry';
import Entry, { InterfaceEntryOptions } from './Entry';
import inputOptions from './inputOptions';
import JSEntry from './JSEntry';
import Module from './Module';
import StyleEntry from './StyleEntry';
import { getAnuPath } from './utils';
const alias = require('rollup-plugin-alias');
// treat as external dependency
const { template } = require('../src/translator/bridge');
interface InterfaceFragment {
id: string;
content: string;
}
type BuildTarget = 'wx' | 'baidu' | 'ali';
interface InterfaceBuild {
cwd?: string;
minify?: boolean;
srcDir?: string;
target?: BuildTarget;
destDir?: string;
assetsDir?: string;
silent?: boolean;
forceUpdateLibrary?: boolean;
}
export default class Build {
// 静默编译
public readonly silent: boolean;
// 编译目标
public readonly target: string;
// 是否压缩
public readonly minify: boolean;
private files: Map<string, Entry | JSEntry | Module>;
private cwd: string;
private srcDir: string;
private destDir: string;
private assetsDir: string;
private watcher: chokidar.FSWatcher;
// 是否强制拉取最新定制版 React
private forceUpdateLibrary: boolean;
private nodeModulesFiles: string[];
private logService: LogService;
private fragments: {
[property: string]: string;
};
constructor({
cwd = process.cwd(),
minify = false,
target = 'wx',
srcDir = 'src',
destDir = 'dist',
assetsDir = 'assets',
forceUpdateLibrary = false,
silent = false
}: InterfaceBuild) {
this.cwd = cwd;
this.minify = minify;
this.srcDir = srcDir;
this.target = target;
this.destDir = destDir;
this.assetsDir = assetsDir;
this.silent = silent;
this.forceUpdateLibrary = forceUpdateLibrary;
this.files = new Map();
this.nodeModulesFiles = [];
this.fragments = {};
this.logService = new LogService({ silent });
}
public get spinner() {
return this.logService;
}
public async build() {
this.beforeStart();
if (!getAnuPath(this.target) || this.forceUpdateLibrary) {
await this.fetchLatestReact();
}
this.listeningFragments();
await this.collectDependencies();
await this.process();
this.spinner.stop();
}
public async start() {
await this.build();
this.watch();
this.spinner.succeed(
chalk`Starting incremental compilation at {cyan ${this.srcDir}}\n`
);
}
private async copyStatics() {
const sourceDir = path.resolve(this.cwd, this.srcDir, this.assetsDir);
const destinationDir = path.resolve(this.cwd, this.destDir, this.assetsDir);
const relativeSourceDir = path.relative(this.cwd, sourceDir);
const relativeDestinationDir = path.relative(this.cwd, destinationDir);
await fs.copy(sourceDir, destinationDir);
this.spinner.succeed(
chalk`Copied files from {cyan ${relativeSourceDir}} to {cyan ${relativeDestinationDir}}\n`
);
}
private listeningFragments() {
template.on('fragment', (fragment: InterfaceFragment) => {
const { id, content } = fragment;
if (!this.fragments[id]) {
this.fragments[id] = content;
}
});
}
private async writeFragments() {
const destDir = path.join(
this.cwd,
this.destDir,
'components',
'Fragments'
);
await Object.keys(this.fragments).map(async id => {
const filePath =
destDir + '/' + id + targetExtensions[this.target].template;
await fs.ensureFile(filePath);
await this.writeFile(filePath, this.fragments[id]);
});
}
private async writeFile(filePath: string, content: string) {
try {
await fs.writeFile(filePath, content);
} catch (error) {
// tslint:disable-next-line
console.log(error);
}
}
private watch() {
this.watcher = chokidar.watch(path.resolve(this.cwd, this.srcDir));
const eventHandler: {
[property: string]: (filePath: string) => Promise<void>;
} = {
add: this.watchAdd,
change: this.watchChange,
unlink: this.watchUnlink
};
const createEventHandler = (type: string) => {
this.watcher.on(type, (relatedPath: string) => {
eventHandler[type].call(this, relatedPath).catch((error: Error) => {
// tslint:disable-next-line
console.log(error);
});
});
};
createEventHandler('add');
createEventHandler('change');
createEventHandler('unlink');
process.on('SIGINT', () => this.beforeExitLog());
process.on('uncaughtException', () => process.exit(1));
process.on('unhandledRejection', () => process.exit(1));
}
private async fetchLatestReact() {
this.spinner.start(
chalk`fetching latest customized {cyan React} library from GitHub`
);
const libraryName = customizedReactFileNames[this.target].primary;
const libraryRemoteUri = `https://raw.githubusercontent.com/RubyLouvre/anu/master/dist/${libraryName}`;
try {
const lib = await axios.get(libraryRemoteUri);
const filePath = path.resolve(
this.cwd,
`node_modules/anujs/dist/${
customizedReactFileNames[this.target].primary
}`
);
await fs.ensureFile(filePath);
await fs.writeFile(filePath, lib.data, {
encoding: 'utf8'
});
this.spinner.succeed(
chalk`latest customized {cyan React} library fetched from GitHub`
);
} catch (error) {
this.spinner.stop(
chalk`Cannot retrieve latest customized {cyan React} library` +
chalk` from {cyan ${libraryRemoteUri}}, make sure you can access GitHub`
);
process.exit(1);
}
}
private async watchChange(changedPath: string) {
const file = this.files.get(changedPath);
if (file) {
await file.process();
}
}
private async watchUnlink(unlinkedPath: string) {
const file = this.files.get(unlinkedPath);
if (file) {
await file.unlink();
this.files.delete(unlinkedPath);
}
}
private async watchAdd(addedPath: string) {
if (this.files.has(addedPath)) return;
if (path.parse(addedPath).ext !== '.js') return;
this.createModule({
sourcePath: addedPath,
cwd: this.cwd,
code: '',
originalCode: await fs.readFile(addedPath, 'utf8'),
srcDir: this.srcDir,
destDir: this.destDir,
silent: this.silent,
build: this,
target: this.target
});
this.watcher.add(addedPath);
const file = this.files.get(addedPath);
if (file) {
await this.files.get(addedPath).process();
}
}
private beforeStart() {
this.spinner.info(
chalk`{bold.underline nanachi@${require('../package.json').version}}`
);
}
private beforeExitLog() {
this.spinner.stop(chalk`{green.bold \nBye!}`);
process.exit(0);
}
private createModule(module: InterfaceEntryOptions, index?: number) {
const ext = path.parse(module.sourcePath).ext;
switch (true) {
case index === 0:
this.files.set(module.sourcePath, new AppEntry(module));
break;
case /node_modules/.test(module.sourcePath):
this.nodeModulesFiles.push(module.sourcePath);
this.files.set(
module.sourcePath,
new Module({
cwd: module.cwd,
sourcePath: module.sourcePath,
destinationDirName: 'npm',
destDir: this.destDir,
target: this.target
})
);
break;
case ext === '.js':
this.files.set(module.sourcePath, new JSEntry(module));
break;
case ext === '.sass':
case ext === '.scss':
case ext === '.less':
this.files.set(module.sourcePath, new StyleEntry(module));
break;
default:
break;
}
}
private async collectDependencies() {
this.spinner.start('collecting dependencies...');
// 如果本地没有定制版 React 的话,alias 中的 @react 和 react 将会是空字符
// 因此在获取到定制版 React 之后再解析
inputOptions.plugins.push(
alias({
'@components': path.resolve(process.cwd(), './src/components'),
'@react': getAnuPath(this.target),
react: getAnuPath(this.target)
})
);
const bundle = await rollup.rollup(inputOptions);
const modules = bundle.modules.map(module => ({
sourcePath: module.id,
code: '',
originalCode: module.originalCode,
cwd: this.cwd,
srcDir: this.srcDir,
destDir: this.destDir,
silent: this.silent,
build: this,
target: this.target
}));
modules.push({
originalCode: '',
code: '',
sourcePath: getAnuPath(this.target),
cwd: this.cwd,
srcDir: this.srcDir,
destDir: this.destDir,
silent: this.silent,
build: this,
target: this.target
});
this.files = new Map();
// rollup 在使用了 rollup-plugin-commonjs 插件之后
// 会存在以 commonjs-proxy: 开头的路径
// 需要过滤掉
modules
.filter(module => path.isAbsolute(module.sourcePath))
.forEach(this.createModule, this);
this.spinner.succeed(
chalk`dependencies collected, {cyan ${this.files.size.toString()}} entries total`
);
}
private async emptyDir() {
if (await fs.pathExists(this.destDir)) {
await fs.emptyDir(this.destDir);
} else {
await fs.ensureDir(this.destDir);
}
this.spinner.succeed(chalk`{cyan ${this.destDir}} has been emptied`);
this.spinner.start('compiling...');
}
private async process() {
await this.emptyDir();
await this.copyStatics();
const processes: Array<Promise<void>> = [];
this.files.forEach(file => processes.push(file.process()));
await Promise.all(processes);
await this.writeFragments();
}
}
<file_sep>import * as spinner from '@shared/spinner';
import chalk from 'chalk';
import { execSync } from 'child_process';
import * as fs from 'fs-extra';
import * as path from 'path';
import resolve from 'resolve';
import { getAnuPath } from '../commands/build/utils';
const alias: {
[property: string]: string;
} = {};
export const resolvePackage = (
name: string,
basedir: string,
target: string
) => {
if (name === 'react') {
alias[name] = getAnuPath(target);
}
if (name.startsWith('@components')) {
return path.resolve(
process.cwd(),
'components',
name
.split('/')
.slice(1)
.join('/')
);
}
// 缓存
if (alias[name]) return alias[name];
// 尝试解析
let resolved;
try {
resolved = resolve.sync(name, { basedir });
} catch (error) {
if (name === 'regenerator-runtime/runtime') {
spinner.info(chalk`missing {cyan regenerator-runtime}`);
spinner.start(chalk`installing {cyan regenerator-runtime}`);
execSync('npm install regenerator-runtime', { cwd: process.cwd() });
} else {
throw error;
}
}
// cjs 解析结果
alias[name] = resolved;
const packageJsonPath = path.resolve(
process.cwd(),
'node_modules',
name,
'package.json'
);
let packageJson: any = {};
try {
packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
} catch (error) {
// 解析失败的结果不会显示
}
// 如果该包存在 ESModule
if (packageJson.module) {
// 统一形式,./dist -> dist
const normalize = (n: string) => n.replace(/^\.?[/\\]?/, '');
const main = normalize(packageJson.main);
const module = normalize(packageJson.module);
// 将 cjs 的解析结果替换为 esm
// main = dist/cjs; esm = dist/esm;
// 比如 dist/cjs/index.js -> dist/esm/index.js
let regex = new RegExp(`${main}`);
// 若 module 是一个文件而 main 是一个目录
// 需要将路径中 main 之后的字符串都替换掉
// 如 main = dist/cjs; module = dist/esm/production.js; resolved = dist/cjs/index.js
// 需要将 dist/cjs/index.js 替换为 dist/esm/production.js
if (path.parse(module).ext) {
regex = new RegExp(`${main}.*`);
}
alias[name] = resolved.replace(regex, module);
}
return alias[name];
};
<file_sep>import fs from 'fs-extra';
export interface InterfaceWriteFile {
type: 'write';
sourcePath?: string;
content: string;
destinationPath: string;
}
export interface InterfaceCopyFile {
type: 'copy';
sourcePath: string;
content?: string;
destinationPath: string;
}
export default class File {
public async write({
content,
destinationPath,
type,
sourcePath
}: InterfaceWriteFile | InterfaceCopyFile) {
switch (type) {
case 'write':
await fs.ensureFile(destinationPath);
await fs.writeFile(destinationPath, content);
break;
case 'copy':
if (!(await fs.pathExists(destinationPath))) {
await fs.copy(sourcePath, destinationPath);
}
break;
default:
throw new Error(
`No \`type\` provided, type: ${type} sourcePath: ${sourcePath} destinationPath: ${destinationPath} `
);
}
}
}
|
f0c2577c075ef49f018d02c8cbcb3a2793812ab0
|
[
"TypeScript"
] | 5
|
TypeScript
|
roland-reed/nanachi-cli
|
743fc7978b334f8c6be434c3c56b72c6783599b2
|
a1bf2b420a366d7ed3b684635c337be5dae3d6be
|
refs/heads/master
|
<file_sep>/* mmtuts
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mailTo = "<EMAIL>"; /*will not work gmail blocks php mail*/
$headers = "From: ".$mailFrom; /*if this worked it would actually show who mail is from*/
$txt = "You have received an e-mail from ".$name.".\n\n".$message; /*same with message*/
mail($mailTo, $subject, $txt, $headers);
header("Location: index, php?mailsend");
} */
|
90e070358922473485a8943cd0fefd0b50f0cb54
|
[
"PHP"
] | 1
|
PHP
|
DPerry113/My-First-Portfolio
|
017a04b75a21cf9a62bf6993bb1efc1193f7439a
|
89ae49c806bd4034325a1d0835e11ca648ff6d15
|
refs/heads/master
|
<file_sep>#include "block.h"
Block::Block(uint64_t nIndexIn, const string &sDataIn) {
_nNonce = -1;
_tTime = time(nullptr);
_sHash = _CalculateHash();
}
string Block::GetHash(){
return _sHash[0];
}
Block Block::MineBlock(uint64_t nDifficulty, string WalletAddress){
_sSender = "SYSTEM";
_sRecipient = WalletAddress;
_fAmount = 5;
char cstr[nDifficulty + 1];
for (uint64_t i = 0; i < nDifficulty; ++i){
cstr[i] = '0';
}
cstr[nDifficulty] = '\0';
string str(cstr);
while (_sHash[0].substr(0, nDifficulty) != str){
_nNonce++;
_sHash = _CalculateHash();
}
cout << "Block mined: " << _sHash[0] << endl;
cout << "Block detail: " << _sHash[1] << endl;
Block result(_nIndex, _sData);
result._nIndex = _nIndex;
result._nNonce = _nNonce;
result._sData = _sData;
result._sSender = _sSender;
result._sRecipient = _sRecipient;
result._fAmount = _fAmount;
result._tTime = _tTime;
result._sHash = _sHash;
return result;
}
inline vector<string> Block::_CalculateHash() const {
json b;
// block = {
// 'index': 1,
// 'timestamp': 1506057125.900785,
// 'transactions': [
// {
// 'sender': "SYSTEM",
// 'recipient': "SYSTEM",
// 'amount': 5,
// }
// ],
// 'proof': 324984774000,
// 'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
// }
b["index"] = _nIndex;
b["timestamp"] = _tTime;
b["transactions"][0]["sender"] = _sSender;
b["transactions"][0]["recipient"] = _sRecipient;
b["transactions"][0]["amount"] = _fAmount;
b["proof"] = _sData;
b["previous_hash"] = sPrevHash;
b["nonce"] = _nNonce;
// stringstream ss;
// ss << _nIndex << _tTime << _sData << _nNonce << sPrevHash;
// cout << b.dump();
vector<string> result(2);
result[0] = sha256(b.dump());
result[1] = b.dump();
return result;
}<file_sep>#ifndef TESTCHAIN_BLOCK_H
#define TESTCHAIN_BLOCK_H
#include <cstdint>
#include <iostream>
#include <string>
#include "sha256.h"
#include <sstream>
#include "json.hpp"
// for convenience
using json = nlohmann::json;
// for convenience
using namespace std;
class Block {
public:
string sPrevHash;
Block(uint64_t nIndexIn, const string &DataIn);
Block MineBlock(uint64_t nDifficulty, string WalletAddress);
string GetHash();
uint64_t _nIndex;
uint64_t _nNonce;
string _sData;
vector<string> _sHash;
string _sSender;
string _sRecipient;
float _fAmount;
time_t _tTime;
vector<string> _CalculateHash() const;
};
#endif<file_sep>#include <iostream>
#include <string>
#include <vector>
class Transaction{
public:
Transaction();
string sender;
string recipient:
float amount;
vector<Transaction> currentTransaction();
void addTransaction(Transaction tNew);
private:
vector<Transaction> _vTransaction;
}
Transaction::Transaction(){
vector<Transaction> _vTransaction;
}
vector<Transaction> Transaction::currentTransaction(){
return _vTransaction;
}
void Transaction::addTransaction(Transaction tNew)(){
if((!tNew.sender) || (!tNew.recipient) || (amount < 0)){
cout << "Invalid transaction" << endl;
}else{
_vTransaction.push_back(tNew)
cout << "New Transaction" << endl;
}
}<file_sep>#include "log.h"
Log::Log(){}
string Log::getCurrentTime(){
stringstream ss;
time_t t = time(0); // get time now
tm* now = localtime(&t);
ss << (now->tm_year + 1900) \
<< '-' << (now->tm_mon + 1) \
<< '-' << now->tm_mday \
<< '-' << now->tm_hour \
<< ':' << now->tm_min \
<< ':' << now->tm_sec \
<< "\n";
return ss.str();
}
void Log::printLog(string sInputLog){
cout << "INFO: " << getCurrentTime() << sInputLog << endl;
}<file_sep>all:
gcc -lstdc++ \
-o blockchain \
-std=c++11 \
-x c++ \
main.cpp block.cpp blockchain.cpp sha256.cpp log.cpp json.hpp
<file_sep>#ifndef TESTCHAIN_LOG_H
#define TESTCHAIN_LOG_H
#include <iostream>
#include <string>
#include <ctime>
#include <sstream>
using namespace std;
class Log{
public:
Log();
void printLog(string sInputLog);
string getCurrentTime();
};
#endif<file_sep># simple c++ blockchain
basic component block chain. Create block, mining
# How to compile
```
make
sudo chmod +x ./blockchain
./blockchain
```
# Result
```
duclinh@debian ~/source $ ./blockchain
INFO: 2018-5-25-14:32:13
Mining block 1...
Block mined: 0000069934d4fb5c1ecd70ec28015322e5c66b6124b1c0bcee475ec20abf5589
Block detail: {"index":65280,"nonce":1218985,"previous_hash":"885db35525b8fe9ff8c60145629cd6857b466dd830b96fbe9ba4e9acb7fbbdf1","proof":"","timestamp":1527233533,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:32:54
Mining block 2...
Block mined: 00000c4f3256df0647780a79c7629f27f788f8f386cb099d04d410a473cca4cf
Block detail: {"index":65280,"nonce":530136,"previous_hash":"0000069934d4fb5c1ecd70ec28015322e5c66b6124b1c0bcee475ec20abf5589","proof":"","timestamp":1527233574,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:33:12
Mining block 3...
Block mined: 00000c3ebed0183852072598dfdea25c13c40d9e88f682726798f9bb063eeffa
Block detail: {"index":65280,"nonce":1279871,"previous_hash":"00000c4f3256df0647780a79c7629f27f788f8f386cb099d04d410a473cca4cf","proof":"","timestamp":1527233592,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:33:56
Mining block 4...
Block mined: 00000354c4127243d22ac3d595a030f866be298d801fb5659ec52f74578aadcc
Block detail: {"index":65280,"nonce":579077,"previous_hash":"00000c3ebed0183852072598dfdea25c13c40d9e88f682726798f9bb063eeffa","proof":"","timestamp":1527233636,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:34:16
Mining block 5...
Block mined: 00000213a27f9705d77e3ce7f95bc445dfd8fbec3fb3a82e47b9007754e9c848
Block detail: {"index":65280,"nonce":57284,"previous_hash":"00000354c4127243d22ac3d595a030f866be298d801fb5659ec52f74578aadcc","proof":"","timestamp":1527233656,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:34:18
Mining block 6...
Block mined: 00000cb51572753d7b7ef472eca857c29f8db8c2527ff072ff43eae45782f33e
Block detail: {"index":65280,"nonce":162642,"previous_hash":"00000213a27f9705d77e3ce7f95bc445dfd8fbec3fb3a82e47b9007754e9c848","proof":"","timestamp":1527233658,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:34:23
Mining block 7...
Block mined: 000002c7002ba34c050cebb05131cc720107211a4ee584526fe11c25ba807c3f
Block detail: {"index":65280,"nonce":535557,"previous_hash":"00000cb51572753d7b7ef472eca857c29f8db8c2527ff072ff43eae45782f33e","proof":"","timestamp":1527233663,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:34:42
Mining block 8...
Block mined: 0000053a909ff9cc557c9d39a13dcde5c0abdab90b53a6dd8ad2af6d4e5cdeca
Block detail: {"index":65280,"nonce":1016721,"previous_hash":"000002c7002ba34c050cebb05131cc720107211a4ee584526fe11c25ba807c3f","proof":"","timestamp":1527233682,"transactions":[{"amount":5.0,"recipient":"e064ae7ff58d666ac8d96b1d86d213257d9dab9b541ed81d0d20b8b553ef3d66","sender":"SYSTEM"}]}
INFO: 2018-5-25-14:35:17
```<file_sep>#include "blockchain.h"
#include "log.h"
int main(){
Blockchain bchain = Blockchain();
Log lLog = Log();
lLog.printLog("Mining block 1...");
for(int i = 2; i < 10; ++i){
stringstream text_log;
text_log << "Mining block " << i << "...";
Block b = Block(i, text_log.str());
string myWallet = sha256("<PASSWORD>");
bchain.AddBlock(b, myWallet);
lLog.printLog(text_log.str());
}
return 0;
}
|
41c6bb0ed7c7373b2ec171eedbaf33e0fb5027c7
|
[
"Markdown",
"Makefile",
"C++"
] | 8
|
C++
|
haanhduclinh/blockchain
|
d3762cfaa24931307a07792685fe966ce395b55e
|
5e5e837917e75cc2e397820558f33ae7a7cde45b
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
import os
import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator, load_img
nb_epoch = 5
temp_dir = "temp"
if not os.path.exists(temp_dir):
os.mkdir(temp_dir)
result_dir = 'results'
if not os.path.exists(result_dir):
os.mkdir(result_dir)
def save_history(history, result_file):
loss = history.history['loss']
acc = history.history['acc']
val_loss = history.history['val_loss']
val_acc = history.history['val_acc']
nb_epoch = len(acc)
with open(result_file, "w") as fp:
fp.write("epoch\tloss\tacc\tval_loss\tval_acc\n")
for i in range(nb_epoch):
fp.write("%d\t%f\t%f\t%f\t%f\n" % (i, loss[i], acc[i], val_loss[i], val_acc[i]))
def draw_images(temp_dir):
images = glob.glob(os.path.join(temp_dir, "*.jpg"))
gs = gridspec.GridSpec(3, 3)
gs.update(wspace=0.1, hspace=0.1)
for i in range(9):
img = load_img(images[i])
plt.subplot(gs[i])
plt.imshow(img, aspect='auto')
plt.axis("off")
plt.savefig("Generated Images")
if __name__ == '__main__':
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(150, 150, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(5))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rescale=1.0 / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1.0 / 255)
train_generator = train_datagen.flow_from_directory(
'images',
target_size=(150, 150),
batch_size=32,
class_mode='categorical')
# ,
# save_to_dir=temp_dir,
# save_prefix='img',
# save_format='jpg')
validation_generator = test_datagen.flow_from_directory(
'images',
target_size=(150, 150),
batch_size=32,
class_mode='categorical')
# i = 0
# for batch in train_generator:
# i += 1
# if i > 2:
# break
# draw_images(temp_dir)
history = model.fit_generator(
train_generator,
samples_per_epoch=200,
nb_epoch=nb_epoch
,
validation_data=validation_generator,
nb_val_samples=50)
model.save_weights(os.path.join(result_dir, 'cnn.h5'))
save_history(history, os.path.join(result_dir, 'cnn.txt'))
<file_sep># -*- coding: utf-8 -*-
import os
import sys
from keras.models import Sequential, Model
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Input, Activation, Dropout, Flatten, Dense
from keras.preprocessing import image
import numpy as np
IMAGE_FILE = "images/B/B13.JPG"
result_dir = 'results'
img_height, img_width = 150, 150
channels = 3
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(150, 150, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(5))
model.add(Activation('softmax'))
model.load_weights(os.path.join(result_dir, 'cnn.h5'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
img = image.load_img(IMAGE_FILE, target_size=(img_height, img_width))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = x / 255.0
pred = model.predict(x)[0]
print(pred)
|
446ac1c8362a53c5bc2f86f2067d079281b81305
|
[
"Python"
] | 2
|
Python
|
nyantaco/CrackCheck
|
47924c29d2ef89a31ddf59ebe3a8360fc9332a41
|
11fd409d4fee07f20b60b92271e5f7bbeea23f21
|
refs/heads/master
|
<repo_name>ArseniyCool/1.Beginning<file_sep>/ENG/Gyroscope.py
a = input("Enter your name:")
b = input("Enter your surname:")
c = input("Enter your favourite animal:")
d = input("Enter your zodiac sign:")
print('Individual gyroscope for the user', a, b)
print('Who were you in last life:', c)
print('Your zodiac sign is ', d, ', so you have a delicate nature.')
<file_sep>/ENG/Parrot.py
# The program display entered words in reverse order
a = input()
b = input()
c = input()
print(a)
print(b)
print(c)
<file_sep>/ENG/Shop.py
price = int(input('Enter the amount of the first order:'))
price2 = int(input('Enter the amount of the second order:'))
price_all = price + price2
print('There is their total amount:', price_all)
<file_sep>/ENG/Ticket office.py
# The program reserves movie spots at the direction of the user
a = input('Enter the name of the film:')
b = input('Enter the name of the cinema or shopping mall:')
c = input('Enter session time:')
print('Ticket on "', a, '" in "', b, '" at', c, 'booked.')
<file_sep>/RUS/Эхо(Работа с файлом).py
a = '<NAME>!'
file = open('output.txt', 'w', encoding="utf-8")
file.write(a)
file.close()
<file_sep>/ENG/Knowing.py
print('Привет, пользователь')
name = input('К<NAME>?')
print('Приятно познакомиться,', name)
<file_sep>/ENG/Echo(Work with files).py
a = '<NAME>!'
file = open('output.txt', 'w')
file.write(a)
file.close()
<file_sep>/RUS/Магазин.py
price = int(input('Введите сумму первого заказа:'))
price2 = int(input('Введите сумму второго заказа:'))
price_all = price + price2
print('Вот их общая сумма:', price_all)
<file_sep>/RUS/Попугай.py
# Программа выводит введенные слова или словосочетания по порядку
a = input()
b = input()
c = input()
print(a)
print(b)
print(c)
<file_sep>/RUS/Билетная касса.py
# Программа бронирует места в кино по указанием пользователя
a = input('Введите название фильма:')
b = input('Введите название кинотеатра или торгового центра:')
c = input('Введите время сеанса:')
print('Билет на "', a, '" в "', b, '" на', c, 'забронирован.')
<file_sep>/RUS/Гороскоп.py
a = input("Введите своё имя:")
b = input("Введитк свою фамилию:")
c = input("Введите Ваше любимое животное:")
d = input("Введите свой знак зодиака:")
print('Индивидуальный гороскоп для пользователя', a, b)
print('Кем вы были в прошлой жизни:', c)
print('Ваш знак зодиака -', d, ', поэтому вы - тонко чувствующая натура.')
<file_sep>/ENG/Bit & byte.py
print('ENG')
print('1 bit - minimum unit of amount of information.')
print('1 byte = 8 bits.')
print('1 kilobit = 1024 bits.')
print('1 kilobyte = 1024 bytes.')
X = 8 * 1024
print('1 kilobyte =', X, 'bits.')
<file_sep>/README.md
# 1.Beginning
ENGLISH
-
"Take a step - the road will appear by itself ..."
-
Welcome to my first repository in Github! At this repository I show my first codes from Python,so they are very simple.
There are basic themes:
- "print" command
- "input" command
- variables
- PEP8 rules
РУССКИЙ
-
«Сделай шаг - дорога появится сама собой ...»
-
Добро пожаловать в мой первый репозиторий в Github! В этом репозитории я показываю свои первые коды из Python, поэтому они очень просты.
Вот основные темы:
- команда печати "print"
- команда ввода "input"
- переменные
- правила PEP8
<file_sep>/ENG/Echo-2.py
a = 'Heeelp!'
print(a)
print(a)
|
84b1b163d99d389ff2c68be0675fb51e294acb6c
|
[
"Markdown",
"Python"
] | 14
|
Python
|
ArseniyCool/1.Beginning
|
52a68996436e05522ab34b73ed1b381396901985
|
c96f244019c1397d9adb22ced36d833ddcf7ec3c
|
refs/heads/master
|
<repo_name>himicakhurana/didyouknow<file_sep>/README.md
MAGIC Mentoring Project:
Made by <NAME> and <NAME>.
This project is called Did You Know. This project is a fun way to learn about world problems by using trivia! There are many questions
to answer and to learn! There are 5 categories and you can choose which one you want to do!
You can run the program by going to this website: You will have to sign up first:
http://didyouknow.wiki/
Code is in HTML,Javascript and CSS.
You can run it on browser like Chrome,Firefox and Safari.
There are no environment settings needed to run this project.
Github link: https://github.com/himicakhurana/didyouknow
<file_sep>/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Did You Know</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="quiz.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.html"><img class="logo" src="logo.PNG"></a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="quiz_login.html">Login</a></li>
<li><a href="quiz_signup.html">Sign Up</a></li>
<li><a href="instructions.html">Instructions</a></li>
<li><a href="ocean.html">Ocean</a></li>
<li><a href="gun.html">Guns</a></li>
<li><a href="lgbtq.html">LGBTQ</a></li>
<li><a href="rights.html">Rights</a></li>
<li><a href="quiz_aria.html">Calculator </a></li>
</ul>
</div>
</nav>
<div class="container">
<h3>Did U Know?</h3>
<h5>Welcome to Did U Know! If you already have an account, you can sign in. If you are just joining us,</h5>
<h5>click to sign up! I hope you enjoy yourself on this fun, challenging, trivia game that helps you</h5>
<h5>learn about the problems in the world in a fun way!</h5>
</div>
</body>
</html>
<file_sep>/quiz.js
$(document).ready(function() {
$("#login").submit(function (event) {
var username = document.getElementById("username").value;
var password_val = document.getElementById("password").value;
var pass = localStorage.getItem(username);
console.log(pass);
if(password_val==pass){
alert("Logged in.");
location.href = "index.html";
}else{
alert('Invalid Credentials. Please signup!');
location.href = "quiz_signup.html";
}
event.preventDefault();
});
$("#signup").submit(function (event) {
var password1 = document.getElementById("password1").value;
var password2 = document.getElementById("password2").value;
var email = document.getElementById("email").value;
var fname = document.getElementById("fname").value;
if(password2==password1){
var length=password1.length;
if (length>10){
alert("Your password is too long. Change it please.")
}
validate_name(fname);
console.log(email);
localStorage.setItem(email, password1);
alert('Hi '+fname+ '. You can login now.');
location.href = "quiz_login.html";
}else{
alert("Password 1 and password 2 do not match")
}
event.preventDefault();
});
/**
* Created by himica on 2/4/2019.
*/
});
function validate_name(name){
}
const myQuestions = [
{
question:"What is the average number of guns per person in the U.S?",
answers: {
a: "1 gun per 2 people",
b: "1 gun per 3 people",
c: "6 guns per 5 people",
d: "1 gun per 1 person"
},
correctAnswer: "c"
},
{
question: "How many children are killed or injured due to guns?",
answers: {
a: "5 children injured or killed a week.",
b: "One child killed or injured per day.",
c: "6 children killed or injured per week.",
d: "2 children killed or injured per hour."
},
correctAnswer: "c"
}];
|
19839f25a23ea14b2c6dc71ab9498878c1cf330d
|
[
"Markdown",
"JavaScript",
"HTML"
] | 3
|
Markdown
|
himicakhurana/didyouknow
|
1c6d9255c19e991cc95e8d47ab9f60a64d8e0638
|
04f87dabd2aacf67c440033f8a47da3acd73b03b
|
refs/heads/master
|
<repo_name>thinhhuynh/django-bulk-update-or-create<file_sep>/tests/README.md
# tests
This is a django app to run tests on `bulk_update_or_create`.
`manage.py` has been patched to include parent directory in `sys.path` so you can simply run:
```
./manage.py test
```
`pytest.ini` added to make it easier to run tests from IDEs (such as VSCode), thanks to [pytest-django](https://github.com/pytest-dev/pytest-django/).
`pytest` needs to be executed inside this directory (where `manage.py` is) and [requirements.txt](requirements.txt) need to be installed:
```
pip install -r requirements.txt
```
Use `make -f ../Makefile startmysql` to spin up a mysql docker (or set `DJANGO_SETTINGS_MODULE` env var to different settings).
## VSCode
To run/debug the tests in VSCode:
* make sure to open this folder (not parent) as workspace
* or use multi-project workspaces: open parent and then select "Add Folder to Workspace" and add this one
* select `Python > Configure Tests` and choose `pytest`
:heavy_check_mark:
<file_sep>/tests/tests/tests.py
from django.test import TestCase
from django.core.exceptions import FieldDoesNotExist
from tests.models import RandomData
class Test(TestCase):
def test_all_create(self):
items = [RandomData(uuid=i, data=i) for i in range(10)]
# 1 select + 10 creates, all new
with self.assertNumQueries(11):
RandomData.objects.bulk_update_or_create(items, ['data'], match_field='uuid')
self.assertEqual(RandomData.objects.count(), 10)
self.assertEqual(sorted(int(x.data) for x in RandomData.objects.all()), list(range(10)))
def test_update_some(self):
self.test_all_create()
items = [RandomData(uuid=i + 5, data=i + 10) for i in range(10)]
# 1 select, 1 bulk update, 5 create
with self.assertNumQueries(7):
RandomData.objects.bulk_update_or_create(items, ['data'], match_field='uuid')
self.assertEqual(RandomData.objects.count(), 15)
self.assertEqual(
sorted(int(x.data) for x in RandomData.objects.all()),
list(range(5)) + list(range(10, 20)),
)
def test_all_update(self):
self.test_all_create()
items = [RandomData(uuid=i, data=i + 10) for i in range(10)]
# 1 select, 1 bulk update
with self.assertNumQueries(2):
RandomData.objects.bulk_update_or_create(items, ['data'], match_field='uuid')
self.assertEqual(RandomData.objects.count(), 10)
self.assertEqual(
sorted(int(x.data) for x in RandomData.objects.all()),
list(range(10, 20)),
)
def test_update_some_generator(self):
self.test_all_create()
items = [RandomData(uuid=i + 5, data=i + 10) for i in range(10)]
updated_items = RandomData.objects.bulk_update_or_create(
items, ['data'], match_field='uuid', yield_objects=True
)
# not executed yet, just generator
self.assertEqual(RandomData.objects.count(), 10)
updated_items = list(updated_items)
self.assertEqual(RandomData.objects.count(), 15)
self.assertEqual(
sorted(int(x.data) for x in RandomData.objects.all()),
list(range(5)) + list(range(10, 20)),
)
# one batch
self.assertEqual(len(updated_items), 1)
# tuple with (created, updated)
self.assertEqual(len(updated_items[0]), 2)
# 5 were created - 15 to 19
self.assertEqual(len(updated_items[0][0]), 5)
self.assertEqual(
sorted(int(x.data) for x in updated_items[0][0]),
list(range(15, 20)),
)
for x in updated_items[0][0]:
self.assertIsNotNone(x.pk)
# 5 were updated - 10 to 14 (from 5 to 9)
self.assertEqual(len(updated_items[0][1]), 5)
self.assertEqual(
sorted(int(x.data) for x in updated_items[0][1]),
list(range(10, 15)),
)
for x in updated_items[0][1]:
self.assertIsNotNone(x.pk)
def test_errors(self):
with self.assertRaises(ValueError) as cm:
RandomData.objects.bulk_update_or_create([None], [])
self.assertEqual(cm.exception.args, ('update_fields cannot be empty',))
with self.assertRaises(ValueError) as cm:
RandomData.objects.bulk_update_or_create([None], ['data'], batch_size=-1)
self.assertEqual(cm.exception.args, ('Batch size must be a positive integer.',))
with self.assertRaises(FieldDoesNotExist) as cm:
RandomData.objects.bulk_update_or_create([RandomData(uuid=1, data='x')], ['data'], match_field='x')
self.assertEqual(cm.exception.args, ("RandomData has no field named 'x'",))
with self.assertRaises(FieldDoesNotExist) as cm:
RandomData.objects.bulk_update_or_create([RandomData(uuid=1, data='x')], ['x'], match_field='uuid')
self.assertEqual(cm.exception.args, ("RandomData has no field named 'x'",))
def test_case_sensitivity(self):
"""
match_fields should always be unique but for test simplicity (no extra model),
using RandomData.data
"""
RandomData.objects.bulk_update_or_create(
[
RandomData(uuid=1, data='x'),
],
['uuid'],
match_field='data',
)
self.assertEqual(RandomData.objects.count(), 1)
self.assertEqual(sorted(x.data for x in RandomData.objects.all()), ['x'])
RandomData.objects.bulk_update_or_create(
[
RandomData(uuid=2, data='X'),
],
['uuid'],
match_field='data',
case_insensitive_match=True,
)
self.assertEqual(RandomData.objects.count(), 1)
self.assertEqual(sorted(x.data for x in RandomData.objects.all()), ['x'])
RandomData.objects.bulk_update_or_create(
[
RandomData(uuid=3, data='X'),
],
['uuid'],
match_field='data',
)
self.assertEqual(RandomData.objects.count(), 2)
self.assertEqual(sorted(x.data for x in RandomData.objects.all()), ['X', 'x'])
def test_update_some_with_context_manager(self):
self.test_all_create()
with self.assertNumQueries(7):
with RandomData.objects.bulk_update_or_create_context(
['data'], match_field='uuid', batch_size=500
) as bulkit:
for i in range(10):
bulkit.queue(RandomData(uuid=i + 5, data=i + 10))
self.assertEqual(RandomData.objects.count(), 15)
self.assertEqual(
sorted(int(x.data) for x in RandomData.objects.all()),
list(range(5)) + list(range(10, 20)),
)
# smaller batch_size to test more than 1 batch and test status_cb
cb_calls = []
def _cb(x):
# nothing created
self.assertEqual(x[0], [])
cb_calls.extend(x[1])
# 4 all-update batches = 8 queries
with self.assertNumQueries(8):
with RandomData.objects.bulk_update_or_create_context(
['data'], match_field='uuid', batch_size=3, status_cb=_cb
) as bulkit:
for i in range(10):
bulkit.queue(RandomData(uuid=i, data=i + 20))
self.assertEqual(RandomData.objects.count(), 15)
self.assertEqual(
# 20 to 29 ... 15 to 19
sorted(int(x.data) for x in RandomData.objects.all()),
list(range(15, 30)),
)
self.assertEqual(len(cb_calls), 10)
for i in range(10):
self.assertEqual(cb_calls[i].uuid, i)
self.assertEqual(cb_calls[i].data, i + 20)
def test_context_manager_exact_batch_size(self):
# test made to hit *empty* queue on context manager __exit__()!
with self.assertNumQueries(11):
with RandomData.objects.bulk_update_or_create_context(
['data'], match_field='uuid', batch_size=10
) as bulkit:
for i in range(10):
bulkit.queue(RandomData(uuid=i + 5, data=i + 10))
self.assertSum(145)
def test_context_manager_queue_kwargs(self):
with self.assertNumQueries(11):
with RandomData.objects.bulk_update_or_create_context(
['data'], match_field='uuid', batch_size=10
) as bulkit:
for i in range(10):
bulkit.queue_obj(uuid=i + 5, data=i + 10)
self.assertSum(145)
def test_empty_objs(self):
"""
test change of behaviour for empty objs to match bulk_update
https://github.com/fopina/django-bulk-update-or-create/issues/10
"""
with self.assertNumQueries(0):
RandomData.objects.bulk_update([], fields=['data'])
with self.assertNumQueries(0):
RandomData.objects.bulk_update_or_create([], ['data'], match_field='uuid')
def test_keyerror(self):
"""
test for issue https://github.com/fopina/django-bulk-update-or-create/issues/11
eg: using string values in model IntegerFields cause obj_map lookups to fail on existing objects
"""
self.test_all_create()
self.assertSum(45)
# this works
RandomData.objects.bulk_update_or_create(
[RandomData(uuid=i, data=i + 1) for i in range(10)], ['data'], match_field='uuid'
)
self.assertSum(55)
# but this *DID* not - it does now though!
RandomData.objects.bulk_update_or_create(
[RandomData(uuid=str(i), data=i + 2) for i in range(10)], ['data'], match_field='uuid'
)
self.assertSum(65)
def assertSum(self, total):
self.assertEqual(sum(int(x.data) for x in RandomData.objects.all()), total)
def test_multiple_match_fields_update(self):
items = [RandomData(uuid=i, value=i % 5, data=i) for i in range(10)]
RandomData.objects.bulk_create(items)
items = [RandomData(uuid=i, value=i % 5, data=i + 10) for i in range(10)]
# 1 select, 1 bulk update
with self.assertNumQueries(2):
RandomData.objects.bulk_update_or_create(items, ['data'], match_field=('uuid', 'value'))
self.assertEqual(RandomData.objects.count(), 10)
self.assertEqual(
sorted(int(x.data) for x in RandomData.objects.all()),
list(range(10, 20)),
)
def test_multiple_match_fields_update_create(self):
items = [RandomData(uuid=i, value=i % 5, data=i) for i in range(10)]
RandomData.objects.bulk_create(items)
items = [RandomData(uuid=i + 5, value=i % 5, data=i + 10) for i in range(10)]
# 1 select, 1 bulk update, 5 inserts
with self.assertNumQueries(7):
RandomData.objects.bulk_update_or_create(items, ['data'], match_field=('uuid', 'value'))
self.assertEqual(RandomData.objects.count(), 15)
self.assertEqual(
list(int(x.data) for x in RandomData.objects.order_by('uuid')),
[*range(5), *range(10, 15), *range(15, 20)],
)
def test_multiple_match_fields_update_pk(self):
items = [RandomData(uuid=i, value=i % 5, data=str(i)) for i in range(10)]
RandomData.objects.bulk_create(items)
items = [RandomData(uuid=i + 100, value=i % 5, data=str(i)) for i in range(10)]
# 1 select, 1 bulk update
with self.assertNumQueries(2):
RandomData.objects.bulk_update_or_create(items, ['uuid'], match_field=('data', 'value'))
self.assertEqual(RandomData.objects.count(), 10)
self.assertEqual(
list(x.uuid for x in RandomData.objects.order_by('data', 'value')),
list(range(100, 110)),
)
<file_sep>/tox.ini
[tox]
envlist =
flake8
py{37,38,39}-dj{22,30,32}-{sqlite,postgresql,mysql}
[testenv]
deps =
dj22: Django==2.2.*
dj30: Django==3.0.*
dj32: Django==3.2.*
postgresql: psycopg2-binary
mysql: mysqlclient
coverage
setenv =
PYTHONPATH = {toxinidir}
sqlite: DJANGO_SETTINGS_MODULE = settings
postgresql: DJANGO_SETTINGS_MODULE = settings_postgresql
mysql: DJANGO_SETTINGS_MODULE = settings_mysql
whitelist_externals = make
pip_pre = True
commands = make coverage TEST_ARGS='{posargs:tests}'
[testenv:flake8]
basepython = python3
commands = make flake8
deps = flake8
skip_install = true
[testenv:style]
basepython = python3
commands = make style_check
deps =
black>=19.10b0
flake8
skip_install = true
<file_sep>/README.md
# django-bulk-update-or-create
[](https://github.com/fopina/django-bulk-update-or-create/actions?query=workflow%3Atests)
[](https://codecov.io/gh/fopina/django-bulk-update-or-create)
[](https://pypi.org/project/django-bulk-update-or-create/)
[](https://pypi.org/project/django-bulk-update-or-create/)


Everyone using Django ORM will eventually find himself doing batch `update_or_create` operations: ingest files from external sources, sync with external APIs, etc.
If the number of records is big, the slowliness of `QuerySet.update_or_create` will stand out: it is very practical to use but it always does one `SELECT` and then one `INSERT` (if select didn't return anything) or `UPDATE`/`.save` (if it did).
Searching online shows that this does indeed happen to quite a few people though it doesn't seem to be any good solution:
* `bulk_create` is really fast if you know all records are new (and you're not using multi-table inheritance)
* `bulk_update` does some nice voodoo to update several records with the same `UPDATE` statement (using a huge `WHERE` condition together with `CASE`), but you need to be sure they all exist
* UPSERTs [(INSERT .. ON DUPLICATE KEY UPDATE](https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html)) look interesting (TODO on different package) but they will be retricted by `bulk_create` limitations ==> cannot use on models with multi-table inheritance
This package tries to tackle this introducing `bulk_update_or_create` to model QuerySet/Manager:
* `update_or_create`: `(1 SELECT + 1 INSERT/UPDATE) * N`
* `bulk_update_or_create`: `1 BIG_SELECT + 1 BIG_UPDATE + (lte_N) INSERT`
For a batch of records:
* `SELECT` all from database (based on the `match_field` parameter)
* Update records in memory
* Use `bulk_update` for those
* Use `INSERT`/`.create` on each of the remaining
The (*SOFTCORE*) [performance test](tests/tests/management/commands/bulk_it.py) looks promising, more than 70% less time (average):
```shell
$ make testcmd
# default - sqlite
DJANGO_SETTINGS_MODULE=settings tests/manage.py bulk_it
loop of update_or_create - all creates: 3.966486692428589
loop of update_or_create - all updates: 4.020653247833252
loop of update_or_create - half half: 3.9968857765197754
bulk_update_or_create - all creates: 2.949239730834961
bulk_update_or_create - all updates: 0.15633511543273926
bulk_update_or_create - half half: 1.4585723876953125
# mysql
DJANGO_SETTINGS_MODULE=settings_mysql tests/manage.py bulk_it
loop of update_or_create - all creates: 5.511938571929932
loop of update_or_create - all updates: 5.321666955947876
loop of update_or_create - half half: 5.391834735870361
bulk_update_or_create - all creates: 1.5671980381011963
bulk_update_or_create - all updates: 0.14612770080566406
bulk_update_or_create - half half: 0.7262606620788574
# postgres
DJANGO_SETTINGS_MODULE=settings_postgresql tests/manage.py bulk_it
loop of update_or_create - all creates: 4.3584535121917725
loop of update_or_create - all updates: 3.6183276176452637
loop of update_or_create - half half: 4.145816087722778
bulk_update_or_create - all creates: 1.044851541519165
bulk_update_or_create - all updates: 0.14954638481140137
bulk_update_or_create - half half: 0.8407495021820068
```
Installation
============
```
pip install django-bulk-update-or-create
```
```py
INSTALLED_APPS = [
...
'bulk_update_or_create',
...
]
```
Usage
=====
* use `BulkUpdateOrCreateQuerySet` as manager of your model(s)
```python
from django.db import models
from bulk_update_or_create import BulkUpdateOrCreateQuerySet
class RandomData(models.Model):
objects = BulkUpdateOrCreateQuerySet.as_manager()
uuid = models.IntegerField(unique=True)
data = models.CharField(max_length=200, null=True, blank=True)
```
* call `bulk_update_or_create`
```python
items = [
RandomData(uuid=1, data='data for 1'),
RandomData(uuid=2, data='data for 2'),
]
RandomData.objects.bulk_update_or_create(items, ['data'], match_field='uuid')
```
* or use the context manager, if you are updating a big number of items, as it manages a batch queue
```python
with RandomData.objects.bulk_update_or_create_context(['data'], match_field='uuid', batch_size=10) as bulkit:
for i in range(10000):
bulkit.queue(RandomData(uuid=i, data=i + 20))
```
`bulk_update_or_create` supports `yield_objects=True` so you can iterate over the created/updated objects.
`bulk_update_or_create_context` provides the same information to the callback function specified as `status_cb`
Docs
====
WIP
ToDo
====
* [ ] Docs!
* [ ] Add option to use `bulk_create` for creates: assert model is not multi-table, if enabled
* [ ] Fix the collation mess: the keyword arg `case_insensitive_match` should be dropped and collation detected in runtime
* [x] Add support for multiple `match_field` - probably will need to use `WHERE (K1=X and K2=Y) or (K1=.. and K2
=..)` instead of `IN` for those, as that SQL standard doesn't seem widely adopted yet
* [ ] Link to `UPSERT` alternative package once done!
<file_sep>/tests/settings_mysql.py
from settings import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql',
'USER': 'root',
'PASSWORD': '<PASSWORD>',
'HOST': '127.0.0.1',
'PORT': '8877',
'TEST': {'CHARSET': 'utf8mb4', 'COLLATION': 'utf8mb4_bin'},
}
}
<file_sep>/Makefile
.PHONY: flake8 test coverage style style_check
style:
black --target-version=py36 \
--line-length=120 \
--skip-string-normalization \
bulk_update_or_create tests setup.py
flake8 bulk_update_or_create tests
style_check: flake8
black --target-version=py36 \
--line-length=120 \
--skip-string-normalization \
--check \
bulk_update_or_create tests setup.py
flake8:
flake8 bulk_update_or_create tests
startmysql:
@docker inspect django-bulk_update_or_create-mysql | grep -q '"Running": true' || \
docker run --name django-bulk_update_or_create-mysql \
-e MYSQL_ROOT_PASSWORD=<PASSWORD> \
--rm -p 8877:3306 -d \
--health-cmd "mysqladmin ping" \
--health-interval 10s \
--health-timeout 5s \
--health-retries=5 \
mysql:5 # TODO: wait for healthy
startpg:
@docker inspect django-bulk_update_or_create-pg | grep -q '"Running": true' || \
docker run --name django-bulk_update_or_create-pg \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=<PASSWORD> \
-e POSTGRES_DB=postgres \
--rm -p 8878:5432 -d \
--health-cmd pg_isready \
--health-interval 10s \
--health-timeout 5s \
--health-retries 5 \
postgres:10 # TODO: wait for healthy
test: startmysql
DJANGO_SETTINGS_MODULE=settings_mysql \
tests/manage.py test $${TEST_ARGS:-tests}
testpg: startpg
DJANGO_SETTINGS_MODULE=settings_postgresql \
tests/manage.py test $${TEST_ARGS:-tests}
testcmd: startpg startmysql
# default - sqlite
DJANGO_SETTINGS_MODULE=settings tests/manage.py migrate
DJANGO_SETTINGS_MODULE=settings tests/manage.py bulk_it
# mysql
DJANGO_SETTINGS_MODULE=settings_mysql tests/manage.py migrate
DJANGO_SETTINGS_MODULE=settings_mysql tests/manage.py bulk_it
# postgres
DJANGO_SETTINGS_MODULE=settings_postgresql tests/manage.py migrate
DJANGO_SETTINGS_MODULE=settings_postgresql tests/manage.py bulk_it
coverage:
PYTHONPATH="tests" \
python -b -W always -m coverage run tests/manage.py test $${TEST_ARGS:-tests}
coverage report
<file_sep>/tests/tests/management/commands/bulk_it.py
from time import time
from django.core.management.base import BaseCommand
from tests.models import RandomData
from contextlib import contextmanager
@contextmanager
def timing(description: str) -> None:
start = time()
yield
ellapsed_time = time() - start
print(f"{description}: {ellapsed_time}")
class Command(BaseCommand):
help = 'Lock it!'
def _loop(self, n=1000, offset=0, data_offset=0):
for i in range(n):
RandomData.objects.update_or_create(
uuid=i + offset,
defaults={'data': str(i + offset + data_offset)},
)
def _bulk(self, n=1000, offset=0, data_offset=0):
items = [RandomData(uuid=i + offset, data=str(i + offset + data_offset)) for i in range(n)]
RandomData.objects.bulk_update_or_create(items, ['data'], match_field='uuid')
def _clear(self):
RandomData.objects.all().delete()
def _check(self, n=1000, min=0, max=999):
values = sorted([int(x.data) for x in RandomData.objects.all()])
assert len(values) == n
assert values[0] == min
assert values[-1] == max
def handle(self, *args, **options):
self._clear()
with timing('loop of update_or_create - all creates'):
self._loop()
self._check()
with timing('loop of update_or_create - all updates'):
self._loop(data_offset=1)
self._check(1000, 1, 1000)
with timing('loop of update_or_create - half half'):
self._loop(offset=500, data_offset=2)
self._check(1500, 1, 1501)
self._clear()
with timing('bulk_update_or_create - all creates'):
self._bulk()
self._check()
with timing('bulk_update_or_create - all updates'):
self._bulk(data_offset=1)
self._check(1000, 1, 1000)
with timing('bulk_update_or_create - half half'):
self._bulk(offset=500, data_offset=2)
self._check(1500, 1, 1501)
<file_sep>/tests/tests/models.py
from django.db import models
from bulk_update_or_create import BulkUpdateOrCreateQuerySet
class RandomData(models.Model):
objects = BulkUpdateOrCreateQuerySet.as_manager()
uuid = models.IntegerField(unique=True)
value = models.IntegerField(default=0)
data = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return f'{self.uuid} - {self.data} - {self.value}'
<file_sep>/bulk_update_or_create/query.py
from django.db import models
class BulkUpdateOrCreateMixin:
def bulk_update_or_create_context(
self,
update_fields,
match_field='pk',
batch_size=100,
case_insensitive_match=False,
status_cb=None,
):
"""
Helper method that returns a context manager (_BulkUpdateOrCreateContextManager) that makes it easier to handle
a stream of objects with unknown size.
Call `.queue(obj)` and whenever `batch_size` is reached or the context terminates, this context manager will
call `bulk_update_or_create` on the queue
:param update_fields: fields that will be updated if record already exists (passed on to bulk_update)
:param match_field: model field that will match existing records (defaults to "pk")
:param batch_size: number of records to process in each batch (defaults to 100)
:param case_insensitive_match: set to True if using MySQL with "ci" collations (defaults to False)
:param status_cb: if set to a callable, status_cb is called a tuple of lists with ([created],
[updated]) objects as they're yielded
"""
return _BulkUpdateOrCreateContextManager(
self,
update_fields,
batch_size=batch_size,
status_cb=status_cb,
match_field=match_field,
case_insensitive_match=case_insensitive_match,
)
def bulk_update_or_create(
self,
objs,
update_fields,
match_field='pk',
batch_size=None,
case_insensitive_match=False,
yield_objects=False,
):
"""
:param objs: model instances to be updated or created
:param update_fields: fields that will be updated if record already exists (passed on to bulk_update)
:param match_field: model fields that will match existing records (defaults to ["pk"])
:param batch_size: number of records to process in each batch (defaults to len(objs))
:param case_insensitive_match: set to True if using MySQL with "ci" collations (defaults to False)
:param yield_objects: if True, method becomes a generator that will yield a tuple of lists
with ([created], [updated]) objects
"""
r = self.__bulk_update_or_create(
objs,
update_fields,
match_field,
batch_size,
case_insensitive_match,
yield_objects,
)
if yield_objects:
return r
return list(r)
def __bulk_update_or_create_inner_methods(self, match_fields, case_insensitive_match):
single_match_field = len(match_fields) == 1
def _obj_key_getter_sensitive(obj):
# use to_python to coerce value same way it's done when fetched from DB
# https://github.com/fopina/django-bulk-update-or-create/issues/11
# k = _match_field.to_python(_match_field.value_from_object(obj))
return tuple(match_field.to_python(match_field.value_from_object(obj)) for match_field in match_fields)
_obj_key_getter = _obj_key_getter_sensitive
if case_insensitive_match:
def _obj_key_getter(obj):
return tuple(
map(
lambda v: v.lower() if hasattr(v, 'lower') else v,
_obj_key_getter_sensitive(obj),
)
)
if single_match_field:
def _obj_filter(obj_map):
return models.Q(**{f'{match_fields[0].name}__in': obj_map.keys()})
def _obj_key_getter_single(obj):
return _obj_key_getter(obj)[0]
return _obj_key_getter_single, _obj_filter
else:
def _obj_filter(obj_map):
return models.Q(
*(
models.Q(**{k.name: obj_key[i] for i, k in enumerate(match_fields)})
for obj_key in obj_map.keys()
),
_connector=models.Q.OR,
)
return _obj_key_getter, _obj_filter
def __bulk_update_or_create(
self,
objs,
update_fields,
match_field='pk',
batch_size=None,
case_insensitive_match=False,
yield_objects=False,
):
# validations like bulk_update
if batch_size is not None and batch_size < 0:
raise ValueError('Batch size must be a positive integer.')
if not update_fields:
raise ValueError('update_fields cannot be empty')
match_field = (match_field,) if isinstance(match_field, str) else match_field
_match_fields = [self.model._meta.get_field(name) for name in match_field]
_update_fields = [self.model._meta.get_field(name) for name in update_fields]
if any(not f.concrete or f.many_to_many for f in _update_fields):
raise ValueError('bulk_update_or_create() can only be used with concrete fields.')
if any(f.primary_key for f in _update_fields):
raise ValueError('bulk_update_or_create() cannot be used with primary key fields.')
# generators not supported (for now?), as bulk_update doesn't either
objs = list(objs)
if not objs:
return
if batch_size is None:
batch_size = len(objs)
batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))
_obj_key_getter, _obj_filter = self.__bulk_update_or_create_inner_methods(_match_fields, case_insensitive_match)
for batch in batches:
obj_map = {_obj_key_getter(obj): obj for obj in batch}
# mass select for bulk_update on existing ones
to_update = self.filter(_obj_filter(obj_map))
for to_u in to_update:
obj = obj_map[_obj_key_getter(to_u)]
for _f in update_fields:
setattr(to_u, _f, getattr(obj, _f))
del obj_map[_obj_key_getter(to_u)]
self.bulk_update(to_update, update_fields)
# .create on the remaining (bulk_create won't work on multi-table inheritance models...)
created_objs = []
for obj in obj_map.values():
obj.save()
created_objs.append(obj)
if yield_objects:
yield created_objs, to_update
class BulkUpdateOrCreateQuerySet(BulkUpdateOrCreateMixin, models.QuerySet):
pass
class _BulkUpdateOrCreateContextManager:
def __init__(self, queryset, update_fields, batch_size=500, status_cb=None, **kwargs):
self._queue = []
self._queryset = queryset
self._batch_size = batch_size
assert status_cb is None or callable(status_cb)
self._cb = status_cb
self._fields = update_fields
self._kwargs = kwargs
def queue(self, obj):
self._queue.append(obj)
if len(self._queue) >= self._batch_size:
self.dump_queue()
def queue_obj(self, **kwargs):
"""
proxy method to forward kwargs to self.model instantiation before calling queue()
"""
return self.queue(self._queryset.model(**kwargs))
def dump_queue(self):
if not self._queue:
return
r = self._queryset.bulk_update_or_create(
self._queue,
self._fields,
yield_objects=self._cb is not None,
**self._kwargs,
)
if self._cb is not None:
for st in r:
self._cb(st)
self._queue = []
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.dump_queue()
<file_sep>/bulk_update_or_create/__init__.py
from .query import BulkUpdateOrCreateQuerySet, BulkUpdateOrCreateMixin
__all__ = ['BulkUpdateOrCreateQuerySet', 'BulkUpdateOrCreateMixin']
default_app_config = 'bulk_update_or_create.apps.BulkUpdateOrCreateConfig'
|
95f0e5f42dbfd04004ae35caf06562dde3dec89f
|
[
"Markdown",
"Python",
"Makefile",
"INI"
] | 10
|
Markdown
|
thinhhuynh/django-bulk-update-or-create
|
a1f20ff146b3e5fd9612e77f799d9233488fe71a
|
9ba7e5f5fdf9fb61a5c1bf1a391ee7ea1a319aad
|
refs/heads/master
|
<repo_name>nerudxlf/numberErdos<file_sep>/README.md
# numberErdos
number Erdos
<file_sep>/numberErdos.py
AVTOR = "<NAME>" # Константа
stringNameArticle = []
stringNameAvtor = []
stringNameAvtorOne = set()
stringNameAvtorTwo = set()
nameAvtorResult = []
def addArr(List):
"""Фунция обработки строки"""
List = List.split("., ")
lastElem = List[-1].split(".: ")
del List[-1]
List.append(lastElem[0])
return List
def one(List):
"""Функция для получения числа один то есть
людей которые непосредсвенно первыми печатались в статье"""
List = addArr(List)
cout = 0
if AVTOR in List:
List.remove(AVTOR)
cout = 1
return List, cout
return List, 0
def two(ListSet, ListSetForOne):
"""функция для нахождения людей которые писали статью
с людьми номер которых равен одному"""
cout = 0
for i in range(0, len(ListSet)):
if ListSet[i] in ListSetForOne:
ListSetForOne.remove(ListSet[i])
cout = 1
if cout:
return ListSetForOne, cout
return 0, 0
def result(name, number):
"""Конкатенация строк"""
if number == 0:
number = "Infinity"
string = str(name) + " " + str(number)
return string
def main():
valueS = int(input())
stringPN = str(input())
stringPN = stringPN.split()
arrStringPN = [int(elem) for elem in stringPN]
for i in range(0, arrStringPN[0]):
line = str(input())
cout = 0
line, cout = one(line)
if cout:
stringNameAvtorOne.update(set(line))
cout = 0
else:
line, cout = two(list(stringNameAvtorOne), line)
if cout:
stringNameAvtorTwo.update(set(line))
for i in range(0, arrStringPN[1]):
line = str(input())
stringNameAvtor.append(line)
if stringNameAvtor[i] in stringNameAvtorOne:
nameAvtorResult.append(result(stringNameAvtor[i], 1))
elif stringNameAvtor[i] in stringNameAvtorTwo:
nameAvtorResult.append(result(stringNameAvtor[i], 2))
else:
nameAvtorResult.append(result(stringNameAvtor[i], 0))
for i in range(0, len(nameAvtorResult)):
print(nameAvtorResult[i])
if __name__ == '__main__':
main()
|
e0e77ac8813ddc2a4edc745a88635833d79e14cb
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
nerudxlf/numberErdos
|
38ddfd2c0e6d9a3482e4387c80092718ac6113ec
|
00772e8477c3684889f8a676b65ff4bfadf21c53
|
refs/heads/master
|
<file_sep>#include "Window.h"
Window::Window(int width, int height)
{
window = NULL;
this->width = width;
this->height = height;
}
Window::~Window()
{
glfwTerminate();
}
void Window::createWindowHints(int majorVersion, int minorVersion)
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, majorVersion);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minorVersion);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
}
void Window::frameBufferSizeCallback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
this->width = width;
this->height = height;
}
<file_sep>#pragma once
#include "Include.h"
struct ShaderProgramSource
{
string vertexSource;
string fragmentSource;
};
ShaderProgramSource parseShader(const string& filePath);
unsigned int compileShader(unsigned int type, const string& source);
unsigned int createShader(const string& vertexShader, const string& fragmentShader);
<file_sep>#include "Debug.h"
#include "VertexBuffer.h"
#include "IndexBuffer.h"
#include "Parser.h"
#include "Window.h"
using namespace std;
int main(void)
{
Window window (640, 480);
/* Initialize the library */
if (!glfwInit())
return -1;
int a = window.getHeight();
cout << a;
window.createWindowHints(3, 3);
/* Create a windowed mode window and its OpenGL context */
window.setWindow(glfwCreateWindow(window.getWidth(), window.getHeight(), "Hello World", NULL, NULL));
if (window.getWindow() == NULL)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window.getWindow());
//Vertical synchronization
glfwSwapInterval(1);
if (glewInit() != GLEW_OK)
{
cout << "Error when init glew" << endl;
}
cout << glGetString(GL_VERSION) << endl;
float positions[] = {
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f,
};
unsigned int indices[] = {
0, 1, 2,
2, 3, 0
};
unsigned int vao;
GLCall(glGenVertexArrays(1, &vao));
GLCall(glBindVertexArray(vao));
VertexBuffer vb(positions, sizeof(positions));
GLCall(glEnableVertexAttribArray(0));
GLCall(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0));
IndexBuffer ib(indices, sizeof(indices) / sizeof(unsigned int));
ShaderProgramSource source = parseShader("res/shaders/Basic.shader");
unsigned int shader = createShader(source.vertexSource, source.fragmentSource);
GLCall(glUseProgram(shader));
int location = glGetUniformLocation(shader, "u_Color");
ASSERT(location != -1);
GLCall(glBindVertexArray(0));
GLCall(glUseProgram(0));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
float r = 0.0f;
float increment = 0.002f;
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window.getWindow()))
{
/* Render here */
GLCall(glClear(GL_COLOR_BUFFER_BIT));
GLCall(glUseProgram(shader));
GLCall(glUniform4f(location, r, 0.3f, 0.8f, 1.0f));
GLCall(glBindVertexArray(vao));
ib.Bind();
//glDrawArrays(GL_TRIANGLES, 0, 4);
GLCall(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr));
if (r >= 1)
increment = -0.002f;
else if (r <= 0)
increment = 0.002f;
r += increment;
/* Swap front and back buffers */
glfwSwapBuffers(window.getWindow());
/* Poll for and process events */
glfwPollEvents();
}
glDeleteProgram(shader);
glfwTerminate();
return 0;
}<file_sep># GameEngine
Список источников:
1) Великолепный канал, на котором объясняют openGL с самых основ (а также есть плейлист с С++ и игровым движком)
https://www.youtube.com/watch?v=W3gAzLwfIP0&list=PLlrATfBNZ98foTJPJ_Ev03o2oq3-GGOS2
2) Цикл статей на хабре с переводом неплохово гайда (сбер блочит сам гайд, поэтому смотрю на хабре)
https://habr.com/ru/post/310790/
3) Тоже отличный цикл статей с веедением в основы рендеринга (в статье есть ссылка на гит, в котором все в оригинале и с обновлениями)
https://habr.com/ru/post/248153/
4) Real Time Rendering (4 издание)
5) OpenGL Red Book
6) OpenGl 4. Язык Шейдеров. Книга рецептов.
Помимо этого пользуюсь кучей онлайн гайдов и статей, они легко гуглятся, но если что, пишите, добавлю основное в ридми.
<file_sep>#pragma once
#include "Include.h"
class Window
{
private:
GLFWwindow* window;
unsigned int width;
unsigned int height;
public:
Window(int width, int height);
~Window();
void createWindowHints(int majorVersion, int MinorVersion);
void frameBufferSizeCallback(GLFWwindow* window, int weight, int height);
inline void setWindow(GLFWwindow* window) { this->window = window; }
inline GLFWwindow *getWindow() const { return window; }
inline unsigned int getWidth() const { return width; }
inline unsigned int getHeight() const { return height; }
};
|
55964e4e244f02d3ab553ed04c4e01e729c84611
|
[
"Markdown",
"C",
"C++"
] | 5
|
C++
|
zhmak/GameEngine
|
91ac085fd70d83fd00d7da7b594cb38f2e739431
|
4377833bc574d53753a87d93baa6a1769a239973
|
refs/heads/master
|
<file_sep>## Sobre o projeto
- Interface de um catálogo de busca de filmes que consome uma API.
## Pré-requisitos
- Ter instalado o Gerenciador de Pacotes do Nodejs (npm).
## Instalação
- Primeiramente, baixe ou clone o arquivo.
- Entre na pasta do arquivo pelo terminal e execute o comando:
```
npm install
```
- Após concluída a instação, utilize o comando:
```
npm start
```
- Após o carregamento, a página será exibida em seu navegador.
## Uso
Exemplos de casos de uso:
- Deseja-se catalogar determinados filmes em uma página web.
- Cadastrar filmes contidos em determinado site de download de filmes.
## Tecnologias usadas
- Javascript - Linguagem de programação.
- React - Biblioteca Javascript para desenvolvimento web.
## Autor
- <NAME> - Developer - guilhermefaleiros.
<file_sep>import React, {useState, useEffect} from 'react'
import api from '../../services/api'
import './styles1.css'
export default function Busca({history}){
const [filtro, setFiltro] = useState('')
const [movies, setMovies] = useState([])
useEffect(() => {
async function loadMovies(){
const response = await api.get('/dashboard')
setMovies(response.data)
console.log(response.data)
}
loadMovies()
setFiltro("Drama")
}, [])
async function handleSubmit(event){
event.preventDefault()
const str = filtro.toLowerCase()
localStorage.setItem('filtro', str)
console.log(str)
if(str!==''){
history.push('/dashboard')
localStorage.setItem('vazio', false);
}
}
return (
<div className="container">
<div className="content">
<p>
Procure seus filmes preferidos!
</p>
<form onSubmit={handleSubmit}>
<label htmlFor="filtro">SELECIONE O GÊNERO DO FILME DESEJADO</label>
<select name="" id="filtro" value={filtro}
onChange={event => setFiltro(event.target.value)}>
<option value="Drama">Drama</option>
<option value="Ação">Ação</option>
<option value="Romance">Romance</option>
<option value="Terror">Terror</option>
<option value="Histórico">Histórico</option>
<option value="Guerra">Guerra</option>
<option value="Documentário">Documentário</option>
<option value="Thriller">Thriller</option>
<option value="Comédia">Comédia</option>
<option value="Aventura">Aventura</option>
<option value="Animação">Animação</option>
<option value="Família">Família</option>
<option value="Ficção Científica">Ficção Científica</option>
<option value="Biografia">Biografia</option>
<option value="Crime">Crime</option>
<option value="Mistério">Mistério</option>
</select>
<button className="btn" type="submit">
Buscar
</button>
</form>
<ul className="movie-list">
{movies.map(movie => (
<li key={movie._id}>
<header style={{ backgroundImage: `url(${movie.thumbnail})` }}/>
<strong>{movie.title}</strong>
<span>Nota IMDB: {movie.score}</span>
<span>N° IMDB: {movie.id}</span>
<span><a href={`http://www.imdb.com/title/tt0${movie.id}`}>Clique para acessar no IMDB</a></span>
</li>
))}
</ul>
</div>
</div>
)
}<file_sep>import React, {useEffect, useState} from 'react'
import api from '../../services/api'
import './styles.css'
export default function Dashboard({history}){
const [movies, setMovies] = useState([])
useEffect(() => {
async function loadMovies(){
const filtro = localStorage.getItem('filtro')
const response = await api.get('/movies', {
headers:{filtro}
})
setMovies(response.data)
console.log(response.data)
}
loadMovies()
}, [])
const filtro = localStorage.getItem('filtro')
function backToFilter(){
history.push('/')
}
return (
<div className="container">
<div className="content">
<button onClick={backToFilter}>Voltar para o campo de filtro</button>
<p>Exibindo resultados para <strong>{filtro}</strong>:</p>
<ul className="movie-list">
{movies.map(movie => (
<li key={movie._id}>
<header style={{ backgroundImage: `url(${movie.thumbnail})` }}/>
<strong>{movie.title}</strong>
<span>Gênero: {filtro}</span>
<span>Nota IMDB: {movie.score}</span>
<span>N° IMDB: {movie.id}</span>
<span><a href={`http://www.imdb.com/title/tt0${movie.id}`}>Clique para acessar no IMDB</a></span>
</li>
))}
</ul>
</div>
</div>
)
}
|
d14e044ea9f49e31ba50ca2bfc6bfb1181cbedef
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
guilhermefaleiros/proj-filme-frontend
|
4e3a2c545fde02653b25c10f04540ed9db736354
|
15f175f68c5ccbef6478f327b3db0d028abd7f9c
|
refs/heads/master
|
<file_sep>import React, { createContext, useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import "../node_modules/bootstrap/dist/css/bootstrap.min.css"
import './App.css';
// import {BrowserRouter} from "react-router-dom";
import {Route, Switch} from "react-router-dom";
import About from './Components/About';
import Contact from './Components/Contact';
import Nav from './Components/Nav';
import Signup from "./Components/Signup/Signup";
import Login from "./Components/Signup/Login";
import Services from "./Components/Servivces";
// import User from "./Components/User";
import Error from "./Components/Error";
import Home from "./Components/Home";
import Product from "./Components/Product";
function App() {
return (<>
<Nav />
<Switch>
{/* <Redirect to="/"/> */}
<Route exact path="/home" component={Home} />
<Route exact path="/about" component ={()=> <About /> } />
<Route exact path="/product" component ={Product} />
<Route exact path="/contact" component ={Contact} />
<Route exact path="/signup" component ={Signup} />
<Route exact path="/login" component ={Login} />
<Route exact path="/services" component ={Services} />
{/* <Route exact path="/user" component ={User} /> */}
{/* <Route exact path="/user/:fname/:lname" component ={User} /> */}
<Route exact component ={Error} />
</Switch>
{/* <About />
<Contact /> */}
</>
)
}
export default App;
<file_sep>import React from 'react'
import { NavLink } from 'react-router-dom';
import "../Components/Home/home.css"
function Home() {
return (
<>
<section id="header" className="container">
<div className="container-fluid">
<div className="row2">
{/* <div className="col-10 mx-auto"> */}
{/* <div className="col-md-6 pt-5 pt-lg-0 order-2 order-lg-1 d-flex justify-content-center flex-column"> */}
<h5 style={{fontSize:"2.8rem", marginTop:"1rem"}}>Watch Movies With <span> </span>
<strong>TSM</strong> </h5>
<br/>
<h5 className="my-1" style={{fontSize:"2.5rem" , paddingTop:"2px"}}>We are providing
<br/> latest movies !</h5>
<div className="mt-3">
<NavLink to="/home" className="btn-get-started">
Get Started
</NavLink>
</div>
<div className="col-lg-6 order-1 order-lg-2 header-img">
<div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel">
<div className="carousel-inner">
<div className="carousel-item active">
<img src="https://besthqwallpapers.com/Uploads/22-2-2019/81386/thumb2-4k-avengers-endgame-characters-2019-movie-avengers-4.jpg
" className="img-fluid animated" alt="..." />
</div>
<div className="carousel-item">
<img src="https://wallpapercave.com/wp/24t2Yct.jpg"
className="img-fluid animated" alt="..." />
</div>
<div className="carousel-item">
<img src="https://th.bing.com/th/id/OIP.G8PYSdBlBtnMvrlcXHNubgHaEC?pid=ImgDet&rs=1"
className="img-fluid animated" alt="..." />
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</>
)
}
export default Home;<file_sep>import React from 'react'
import {FName ,LName} from "../App";
function C() {
return (
<div>
<FName.Consumer>
{(fname) =>{
return <LName.Consumer>
{(lname)=>{
return <h2> Anurag {fname} & {lname} </h2>
}}
</LName.Consumer>
}}
</FName.Consumer>
</div>
)
}
export default C;
// export { FName };<file_sep>import React from 'react';
import "../Components/Signup/product.css";
import Img from "../Img/img.jpg"
function Product() {
return (
<>
<div class="card" style={{width: "18rem", marginTop:"3rem"}} > <img src="..." class="card-img-top" alt="..." />
<div class="card-body">
<h1 class="card-title">Card title</h1>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</>
)
}
export default Product;
// https://api.themoviedb.org/3/movie/550?api_key=19f84e11932abbc79e6d83f82d6d1045<file_sep>import React, { useState } from 'react';
import "./Grid.css"
import Menu from "./Menu";
function Grid() {
const [item, setItems] = useState(Menu);
// const onChange=()=>{
// fileSelectHandler =
// }
return (<>
<div className="menu-items container-fluid mt-5">
<div className="row">
<div className="col-11 mx-auto">
<div className="row my-5">
{
item.map((el) => {
const {id,name, image, price}= el;
return(
<div className="item1 col-14 col-md-6 col-lg-6 col-xl-4">
<div className="row Item-inside">
<div className="col-12 col-, d-12 col-lg-4 img-div">
< img src="https://wallpaperaccess.com/full/345330.jpg"
alt-imgsrc="../img/logo.png"
></img> </div>
<div className="col1">
<div className="main-title"><h1>Product-Price</h1>
<button type="submit" className="button">Add Product</button></div>
</div>
{/* <div className="col-12 col-, d-12 ">
</div> */}
</div>
</div>
)
})
}
</div>
</div>
</div>
</div>
</>
);
}
export default Grid;
<file_sep>import React, { useState , useEffect} from 'react'
function A() {
const [num, setNum] =useState(0);
useEffect(() => {
document.title = `Anurag ${num} `
})
return (
<div>
<h1> {num} </h1>
<button onClick={()=>{
setNum(num +1)
}}
> Destroy </button>
</div>
)
}
export default A;<file_sep>import React from 'react'
import { NavLink , useHistory} from 'react-router-dom';
import "../Components/Css.css"
function Error() {
const history = useHistory();
console.log(history)
const btnEv =()=>{
history.goBack();
}
return (<>
<div className="container-error">
<h6>404 Error Page</h6>
<p>
Sorry! This Page Doesn't Exist
</p>
<button onClick={btnEv} className="err-btn">Go Back</button>
<NavLink to ="/" className="err-btn1" >Go Home</NavLink>
</div>
</>
)
}
export default Error;<file_sep>{/* <div class="https://th.bing.com/th/id/OIP.Qbag5Cux7HLMNo-BaZoHewHaI_?pid=ImgDet&rs=1" alt="/public/image/image (1).png" />
<div class="container d-flex justify-content-center">
<div class="d-flex flex-column justify-content-between">
<div class="d-flex justify-content-center align-items-center mt-5">
<div class="card">
<ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
<li class="nav-item text-center"> <a class="nav-link active btl" id="pills-home-tab" data-toggle="pill"
href="#pills-home" role="tab" aria-controls="pills-home" aria-selected="true">Login</a> </li>
<li class="nav-item text-center"> <a class="nav-link btr" id="pills-profile-tab" data-toggle="pill"
href="#pills-profile" role="tab" aria-controls="pills-profile" aria-selected="false">Signup</a>
</li>
</ul>
<div class="tab-content" id="pills-tabContent">
<div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">
<div class="form px-4 pt-5"> <input type="text" name="" class="form-control"
placeholder="Email or Phone"> <input type="text" name="" class="form-control"
placeholder="<PASSWORD>"> <button class="btn btn-dark btn-block">Login</button> </div>
</div>
<div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">
<form action="/register" method="POST">
<div class="form px-4">
<input type="text" name="name" class="form-control" placeholder="Name">
<input type="text" name="email" class="form-control" placeholder="Email">
<input type="text" name="phone" class="form-control" placeholder="Phone">
<input type="text" name="password" class="form-control" placeholder="<PASSWORD>">
<input type="text" name="cpassword" class="form-control" placeholder="<PASSWORD>Password">
<input type="text" name="age" class="form-control" placeholder="Age">
<input type="submit" class="btnRegister" value="Register" />
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div></div>
</div> */}<file_sep>import React ,{useContext} from 'react';
import {FName, LName} from "../App";
function B() {
const fname = useContext(FName,)
const lname = useContext(LName,)
return (
<div>
<h3> Yo {fname} & {lname} </h3>
</div>
)
}
export default B;<file_sep>import React, { useState } from 'react';
import './index.css';
const App = ()=>{
const [name , setName] = useState({
name: "",
email: "",
phone : "",
password : "",
cpassword : "",
age : ""
});
// const [email , setEmail] = useState("");
// const [fname , setFName] = useState();
const InputEvent = (e) =>{
console.log(e.target.value);
console.log(e.target.name);
// const value = e.target.value;
// const name = e.target.name;
const {value,name} =e.target;
setName((preval)=>{
if(name === "name"){
return{
name:value,
email: preval.email,
phone : preval.phone,
password : <PASSWORD>,
cpassword : <PASSWORD>,
age :preval.age
} }
else if (name === "email"){
return{
name: preval.name,
email: value,
phone : preval.phone,
password : <PASSWORD>,
cpassword : <PASSWORD>,
age :preval.age
} }
else if (name === "phone"){
return{
name:preval.name,
email: preval.email,
phone : value,
password : <PASSWORD>,
cpassword : <PASSWORD>,
age :preval.age} }
else if (name === "password"){
return{
name:preval.name,
email: preval.email,
phone : preval.phone,
password : <PASSWORD>,
cpassword : <PASSWORD>,
age :preval.age} }
else if (name === "cpassword"){
return{
name:preval.name,
email: preval.email,
phone : preval.phone,
password : <PASSWORD>,
cpassword : <PASSWORD>,
age :preval.age
} }
if(name === "age"){
return{
name: preval.name,
email: preval.email,
phone : preval.phone,
password : <PASSWORD>,
cpassword : <PASSWORD>assword,
age : value
} }
})
}
const onSubmits =(e) =>{
e.preventDefault();
alert("successful");
}
return(<>
<div className = "main_div">
<h1 className="h"> Registration Form </h1>
<p>{name.name},{name.email},{name.phone},{name.password},{name.cpassword}, {name.age}</p>
{/* <form action="/register" method="POST"> */}
<form action="" onSubmit= {onSubmits}>
<div className="form">
<h2> Welcome <span> YO</span></h2>
<input type="text" name="name" placeholder="Name" id ="name" onChange={InputEvent} value={name.name} />
<input type="text" name="email" placeholder="Email" id ="email" onChange={InputEvent} value={name.email} />
<input type="text" name="phone" placeholder="Phone" id ="phone" onChange={InputEvent} value={name.phone} />
<input type="text" name="password" placeholder="<PASSWORD>" id ="password" onChange={InputEvent} value={name.password} />
<input type="text" name="cpassword" placeholder="<PASSWORD>" id ="cpassword" onChange={InputEvent} value={name.cpassword} />
<input type="text" name="age" placeholder="Age" id ="age" onChange={InputEvent} value={name.age} />
<button type="submit" >Signup</button>
<button type="submit" >Login</button>
</div>
</form>
</div>
</>);
}
export default App;
// style={{ backgroundColor: bg}}
// onChange={InputEvent}
// autoComplete="off"<file_sep>import React from 'react';
import "../Components/Signup/contact.css";
function Contact() {
return (
<div class="container4">
<div class="col-sm-6">
<form class="row g-3">
<div class="col-md-6">
<label for="inputEmail4" class="form-label">Name</label>
<input type="email" class="form-control" id="inputEmail4" />
</div>
<div class="col-md-6">
<label for="inputEmail4" class="form-label">Email</label>
<input type="email" class="form-control" id="inputEmail4" />
</div>
<div class="col-md-6">
<label for="inputPassword4" class="form-label">Password</label>
<input type="<PASSWORD>" class="form-control" id="inputPassword4" />
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">Number</label>
<input type="text" class="form-control" id="inputCity" />
</div>
<div class="col-12">
<label for="inputAddress" class="form-label">Address</label>
<input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St" />
</div>
<div class="col-12">
<label for="inputAddress2" class="form-label">Message</label>
<input type="text" class="form-control" id="inputAddress2" placeholder="Message" />
</div>
<div class="col-md-6">
<label for="inputCity" class="form-label">City</label>
<input type="text" class="form-control" id="inputCity" />
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck" />
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Sign in</button>
</div>
</form>
</div>
</div>
)
}
export default Contact;
{/* <img src="https://source.unsplash.com/random" class="card-img-top" alt="..." /> */}
{/* <div class="card-body">
<h4 class="card-title">Card title</h4>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
<a href="#" class="btn btn-primary">Go somewhere</a> */}
<file_sep>import React from 'react';
import "./signup.css";
function Signup() {
return (
<>
<div className="container1">
<div className="row1">
<form action="/register" method="POST" />
<div className="form1">
<h1>Signup Form</h1>
<input type="text" name="name" className="form-control" placeholder="Name" /> <br/>
<input type="text" name="email" className="form-control" placeholder="Email" /> <br/>
<input type="text" name="phone" className="form-control" placeholder="Phone" /> <br/>
<input type="text" name="password" className="form-control" placeholder="<PASSWORD>" /> <br/>
<input type="text" name="cpassword" className="form-control" placeholder="<PASSWORD>" /> <br/>
<input type="text" name="age" className="form-control" placeholder="Age" /> <br/>
<button type="submit" className="btnRegister" value="Register">Register</button> <button className="login-btn">Login</button> <br/>
</div>
</div>
</div>
</>
)
}
export default Signup;
<file_sep>import React, { createContext, useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import C from './Comp/C';
import B from './Comp/B';
import A from './Comp/A';
// import A from './Comp/A';
// import B from './Comp/B';
// import C from './Comp/C';
const FName = createContext();
const LName = createContext();
function App() {
return (<>
<FName.Provider value={"Death"}>
<LName.Provider value={"DEasto"}>
<B/>
</LName.Provider>
</FName.Provider >
<A />
{/* <A />
<B />
<C /> */}
</>
)
}
export default App;
export {FName ,LName};
<file_sep>
import Button from 'react-bootstrap/Button';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
import "../Comp/nav.css";
function nav() {
return ( <>
<ReactBootStrap.Navbar bg="primary" variant="dark">
<ReactBootStrap.Navbar.Brand href="#home">
<img
src="https://wallpaperaccess.com/full/345330.jpg"
width="30"
height="30"
className="d"
alt-imgsrc="../img/logo.png"
/>
</ReactBootStrap.Navbar.Brand>
<ReactBootStrap.Nav className="mr-auto">
<ReactBootStrap.Nav.Link href="#home">Home</ReactBootStrap.Nav.Link>
<ReactBootStrap.Nav.Link href="#features">About</ReactBootStrap.Nav.Link>
<ReactBootStrap.Nav.Link href="#pricing">Services</ReactBootStrap.Nav.Link>
<ReactBootStrap.Nav.Link href="#features">login</ReactBootStrap.Nav.Link>
<ReactBootStrap.Nav.Link href="#pricing">Signup</ReactBootStrap.Nav.Link>
</ReactBootStrap.Nav>
<ReactBootStrap.Form inline>
<ReactBootStrap.FormControl type="text" placeholder="Search" className="mr-sm-2" />
<ReactBootStrap.Button variant="outline-light">Search</ReactBootStrap.Button>
</ReactBootStrap.Form>
</ReactBootStrap.Navbar>
</>
)
}
export default nav;
<file_sep>import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactBootStrap from "react-bootstrap";
import React ,{useState} from 'react';
import "../Comp/Slid.css";
function Slid() {
const [index, setIndex] = useState(0);
const handleSelect = (selectedIndex, e) => {
setIndex(selectedIndex);
};
const mystyle = {
color: "white",
// width: "80rem",
// height: "50rem",
padding: "2px",
paddingLeft:"5rem",
fontFamily: "Arial"}
return (
<ReactBootStrap.Carousel activeIndex={index} onSelect={handleSelect}>
<ReactBootStrap.Carousel.Item style={mystyle}>
<img
className="d-block"
src="https://wallpaperaccess.com/full/345330.jpg"
alt="First slide"
/>
</ReactBootStrap.Carousel.Item>
<ReactBootStrap.Carousel.Item style={mystyle}>
<img
className="d-block"
src="https://wallpaperaccess.com/full/345330.jpg"
alt="Second slide"
/>
</ReactBootStrap.Carousel.Item>
<ReactBootStrap.Carousel.Item style={mystyle}>
<img
className="d-block"
src="https://wallpaperaccess.com/full/345330.jpg"
alt="Third slide"
/>
{/* <ReactBootStrap.Carousel.Caption>
<h3>Third slide label</h3>
</ReactBootStrap.Carousel.Caption> */}
</ReactBootStrap.Carousel.Item>
</ReactBootStrap.Carousel>
);
}
export default Slid;
<file_sep>// import React from 'react';
// import {useParams, useLocation, useHistory} from "react-router-dom";
// // function User({match}) {
// // return (
// // <div>
// // <h1> User {match.params.name} Page </h1>
// // </div>
// // )}
// function User() {
// const {fname, lname} = useParams();
// const location = useLocation();
// console.log(location);
// const history = useHistory();
// console.log(history);
// const btnEvent =()=>{
// // alert('Yoshi');
// history.goBack();
// }
// const btnEvent1 =()=>{
// // alert('Yoshi');
// history.push("/about");
// // history.goForward();
// }
// return (
// <div>
// <h1> User {fname} {lname} Page </h1>
// <h1> My current location is {location.pathname} {location.hash}
// {location.key} {location.search} </h1>
// {location.pathname === `/user/anurag/chandra` ? (<button onClick= {btnEvent}> Anurag </button>)
// : <button onClick={btnEvent1}> Death </button> }
// </div>
// )}
// export default User;<file_sep>import React from 'react'
import {Link} from "react-router-dom";
function Menu() {
return (
<>
<Link to ="/" > About Us </Link>
</>
)
}
export default Menu;<file_sep>import React from 'react'
function Login() {
return (
<div className="container1">
<div className="row1">
<form action="/register" method="POST" />
<div className="form1">
<h1>Login Form</h1>
<input type="text" name="" class="form-control" placeholder="Email or Phone" /> <br/>
<input type="text" name="" class="form-control" placeholder="<PASSWORD>" /> <br/>
<button className="btn btn-dark btn-block">Login</button> <br/>
</div>
</div>
</div>
)
}
export default Login;
|
5f02ace119ad5b331e927b320ad6cd3cd26cd975
|
[
"JavaScript"
] | 18
|
JavaScript
|
anurag181298/tsmsite
|
0a650c592577894e129755d3ddcd763ff6607952
|
0bf3c8da59e65800c6882da7262812472dab6175
|
refs/heads/master
|
<file_sep>module.exports = function(grunt) {
//load plugins for grunt
[
'grunt-cafe-mocha',
'grunt-contrib-jshint',
'grunt-exec'
].forEach(function (task) {
grunt.loadNpmTasks(task);
});
//configure plugins
grunt.initConfig({
cafemocha: {
all: { src: 'qa/tests-*.js', options : {ul: 'tdd'} }
},
jshint: {
app: ['my-node-app/app.js', 'my-node-app/lib/*.js', 'lib/*.js'],
qa: ['Gruntfile.js', 'my-node-app/public/qa/*.js', 'public/qa/*.js']
},
exec: {
//linkchecker: { cmd: 'linkchecker http://localhost/3000'
}
//explore grunt.option plugin to paramaterize
});
//register tasks
grunt.registerTask('default', ['cafemocha', 'jshint']);
};
<file_sep>var tips = [
"Banana's aren't yellow.",
"Learn to use a text editor.",
"Sometimes lightning goes backward."
];
exports.getRandomTip = function () {
var randomIndex = Math.floor(Math.random() * tips.length);
return tips[randomIndex];
};
<file_sep># Experimenting with node
## How to run web app:
- clone repo and cd into it
- type 'npm install' from the terminal to install project dependencies
- cd to sandbox-node-app/site
- enter 'node app.js' to start the server
- in an internet browser enter localhost:3000
|
6f3eb085472bc3175147ad70315fc2f2219d34cd
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
mcpengelly/sandbox-node-app
|
2776fddbd06c364991a0c1c9d798a51a2db49f06
|
6001e9a3d48534251b718d94b52e37470fd39c8b
|
refs/heads/master
|
<file_sep>import { Injectable } from '@angular/core';
import { environment } from './../environments/environment';
import { io } from 'socket.io-client';
@Injectable({
providedIn: 'root'
})
export class ServerService {
socket = io(environment.SOCKET_ENDPOINT);;
constructor() { }
listen() {
this.socket.on('response', (data: string) => {
console.log(data);
});
}
public sendMessage(message: string = 'hello from the other side') {
this.socket.emit('message', message);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ServerService } from '../server.service';
@Component({
selector: 'app-opponent',
templateUrl: './opponent.component.html',
styleUrls: ['./opponent.component.css']
})
export class OpponentComponent implements OnInit {
opps: Array<string>;
constructor(private serverService: ServerService) { }
ngOnInit(): void {
this.opps = ['Opponent 1', 'Opponent 2', 'Opponent 3', 'Opponent 4'];
}
transmit(message) {
this.serverService.sendMessage(message);
}
}
|
1ffba7bf649f7d234891ae0412fcedc4592fb05a
|
[
"TypeScript"
] | 2
|
TypeScript
|
Konntroll/coup
|
f967aff0824248029fcf0a33d85d417639956e81
|
da7d80c473ad9a9692813109c59f27ae89cccfc9
|
refs/heads/master
|
<repo_name>litmus/fake_braintree<file_sep>/spec/spec_helper.rb
require 'spork'
Spork.prefork do
require 'rspec'
require 'fake_braintree'
require 'timecop'
require 'bourne'
def clear_braintree_log
Dir.mkdir('tmp') unless File.directory?('tmp')
File.new('tmp/braintree_log', 'w').close
end
Dir[File.join(File.dirname(__FILE__), "support/**/*.rb")].each {|f| require f}
clear_braintree_log
TEST_CC_NUMBER = %w(4111 1111 1111 1111).join
RSpec.configure do |config|
config.mock_with :mocha
config.include BraintreeHelpers
config.include CustomerHelpers
config.include SubscriptionHelpers
config.include FakeBraintree::Helpers
config.before do
FakeBraintree.clear!
FakeBraintree.verify_all_cards = false
end
end
end
Spork.each_run do
end
<file_sep>/spec/support/subscription_helpers.rb
module SubscriptionHelpers
def create_subscription(options = {})
Braintree::Subscription.create({ :payment_method_token => cc_token,
:plan_id => 'my_plan_id' }.merge(options))
end
end
<file_sep>/spec/fake_braintree/transaction_spec.rb
require 'spec_helper'
describe FakeBraintree::SinatraApp do
context "Braintree::Transaction.sale" do
it "successfully creates a transaction" do
result = Braintree::Transaction.sale(:payment_method_token => cc_token, :amount => 10.00)
result.should be_success
end
context "when all cards are declined" do
before { FakeBraintree.decline_all_cards! }
it "fails" do
result = Braintree::Transaction.sale(:payment_method_token => cc_token, :amount => 10.00)
result.should_not be_success
end
end
end
end
describe FakeBraintree::SinatraApp do
context "Braintree::Transaction.refund" do
it "successfully refunds a transaction" do
result = Braintree::Transaction.refund(create_id('foobar'), '1')
result.should be_success
end
end
end
describe FakeBraintree::SinatraApp do
context "Braintree::Transaction.void" do
it "successfully voids a transaction" do
sale = Braintree::Transaction.sale(:payment_method_token => cc_token, :amount => 10.00)
result = Braintree::Transaction.void(sale.transaction.id)
result.should be_success
result.transaction.status.should == Braintree::Transaction::Status::Voided
end
end
end
describe FakeBraintree::SinatraApp do
context "Braintree::Transaction.find" do
it "can find a created sale" do
id = create_transaction.id
result = Braintree::Transaction.find(id)
result.amount.should == amount
end
it "can find >1 transaction" do
Braintree::Transaction.find(create_transaction.id).should be
Braintree::Transaction.find(create_transaction.id).should be
end
it "raises an error when the transaction does not exist" do
expect { Braintree::Transaction.find('foobar') }.to raise_error(Braintree::NotFoundError)
end
def create_transaction
Braintree::Transaction.sale(:payment_method_token => cc_token, :amount => amount).transaction
end
let(:amount) { 10.00 }
end
end
|
012a0ec50b92c73a9c396e8e1a4a6fa4782d6cdd
|
[
"Ruby"
] | 3
|
Ruby
|
litmus/fake_braintree
|
df1660fdaf266c8be7b2d8c986f3801c547dc136
|
f34d55c6e2355d40803bdff59e4b3e81a1da576c
|
refs/heads/master
|
<file_sep>var express = require('express');
var router = express.Router();
var signupModel = require('../database/db').signupModel;
router.get('/', function(req, res, next) {
signupModel.find(function(error, doc) {
if (error) {
console.log("mongodb find error : " + error);
var data = {
"data": "there stand some wrong , so no data"
};
res.render('signup', { info: JSON.stringify(data) });
} else {
var data = {
"data": doc
};
console.log(data.data.length)
res.render('signup', { info: JSON.stringify(data) });
}
})
});
router.post('/', function(req, res, next) {
var query = {
name: req.body.slide_name,
telephone: req.body.slide_telephone,
depart: req.body.slide_depart,
center: req.body.slide_center,
part: req.body.slide_part
};
signupModel.findOne({ "telephone": query.telephone }, function(error, doc) {
if (error) {
console.log("mongodb findOne error : " + error);
}
if (doc) {
if (doc.center !== query.center) {
var signupEntity = new signupModel({
name: query.name,
telephone: query.telephone,
depart: query.depart,
center: query.center,
part: query.part
});
signupEntity.save(function(error, doc) {
if (error) {
console.log("mongodb save error : " + error);
} else {
console.log(doc);
}
})
}
} else {
var signupEntity = new signupModel({
name: query.name,
telephone: query.telephone,
depart: query.depart,
center: query.center,
part: query.part
});
signupEntity.save(function(error, doc) {
if (error) {
console.log("mongodb save error : " + error);
} else {
console.log(doc);
}
})
}
})
if (query.center == "技术研发中心") {
res.redirect('/scan');
} else {
res.redirect('/');
}
});
module.exports = router;<file_sep>var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://127.0.0.1:27017/rixin_hr');
db.connection.on('error', function(error) {
console.log("connect mongodb fail : " + error);
});
db.connection.on("open", function() {
console.log("connect to mongodb success");
});
var signupSchema = new mongoose.Schema({
name: { type: String },
telephone: { type: String },
depart: { type: String },
center: { type: String },
part: { type: String }
});
var signupModel = mongoose.model('signup', signupSchema);
exports.signupModel = signupModel;
<file_sep># hr-app-node
日新的移动端hr招新页面
这个招新页做的比较简单,毕竟要赶工
|
230787bf50ec17434ddaa9b94bce7d7f99040040
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
dida-1894/hr-rixin
|
9a7fb7148b33d7a41cafb36ac9a15100690ebfd9
|
fa4825e6102bbbf4f42d1fec6bae134c22407226
|
refs/heads/main
|
<file_sep>import axios from 'axios';
const GITHUB_API_URL = 'https://api.github.com';
const GITHUB_TOKEN = process.env.REACT_APP_GITHUB_TOKEN;
const request = axios.create({
baseURL: GITHUB_API_URL,
headers: {
'Content-Type': 'application/vnd.github.v3+json',
Authorization: `token ${GITHUB_TOKEN}`,
},
responseType: 'json',
});
export const getGithubUser = async (
githuUserName: string | undefined,
): Promise<void | any> => {
return request.get(`/users/${githuUserName}`).then((res: any) => res.data);
};
export const getGithubEvents = async (
githuUserName: string | undefined,
): Promise<void | any> => {
return request
.get(`/users/${githuUserName}/events`)
.then((res: any) => res.data);
};
export const getGithubRepos = async (
githuUserName: string | undefined,
): Promise<void | any> => {
return request
.get(`/users/${githuUserName}/repos`)
.then((res: any) => res.data);
};
<file_sep>module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
tsconfigRootDir: __dirname,
project: ['./tsconfig.eslint.json']
},
plugins: [
'@typescript-eslint',
'import'
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:react/recommended',
'plugin:import/errors',
'prettier'
],
settings: {
react: {
version: 'detect',
},
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx']
}
}
},
env: {
'node': true
},
rules: {
'sort-imports': 0,
'import/order': [2, { 'alphabetize': { 'order': 'asc' } }]
}
};
<file_sep>
# Name
github contribution stats
# What
two stats of github contributions.
1. stats used languages in your all repositories
2. stats commits per day in a week
# Usage
show your github stats after entering your github user name
# Build & Start
```bash
git clone <EMAIL>:dak2/github_contribution_stats
docker-compose up --build
```
# Author
Name : <NAME>
<file_sep>import { format, utcToZonedTime } from 'date-fns-tz';
import { timeZone, weekDays, today } from '../utils/constDate';
import { Events } from '../utils/propsType';
type groupedCommits = {
x: number;
y: number;
};
type groupedByDates = {
dayOfWeek: number;
commitDate: Date;
commitSize: number;
};
type commitSizeByDate = {
date: Date;
commitSize: number;
};
export const groupedCommits = (events: Events[]): groupedCommits[] => {
const commitSizes = commitSizeByDate(events);
const commitComparedDate = dateCompare(today, commitSizes);
return orderByAsc(grouping(commitComparedDate));
};
const commitSizeByDate = (events: Events[]): commitSizeByDate[] => {
return events.map((event) => {
return {
date: new Date(
format(
utcToZonedTime(event.created_at, timeZone),
'yyyy-MM-dd HH:mm:ss',
),
),
commitSize: event.payload.size,
};
});
};
const dateCompare = (
today: Date,
commitSizes: commitSizeByDate[],
): groupedByDates[] => {
const res: groupedByDates[] = [];
weekDays(today).map((element) => {
commitSizes.map((commit) => {
// 指定日付内のcommitかどうか確認
const date_compared =
element.dates.start <= commit.date && commit.date <= element.dates.end;
date_compared
? res.push({
dayOfWeek: commit.date.getDay(),
commitDate: commit.date,
commitSize: commit.commitSize,
})
: null;
});
});
return res;
};
const grouping = (commitComparedDate: groupedByDates[]): groupedCommits[] => {
return [0, 1, 2, 3, 4, 5, 6].map((week) => {
const list = commitComparedDate.filter(
(commit) => commit.dayOfWeek === week,
);
console.log('list', list);
const commitSize = list.reduce(
(prev, current) => prev + current.commitSize,
0,
);
return {
x: week,
y: commitSize,
};
});
};
const orderByAsc = (groupedCommits: groupedCommits[]): groupedCommits[] => {
const dayOfWeek = today.getDay();
// 今日を一番最後として並び替える
// https://stackoverflow.com/a/17892824
const orderedCommits = groupedCommits
.slice(dayOfWeek + 1)
.concat(groupedCommits.slice(0, dayOfWeek + 1));
return orderedCommits.map((commit, index) => {
return {
x: index + 1,
y: commit.y,
};
});
};
<file_sep>import { Repos } from '../utils/propsType';
type groupedLanguages = {
x: number;
y: number;
label: string;
};
export const groupedLanguages = (repos: Repos[]) => {
const existsLanguages = repos.filter((repo) => repo.language != null);
const res = orderdDesc(Object.entries(groupBy(existsLanguages, 'language')));
return convertToChartData(res);
};
const groupBy = (objectArray: any[], property: string) => {
return objectArray.reduce(function (acc, obj) {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
if (acc[key] != {}) {
acc[key].push(1);
acc[key] = [
acc[key].reduce((prev: number, current: number) => prev + current, 0),
];
}
return acc;
}, {});
};
const orderdDesc = (ary: any[]) => {
return ary.sort((a: any, b: any) => {
return b[1][0] - a[1][0];
});
};
const convertToChartData = (ary: any[]) => {
const res: any = [];
ary.forEach((elm, index) => {
return res.push({
x: index + 1,
y: elm[1][0],
label: `${elm[0]} : ${elm[1][0]}`,
});
});
return res;
};
<file_sep>import { add, startOfDay, endOfDay } from 'date-fns';
import { format, utcToZonedTime } from 'date-fns-tz';
type weekDays = {
dates: {
start: Date;
end: Date;
};
};
export const timeZone = 'Asia/Tokyo';
export const today = new Date();
export const weekDays = (today: Date): weekDays[] => {
return [...Array(7)].map((_, index) => {
const startDate = new Date(
format(
utcToZonedTime(startOfDay(add(today, { days: -index })), timeZone),
'yyyy-MM-dd HH:mm:ss',
),
);
const endDate = new Date(
format(
utcToZonedTime(endOfDay(add(today, { days: -index })), timeZone),
'yyyy-MM-dd HH:mm:ss',
),
);
return {
dates: {
start: startDate,
end: endDate,
},
};
});
};
export const weekDaysBarData = (): string => {
const dayOfWeek = new Date().getDay();
const weekList = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
return weekList
.slice(dayOfWeek + 1)
.concat(weekList.slice(0, dayOfWeek + 1))
.join();
};
<file_sep>export type Events = {
id: string;
type: string;
created_at: Date;
actor: Record<string, unknown>;
repo: Record<string, unknown>;
payload: Commits;
};
export type Commits = {
before: string;
commits: any[];
distinct_size: number;
head: string;
push_id: number;
ref: string;
size: number;
};
export type User = {
avatar_url: string;
login: string;
url: string;
};
export type Repos = {
name: string;
language: string;
fork: boolean;
};
|
1b9e8cfa18d1350acf16c54dc1d61adc68fc93c7
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 7
|
TypeScript
|
dak2/github_contribution_stats
|
8ca567c8e077463725a2c432a65a071028c7b5b2
|
39ef80f21425aaa06756bf94a4a24efb1db35f53
|
refs/heads/master
|
<file_sep># SimpleRestApiServer
## Getting Started
### Prerequisites
Docker
Make
git
### Installing
``git clone https://github.com/VanLePham/simpleRestApiServer.git``
``make docker_build``
``make docker_run``
If running locally, in your browser hit:
``http://localhost:8080/users``
## Deployment
Add additional notes about how to deploy this on a live system
<file_sep>package com.example.simpleRestApiServer.model;
import javax.validation.constraints.NotBlank;
public class User {
//Just for simple api for now
public User(@NotBlank String firstName, @NotBlank String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
@NotBlank
private String firstName;
@NotBlank
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
<file_sep>docker_build:
docker build -t simple:v1 ./
docker_run:
docker run -p 8080:8080 -t simple:v1
|
0e9b1516b197b67e244e3649986944e7e7bdd781
|
[
"Markdown",
"Java",
"Makefile"
] | 3
|
Markdown
|
VanLePham/simpleRestApiServer
|
9f9d81d7cf3dfd9ca5b3b99b64ea921cb9fb67b7
|
7820a23cbe12f3e170dc860d10c8ab521c73585f
|
refs/heads/master
|
<repo_name>MrZhousf/MaterialDesign<file_sep>/README.md
# MaterialDesign
Material Design:质感设计
### 相关截图


### 有问题反馈
在使用中有任何问题,欢迎反馈给我,可以用以下联系方式跟我交流
* QQ: 424427633
<file_sep>/app/src/main/java/com/materialdesign/util/SnackUtil.java
package com.materialdesign.util;
import android.content.Context;
import android.support.design.widget.Snackbar;
/**
* @author: zhousf
*/
public class SnackUtil {
static Snackbar snackbar;
public static void show(Context context){
// Snackbar.make(mContainer, "Hello SnackBar!", Snackbar.LENGTH_LONG)
// .setAction(context.getResources().getString(R.string.close), new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// // do something
// }
// }).show();
}
}
|
b6c11a195fa6d05ee5ce0146292489b532fa69f3
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
MrZhousf/MaterialDesign
|
759184c9cf2f1544446d68626cf6d57700264359
|
21e0c7f3ef039b4edca86a4c67f6f89651ea5407
|
refs/heads/master
|
<repo_name>Angelicogfa/algoritmo-genetico-maximizar-funcao<file_sep>/MaximizarFuncao/Main.cs
using AlgoritmoGenetico;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZedGraph;
namespace MaximizarFuncao
{
public partial class Main : Form
{
private Populacao populacao;
private AlgoritmoGen algoritmoGen;
private GraphPane panePopulacao;
private GraphPane paneMediaPopulacao;
private PointPairList curvaGrafico = new PointPairList();
private PointPairList populacaoGrafico = new PointPairList();
private PointPairList mediaPopulacao = new PointPairList();
public Main()
{
InitializeComponent();
panePopulacao = grafPopulacao.GraphPane;
panePopulacao.Title.Text = "População";
panePopulacao.XAxis.Title.Text = "Gerações";
panePopulacao.YAxis.Title.Text = "Indivíduos";
grafPopulacao.Refresh();
paneMediaPopulacao = grafMediaPopulacao.GraphPane;
paneMediaPopulacao.Title.Text = "Média da população";
paneMediaPopulacao.XAxis.Title.Text = "Gerações";
paneMediaPopulacao.YAxis.Title.Text = "Média";
grafMediaPopulacao.Refresh();
for (int i = 0; i < Constantes.TamanhoEixoX; i++)
curvaGrafico.Add(i, Constantes.FuncaoAptidao(i));
LineItem func = panePopulacao.AddCurve("Função", curvaGrafico, System.Drawing.Color.Red, SymbolType.None);
AtualizarGraficoPopulacao();
AtualizarGraficoMediaPopulacao();
}
private void AtualizarGraficoMediaPopulacao()
{
grafMediaPopulacao.AxisChange();
grafMediaPopulacao.Invalidate();
grafMediaPopulacao.Refresh();
}
private void AtualizarGraficoPopulacao()
{
grafPopulacao.AxisChange();
grafPopulacao.Invalidate();
grafPopulacao.Refresh();
}
private void btnPopulacao_Click(object sender, System.EventArgs e)
{
btnExecucao.Enabled = true;
populacao = new Populacao();
populacaoGrafico = new PointPairList();
for (int i = 0; i < Constantes.TamanhoPopulacao; i++)
{
populacaoGrafico.Add(populacao[i].Valor, populacao[i].Aptidao);
}
LineItem lineItem = panePopulacao.AddStick("Indivíduos", populacaoGrafico, Color.Blue);
AtualizarGraficoPopulacao();
}
private void btnExecucao_Click(object sender, System.EventArgs e)
{
btnExecucao.Enabled = btnPopulacao.Enabled = false;
algoritmoGen = new AlgoritmoGen((double)txtCrossover.Value, (double)txtMutacao.Value);
for (int i = 0; i < txtIteracao.Value; i++)
{
populacao = algoritmoGen.ExecutaAG(populacao);
mediaPopulacao.Add(i, populacao.Media);
grafPopulacao.GraphPane.CurveList.Clear();
grafPopulacao.GraphPane.GraphObjList.Clear();
grafMediaPopulacao.GraphPane.CurveList.Clear();
grafMediaPopulacao.GraphPane.GraphObjList.Clear();
populacaoGrafico = new PointPairList();
for (int j = 0; j < Constantes.TamanhoPopulacao; j++)
populacaoGrafico.Add(populacao[j].Valor, populacao[j].Aptidao);
LineItem media = paneMediaPopulacao.AddCurve("Média", mediaPopulacao, Color.Red, SymbolType.None);
LineItem func = panePopulacao.AddCurve("Função", curvaGrafico, Color.Red, SymbolType.None);
LineItem individuos = panePopulacao.AddStick("Indivíduos", populacaoGrafico, Color.Blue);
AtualizarGraficoPopulacao();
AtualizarGraficoMediaPopulacao();
}
populacao.OrdenarPopulacao();
StringBuilder pioresIndividuos = new StringBuilder();
for (int i = 0; i < 10; i++)
pioresIndividuos.AppendLine(populacao[i].ToString());
StringBuilder melhoresIndividuos = new StringBuilder();
for (int i =Constantes.TamanhoPopulacao -1; i > (Constantes.TamanhoPopulacao - 1) - 10; i--)
melhoresIndividuos.AppendLine(populacao[i].ToString());
txtMelhoresIndividuos.Text = melhoresIndividuos.ToString();
txtPioresIndividuos.Text = pioresIndividuos.ToString();
btnExecucao.Enabled = btnPopulacao.Enabled = true;
}
}
}
<file_sep>/AlgoritmoGenetico/PopulacaoExtension.cs
namespace AlgoritmoGenetico
{
public static class PopulacaoExtension
{
public static void OrdenarPopulacao(this Individuo[] individuos)
{
Individuo aux = null;
for (int i = 0; i < individuos.Length; i++)
for (int j = 0; j < individuos.Length; j++)
{
if (individuos[i].PercentualAptidao < individuos[j].PercentualAptidao)
{
aux = individuos[i];
individuos[i] = individuos[j];
individuos[j] = aux;
}
}
}
}
}
<file_sep>/AlgoritmoGenetico.Teste/IndividuoTeste.cs
using Xunit;
namespace AlgoritmoGenetico.Teste
{
public class IndividuoTeste
{
[Fact]
public void GerarIndividuo()
{
Individuo individuo = new Individuo();
Assert.NotNull(individuo);
Assert.NotEqual("", individuo.ToString());
}
[Fact]
public void GerarFilho()
{
Individuo pai = new Individuo();
var filho = pai.GerarFilho(null, 0, false);
for (int i = 0; i < pai.Genes.Length; i++)
Assert.Equal(pai.Genes[i], filho.Genes[i]);
}
[Fact]
public void GerarFilhoCrossover()
{
int crossoverIndex = 5;
Individuo pai = new Individuo();
Individuo mae = new Individuo();
var filhoPai = pai.GerarFilho(mae, crossoverIndex, true);
var filhoMae = mae.GerarFilho(pai, crossoverIndex, true);
Assert.NotEqual(pai.Genes, filhoPai.Genes);
Assert.NotEqual(mae.Genes, filhoPai.Genes);
Assert.NotEqual(pai.Genes, filhoMae.Genes);
Assert.NotEqual(mae.Genes, filhoMae.Genes);
for (int i = 0; i < filhoPai.Genes.Length; i++)
{
if(i < crossoverIndex)
Assert.Equal(pai.Genes[i], filhoPai.Genes[i]);
else
Assert.Equal(mae.Genes[i], filhoPai.Genes[i]);
}
for (int i = 0; i < filhoMae.Genes.Length; i++)
{
if (i < crossoverIndex)
Assert.Equal(mae.Genes[i], filhoMae.Genes[i]);
else
Assert.Equal(pai.Genes[i], filhoMae.Genes[i]);
}
}
}
}
<file_sep>/AlgoritmoGenetico/Constantes.cs
using System;
namespace AlgoritmoGenetico
{
public static class Constantes
{
public static int TamanhoCromossomo => 9;
public static int TamanhoPopulacao => 500;
public static int TamanhoEixoX { get { return (int)Math.Pow(2, TamanhoCromossomo); } }
public static Random random = new Random((int)DateTime.Now.Ticks);
public static double FuncaoAptidao(double valor)
{
return (100 + Math.Abs(valor * Math.Sin(Math.Sqrt(Math.Abs(valor)))));
}
}
}
<file_sep>/AlgoritmoGenetico/Individuo.cs
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace AlgoritmoGenetico
{
public class Individuo
{
private BitArray cromossomo;
public Individuo()
{
cromossomo = new BitArray(Constantes.TamanhoCromossomo);
for (int i = 0; i < cromossomo.Length; i++)
cromossomo[i] = Constantes.random.NextDouble() > 0.5f;
}
public bool this[int index]
{
get { return cromossomo[index]; }
set { AlterarGene(index, value); }
}
public bool[] Genes => cromossomo.Cast<bool>().ToArray();
public void AlterarGene(int index, bool gene) => cromossomo[index] = gene;
public double Aptidao { get; private set; }
public double PercentualAptidao { get; private set; }
public double[] FaixaRoleta { get; private set; } = { 0, 0 };
public void AlterarAptidao(double aptidao) => Aptidao = aptidao;
public void AlterarPercentualAptidao(double percentual) => PercentualAptidao = percentual;
public void MutarGene(int index)
{
if (index < cromossomo.Length)
this[index] = !this[index];
}
public Individuo GerarFilho(Individuo outro, int pontoCorte, bool crossover = true)
{
Individuo filho = new Individuo();
for (int i = 0; i < Genes.Length; i++)
filho[i] = this[i];
if (!crossover) return filho;
for (int i = pontoCorte; i < Genes.Length; i++)
filho[i] = outro[i];
return filho;
}
public void AlterarRoleta(double inicio, double fim)
{
FaixaRoleta[0] = inicio;
FaixaRoleta[1] = fim;
}
public int Valor
{
get
{
if (cromossomo.Length > 32)
throw new InvalidOperationException("O comprimento do do cromossomo não deve ultrapassar 32 bits");
int[] valor = new int[1];
cromossomo.CopyTo(valor, 0);
return valor[0];
}
}
public override string ToString()
{
StringBuilder texto = new StringBuilder();
texto.Append("Genes:");
foreach (var item in Genes.Reverse())
texto.AppendFormat("{0}", item ? 1 : 0);
texto.AppendFormat(" Valor:{0}", Valor);
texto.AppendFormat(" Aptidão:{0}", Aptidao);
texto.AppendFormat(" Percentual Aptidão:{0}", PercentualAptidao);
return texto.ToString();
}
}
}
<file_sep>/AlgoritmoGenetico/AlgoritmoGen.cs
using System.Collections.Generic;
namespace AlgoritmoGenetico
{
public class AlgoritmoGen
{
private readonly double taxaCrossover;
private readonly double taxaMutacao;
public AlgoritmoGen(double taxaCrossover, double taxaMutacao)
{
this.taxaCrossover = taxaCrossover;
this.taxaMutacao = taxaMutacao;
}
/// <summary>
/// Inicia o AG
/// Avaliação da população
/// Selecionar pais
/// realizar cruzamento
/// aplicar mutacao
/// apagar velhos membros
/// inserir novos
/// re-avaliar a população
/// </summary>
/// <param name="populacao"></param>
/// <returns></returns>
public Populacao ExecutaAG(Populacao populacao)
{
List<Individuo> buffer = new List<Individuo>();
for (int i = 0; i < Constantes.TamanhoPopulacao / 2; i++)
{
Individuo pai = GirarRoleta(populacao);
Individuo mae = GirarRoleta(populacao);
Individuo[] filhos = Crossover(pai, mae);
filhos[0] = Mutacao(filhos[0]);
filhos[1] = Mutacao(filhos[1]);
buffer.AddRange(filhos);
}
Populacao novaPopulacao = new Populacao(buffer);
return novaPopulacao;
}
private Individuo[] Crossover(Individuo pai, Individuo mae)
{
Individuo[] filhos = new Individuo[2];
int pontoCorte = Constantes.random.Next(0, Constantes.TamanhoCromossomo - 1);
bool crossover = Constantes.random.NextDouble() < taxaCrossover;
filhos[0] = pai.GerarFilho(mae, pontoCorte, crossover);
filhos[1] = mae.GerarFilho(pai, pontoCorte, crossover);
return filhos;
}
private Individuo Mutacao(Individuo individuo)
{
bool mutacao = Constantes.random.NextDouble() < taxaMutacao;
if (!mutacao) return individuo;
int pontoMutacao = Constantes.random.Next(0, Constantes.TamanhoCromossomo - 1);
individuo.MutarGene(pontoMutacao);
return individuo;
}
private Individuo GirarRoleta(Populacao populacao)
{
double numeroSorteado = Constantes.random.NextDouble() * 100;
foreach (var individuo in populacao.Individuos)
{
if (numeroSorteado >= individuo.FaixaRoleta[0] &&
numeroSorteado <= individuo.FaixaRoleta[1])
return individuo;
}
return null;
}
}
}
<file_sep>/AlgoritmoGenetico/Populacao.cs
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AlgoritmoGenetico
{
public class Populacao
{
public Populacao()
{
Individuos = new Individuo[Constantes.TamanhoPopulacao];
for (int i = 0; i < Individuos.Length; i++)
Individuos[i] = new Individuo();
AtualizarPopulacao();
}
internal Populacao(IEnumerable<Individuo> novosIndividuos)
{
Individuos = novosIndividuos.ToArray();
AtualizarPopulacao();
}
public Individuo[] Individuos { get; private set; }
public Individuo this[int index]
{
get { return Individuos[index]; }
set { Individuos[index] = value; }
}
public double Media
{
get
{
double media = 0;
foreach (var individuo in Individuos)
{
media += individuo.Aptidao;
}
return media / Individuos.Length;
}
}
private void CalcularApitidao()
{
foreach (var individuo in Individuos)
individuo.AlterarAptidao(Constantes.FuncaoAptidao(individuo.Valor));
}
private void CalcularPercentualApitidao()
{
double total = 0;
foreach (var individuo in Individuos)
total += individuo.Aptidao;
foreach (var individuo in Individuos)
individuo.AlterarPercentualAptidao(individuo.Aptidao * 100 / total);
}
private void CalularRangeRoleta()
{
OrdenarPopulacao();
double somatoria = 0;
for (int i = 0; i < Individuos.Length; i++)
{
if(i == 0)
{
somatoria += Individuos[i].PercentualAptidao;
Individuos[i].AlterarRoleta(0, somatoria);
}
else if(i == Individuos.Length - 1)
Individuos[i].AlterarRoleta(somatoria, 100);
else
Individuos[i].AlterarRoleta(somatoria, somatoria += Individuos[i].PercentualAptidao);
}
}
public void OrdenarPopulacao() => Individuos.OrdenarPopulacao();
public void AtualizarPopulacao()
{
CalcularApitidao();
CalcularPercentualApitidao();
CalularRangeRoleta();
}
public override string ToString()
{
StringBuilder texto = new StringBuilder();
foreach (var individuo in Individuos)
{
texto.AppendFormat("{0} | {1} \n",
individuo.ToString(),
individuo.FaixaRoleta[0].ToString() + ':' + individuo.FaixaRoleta[1].ToString());
}
return texto.ToString();
}
}
}
<file_sep>/AlgoritmoGenetico.Teste/AlgoritmoGenTeste.cs
using Xunit;
namespace AlgoritmoGenetico.Teste
{
public class AlgoritmoGenTeste
{
[Fact]
public void GerarPopulacao()
{
AlgoritmoGen algoritmoGen = new AlgoritmoGen(0.8, 0.01);
Populacao populacao = new Populacao();
Populacao novaPopulacao = algoritmoGen.ExecutaAG(populacao);
Assert.NotEqual(populacao, novaPopulacao);
Assert.NotEqual(populacao.ToString(), novaPopulacao.ToString());
}
}
}
|
ae3191a5c8d43b8fd2cb9ec75645c172a4546530
|
[
"C#"
] | 8
|
C#
|
Angelicogfa/algoritmo-genetico-maximizar-funcao
|
b614ad4d1d397e8a9af500709b209f7295cffdf4
|
c57e99377214f4431fb82e930b3257d76c5bd110
|
refs/heads/master
|
<file_sep># import os
# import sys
# import json
# target = sys.argv[1]
# with open(target, 'r') as reader:
# json_str = reader.read()
# json_lists = json.loads(json_str) # dict, read
# with open(target, 'w+') as writer:
# sorted_list = sorted(json_lists, key = lambda i: i["date"], reverse = True) # only work for list of dicts
# json_sorted_str = json.dumps(sorted_list, indent=4) # write
# writer.write(json_sorted_str)
# print(f"Sort {target} by dates.")
<file_sep>import scrapy
class RustNotificationSpider(scrapy.Spider):
name = 'rust_notification'
start_urls = ['https://this-week-in-rust.org/']
def parse(self, response):
for href in response.css("div.custom-xs-text-left > a::attr(href)").getall():
yield response.follow(href, self.parse_post_and_jobs)
def parse_post_and_jobs(self, response):
date = ".".join(response.url.split("/")[4:7]).replace(".","-")
post_titles = response.css("#news-blog-posts + ul > li > a::text").getall()
post_urls = response.css("#news-blog-posts + ul > li > a::attr(href)").getall()
posts = { "posts": len(post_titles), **dict(zip(post_titles, post_urls)) }
job_titles = response.css("#rust-jobs + ul > li > a::text").getall()
job_urls = response.css("#rust-jobs + ul > li > a::attr(href)").getall()
jobs = { "job": len(job_titles), **dict(zip(job_titles, job_urls)) }
# sorted(list, key = lambda i: i["Posts"], reverse = True)
yield {
"date": date,
**posts,
**jobs,
}
|
cd1717c43b727118c11c2c741b8012e8b2d53b49
|
[
"Python"
] | 2
|
Python
|
steadylearner/scrapy-examples
|
8f5ecbeb837653b5b20a1b0a1149cd078067c80f
|
adb79e3ed5bb39b81ed641b0f9d840951a8cfa9c
|
refs/heads/master
|
<repo_name>mattoffice/SilverlakeMock<file_sep>/src/settings.js
module.exports = {
port: 5000,
silverlake_service_port: 5001
}
|
6d0714a23a584e9e7fe55331182b37590f8af894
|
[
"JavaScript"
] | 1
|
JavaScript
|
mattoffice/SilverlakeMock
|
8a8a69079c9eaa3d8af1bcbbe571f443a761205e
|
f2fc9a82f06fc9328dcd8a159f7fb307005ee9f2
|
refs/heads/master
|
<file_sep>var knex = require('knex')({
client: 'pg',
connection: {
host: '127.0.0.1',
database: 'test_db',
user: 'development',
password: '<PASSWORD>'
}
});
const query = process.argv.slice(2)[0];
console.log("QUERY", query)
knex.select('*').from('famous_people').where({first_name : query}).asCallback((err, res) => {
if (err) return console.log( err);
console.log(
`Searching...
Found ${res.length} person(s) by the name '${query}': `)
for (i in res) {
console.log(
`- ${Number(i) + 1} ${res[i].first_name} ${res[i].last_name}, born '${res[i].birthdate.toLocaleString()}'`)
}
knex.destroy();
})
|
889cd70d8b27688441cfc662e666ffe636ef3675
|
[
"JavaScript"
] | 1
|
JavaScript
|
superskyy/Test_db
|
3304274df130eb6335424738db200c41c1283990
|
f8b1ce6e5232737fb80d185319806c6bfeefcef7
|
refs/heads/window
|
<file_sep>"""
这个程序直接将不同关节的三位坐标作为图像的RGB分量做2维卷积
将前后帧之差(time_diff)放入feature map中
acc稳定0.8
"""
import cv2
import h5py
import numpy as np
import scipy.stats as stat
import json
import tensorflow as tf
from tensorflow.keras.initializers import TruncatedNormal, Zeros
from tensorflow.keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPooling2D, Input, concatenate
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.regularizers import l1, l2
from tensorflow import image
from tensorflow.keras.utils import plot_model, to_categorical
from skimage import transform
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from util.dataset_processing import rand_perm_dataset, split_dataset
from util.preprocessing import (flip_img_horizontal, random_select_patch,
standardize_img)
from util.training import (te_batch_generator, tr_x_generator, tr_batch_generator,
val_batch_generator)
RESIZE_ISIZE = (60, 60, 3)
INPUT_ISIZE = (52, 52, 3)
def build_feat_extraction_module(input_shape):
input_layer = Input(shape=input_shape)
time_diff = input_layer[:, :, 1:]-input_layer[:, :, :-1]
time_diff = image.resize(
time_diff, list(input_shape[:-1]),
method=image.ResizeMethod.NEAREST_NEIGHBOR)
shared_layer = concatenate([
input_layer, time_diff], axis=-1)
# start_time = input_layer[:, :, 0]
# start_time = tf.tile(start_time[:, :, tf.newaxis],
# [1, 1, input_shape[0]-1, 1])
# start_time_diff = input_layer[:, :, 1:]-start_time
# start_time_diff = image.resize(
# time_diff, list(input_shape[:-1]),
# method=image.ResizeMethod.NEAREST_NEIGHBOR)
# shared_layer = concatenate([
# input_layer, time_diff, start_time_diff], axis=-1)
features_module = Model(input_layer, shared_layer)
features_module.summary()
return features_module
def build_classify_module(input_shape):
model = Sequential()
model.add(build_feat_extraction_module(input_shape))
model.add(Conv2D(32, (3, 3), activation='relu', strides=1, padding='same'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
model.add(Conv2D(32, (3, 3), activation='relu', strides=1, padding='same'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Conv2D(64, (3, 3), activation='relu', strides=1, padding='same'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
model.add(Conv2D(64, (3, 3), activation='relu', strides=1, padding='same'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(256, activation='relu', kernel_regularizer=l2(1.e-2)))
model.add(Dense(20, activation='softmax', kernel_regularizer=l2(1.e-2)))
# decay=1e-6, lr=0.00002
sgd = SGD(lr=0.01, decay=1e-4, momentum=0.9, nesterov=True)
# 论文中写的loss和这里不一样
# 试试categorical_crossentropy,mean_squared_error
model.compile(loss='categorical_crossentropy',
optimizer=sgd, metrics=['accuracy'])
return model
def training_pipline(features, subject_labels, action_labels, tr_subjects, te_subjects):
action_labels = to_categorical(action_labels - 1, 20)
i = 1
model = build_classify_module(INPUT_ISIZE)
model.summary()
tr_features, tr_labels, te_features, te_labels = split_dataset(
features, action_labels, subject_labels, tr_subjects[i, :], te_subjects[i, :])
tr_features, tr_labels = rand_perm_dataset(tr_features, tr_labels)
n_actions = np.unique(action_labels, axis=0).shape[0]
n_tr_samples = tr_labels.shape[0]
n_te_samples = te_labels.shape[0]
'''-----------------------个人复现版------------------------'''
epochs = 1
# 7 orig samples is used and each orig sample gen 5 patches
n_orig_samples_per_step, n_patches = 7, 5
batch_size = n_orig_samples_per_step * n_patches
tr_gen = tr_batch_generator(tr_features, tr_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_tr_samples,
n_orig_samples_per_step)
val_gen = val_batch_generator(te_features, te_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_te_samples,
n_orig_samples_per_step)
model.fit_generator(tr_gen, steps_per_epoch=n_tr_samples,
epochs=epochs, validation_data=val_gen,
validation_steps=300)
te_gen = te_batch_generator(te_features, te_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_te_samples,
n_orig_samples_per_step)
pred_list = model.predict_generator(generator=te_gen,
steps=n_te_samples)
pred_list = np.array(pred_list)
pred_list = np.reshape(pred_list, newshape=(
n_te_samples, 2*(n_patches), -1))
preds = np.argmax(pred_list, axis=2) + 1 # (number, 2*n_group)
te_labels = np.argmax(te_labels, axis=1)+1
print(te_labels)
# (amount_testset, 1) numpy array
pred_result = np.squeeze(stat.mode(preds, axis=1)[0])
print(pred_result)
print(np.sum(te_labels == pred_result)/te_labels.size)
return model, te_features, te_labels
def additional_tr_pipline(model, te_features, te_labels):
n_te_samples = te_labels.shape[0]
te_labels = to_categorical(te_labels - 1, 20)
epochs, n_orig_samples_per_step = 1, 7
n_actions = np.unique(action_labels, axis=0).shape[0]
tr_gen = tr_batch_generator(te_features, te_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_te_samples,
n_orig_samples_per_step)
model.fit_generator(tr_gen, steps_per_epoch=n_te_samples,
epochs=epochs)
return model
def classification_pipline(model, samples):
n_actions = 20
if np.ndim(samples) == 2:
samples = samples[np.newaxis, :, :]
labels = to_categorical(0, n_actions)
labels = labels[np.newaxis, :]
n_samples = 1
else:
n_samples = samples.shape[0]
labels = to_categorical(np.zeros(n_samples), n_actions)
n_orig_samples_per_step = 7
te_gen = te_batch_generator(samples, labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_samples,
n_orig_samples_per_step)
pred_list = model.predict_generator(generator=te_gen,
steps=n_samples)
if np.ndim(pred_list) == 2:
pred_list = pred_list[np.newaxis, :, :]
preds = np.argmax(pred_list, axis=2) + 1
pred_result = np.squeeze(stat.mode(preds, axis=1)[0])
return pred_result
if __name__ == "__main__":
# 读取特征
f = h5py.File(
'data/MSRAction3D/features.mat', 'r')
features = np.array([f[element]
for element in np.squeeze(f['features'][:])])
# 读取标签
f = h5py.File(
'data/MSRAction3D/labels.mat', 'r')
subject_labels = f['subject_labels'][:, 0]
action_labels = f['action_labels'][:, 0]
# 读取数据集划分方案
f = json.load(open(
'data/MSRAction3D/tr_te_splits.json', 'r'))
tr_subjects = np.array(f['tr_subjects'])
te_subjects = np.array(f['te_subjects'])
n_tr_te_splits = tr_subjects.shape[0]
model, te_features, te_labels = training_pipline(features, subject_labels,
action_labels, tr_subjects, te_subjects)
model = additional_tr_pipline(model, te_features, te_labels)
print(classification_pipline(model, te_features[6]))
model.save('model/multiple_mapping.h5')
<file_sep>import json
import os
import random
import sys
import h5py
import matplotlib
import mpl_toolkits.mplot3d.axes3d as p3
import numpy as np
from keras.models import load_model
from matplotlib.backends.backend_qt5agg import \
FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from numpy import arange, pi, sin
from PyQt5 import QtCore
from PyQt5.QtCore import (QAbstractListModel, QModelIndex, QSize,
QStringListModel, Qt)
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QAction, QApplication, QFileDialog, QGridLayout,
QHBoxLayout, QLabel, QListView, QMainWindow,
QMenu, QMessageBox, QSizePolicy, QWidget)
from rgb_mapping import classification_pipline
matplotlib.use("Qt5Agg")
class Canvas(FigureCanvas):
"""这是一个窗口部件,即QWidget(当然也是FigureCanvasAgg)"""
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = p3.Axes3D(fig, azim=-90, elev=10)
self.compute_initial_figure()
#
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def compute_initial_figure(self):
pass
class DynamicCanvas(Canvas):
"""动态画布:每秒自动更新"""
def __init__(self, *args, **kwargs):
Canvas.__init__(self, *args, **kwargs)
timer = QtCore.QTimer(self)
timer.timeout.connect(self.update_figure)
timer.start(100)
def compute_initial_figure(self):
self.points = self.axes.scatter([], [], [])
self.fcounter = 0
self.axes.set_xlim3d([1, 3])
self.axes.set_xlabel('X')
self.axes.set_ylim3d([1, 3])
self.axes.set_ylabel('Z')
self.axes.set_zlim3d([1, 3])
self.axes.set_zlabel('Y')
self.lc = Line3DCollection(segments=[])
self.axes.add_collection3d(self.lc)
f = json.load(open('data/MSRAction3D/body_model.json', 'r'))
self.bones = np.array(f['bones']) - 1
self.video = None
def update_figure(self):
if self.video is None:
return
if self.fcounter > self.video.shape[0]:
self.fcounter = self.video.shape[0]-1
frame = self.video[self.fcounter]+2
self.points._offsets3d = (frame[:, 0], frame[:, 1], frame[:, 2])
lines = [np.array([frame[self.bones[i, 0]], frame[self.bones[i, 1]]])
for i in range(self.bones.shape[0])]
self.lc.set_segments(lines)
self.fcounter += 1
self.draw()
def set_video(self, video):
self.video = video
self.fcounter = 0
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setWindowTitle("skeleton display")
# top-level menu
file_menu = QMenu('&File', self)
help_menu = QMenu('&Help', self)
# list view
listModel_1 = QStringListModel() # models list
listModel_2 = QStringListModel() # features list
listView_1 = QListView()
listView_1.setModel(listModel_1)
listView_2 = QListView()
listView_2.setModel(listModel_2)
listView_2.clicked.connect(self.selectFeature)
# menu action
file_menu.addAction(
'&Import Features', lambda: self.importFeatures(listModel_2), QtCore.Qt.CTRL + QtCore.Qt.Key_F)
file_menu.addAction(
'&Import Labels', lambda: self.importLabels(listModel_2), QtCore.Qt.CTRL + QtCore.Qt.Key_L)
file_menu.addAction(
'&Import Models', lambda: self.importModels(listModel_1), QtCore.Qt.CTRL + QtCore.Qt.Key_M)
file_menu.addAction('&Quit', self.quit,
QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
help_menu.addAction('&About', self.about)
# add menu
self.menuBar().addMenu(file_menu)
self.menuBar().addSeparator()
self.menuBar().addMenu(help_menu)
# add labels
label_1 = QLabel(self)
label_1.setText("Samples")
label_1.setAutoFillBackground(True)
label_1.setAlignment(Qt.AlignLeft)
label_2 = QLabel(self)
label_2.setText("Models")
label_2.setAutoFillBackground(True)
label_2.setAlignment(Qt.AlignLeft)
label_3 = QLabel(self)
label_3.setText("Frames")
label_3.setAutoFillBackground(True)
label_3.setAlignment(Qt.AlignLeft)
# window
self.main_widget = QWidget(self)
# canvas
self.canvas = DynamicCanvas(
self.main_widget, width=5, height=4, dpi=100)
layout = QGridLayout(self.main_widget)
layout.addWidget(label_2, 0, 0)
layout.addWidget(listView_1, 1, 0)
layout.addWidget(label_1, 0, 1)
layout.addWidget(listView_2, 1, 1)
layout.addWidget(label_3, 0, 2)
layout.addWidget(self.canvas, 1, 2)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
self.statusBar().showMessage("skeleton display program")
self.initVariables()
def initVariables(self):
self.models = dict()
def importFeatures(self, listModel):
fname = QFileDialog.getOpenFileName(
self, 'open feature file', 'data/MSRAction3D')
if fname[0] is not None:
f = h5py.File(fname[0], 'r')
self.features = np.array([f[element]
for element in np.squeeze(f['features'][:])])
n_features = self.features.shape[0]
idx = np.arange(n_features).astype(str)
listModel.setStringList(idx)
def importLabels(self, listModel):
fname = QFileDialog.getOpenFileName(
self, 'open label file', 'data/MSRAction3D')
if fname[0] is not None:
f = h5py.File(fname[0], 'r')
features = np.array([f[element]
for element in np.squeeze(f['features'][:])])
n_features = features.shape[0]
idx = np.arange(n_features).astype(str)
listModel.setStringList(idx)
def importModels(self, listModel):
fpath = QFileDialog.getOpenFileName(self, 'open model file', '/')
for fp in fpath[:-1]:
if fp is not None:
model = load_model(fp)
mname = os.path.splitext(os.path.basename(fp))[0]
self.models[mname] = model
n_rows = listModel.rowCount()
if listModel.insertRow(n_rows):
i = listModel.index(n_rows)
listModel.setData(i, mname)
def selectFeature(self, modelIndex):
self.canvas.set_video(self.features[modelIndex.row()])
def quit(self):
self.close()
def closeEvent(self, ce):
self.quit()
def about(self):
QMessageBox.about(self, "About",
"""embedding_in_qt5.py example
Copyright 2015 BoxControL
This program is a simple example of a Qt5 application embedding matplotlib
canvases. It is base on example from matplolib documentation, and initially was
developed from <NAME> and <NAME>.
http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html
It may be used and modified with no restriction; raw copies as well as
modified versions may be distributed without limitation.
"""
)
if __name__ == '__main__':
app = QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
# sys.exit(qApp.exec_())
app.exec_()
<file_sep>import os
import sys
import numpy as np
import json
import hdf5storage
def parse_single_file(filename):
f = open(file, 'r')
lines = f.read().splitlines()
elements = np.float64([each_line.split(' ') for each_line in lines])
n_frames = elements.size//(4*20)
video = np.array([elements[20*f:20*(f+1)] for f in range(n_frames)])
return video[:, :, :3]
def correct_coord(mat):
temp = mat[:, :, 1].copy()
mat[:, :, 1] = mat[:, :, 2]
mat[:, :, 2] = temp
return mat
def center_hip_loc(mat, body_model):
hci = body_model['hip_center_index']-1
hip_loc = mat[:, hci, :]
hip_loc = np.repeat(hip_loc[:, np.newaxis, :], 20, axis=1)
mat -= hip_loc
return mat
def unify_bone_len(mat, body_model):
'''每根骨头缩放到统一的长度'''
n_frames, n_actions = mat.shape[:2]
bone_lengths = body_model['bone_lengths']
# b1_joints = body_model['primary_pairs'][:, :2]
primary_pairs = np.array(body_model['primary_pairs'])
j_pairs = primary_pairs[:, 2:] - 1
for t in range(n_frames):
for k in range(len(bone_lengths)):
unit = mat[t, j_pairs[k, 1]]-mat[t, j_pairs[k, 0]]
unit /= np.linalg.norm(unit)
mat[t, j_pairs[k, 1]] = bone_lengths[k] * \
unit+mat[t, j_pairs[k, 0]]
return mat
def valid_normlise(vec, epsilon):
norm = np.linalg.norm(vec)
vec = vec.astype(np.float32)
if norm <= epsilon:
vec = np.zeros_like(vec)
else:
vec /= norm
return vec
def vrrotvec(a, b):
epsilon = 1e-12
a = valid_normlise(a, epsilon)
b = valid_normlise(b, epsilon)
ax = valid_normlise(np.cross(a, b), epsilon)
angle = np.arccos(min([np.dot(a, b), 1]))
if not np.any(ax):
absa = np.abs(a)
mind = np.argmin(absa)
c = np.zeros(3)
c[mind] = 1
ax = valid_normlise(np.cross(a, c), epsilon)
return np.append(ax, angle)
def vrrotvec2mat(r):
epsilon, ax, angle = 1e-12, r[:3], r[-1]
s, c = np.sin(angle), np.cos(angle)
t = 1-c
n = valid_normlise(ax, epsilon)
x, y, z = n[0], n[1], n[2]
return np.array([
[t*x*x + c, t*x*y - s*z, t*x*z + s*y],
[t*x*y + s*z, t*y*y + c, t*y*z - s*x],
[t*x*z - s*y, t*y*z + s*x, t*z*z + c]
])
def compute_relative_angles(mat, body_model):
n_frames = mat.shape[0]
primary_pairs = np.array(body_model['primary_pairs']) - 1
bone1_joints = primary_pairs[:, :2]
bone2_joints = primary_pairs[:, 2:]
assert mat.shape[2] == 3, 'skeletons are expected to be 3 dimensional'
n_angles = bone1_joints.shape[0]
rot_mats = np.empty((n_frames, n_angles), dtype=object)
for j in range(n_frames):
for i in range(n_angles):
bone1_global = None
if bone1_joints[i, 1] != -1:
bone1_global = mat[j, bone1_joints[i, 1]] - \
mat[j, bone1_joints[i, 0]]
else:
bone1_global = np.array([1, 0, 0])-mat[j, bone1_joints[i, 0]]
bone2_global = mat[j, bone2_joints[i, 1]] - \
mat[j, bone2_joints[i, 0]]
if np.all(bone1_global == np.zeros(3)) or np.all(bone2_global == np.zeros(3)):
rot_mats[j, i] = None
else:
R = vrrotvec2mat(vrrotvec(bone1_global, np.array([1, 0, 0])))
rot_mats[j, i] = vrrotvec2mat(
vrrotvec(np.matmul(R, bone1_global), np.matmul(R, bone2_global)))
return rot_mats
def reconstruct_locations_per_frame(R, bone1_joints, bone2_joints, bone_lengths):
n_angles = R.shape[0]
n_joints = n_angles + 1
joint_locations = np.zeros((n_joints, 3))
joint_locations[bone1_joints[0, 0], :] = [0, 0, 0]
joint_locations[bone2_joints[0, 1], :] = bone_lengths[0] * \
np.matmul(R[0], np.array([1, 0, 0]))
for k in range(1, n_angles):
bone1_global = joint_locations[bone1_joints[k, 1]] - \
joint_locations[bone1_joints[k, 0]]
rmat = vrrotvec2mat(vrrotvec(np.array([1, 0, 0]), bone1_global))
bone2_global = np.matmul(np.matmul(rmat, R[k]), np.array([1, 0, 0]))
joint_locations[bone2_joints[k, 1], :] = bone_lengths[k] * \
bone2_global + joint_locations[bone2_joints[k, 0], :]
return joint_locations
def reconstruct_locations(R, body_model):
bone_lengths = body_model['bone_lengths']
primary_pairs = np.array(body_model['primary_pairs']) - 1
bone1_joints = primary_pairs[:, :2]
bone2_joints = primary_pairs[:, 2:]
n_frames, n_angles = R.shape[:2]
normalized_locations = np.empty(
(n_frames, n_angles + 1, 3), dtype=np.float32)
frame_validity = np.ones(n_frames)
for j in range(n_frames):
reconstruct = True
for i in range(body_model['n_primary_angles']):
if R[j, i] is None:
reconstruct = False
if reconstruct:
normalized_locations[j] = reconstruct_locations_per_frame(
R[j], bone1_joints, bone2_joints, bone_lengths)
else:
frame_validity[j] = 0
frame_validity = frame_validity == 1
normalized_locations = normalized_locations[frame_validity]
# time_stamps = np.arange(n_frames[frame_validity])
# time_stamps += 1
return normalized_locations
if __name__ == "__main__":
n_actions = 20
n_subjects = 10
n_instances = 3
dataset_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(dataset_dir)
uniform_skeletal_data = np.empty(
(n_actions, n_subjects, n_instances), dtype=object)
original_skeletal_data = uniform_skeletal_data.copy()
skeletal_data_validity = np.zeros(
(n_actions, n_subjects, n_instances), dtype=np.int32)
raw_dataset_dir = 'MSRAction3DSkeletonReal3D'
body_model = json.load(open('body_model.json', 'r'))
for a in range(n_actions):
for s in range(n_subjects):
for e in range(n_instances):
file = raw_dataset_dir + \
'/a%02i_s%02i_e%02i_skeleton3D.txt' % (a+1, s+1, e+1)
if os.path.exists(file):
skeletal_data_validity[a, s, e] = 1
joint_locations = parse_single_file(file)
joint_locations = correct_coord(joint_locations)
joint_locations = center_hip_loc(
joint_locations, body_model)
original_skeletal_data[a, s, e] = joint_locations
uniform_skeletal_data[a, s, e] = unify_bone_len(
joint_locations, body_model)
hdf5storage.savemat('uniform_skeletal_data', {
u'skeletal_data': uniform_skeletal_data,
u'skeletal_data_validity': skeletal_data_validity
})
hdf5storage.savemat('original_skeletal_data', {
u'skeletal_data': original_skeletal_data,
u'skeletal_data_validity': skeletal_data_validity
})
<file_sep>import numpy as np
from tensorflow.keras.utils import to_categorical
from skimage import transform
from .preprocessing import (corner_select_patch,
flip_img_horizontal,
map_skeletal_img,
random_select_patch,
compute_relative_loaction,
compute_cross_angle,
compute_dot_angle,
standardize_img)
def __init_samples_ret__(input_isize, n_actions):
'''clear samples list for return
'''
ret_x = np.empty(
shape=(0, input_isize[0], input_isize[1], 3),
dtype=np.float32)
ret_y = np.empty(shape=(0, n_actions), dtype=np.float32)
return ret_x, ret_y
def __init_features_ret__(input_isize):
'''clear features list for return
'''
ret_x = np.empty(
shape=(0, input_isize[0], input_isize[1], input_isize[2]),
dtype=np.float32)
return ret_x
def __init_features_list__(input_isize):
assert type(input_isize) == list
return [__init_features_ret__(isize) for isize in input_isize]
def tr_batch_generator(tr_features, tr_labels,
resize_isize, input_isize,
n_actions, n_tr_samples,
n_orig_samples_per_step, n_patches=5):
'''feature generator designed by me.
:n_orig_samples_per_step: how many samples in raw data is used for each iteration
:n_patches: how many patches is genarated by each original sample
'''
while True:
ret_x, ret_y = __init_samples_ret__(input_isize, n_actions)
for s in range(n_tr_samples):
if s != 0 and s % n_orig_samples_per_step == 0:
# if n_orig_samples_per_step is reached
yield ret_x, ret_y
ret_x, ret_y = __init_samples_ret__(input_isize, n_actions)
rgb_img = map_skeletal_img(tr_features[s], resize_isize)
rgb_img = flip_img_horizontal(rgb_img, flip_prob=0.6)
# randomly flip the image horizontally with the probability of filp_prob
patches = random_select_patch(
rgb_img, input_isize, n_patches) # random select patches
label = tr_labels[s]
label = label[np.newaxis, :]
labels = np.tile(label, reps=[n_patches, 1])
ret_x = np.concatenate((ret_x, patches), axis=0)
ret_y = np.concatenate((ret_y, labels), axis=0)
if s == n_tr_samples - 1:
# last step
yield ret_x, ret_y
def tr_x_generator(tr_features, tr_labels,
resize_isize, input_isize,
n_actions, n_tr_samples,
batch_size=35, n_group=7):
'''reference program code, some samples cannot be used. [deprecated]
'''
anchor = 0
while True:
ret_x = np.empty(
shape=(0, input_isize[0], input_isize[1], 3), dtype=np.float32)
ret_y = np.empty(shape=(0, n_actions), dtype=np.float32)
if anchor > n_tr_samples-batch_size:
anchor = 0
continue
# here batch_size has to be the times of n_group
n_samples_in_group = batch_size // n_group
for offset in range(n_group):
current = anchor + offset
# rgb with shape (60, 60, 3)
rgb_img = map_skeletal_img(tr_features[current], resize_isize)
rgb_img = flip_img_horizontal(rgb_img, flip_prob=0.6)
# randomly flip the image horizontally with the probability of filp_prob
patches = random_select_patch(
rgb_img, input_isize, n_samples_in_group) # random select patches
label = tr_labels[current]
label = label[np.newaxis, :]
labels = np.tile(label, reps=[n_samples_in_group, 1])
ret_x = np.concatenate((ret_x, patches), axis=0)
ret_y = np.concatenate((ret_y, labels), axis=0)
anchor += n_group
yield (ret_x, ret_y)
def val_batch_generator(te_features, te_labels,
resize_isize, input_isize,
n_actions, n_te_samples,
n_orig_samples_per_step, n_patches=5):
'''
here we trick and use test set as validation set since the train set is too small in cross-view exp
:return:
'''
validate_max_size = n_te_samples
batch_size = n_patches * n_orig_samples_per_step
while True:
ret_x = np.zeros(shape=(2*n_patches, input_isize[0],
input_isize[1], 3), dtype=np.float32)
ret_y = np.zeros(
shape=(2*n_patches, n_actions), dtype=np.float32)
# random_select = random.sample(range(validate_max_size), 1)[0]
random_select = np.random.randint(validate_max_size)
# rgb with shape (60, 60, 3)
rgb_img = map_skeletal_img(te_features[random_select], resize_isize)
clips = corner_select_patch(rgb_img, input_isize)
flip_clips = corner_select_patch(
flip_img_horizontal(rgb_img, flip_prob=1.00),
input_isize)
ret_x[0:n_patches] = clips
ret_x[n_patches:] = flip_clips
label = te_labels[random_select]
label = label[np.newaxis, :]
labels = np.tile(label, reps=[2*n_patches, 1])
ret_y = labels
yield (ret_x, ret_y)
def te_batch_generator(te_features, te_labels,
resize_isize, input_isize,
n_actions, n_te_samples,
n_orig_samples_per_step, n_patches=5):
'''
select five patches from the four corner and center and their horizontal flip to evaluate. Using the voting result
as the final result
:return: (ret_x, ret_y) with the shape ret_x ~ (10, weight, height, 3), (10, num_actions)
'''
anchor = 0
batch_size = n_orig_samples_per_step*n_patches
while True:
ret_x = np.zeros(shape=(2*n_patches, input_isize[0],
input_isize[1], 3), dtype=np.float32)
ret_y = np.zeros(
shape=(2*n_patches, n_actions), dtype=np.float32)
if anchor > n_te_samples-1:
print('Test traversal has been done !')
break
# rgb with shape (60, 60, 3)
rgb_img = map_skeletal_img(te_features[anchor], resize_isize)
clips = corner_select_patch(rgb_img, input_isize)
flip_clips = corner_select_patch(
flip_img_horizontal(rgb_img, flip_prob=1.00), input_isize)
# flip_clips = clips
ret_x[0:n_patches] = clips
ret_x[n_patches:] = flip_clips
label = te_labels[anchor]
label = label[np.newaxis, :]
labels = np.tile(label, reps=[2*n_patches, 1])
ret_y[:] = labels
anchor += 1
# print(anchor)
yield (ret_x, ret_y)
def empty_batch_migenerator(input_isize, n_actions,
batch_size=35):
while True:
ret_y = to_categorical(0, n_actions)
ret_y = ret_y[np.newaxis, :]
ret_y = np.tile(ret_y, reps=[batch_size, 1])
ret_x = [None, None, None]
ret_x[0] = np.empty((batch_size, input_isize[0][0], input_isize[0][1], input_isize[0][2]),
dtype=np.float32)
ret_x[1] = np.empty((batch_size, input_isize[1][0], input_isize[1][1], input_isize[1][2]),
dtype=np.float32)
ret_x[2] = np.empty((batch_size, input_isize[2][0], input_isize[2][1], input_isize[2][2]),
dtype=np.float32)
yield ret_x, ret_y
def tr_batch_migenerator(tr_features, tr_labels,
resize_isize, input_isize,
n_actions, n_tr_samples,
n_orig_samples_per_step, n_patches=5):
while True:
_, ret_y = __init_samples_ret__(input_isize[0], n_actions)
ret_x = __init_features_list__(input_isize)
for s in range(n_tr_samples):
if s != 0 and s % n_orig_samples_per_step == 0:
# if n_orig_samples_per_step is reached
yield ret_x, ret_y # TODO: 输入还有很多
_, ret_y = __init_samples_ret__(input_isize[0], n_actions)
ret_x = __init_features_list__(input_isize) # TODO: 输入形状
abs_pos_map = map_skeletal_img(tr_features[s], resize_isize[0])
abs_pos_map = flip_img_horizontal(abs_pos_map, flip_prob=0.6)
# randomly flip the image horizontally with the probability of filp_prob
patches = random_select_patch(
abs_pos_map, input_isize[0], n_patches) # random select patches
label = tr_labels[np.newaxis, s]
labels = np.tile(label, reps=[n_patches, 1])
ret_x[0] = np.concatenate((ret_x[0], patches), axis=0)
ret_y = np.concatenate((ret_y, labels), axis=0)
lines = np.array([[20, 3], [3, 1], [3, 4], [3, 2], [1, 8], # for select ll angle
[8, 10], [10, 12], [4, 7], [7, 5], [5, 14],
[14, 16], [16, 18], [7, 6], [6, 15], [15, 17],
[17, 19], [2, 9], [9, 11], [11, 13], [20, 12],
[12, 18], [18, 19], [19, 13], [13, 20], [12, 13],
[13, 18], [18, 20], [20, 19], [19, 12], [13, 9],
[12, 8], [20, 4], [18, 14], [19, 15]])
lines = np.concatenate((lines, lines[:, ::-1]), axis=0)
lines -= 1
rel_loc = compute_relative_loaction(tr_features[s], lines)
cross_ang = compute_cross_angle(tr_features[s], rel_loc, lines)
dot_ang = compute_dot_angle(rel_loc, lines) # TODO: 输入形状
cross_ang = np.swapaxes(cross_ang, 0, 1)
dot_ang = np.swapaxes(dot_ang, 0, 1)
cross_ang = np.uint8(standardize_img(cross_ang))
dot_ang = np.uint8(standardize_img(dot_ang))
cross_ang = transform.resize(cross_ang, resize_isize[1])
dot_ang = transform.resize(dot_ang, resize_isize[2])
cross_ang = flip_img_horizontal(cross_ang, flip_prob=0.6)
dot_ang = flip_img_horizontal(dot_ang, flip_prob=0.6)
patches = random_select_patch(cross_ang, input_isize[1])
ret_x[1] = np.concatenate((ret_x[1], patches), axis=0)
patches = random_select_patch(dot_ang, input_isize[2])
ret_x[2] = np.concatenate((ret_x[2], patches), axis=0)
if s == n_tr_samples - 1:
# last step
yield ret_x, ret_y
def val_batch_migenerator(te_features, te_labels,
resize_isize, input_isize,
n_actions, n_te_samples,
n_orig_samples_per_step, n_patches=5):
validate_max_size = n_te_samples
batch_size = n_patches * n_orig_samples_per_step
ret_x = [None, None, None]
while True:
ret_x[0] = np.zeros(shape=tuple([2*n_patches]+list(input_isize[0])),
dtype=np.float32)
ret_y = np.zeros(
shape=(2*n_patches, n_actions), dtype=np.float32)
# random_select = random.sample(range(validate_max_size), 1)[0]
random_select = np.random.randint(validate_max_size)
# rgb with shape (60, 60, 3)
rgb_img = map_skeletal_img(te_features[random_select], resize_isize[0])
clips = corner_select_patch(rgb_img, input_isize[0])
flip_clips = corner_select_patch(
flip_img_horizontal(rgb_img, flip_prob=1.00),
input_isize[0])
ret_x[0][0:n_patches] = clips
ret_x[0][n_patches:] = flip_clips
label = te_labels[np.newaxis, random_select]
labels = np.tile(label, reps=[2*n_patches, 1])
ret_y = labels
ret_x[1] = np.zeros(shape=tuple([2*n_patches]+list(input_isize[1])),
dtype=np.float32)
ret_x[2] = np.zeros(shape=tuple([2*n_patches]+list(input_isize[2])),
dtype=np.float32)
lines = np.array([[20, 3], [3, 1], [3, 4], [3, 2], [1, 8], # for select ll angle
[8, 10], [10, 12], [4, 7], [7, 5], [5, 14],
[14, 16], [16, 18], [7, 6], [6, 15], [15, 17],
[17, 19], [2, 9], [9, 11], [11, 13], [20, 12],
[12, 18], [18, 19], [19, 13], [13, 20], [12, 13],
[13, 18], [18, 20], [20, 19], [19, 12], [13, 9],
[12, 8], [20, 4], [18, 14], [19, 15]])
lines = np.concatenate((lines, lines[:, ::-1]), axis=0)
lines -= 1
rel_loc = compute_relative_loaction(te_features[random_select], lines)
cross_ang = compute_cross_angle(
te_features[random_select], rel_loc, lines)
dot_ang = compute_dot_angle(rel_loc, lines) # TODO: 输入形状
cross_ang = np.swapaxes(cross_ang, 0, 1)
dot_ang = np.swapaxes(dot_ang, 0, 1)
cross_ang = np.uint8(standardize_img(cross_ang))
dot_ang = np.uint8(standardize_img(dot_ang))
cross_ang = transform.resize(cross_ang, resize_isize[1])
dot_ang = transform.resize(dot_ang, resize_isize[2])
clips = corner_select_patch(cross_ang, input_isize[1])
flip_clips = corner_select_patch(
flip_img_horizontal(cross_ang, flip_prob=1.00), input_isize[1])
ret_x[1][:n_patches] = clips
ret_x[1][n_patches:] = flip_clips
clips = corner_select_patch(dot_ang, input_isize[2])
flip_clips = corner_select_patch(
flip_img_horizontal(dot_ang, flip_prob=1.00), input_isize[2])
ret_x[2][:n_patches] = clips
ret_x[2][n_patches:] = flip_clips
yield ret_x, ret_y
def te_batch_migenerator(te_features, te_labels,
resize_isize, input_isize,
n_actions, n_te_samples,
n_orig_samples_per_step, n_patches=5):
ret_x = [None, None, None]
batch_size = n_orig_samples_per_step*n_patches
for anchor in range(n_te_samples):
ret_x[0] = np.zeros(shape=tuple([2*n_patches]+list(input_isize[0])),
dtype=np.float32)
ret_y = np.zeros(
shape=(2*n_patches, n_actions), dtype=np.float32)
rgb_img = map_skeletal_img(te_features[anchor], resize_isize[0])
clips = corner_select_patch(rgb_img, input_isize[0])
flip_clips = corner_select_patch(
flip_img_horizontal(rgb_img, flip_prob=1.00), input_isize[0])
ret_x[0][0:n_patches] = clips
ret_x[0][n_patches:] = flip_clips
label = te_labels[np.newaxis, anchor]
ret_y = np.tile(label, reps=[2*n_patches, 1])
ret_x[1] = np.zeros(shape=tuple([2*n_patches]+list(input_isize[1])),
dtype=np.float32)
ret_x[2] = np.zeros(shape=tuple([2*n_patches]+list(input_isize[2])),
dtype=np.float32)
lines = np.array([[20, 3], [3, 1], [3, 4], [3, 2], [1, 8], # for select ll angle
[8, 10], [10, 12], [4, 7], [7, 5], [5, 14],
[14, 16], [16, 18], [7, 6], [6, 15], [15, 17],
[17, 19], [2, 9], [9, 11], [11, 13], [20, 12],
[12, 18], [18, 19], [19, 13], [13, 20], [12, 13],
[13, 18], [18, 20], [20, 19], [19, 12], [13, 9],
[12, 8], [20, 4], [18, 14], [19, 15]])
lines = np.concatenate((lines, lines[:, ::-1]), axis=0)
lines -= 1
rel_loc = compute_relative_loaction(te_features[anchor], lines)
cross_ang = compute_cross_angle(
te_features[anchor], rel_loc, lines)
dot_ang = compute_dot_angle(rel_loc, lines) # TODO: 输入形状
cross_ang = np.swapaxes(cross_ang, 0, 1)
dot_ang = np.swapaxes(dot_ang, 0, 1)
cross_ang = np.uint8(standardize_img(cross_ang))
dot_ang = np.uint8(standardize_img(dot_ang))
cross_ang = transform.resize(cross_ang, resize_isize[1])
dot_ang = transform.resize(dot_ang, resize_isize[2])
clips = corner_select_patch(cross_ang, input_isize[1])
flip_clips = corner_select_patch(
flip_img_horizontal(cross_ang, flip_prob=1.00), input_isize[1])
ret_x[1][:n_patches] = clips
ret_x[1][n_patches:] = flip_clips
clips = corner_select_patch(dot_ang, input_isize[2])
flip_clips = corner_select_patch(
flip_img_horizontal(dot_ang, flip_prob=1.00), input_isize[2])
ret_x[2][:n_patches] = clips
ret_x[2][n_patches:] = flip_clips
yield ret_x, ret_y
<file_sep>import numpy as np
from numpy.random import shuffle
def split_dataset(features, action_labels, subject_labels, tr_subjects, te_subjects):
tr_subject_ind = np.isin(subject_labels, tr_subjects)
te_subject_ind = np.isin(subject_labels, te_subjects)
tr_labels = action_labels[tr_subject_ind]
te_labels = action_labels[te_subject_ind]
tr_features = features[tr_subject_ind]
te_features = features[te_subject_ind]
return tr_features, tr_labels, te_features, te_labels
def rand_perm_dataset(features, labels):
n_samples = features.shape[0]
index = np.arange(n_samples)
shuffle(index)
features = features[index]
labels = labels[index]
return features, labels
<file_sep>import h5py
import os
import numpy as np
import json
from scipy.interpolate import interp1d
import hdf5storage
def read_skeletal_data(src_file, n_action,
n_subjects, n_instances):
f = h5py.File(src_file, 'r')
refs = np.array(f['skeletal_data'])
skeletal_data_validity = np.array(
f['skeletal_data_validity'])
n_sequences = np.sum(skeletal_data_validity)
features = np.empty(n_sequences, dtype=np.object)
action_labels = np.empty(n_sequences, np.int32)
subject_labels = np.empty(n_sequences, np.int32)
instance_labels = np.empty(n_sequences, np.int32)
count = 0
for a in range(n_action):
for s in range(n_subjects):
for e in range(n_instances):
if skeletal_data_validity[e, s, a] != 1:
continue
features[count] = np.array(
f[refs[e, s, a]])
action_labels[count] = a+1
subject_labels[count] = s+1
instance_labels[count] = e+1
count += 1
return features[:count], action_labels[:count],\
subject_labels[:count], instance_labels[:count]
def interpolation(sequence, body_model, n_desired_frames):
"""通过插值,统一视频长度
注意matlab与numpy的reshape方式不同
此处使用Fortran方式
"""
for i in range(sequence.size):
joint_locs = sequence[i]
n_dim, n_joints, n_given_frames = joint_locs.shape
joint_locs = np.delete(
joint_locs, body_model['hip_center_index']-1, axis=1)
n_features = (n_joints-1)*n_dim
joint_locs = joint_locs.reshape((n_features, -1), order='F')
valid_frame_indices = np.arange(n_given_frames)+1
features = np.empty((n_features, n_desired_frames),
dtype=np.float32)
for k in range(n_features):
# 编辑插值函数格式
f = interp1d(valid_frame_indices,
joint_locs[k, :], kind="cubic")
# 通过相应的插值函数求得新的函数点
features[k, :] = f(np.linspace(
1, n_given_frames, n_desired_frames, endpoint=True))
features = features.reshape((n_dim, n_joints-1, -1), order='F')
features = np.insert(features, body_model['hip_center_index']-1, np.zeros(
(n_dim, n_desired_frames), np.float32), axis=1)
# features = features.reshape((n_joints*n_dim, -1), order='F')
sequence[i] = features
return sequence
def frames_check(sequence, action_labels, subject_labels, instance_labels):
n_samples = sequence.size
samples_validity = np.empty(n_samples, dtype=np.bool)
for i in range(n_samples):
joint_locs = sequence[i]
n_dim, n_joints, n_given_frames = joint_locs.shape
frames_validity = np.empty(n_given_frames, dtype=np.bool)
for j in range(n_given_frames):
if np.isnan(joint_locs[:, :, j]).any():
frames_validity[j] = False
else:
frames_validity[j] = True
sequence[i] = joint_locs[:, :, frames_validity]
if np.sum(frames_validity) <= 10:
samples_validity[i] = False
else:
samples_validity[i] = True
return sequence[samples_validity], \
action_labels[samples_validity], \
subject_labels[samples_validity], \
instance_labels[samples_validity]
if __name__ == "__main__":
dataset_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(dataset_dir)
src_file = 'uniform_skeletal_data.mat'
features, action_labels, subject_labels, instance_labels = read_skeletal_data(
src_file, 20, 10, 3)
features, action_labels, subject_labels, instance_labels = frames_check(
features, action_labels, subject_labels, instance_labels)
body_model = json.load(open('body_model.json', 'r'))
features = interpolation(features, body_model, 76)
hdf5storage.savemat('features', {u'features': features})
hdf5storage.savemat('labels', {
u'action_labels': action_labels,
u'subject_labels': subject_labels,
u'instance_labels': instance_labels
})
<file_sep>import numpy as np
from skimage import transform
def map_skeletal_img(mat, resize_isize):
'''map skeletal action to rgb image
:param mat: (n_frames, feat_dim)
:return: (60, 60, 3)
'''
# mat = np.reshape(mat, newshape=(-1, 20, 3))
mat = np.swapaxes(mat, 0, 1) # mat: (n_feat, n_frames, n_dim)
n_frames = mat.shape[1]
# part_config = [25, 12, 24, 11, 10, 9, 21, 21, 5, 6, 7, 8, 22, 23,
# 21, 3, 4, 21, 2, 1, 17, 18, 19, 20, 21, 2, 1, 13, 14, 15, 16]
part_config = np.array([12, 10, 8, 1, 1, 3, 2, 2, 9, 11, 13, 20, 3, 4, 7, 7,
5, 6, 5, 14, 16, 18, 6, 15, 17, 19])
mat = mat[part_config - 1]
# TODO:以下代码替换
rgb_image = np.uint8(standardize_img(mat))
rgb_image = transform.resize(
rgb_image, (resize_isize[0], resize_isize[1], 3))
return rgb_image
def standardize_img(mat):
'''standardize each pixel of this image
'''
local_max = np.max(mat)
local_min = np.min(mat)
p = 255*(mat-local_min)/(local_max-local_min)
return p
def flip_img_horizontal(mat, flip_prob=0.6):
'''flip the image horizontally randomly with probability of $flip_prob$
'''
rand = np.random.uniform(low=0, high=1.0)
if rand > flip_prob:
return mat
else:
# flip horizontally
return np.fliplr(mat)
def random_select_patch(mat, input_isize, number=5):
'''randomly select $number$ patch from image
'''
resize_isize = mat.shape[:2]
patches = np.zeros(
shape=(number, input_isize[0], input_isize[1], input_isize[2]), dtype=np.float32)
height = resize_isize[1]-input_isize[1]
weight = resize_isize[0]-input_isize[0]
for each in range(number):
anchor_x = np.random.randint(weight)
anchor_y = np.random.randint(height)
select_patch = mat[anchor_x:anchor_x+input_isize[0],
anchor_y:anchor_y+input_isize[1], :]
patches[each] = select_patch
return patches
def corner_select_patch(mat, input_isize, number=5):
'''select the patches from four corners and center
'''
resize_isize = mat.shape[:2]
patches = np.zeros(
shape=(number, input_isize[0], input_isize[1], input_isize[2]), dtype=np.float32)
height = resize_isize[1]-input_isize[1]
weight = resize_isize[0]-input_isize[0]
anchors = [[0, 0], [weight, 0], [0, height], [
weight, height], [weight//2, height//2]]
for each in range(number):
anchor_x, anchor_y = anchors[each][0], anchors[each][1]
select_patch = mat[anchor_x:anchor_x+input_isize[0],
anchor_y:anchor_y+input_isize[1], :]
patches[each] = select_patch
return patches
def compute_relative_loaction(mat, lines):
n_frames, n_joints, n_dim = mat.shape
n_lines = lines.shape[0]
relative_locations = np.empty(
(n_frames, n_lines, n_dim), dtype=np.float32)
for t in range(n_frames):
for i in range(n_lines):
relative_locations[t, i] = mat[t, lines[i, 0]]-mat[t, lines[i, 1]]
return relative_locations
def compute_cross_angle(abs_loc, rel_loc, lines):
'''
:abs_loc: joint locations
:rel_loc: coordinates of lines(vectors)
:lines: indices of start points and end points of lines
'''
n_frames, n_lines, n_dim = rel_loc.shape
cross = np.empty(
(n_frames, n_lines*(n_lines-1), n_dim), dtype=np.float32)
for t in range(n_frames):
counter = 0
for lid_1 in range(n_lines):
for lid_2 in range(n_lines):
if lines[lid_1, 0] == lines[lid_2, 0] \
and lines[lid_1, 1] != lines[lid_2, 1]:
line_1 = rel_loc[t, lid_1]
line_2 = rel_loc[t, lid_2]
cross[t, counter] = np.cross(line_1, line_2) / \
np.linalg.norm(
abs_loc[t, lines[lid_1, 1]]-abs_loc[t, lines[lid_2, 1]])
counter += 1
return cross[:counter]
def compute_dot_angle(rel_loc, lines):
'''
:abs_loc: joint locations
:rel_loc: coordinates of lines(vectors)
:lines: indices of start points and end points of lines
'''
n_frames, n_lines, n_dim = rel_loc.shape
nloc = np.linalg.norm(rel_loc, axis=2)
dot_ang = np.empty(
(n_frames, n_lines*(n_lines-1)), dtype=np.float32)
for t in range(n_frames):
counter = 0
for lid_1 in range(n_lines//2): # use a half
for lid_2 in range(n_lines//2):
if np.any(lines[lid_1] != lines[lid_2]):
assert nloc[t, lid_1] > 1e-6 and nloc[t, lid_2] > 1e-6
uline_1 = rel_loc[t, lid_1]/nloc[t, lid_1]
uline_2 = rel_loc[t, lid_2]/nloc[t, lid_2]
d = np.clip(np.dot(uline_1, uline_2), -1, 1)
dot_ang[t, counter] = np.arccos(d)
counter += 1
return dot_ang[:, :counter]
<file_sep>"""
acc:0.85
过去骨架数据到图像的映射采用训练前的预处理策略
此处将骨架到图像的映射转移到网络内部
"""
import json
import cv2
import h5py
import numpy as np
import scipy.stats as stat
import tensorflow as tf
from skimage import transform
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from tensorflow import image
from tensorflow.keras.layers import (BatchNormalization, Conv2D, Dense,
Dropout, Flatten, Input, MaxPooling2D,
concatenate)
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.regularizers import l1, l2
from tensorflow.keras.utils import plot_model, to_categorical
from util.dataset_processing import rand_perm_dataset, split_dataset
from util.modeling import (build_conv_module, build_start_time_diff_module,
build_time_diff_module)
from util.preprocessing import (flip_img_horizontal, random_select_patch,
standardize_img)
from util.training import (te_batch_migenerator, tr_batch_migenerator,
val_batch_migenerator, empty_batch_migenerator)
RESIZE_ISIZE = [(60, 60, 3), (128, 76, 3), (128, 76, 1)]
INPUT_ISIZE = [(52, 52, 3), (120, 70, 3), (120, 70, 1)]
def build(input_shape):
input_1 = Input(shape=input_shape[0])
time_diff = build_time_diff_module(input_1, input_shape[0])
start_time_diff = build_start_time_diff_module(input_1, input_shape[0])
raw_data_conv = build_conv_module(input_1)
time_diff_conv = build_conv_module(time_diff)
start_time_diff_conv = build_conv_module(start_time_diff)
input_2 = Input(shape=input_shape[1])
input_3 = Input(shape=input_shape[2])
ll_angle_conv = build_conv_module(input_2)
lp_angle_conv = build_conv_module(input_3)
concat_layer = concatenate([
raw_data_conv, time_diff_conv, start_time_diff_conv,
ll_angle_conv, lp_angle_conv], axis=-1)
fc_1 = Dense(256, activation='relu',
kernel_regularizer=l2(1.e-2))(concat_layer)
output = Dense(20, activation='softmax',
kernel_regularizer=l2(1.e-2))(fc_1)
model = Model([input_1, input_2, input_3], output)
# decay=1e-6, lr=0.00002
sgd = SGD(lr=0.01, decay=1e-4, momentum=0.9, nesterov=True)
# 论文中写的loss和这里不一样
# 试试categorical_crossentropy,mean_squared_error
model.compile(loss='categorical_crossentropy',
optimizer=sgd, metrics=['accuracy'])
return model
def training_pipline(features, subject_labels, action_labels, tr_subjects, te_subjects):
action_labels = to_categorical(action_labels - 1, 20)
i = 1
model = build(INPUT_ISIZE)
model.summary()
tr_features, tr_labels, te_features, te_labels = split_dataset(
features, action_labels, subject_labels, tr_subjects[i, :], te_subjects[i, :])
tr_features, tr_labels = rand_perm_dataset(tr_features, tr_labels)
n_actions = np.unique(action_labels, axis=0).shape[0]
n_tr_samples = tr_labels.shape[0]
n_te_samples = te_labels.shape[0]
'''-----------------------个人复现版------------------------'''
epochs = 100
# 7 orig samples is used and each orig sample gen 5 patches
n_orig_samples_per_step, n_patches = 7, 5
batch_size = n_orig_samples_per_step * n_patches
tr_gen = tr_batch_migenerator(tr_features, tr_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_tr_samples,
n_orig_samples_per_step)
val_gen = val_batch_migenerator(te_features, te_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_te_samples,
n_orig_samples_per_step)
model.fit_generator(tr_gen, steps_per_epoch=n_tr_samples,
epochs=epochs, validation_data=val_gen,
validation_steps=300)
te_gen = te_batch_migenerator(te_features, te_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_te_samples,
n_orig_samples_per_step)
pred_list = model.predict_generator(generator=te_gen,
steps=n_te_samples)
pred_list = np.array(pred_list)
pred_list = np.reshape(pred_list, newshape=(
n_te_samples, 2*(n_patches), -1))
preds = np.argmax(pred_list, axis=2) + 1 # (number, 2*n_group)
te_labels = np.argmax(te_labels, axis=1)+1
print(te_labels)
# (amount_testset, 1) numpy array
pred_result = np.squeeze(stat.mode(preds, axis=1)[0])
print(pred_result)
print(np.sum(te_labels == pred_result)/te_labels.size)
return model, te_features, te_labels
def additional_tr_pipline(model, te_features, te_labels):
n_te_samples = te_labels.shape[0]
te_labels = to_categorical(te_labels - 1, 20)
epochs, n_orig_samples_per_step = 1, 7
n_actions = np.unique(action_labels, axis=0).shape[0]
tr_gen = tr_batch_migenerator(te_features, te_labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_te_samples,
n_orig_samples_per_step)
model.fit_generator(tr_gen, steps_per_epoch=n_te_samples,
epochs=epochs)
return model
def classification_pipline(model, samples):
n_actions = 20
if np.ndim(samples) == 3:
samples = samples[np.newaxis, :, :]
labels = to_categorical(0, n_actions)
labels = labels[np.newaxis, :]
n_samples = 1
else:
n_samples = samples.shape[0]
labels = to_categorical(np.zeros(n_samples), n_actions)
n_orig_samples_per_step = 7
te_gen = te_batch_generator(samples, labels,
RESIZE_ISIZE, INPUT_ISIZE,
n_actions, n_samples,
n_orig_samples_per_step)
pred_list = model.predict_generator(generator=te_gen,
steps=n_samples)
if np.ndim(pred_list) == 2:
pred_list = pred_list[np.newaxis, :, :]
preds = np.argmax(pred_list, axis=2) + 1
pred_result = np.squeeze(stat.mode(preds, axis=1)[0])
return pred_result
if __name__ == "__main__":
# 读取特征
f = h5py.File(
'data/MSRAction3D/features.mat', 'r')
features = np.array([f[element]
for element in np.squeeze(f['features'][:])])
# 读取标签
f = h5py.File(
'data/MSRAction3D/labels.mat', 'r')
subject_labels = f['subject_labels'][:, 0]
action_labels = f['action_labels'][:, 0]
# 读取数据集划分方案
f = json.load(open(
'data/MSRAction3D/tr_te_splits.json', 'r'))
tr_subjects = np.array(f['tr_subjects'])
te_subjects = np.array(f['te_subjects'])
n_tr_te_splits = tr_subjects.shape[0]
model, te_features, te_labels = training_pipline(features, subject_labels,
action_labels, tr_subjects, te_subjects)
model = additional_tr_pipline(model, te_features, te_labels)
print(classification_pipline(model, te_features[6]))
model.save('model/feature_investigating.h5')
<file_sep>import tensorflow as tf
from tensorflow import image
from tensorflow.keras.layers import (BatchNormalization, Conv2D, Dropout,
Flatten, MaxPooling2D, concatenate)
def build_time_diff_module(input_layer, output_shape):
time_diff = input_layer[:, :, 1:]-input_layer[:, :, :-1]
time_diff = image.resize(
time_diff, list(output_shape[:-1]),
method=image.ResizeMethod.NEAREST_NEIGHBOR)
return time_diff
def build_start_time_diff_module(input_layer, output_shape):
start_time = input_layer[:, :, 0]
start_time = tf.tile(start_time[:, :, tf.newaxis],
[1, 1, output_shape[0]-1, 1])
start_time_diff = input_layer[:, :, 1:]-start_time
start_time_diff = image.resize(
start_time_diff, list(output_shape[:-1]),
method=image.ResizeMethod.NEAREST_NEIGHBOR)
return start_time_diff
def build_conv_module(input_layer):
conv_1 = Conv2D(32, (3, 3), activation='relu',
strides=1, padding='same')(input_layer)
pooling_1 = MaxPooling2D(pool_size=(3, 3), strides=2)(conv_1)
conv_2 = Conv2D(32, (3, 3), activation='relu',
strides=1, padding='same')(pooling_1)
pooling_2 = MaxPooling2D(pool_size=(3, 3), strides=2)(conv_2)
bn_1 = BatchNormalization()(pooling_2)
dropout_1 = Dropout(0.5)(bn_1)
conv_3 = Conv2D(64, (3, 3), activation='relu',
strides=1, padding='same')(dropout_1)
pooling_3 = MaxPooling2D(pool_size=(3, 3), strides=2)(conv_3)
conv_4 = Conv2D(64, (3, 3), activation='relu',
strides=1, padding='same')(pooling_3)
pooling_4 = MaxPooling2D(pool_size=(3, 3), strides=2)(conv_4)
bn_2 = BatchNormalization()(pooling_4)
dropout_2 = Dropout(0.5)(bn_2)
flatten = Flatten()(dropout_2)
return flatten
<file_sep>"""
这个程序直接将不同关节的不同坐标(共57维)当成不同channal做一维卷积
accuracy平均达到70%
"""
import tensorflow as tf
# from scipy.interpolate import spline
#TODO:插值自己实现
import h5py
import numpy as np
from tensorflow.keras import Sequential, Model
from tensorflow.keras.layers import Conv1D, MaxPool1D, Flatten, Dense, Activation
from tensorflow.keras.optimizers import RMSprop, SGD
from numpy.random import shuffle
from keras.utils.vis_utils import plot_model
from keras.utils import np_utils
def build():
model = Sequential()
model.add(Conv1D(filters=60, kernel_size=3, input_shape=(76, 57),
strides=1, padding="same", activation='relu',
kernel_initializer=tf.truncated_normal_initializer(0, .05), name='CONV1'))
model.add(MaxPool1D(pool_size=2, strides=1))
model.add(Conv1D(filters=120, kernel_size=3, kernel_initializer=tf.truncated_normal_initializer(0, .05),
strides=1, padding="same", activation='relu', name='CONV2'))
model.add(MaxPool1D(pool_size=2, strides=1))
model.add(Flatten())
model.add(Dense(1024, kernel_initializer=tf.truncated_normal_initializer(0, .05),
activation='relu', name='FC1'))
model.add(
Dense(20, kernel_initializer=tf.truncated_normal_initializer(0, .05), name='FC2'))
model.add(Activation('sigmoid'))
model.compile(loss='mean_squared_error',
optimizer=SGD(lr=0.05), metrics=['accuracy'])
return model
def split_dataset(features, action_labels, subject_labels, tr_subjects, te_subjects):
tr_subject_ind = np.isin(subject_labels, tr_subjects)
te_subject_ind = np.isin(subject_labels, te_subjects)
tr_labels = action_labels[tr_subject_ind]
te_labels = action_labels[te_subject_ind]
tr_features = features[tr_subject_ind]
te_features = features[te_subject_ind]
return tr_features, tr_labels, te_features, te_labels
# 读取特征
f = h5py.File(
'MSRAction3D_experiments/absolute_joint_positions/features.mat', 'r')
features = np.array([f[element][:] for element in f['features'][0]])
# 读取标签
f = h5py.File(
'MSRAction3D_experiments/absolute_joint_positions/labels.mat', 'r')
subject_labels = f['subject_labels'][:][0]
action_labels = f['action_labels'][:][0]
print(features.shape)
print(subject_labels.shape)
print(action_labels.shape)
action_labels = np_utils.to_categorical(action_labels - 1, 20)
# 读取数据集划分方案
f = h5py.File(
'data/MSRAction3D/tr_te_splits.mat', 'r')
tr_subjects = f['tr_subjects'][:].T
te_subjects = f['te_subjects'][:].T
n_tr_te_splits = tr_subjects.shape[0]
total_accuracy = np.empty(n_tr_te_splits, dtype=np.float32)
for i in range(n_tr_te_splits):
model = build()
tr_features, tr_labels, te_features, te_labels = split_dataset(
features, action_labels, subject_labels, tr_subjects[i, :], te_subjects[i, :])
model.fit(tr_features, tr_labels,
batch_size=1, epochs=60, validation_data=(te_features, te_labels))
pr_labels = model.predict(te_features)
pr_labels = np.argmax(pr_labels, axis=-1) + 1
te_labels = np.argmax(te_labels, axis=-1) + 1
total_accuracy[i] = np.sum(pr_labels == te_labels) / te_labels.size
print('split %d is done, accuracy:%f' %
(i + 1, total_accuracy[i]))
# tf.reset_default_graph()
print('all splits is done, avg accuracy:%f' %
(total_accuracy.mean()))
<file_sep>import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d.art3d import Line3D, Line3DCollection
import h5py
import json
f = h5py.File('data/MSRAction3D/features.mat', 'r')
features = np.array([f[element] for element in np.squeeze(f['features'][:])])
data = features[0]
f = json.load(open('data/MSRAction3D/body_model.json', 'r'))
bones = np.array(f['bones']) - 1
fig = plt.figure()
ax = p3.Axes3D(fig, azim=-90, elev=10)
# Setting the axes properties
ax.set_xlim3d([0, 4])
ax.set_xlabel('X')
ax.set_ylim3d([0, 4])
ax.set_ylabel('Z')
ax.set_zlim3d([0, 4])
ax.set_zlabel('Y')
graph = ax.scatter([], [], [])
frame = data[0]+2
lines = [np.array([frame[bones[i, 0]], frame[bones[i, 1]]])
for i in range(bones.shape[0])]
lc = Line3DCollection(segments=lines)
ax.add_collection3d(lc)
# def update_lines()
def animate(i):
frame = data[i]+2
graph._offsets3d = (frame[:, 0], frame[:, 1], frame[:, 2])
lines = [np.array([frame[bones[i, 0]], frame[bones[i, 1]]])
for i in range(bones.shape[0])]
lc.set_segments(lines)
return graph
ani = FuncAnimation(fig, animate, frames=data.shape[0], interval=100)
plt.show()
|
846cb83d555efe8562ed129ba0f6fc4d4d7101de
|
[
"Python"
] | 11
|
Python
|
Mostro-Complexity/skeletal-action-recognition-cnn
|
7d5235f6aa504b1bd1171e055058bcf60ea8cfa1
|
473e85196575bef375e3b412f241087648f411d8
|
refs/heads/master
|
<repo_name>tk-ozawa/hotwords<file_sep>/README.md
# hotwords
複数のニュースサイトの記事タイトルの固有名詞を抽出し、
それぞれの単語を登場頻度でソートしてホットワードを割り出すプログラム
<file_sep>/func.php
<?php
/**
* $sentenceの構造は以下の通り。
* サイト別配列
* └項目別配列
* └タイトル名
*/
function keyphrase($appid, $sentence) {
if (empty($appid) || empty($sentence)) {
return false;
}
$hotwords = '';
foreach($sentence as $item) { // サイト毎
/**
* メモ: 固有名詞の抽出は形態素解析を使うべきかも
*/
// 固有名詞の表記統一 改良の余地ありあり
$search = array('アップル', 'TechCrunch Japan');
$replace = array('Apple' ,'');
$item = str_replace($search, $replace, $item); // タイトルを','で区切って1つの文字列に
$item = preg_replace('/([まさか|する|でなければ|について|ならば|までを|までの|くらい|なのか|として|とは|なら|から|まで|して|だけ|より|ほど|など|って|では|は|で|を|の|が|に|へ|と])/u', '', $item);
// Yahoo!APIでテキスト解析
$responsexml = yahoo($appid, implode(",", $item));
$hotwords_at_site = [];
foreach($responsexml->Result as $value) {
$hotwords_at_site[] = $value->Keyphrase;
}
$hotwords .= ','.implode(",", $hotwords_at_site);
}
// Yahoo!APIでテキスト解析
$responsexml = yahoo($appid, $hotwords);
return $responsexml;
}
function yahoo($appid, $item) {
$request = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract?";
$request .= "appid=".$appid."&sentence=".urlencode($item)."&output=xml";
return simplexml_load_file($request);
}<file_sep>/rss_feed.php
<?php
require_once 'func.php';
$appid = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/yahoo_api_key.txt'); // APIキー読み込み
$sentence = [];
// Impress Watch用
$data = [];
$xml = simplexml_load_file('https://www.watch.impress.co.jp/data/rss/1.0/ipw/feed.rdf');//xmlを読み込む
foreach($xml->item as $value){
$data[] = (string)$value->title;
}
$sentence[] = $data;
// Yahoo! IT用
$data = [];
$xml = simplexml_load_file('https://news.yahoo.co.jp/pickup/computer/rss.xml');//xmlを読み込む
foreach($xml->channel->item as $value){
$data[] = (string)$value->title;
}
$sentence[] = $data;
// TechCrunch用
$data = [];
$xml = simplexml_load_file('https://headlines.yahoo.co.jp/rss/techcrj-c_sci.xml');//xmlを読み込む
foreach($xml->channel->item as $value){
$data[] = (string)$value->title;
}
$sentence[] = $data;
// 日経xTECH IT用
$data = [];
$xml = simplexml_load_file('https://tech.nikkeibp.co.jp/rss/xtech-it.rdf');//xmlを読み込む
foreach($xml->item as $value){
$data[] = (string)$value->title;
}
$sentence[] = $data;
$responsexml = keyphrase($appid, $sentence);
$result_num = count($responsexml->Result);
?>
<html>
<head>
<base target="_blank">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>キーフレーズ抽出</title>
</head>
<body>
<style>
</style>
<h2 class="title">キーフレーズ抽出</h2>
<table>
<tr><td><b>キーフレーズ</b></td><td><b>スコア</b></td></tr>
<?php for($i = 0; $i < $result_num; $i++):
$result = $responsexml->Result[$i]; ?>
<tr>
<td><a href='https://www.google.com/search?q=<?= $result->Keyphrase ?>&source=lnms&tbm=nws'><?= $result->Keyphrase ?></a></td>
<td><?= $result->Score ?></td>
</tr>
<?php endfor; ?>
</table>
<!-- Begin Yahoo! JAPAN Web Services Attribution Snippet -->
<a href="http://developer.yahoo.co.jp/about">
<img src="http://i.yimg.jp/images/yjdn/yjdn_attbtn2_105_17.gif" width="105" height="17" title="Webサービス by Yahoo! JAPAN" alt="Webサービス by Yahoo! JAPAN" border="0" style="margin:15px 15px 15px 15px"></a>
<!-- End Yahoo! JAPAN Web Services Attribution Snippet -->
</body>
</html>
|
b2fbcd2e31b91dbf2fb1a6732d894a79b14da7f5
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
tk-ozawa/hotwords
|
19352249a8d81e8977986b7c89f3be6eb72ef66d
|
b4a0eb7f1300d77bf91bab8c9b2fe0651514c684
|
refs/heads/master
|
<file_sep>import { GET_TASKS, GET_ERRORS, ADD_TASK } from '../actions/types';
const initialState = {
task: []
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_TASKS:
return {
...state,
task: action.payload
};
case ADD_TASK:
return {
...state,
task: [action.payload, ...state.task]
};
case GET_ERRORS:
return {
...state,
error: action.msg
};
default :
return state;
}
}<file_sep>import { GET_ERRORS, GET_TASKS, ADD_TASK } from "./types";
export const getTasks = () => {
return (dispatch) => {
return fetch('https://uxcandy.com/~shapoval/test-task-backend/?developer=admin', {
method: 'GET'
})
.then(res => res.json())
.then(json => dispatch({
type: GET_TASKS,
payload: json
}))
.catch(err => dispatch({
type: GET_ERRORS,
msg: 'Unable to fetch data'
}))
}
}
export const addTask = (data) => {
return (dispatch) => {
return fetch(`https://uxcandy.com/~shapoval/test-task-backend/create?developer=${data.username}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({data})
})
.then(res => res.json())
.then(() => dispatch({
type: ADD_TASK,
payload: data
}))
.catch(err => dispatch({
type: GET_ERRORS,
msg: 'Unable to fetch data'
}))
}
}<file_sep>import { GET_ERRORS, SET_CURRENT_USER } from "./types";
//Login User
<file_sep>export const GET_ERRORS = 'GET_ERRORS';
export const GET_TASKS = 'GET_TASKS';
export const ADD_TASK = 'ADD_TASK';
export const SET_CURRENT_USER = 'SET_CURRENT_USER';<file_sep>import React from 'react';
import { connect } from 'react-redux';
import Spinner from '../common/Spinner';
class TaskItem extends React.Component {
render() {
const tasks = this.props.tasks;
const currentPage = this.props.page;
// Logic for displaying tasks
const indexOfLastTask = currentPage * 3;
const indexOfFirstTask = indexOfLastTask - 3;
const currentTasks = tasks.slice(indexOfFirstTask, indexOfLastTask);
if (currentTasks === null) {
return <Spinner/>
} else {
return (
currentTasks.map(item => (
<div className="col-sm-4" key={item.id}>
<div className="card">
<div className="card-header">
<div className="row h-100">
<div className="col">
<h5 className="card-title">{item.username}</h5>
<p className="email_label">{item.email}</p>
</div>
<div className="col-1 p-0">
<input className="my-auto status" type="checkbox"/>
</div>
</div>
</div>
<div className="card-body">
<p className="card-text">{item.text}</p>
</div>
</div>
</div>
))
);
}
}
}
export default connect()(TaskItem);
|
c151813be925e56d44b871dfc9fcf8b1928691ef
|
[
"JavaScript"
] | 5
|
JavaScript
|
Code7unner/bee_jee
|
2b6aaa0696efdaaa78e6306a008ae5e224f83fe6
|
72b6f99569041a58b359c1e084b1c0d79c1cd10c
|
refs/heads/master
|
<repo_name>michaelberge8/multilayer-perceptron-1-hidden-layer<file_sep>/neural_network.py
import matrix
'''
File name: main.py
Author: <NAME>
Date created: 7/19/2018
Python Version: 3.8.1
'''
class NeuralNetwork:
def __init__(self, input_nodes, hidden_nodes, output_nodes):
self.__input_nodes = input_nodes
self.__hidden_nodes = hidden_nodes
self.__output_nodes = output_nodes
# weights
self.__weights_ih = matrix.Matrix(self.__hidden_nodes, self.__input_nodes)
self.__weights_ho = matrix.Matrix(self.__output_nodes, self.__hidden_nodes)
self.__weights_ih.randomize()
self.__weights_ho.randomize()
# bias
self.__bias_h = matrix.Matrix(self.__hidden_nodes, 1)
self.__bias_o = matrix.Matrix(self.__output_nodes, 1)
self.__bias_h.randomize()
self.__bias_o.randomize()
# Learning rate
self.lr = 0.1
def feed_forward(self, i):
input_ = matrix.Matrix.from_array(i)
hidden = matrix.Matrix.multiply(self.__weights_ih, input_)
hidden.add(self.__bias_h)
hidden.map(matrix.Matrix.sigmoid)
output = matrix.Matrix.multiply(self.__weights_ho, hidden)
output.add(self.__bias_o)
output.map(matrix.Matrix.sigmoid)
return matrix.Matrix.to_array(output)
def train(self, i, target_, gr):
# Feed-forward
input_ = matrix.Matrix.from_array(i)
hidden = matrix.Matrix.multiply(self.__weights_ih, input_)
hidden.add(self.__bias_h)
hidden.map(matrix.Matrix.sigmoid)
output = matrix.Matrix.multiply(self.__weights_ho, hidden)
output.add(self.__bias_o)
output.map(matrix.Matrix.sigmoid)
###################################################################
######################### Backpropagation #########################
###################################################################
# Calculate output errors
target = matrix.Matrix.from_array(target_)
output_errors = matrix.Matrix.subtract(target, output)
# Calculate output gradient
output_gradient = matrix.Matrix.map_(output, matrix.Matrix.d_sigmoid)
output_gradient.multiply_(output_errors)
output_gradient.multiply_(self.lr)
###################################################################
# Calculate hidden --> output weight deltas
hidden_t = matrix.Matrix.transpose(hidden)
weights_ho_deltas = matrix.Matrix.multiply(output_gradient, hidden_t)
# Adjust hidden --> output weights
self.__weights_ho.add(weights_ho_deltas)
###################################################################
# Adjust output bias
self.__bias_o.add(output_gradient)
###################################################################
# Calculate hidden layer errors
weights_ho_transpose = matrix.Matrix.transpose(self.__weights_ho)
hidden_errors = matrix.Matrix.multiply(weights_ho_transpose, output_errors)
# Calculate hidden gradient
hidden_gradient = matrix.Matrix.map_(hidden, matrix.Matrix.d_sigmoid)
hidden_gradient.multiply_(hidden_errors)
hidden_gradient.multiply_(self.lr)
# Calculate input --> hidden weight deltas
input_t = matrix.Matrix.transpose(input_)
weights_ih_deltas = matrix.Matrix.multiply(hidden_gradient, input_t)
# Adjust output --> hidden weights
self.__weights_ih.add(weights_ih_deltas)
###################################################################
# Adjust hidden bias
self.__bias_h.add(hidden_gradient)
###################################################################
# Graphics
gr.draw(input_, hidden, output, self.__weights_ih, self.__weights_ho)<file_sep>/graphics.py
from pygame import gfxdraw
import pygame as pg
import matrix
import sys
'''
File name: main.py
Author: <NAME>
Date created: 7/19/2018
Python Version: 3.8.1
'''
class Graphics:
def __init__(self, i, h, o):
self.__num_i_nodes = i
self.__num_h_nodes = h
self.__num_o_nodes = o
self.__SCREEN_WIDTH = 640
self.__SCREEN_HEIGHT = 480
self.white = (255, 255, 255)
self.black = (50, 50, 50)
self.red = (235, 0, 0)
self.blue = (0, 0, 235)
self.__i_node_spacing = self.__SCREEN_HEIGHT / (i + 1)
self.__h_node_spacing = self.__SCREEN_HEIGHT / (h + 1)
self.__o_node_spacing = self.__SCREEN_HEIGHT / (o + 1)
self.__i_nodes = []
self.__h_nodes = []
self.__o_nodes = []
self.__ih_weights = []
self.__ho_weights = []
self.init_i_nodes(h)
self.init_h_nodes(h)
self.init_o_nodes(h)
self.init_ih_weights()
self.init_ho_weights()
self.screen = self.open_window()
def open_window(self):
pg.init()
size = (self.__SCREEN_WIDTH, self.__SCREEN_HEIGHT)
screen = pg.display.set_mode(size)
pg.display.set_caption("Neural Network Visualization")
return screen
# Initialize
def init_i_nodes(self, h):
y = self.__i_node_spacing
for i in range(self.__num_i_nodes):
self.__i_nodes.append(Node(self.__SCREEN_WIDTH / 8, y, (int) (240 / (h + 15))))
y += self.__i_node_spacing
def init_h_nodes(self, h):
y = self.__h_node_spacing
for i in range(self.__num_h_nodes):
self.__h_nodes.append(Node(self.__SCREEN_WIDTH / 2, y, (int) (240 / (h + 15))))
y += self.__h_node_spacing
def init_o_nodes(self, h):
y = self.__o_node_spacing
for i in range(self.__num_o_nodes):
self.__o_nodes.append(Node(self.__SCREEN_WIDTH / 8 * 7, y, (int) (240 / (h + 15))))
y += self.__o_node_spacing
def init_ih_weights(self):
for i in range(len(self.__i_nodes)):
for j in range(len(self.__h_nodes)):
self.__ih_weights.append(Weight((self.__i_nodes[i].x, self.__i_nodes[i].y), (self.__h_nodes[j].x, self.__h_nodes[j].y)))
def init_ho_weights(self):
for i in range(len(self.__h_nodes)):
for j in range(len(self.__o_nodes)):
self.__ho_weights.append(Weight((self.__h_nodes[i].x, self.__h_nodes[i].y), (self.__o_nodes[j].x, self.__o_nodes[j].y)))
# Draw
def draw_input_nodes(self, screen, black, red):
for i in range(len(self.__i_nodes)):
if self.__i_nodes[i].data >= 0:
color = black
else:
color = red
pg.gfxdraw.filled_circle(screen, int(self.__i_nodes[i].x), int(self.__i_nodes[i].y), self.__i_nodes[i].size, color)
pg.gfxdraw.aacircle(screen, int(self.__i_nodes[i].x), int(self.__i_nodes[i].y), self.__i_nodes[i].size, color)
def draw_hidden_nodes(self, screen, black, red):
for i in range(len(self.__h_nodes)):
if self.__h_nodes[i].data >= 0:
color = black
else:
color = red
pg.gfxdraw.filled_circle(screen, int(self.__h_nodes[i].x), int(self.__h_nodes[i].y), self.__h_nodes[i].size, color)
pg.gfxdraw.aacircle(screen, int(self.__h_nodes[i].x), int(self.__h_nodes[i].y), self.__h_nodes[i].size, color)
def draw_output_nodes(self, screen, black, red):
for i in range(len(self.__o_nodes)):
if self.__o_nodes[i].data >= 0:
color = black
else:
color = red
pg.gfxdraw.filled_circle(screen, int(self.__o_nodes[i].x), int(self.__o_nodes[i].y), self.__o_nodes[i].size, color)
pg.gfxdraw.aacircle(screen, int(self.__o_nodes[i].x), int(self.__o_nodes[i].y), self.__o_nodes[i].size, color)
def draw_ih_weights(self, screen, blue, red):
for i in range(len(self.__ih_weights)):
if self.__ih_weights[i].data >= 0:
color = blue
else:
color = red
if 1 > self.__ih_weights[i].data > -1:
thickness = 1
else:
thickness = abs(round(self.__ih_weights[i].data))
pg.draw.line(screen, color, self.__ih_weights[i].coor1, self.__ih_weights[i].coor2, thickness)
def draw_ho_weights(self, screen, blue, red):
for i in range(len(self.__ho_weights)):
if self.__ho_weights[i].data >= 0:
color = blue
else:
color = red
if 1 > self.__ho_weights[i].data > -1:
thickness = 1
else:
thickness = abs(round(self.__ho_weights[i].data))
pg.draw.line(screen, color, self.__ho_weights[i].coor1, self.__ho_weights[i].coor2, thickness)
# Update
def update_input_nodes(self, arr):
for i in range(len(arr)):
self.__i_nodes[i].data = arr[i]
def update_hidden_nodes(self, arr):
for i in range(len(arr)):
self.__h_nodes[i].data = arr[i]
def update_output_nodes(self, arr):
for i in range(len(arr)):
self.__o_nodes[i].data = arr[i]
def update_ih_weights(self, arr):
for i in range(len(arr)):
self.__ih_weights[i].data = arr[i]
def update_ho_weights(self, arr):
for i in range(len(arr)):
self.__ho_weights[i].data = arr[i]
# Draw screen
def draw(self, input_, hidden, output, __weights_ih, __weights_ho):
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit(0)
self.screen.fill(self.white)
# Update
self.update_input_nodes(matrix.Matrix.to_array(input_))
self.update_hidden_nodes(matrix.Matrix.to_array(hidden))
self.update_output_nodes(matrix.Matrix.to_array(output))
self.update_ih_weights(matrix.Matrix.to_array(__weights_ih))
self.update_ho_weights(matrix.Matrix.to_array(__weights_ho))
# Draw
self.draw_ih_weights(self.screen, self.blue, self.red)
self.draw_ho_weights(self.screen, self.blue, self.red)
self.draw_input_nodes(self.screen, self.black, self.red)
self.draw_hidden_nodes(self.screen, self.black, self.red)
self.draw_output_nodes(self.screen, self.black, self.red)
pg.display.update()
class Node:
def __init__(self, x, y, size):
self.x = x
self.y = y
self.size = size
self.data = 0.0
class Weight:
def __init__(self, coor1, coor2):
self.coor1 = coor1
self.coor2 = coor2
self.data = 0.0<file_sep>/README.md
# Multilayer Perceptron (1 hidden layer)
This is a multilayer neural network (with 1 hidden layer) which solves the XOR problem. The perceptron is trained over a number of iterations defined by the user (epoch). The improvement of the network is graphed over the iterations and displayed. A visualization of the improvment of the network is also displayed during runtime.
|
90aec38e792a9d25347a68438c9ca58395af1da6
|
[
"Markdown",
"Python"
] | 3
|
Python
|
michaelberge8/multilayer-perceptron-1-hidden-layer
|
c5af60810681bb1ff4a57228182668ef58fd7d6b
|
ee4db53b7325267bdf0586558b82df880325dd4d
|
refs/heads/master
|
<file_sep>"""
remove_first_and_last(list_to_clean):
html = ['<h1>', 'Some content', '</h1>']
remove_first_and_last(html)
=> 'some content'
"""
def remove_first_and_last(list_to_clean):
_, *content, _ = list_to_clean
return content
html = ['<h1>', 'Some content', 'more content', '</h1>']
print(remove_first_and_last(html))
|
53d8869e8ef76829b34c980b2221dde9a71dbae4
|
[
"Python"
] | 1
|
Python
|
Uthaeus/devcamp_python
|
e4cbef62bc015e56f3b9dffa58fa573b67be746b
|
203765d6ca6a70317bc48def2019d2356d087c01
|
refs/heads/main
|
<repo_name>eakischuk/whats-in-my-food<file_sep>/app/poros/food_item.rb
class FoodItem
attr_reader :gtin_upc, :description, :brand_owner, :ingredients
def initialize(food_info)
@gtin_upc = food_info[:gtinUpc]
@description = food_info[:description]
@brand_owner = food_info[:brandOwner]
@ingredients = food_info[:ingredients]
end
end
<file_sep>/spec/services/food_service_spec.rb
require 'rails_helper'
RSpec.describe FoodService do
context 'class_methods' do
it 'returns foods with query' do
search = FoodService.foods_with_ingredient('sweet potato')
expect(search).to be_a(Hash)
expect(search).to have_key(:totalHits)
expect(search[:totalHits]).to be_a(Integer)
expect(search).to have_key(:foods)
expect(search[:foods]).to be_an(Array)
food = search[:foods].first
expect(food).to have_key(:description)
expect(food[:description]).to be_a(String)
expect(food).to have_key(:brandOwner)
expect(food[:brandOwner]).to be_a(String)
expect(food).to have_key(:gtinUpc)
expect(food[:gtinUpc]).to be_a(String)
expect(food).to have_key(:ingredients)
expect(food[:ingredients]).to be_a(String)
end
end
end
<file_sep>/spec/poros/food_item_spec.rb
require 'rails_helper'
RSpec.describe FoodItem do
it 'exists and has attributes' do
food_info = {gtinUpc: "86578968",
description: "its food",
brandOwner: "probably nestle",
ingredients: 'potato'
}
food_item = FoodItem.new(food_info)
expect(food_item.gtin_upc).to eq(food_info[:gtinUpc])
expect(food_item.description).to eq(food_info[:description])
expect(food_item.brand_owner).to eq(food_info[:brandOwner])
expect(food_item.ingredients).to eq(food_info[:ingredients])
end
end
<file_sep>/spec/features/foods/index_spec.rb
require 'rails_helper'
RSpec.describe 'food index page' do
it 'returns list of 10 foods for search' do
visit '/'
fill_in :q, with: 'sweet potato'
click_on 'Search'
expect(current_path).to eq(foods_path)
expect(page).to have_content('Total foods found: 46320')
expect(page).to have_content("GTIN/UPC: 819614010394")
expect(page).to have_content("Brand: Country Sweet Produce")
expect(page).to have_content("Description: SWEET POTATO")
expect(page).to have_content("Ingredients: SWEET POTATOES")
end
end
<file_sep>/app/services/food_service.rb
class FoodService
def self.conn
Faraday.new(url: "https://api.nal.usda.gov", params: {api_key: ENV['food_data_key']})
end
def self.foods_with_ingredient(search)
response = conn.get("/fdc/v1/foods/search") do |req|
req.params['query'] = search
end
JSON.parse(response.body, symbolize_names: true)
end
end
<file_sep>/spec/facades/food_facade_spec.rb
require 'rails_helper'
RSpec.describe FoodFacade do
it 'returns a list of foods by search' do
foods_results = FoodFacade.food_search('sweet potato')
expect(foods_results).to be_a(Hash)
expect(foods_results).to have_key(:total_hits)
expect(foods_results[:total_hits]).to be_an(Integer)
expect(foods_results).to have_key(:foods)
expect(foods_results[:foods].count).to eq(10)
expect(foods_results[:foods].first).to be_a(FoodItem)
end
end
<file_sep>/app/facades/food_facade.rb
class FoodFacade
def self.food_search(search)
json = FoodService.foods_with_ingredient(search)
foods = json[:foods].map do |food|
FoodItem.new(food)
end
{
total_hits: json[:totalHits],
foods: foods.take(10)
}
end
end
<file_sep>/app/controllers/foods_controller.rb
class FoodsController < ApplicationController
def index
@foods_results = FoodFacade.food_search(params[:q])
end
end
|
8230168aecf6a200f4ddb3dcd00a2ee478f9e108
|
[
"Ruby"
] | 8
|
Ruby
|
eakischuk/whats-in-my-food
|
4a59f61e4f5bf5da720efcdb6dc52a9e48e4e7bd
|
bb5c3c0065514e6eb789514de4bdd6e43b3b5b87
|
refs/heads/master
|
<repo_name>eNzyOfficial/KissAutoplay<file_sep>/src/bg/background.js
chrome.omnibox.onInputEntered.addListener(function(text) {
let searchURL = '';
switch(text.substr(0,text.indexOf(' '))) {
default:
case "anime":
case "a":
searchURL += 'https://kissanime.ac/Search/?s=';
break;
case "cartoon":
case "c":
searchURL += 'https://kisscartoon.ac/Search/?s=';
break;
}
searchURL += encodeURIComponent(text.substr(text.indexOf(' ')+1));
chrome.tabs.create({ url: searchURL });
});<file_sep>/src/inject/inject.js
chrome.extension.sendMessage({}, function(response) {
let readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
const offlight = document.getElementById('offlight');
let player = document.getElementById('player_html5_html5_api');
let exited_fullscreen = false;
const default_style = () => {
offlight.style.setProperty('z-index', '999999');
offlight.click();
player.style.setProperty('position', '');
player.style.setProperty('object-fit', 'contain');
player.style.setProperty('background', 'transparent');
player.style.setProperty('z-index', '0');
player.removeAttribute("controls");
document.body.style.setProperty('overflow', 'auto');
exited_fullscreen = true;
}
const fullscreen_style = () => {
offlight.style.setProperty('z-index', '0');
offlight.click();
player.style.setProperty('position', 'fixed');
player.style.setProperty('background', 'black');
player.style.setProperty('z-index', '999999');
player.setAttribute("controls","controls");
chrome.storage.sync.get('kiss.settings.fullscreen_stretch', function(val) {
if (val['kiss.settings.fullscreen_stretch']) {
player.style.setProperty('object-fit', 'fill');
}
else {
player.style.setProperty('object-fit', 'contain');
}
});
document.body.style.setProperty('overflow', 'hidden');
exited_fullscreen = false;
}
const set_fullscreen = () => {
chrome.storage.sync.get('kiss.settings.fullscreen', function(val) {
if (val['kiss.settings.fullscreen']) {
fullscreen_style();
}
else {
default_style();
}
});
}
const is_playing = () => {
const previous = window.localStorage.getItem('autoPlayingBefore');
window.localStorage.removeItem('autoPlayingBefore');
const [previous_btn] = document.getElementsByClassName('preev');
return previous_btn.href === previous;
};
const autoplay = () => {
chrome.storage.sync.get('kiss.settings.stutter_fix', function(val) {
let fix_stutter = val['kiss.settings.stutter_fix'];
player.addEventListener('ended', () => {
let loc = location.href;
loc += (fix_stutter) ? '&pfail=1' : '';
window.localStorage.setItem('autoPlayingBefore', loc);
loc = document.getElementsByClassName('nexxt')[0].href;
loc += (fix_stutter) ? '&pfail=1' : '';
window.location.href = loc;
}, false);
});
}
const volume = () => {
chrome.storage.sync.get('kiss.settings.save_volume', function(val) {
if (val['kiss.settings.save_volume']) {
player.volume = (window.localStorage.getItem('volume') || 1.0);
}
});
}
const init = () => {
document.addEventListener('keyup', ({keyCode}) => {
if (keyCode === 27) {
exited_fullscreen ? fullscreen_style() : default_style();
}
});
player = document.getElementById('player_html5_html5_api');
if (player) {
player.addEventListener('volumechange', () => {
window.localStorage.setItem('volume', player.volume);
});
volume();
set_fullscreen();
autoplay();
}
}
setTimeout(() => {
init();
}, 1000);
}
}, 10);
});
|
face4ab2b1297b4e2e4a01540118290ee03f4c65
|
[
"JavaScript"
] | 2
|
JavaScript
|
eNzyOfficial/KissAutoplay
|
6fca8dcb407fe535a767150a244a66e18c8b1559
|
a80bb56d6de0e124204eb4737def61496639160e
|
refs/heads/master
|
<file_sep>using MahApps.Metro.Controls;
using NastoiModels;
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.Navigation;
using System.Windows.Shapes;
namespace NastoiList
{
/// <summary>
/// Логика взаимодействия для NastoiConstructor_s2.xaml
/// </summary>
public partial class NastoiConstructor_s2 : UserControl
{
private IList<Herb> _herbList = new List<Herb>();
public NastoiConstructor_s2(IList<Herb> list)
{
_herbList = list;
InitializeComponent();
foreach (var h in list)
{
var dp = new DockPanel() { LastChildFill = true, Margin = new Thickness(15, 0, 15, 0) };
var ell = new Ellipse() { Width = 15, Height = 15 };
ell.Margin = new Thickness(5);
DockPanel.SetDock(ell, Dock.Right);
var scb = new SolidColorBrush(new Color() { A = h.RGBColor.A, B = h.RGBColor.B, G = h.RGBColor.G, R = h.RGBColor.R });
ell.Fill = scb;
var l = new Label() { Content = h.Name };
dp.Children.Add(ell);
dp.Children.Add(l);
nastoiConsist.Children.Add(dp);
}
}
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
MetroWindow mw = new MetroWindow();
mw.Content = new NastoiConstructor_s3(_herbList, volumeSlider.Value);
mw.Show();
}
private void PrevButton_Click(object sender, RoutedEventArgs e)
{
}
}
}
<file_sep>
namespace ColorModel
{
public class HSVColor
{
public float H { get; set; }
public float S { get; set; }
public float V { get; set; }
}
}
<file_sep>using ColorModel;
using MahApps.Metro.Controls;
using NastoiList.SupportUserControlsAndWindows;
using NastoiModels;
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 Xceed.Wpf.Toolkit;
namespace NastoiList
{
/// <summary>
/// Логика взаимодействия для MixResultWindow.xaml
/// </summary>
public partial class MixResultWindow : MetroWindow
{
public MixResultWindow(List<NastoiModel> mixList, RGBColor resColor)
{
InitializeComponent();
mixColorsView.Width = Application.Current.MainWindow.Width - 20;
foreach (var h in mixList)
{
var c = new RGBColorControl();
c.Margin = new Thickness(10);
c.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
c.RGB_R_Value.Content = h.Description.MainHerb.RGBColor.R;
c.RGB_G_Value.Content = h.Description.MainHerb.RGBColor.G;
c.RGB_B_Value.Content = h.Description.MainHerb.RGBColor.B;
var s = new StackPanel()
{
Background = new SolidColorBrush(Color.FromRgb(h.Description.MainHerb.RGBColor.R, h.Description.MainHerb.RGBColor.G, h.Description.MainHerb.RGBColor.B)),
Width = mixColorsView.Width / mixList.Count,
ToolTip = h.Name,
};
s.Children.Add(new Label() { Content = h.Name, FontSize = 20, FontWeight = FontWeights.Bold, HorizontalAlignment = System.Windows.HorizontalAlignment.Center});
s.Children.Add(c);
mixColorsView.Children.Add(s);
}
this.resColor.Fill = new SolidColorBrush(Color.FromRgb(resColor.R, resColor.G,resColor.B));
this.RGB_R_Value.Content = resColor.R;
this.RGB_G_Value.Content = resColor.G;
this.RGB_B_Value.Content = resColor.R;
this.HSV_H_Value.Content = resColor.ToHSV().H;
this.HSV_S_Value.Content = resColor.ToHSV().S;
this.HSV_V_Value.Content = resColor.ToHSV().V;
colorCanvas.A = 255;
colorCanvas.R = resColor.R;
colorCanvas.G = resColor.G;
colorCanvas.B = resColor.B;
}
}
}
<file_sep>
namespace NastoiModels
{
public class NastoiDescrition
{
public string LatinName { get; set; }
public string Consists { get; set; }
public Herb MainHerb { get; set; }
public string Indication { get; set; }
public string ContraIndication { get; set; }
public string Dozage { get; set; }
public string StorageCondiditons { get; set; }
public string Manufacturer { get; set; }
public string ImageURL { get; set; }
}
}
<file_sep>using NastoiModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ColorMixer
{
public class ColorMixerModel
{
public NastoiModel Nastoi { get; set; }
public int Count { get; set; }
}
}
<file_sep>using ColorModel;
using NastoiModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ColorMixer
{
public static class ColorMixer
{
public static RGBColor Mix(List<NastoiModel> nastois)
{
double red = 0.0, green = 0.0, blue = 0.0;
if (nastois.Count > 0)
{
foreach (var n in nastois)
{
red += n.Description.MainHerb.RGBColor.R;
green += n.Description.MainHerb.RGBColor.G;
blue += n.Description.MainHerb.RGBColor.B;
}
red /= nastois.Count;
green /= nastois.Count;
blue /= nastois.Count;
red = Math.Min(red, 255);
green = Math.Min(green, 255);
blue = Math.Min(blue, 255);
return new RGBColor() { A = 255, R = Convert.ToByte(red), G = Convert.ToByte(green), B = Convert.ToByte(blue) };
}
else
{
return nastois[0].Description.MainHerb.RGBColor;
}
}
public static RGBColor Mix(List<ColorMixerModel> nastois)
{
List<NastoiModel> res = new List<NastoiModel>();
if (nastois.Count > 0)
{
foreach (var n in nastois)
{
for (int i = 0; i < n.Count; i++)
{
res.Add(n.Nastoi);
}
}
return Mix(res);
}
else
{
return nastois[0].Nastoi.Description.MainHerb.RGBColor;
}
}
}
}
<file_sep>using MahApps.Metro.Controls;
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 ColorWheel.Core;
using ColorModel;
using NastoiModels;
namespace NastoiList.SupportUserControlsAndWindows
{
public class ColorMapItemModel
{
public Point point { get; set; }
public NastoiModel MainHerb { get; set; }
}
public partial class ColorMapWindow : MetroWindow
{
private List<ColorMapItemModel> items = new List<ColorMapItemModel>();
public ColorMapWindow()
{
InitializeComponent();
}
public ColorMapWindow(List<NastoiModel> colors)
{
InitializeComponent();
var startPoint = (colorWheelImage.Width - 10) / 2;
Ellipse w = new Ellipse();
w.Height = 15;
w.Width = 15;
w.ToolTip = "0";
w.Stroke = new SolidColorBrush(Colors.Black);
w.StrokeThickness = 10;
Canvas.SetLeft(w, startPoint);
Canvas.SetTop(w, startPoint);
colorWheel.Children.Add(w);
foreach (var c in colors)
{
Ellipse e = new Ellipse();
e.Height = 15;
e.Width = 15;
e.Fill = new SolidColorBrush(
new Color()
{
R = c.Description.MainHerb.RGBColor.R,
G = c.Description.MainHerb.RGBColor.G,
B = c.Description.MainHerb.RGBColor.B,
A = 255
}
);
e.Stroke = new SolidColorBrush(Colors.Black);
e.ToolTip = c.Name;
HSVColor c2 = c.Description.MainHerb.RGBColor.ToHSV();
var distance = c2.S * startPoint;
var angle = c2.H;
var newY = Math.Sin(angle) * distance;
var newX = Math.Cos(angle) * distance;//(distance + ((c2.V * 100) / 255)
var p = new Point();
#region blabla
if(angle == 0)
{
Canvas.SetLeft(e, newY + startPoint);
Canvas.SetTop(e, newX - startPoint);
p.Y = newY + startPoint;
p.X = newX - startPoint;
}
else if (angle >= 1 && angle <= 90)
{
if (newY + startPoint < startPoint)
{
var a = startPoint + newY;
Canvas.SetLeft(e, a + startPoint);
p.Y = a + startPoint;
}
else
{
Canvas.SetLeft(e, newY + startPoint);
p.Y = newY + startPoint;
}
if (newX + startPoint > startPoint)
{
Canvas.SetTop(e, newX);
p.X = newX;
}
else
{
Canvas.SetTop(e, newX + startPoint);
p.X = newX + startPoint;
}
}
else if (angle >= 91 && angle <= 180)
{
if (newY + startPoint > 350)
{
Canvas.SetTop(e, newY + startPoint);
p.Y = newY + startPoint;
}
else
{
Canvas.SetTop(e, newY + startPoint);
}
if (newX < 0)
{
Canvas.SetLeft(e, startPoint + Math.Abs(newX));
p.X = startPoint + Math.Abs(newX);
}
else
{
Canvas.SetLeft(e, newX + startPoint);
p.X = startPoint + startPoint;
}
}
else if (angle >= 181 && angle <= 270)
{
if (newX + startPoint > startPoint)
{
var a = newX - startPoint;
Canvas.SetLeft(e, newX - startPoint);
p.X = newY - startPoint;
}
else
{
Canvas.SetLeft(e, newX);
p.X = newX - startPoint;
}
if (newY + startPoint < startPoint)
{
var a = startPoint + newY;
Canvas.SetTop(e, a + startPoint);
p.Y = a + startPoint;
}
else
{
Canvas.SetTop(e, newY + startPoint);
p.Y = newY + startPoint;
}
}
else if (angle >= 271 && angle <= 359)
{
if (newY > 0)
{
Canvas.SetLeft(e, startPoint - newY);
p.Y = startPoint - newY;
}
else
{
Canvas.SetLeft(e, newY + startPoint);
p.Y = startPoint + newY;
}
if (newX < 0)
{
Canvas.SetTop(e, startPoint - Math.Abs(newX));
p.X = startPoint - Math.Abs(newX);
}
else if (newX < startPoint)
{
Canvas.SetTop(e, startPoint - newX);
p.X = startPoint - newX;
}
else
{
Canvas.SetTop(e, newX);
p.X = newX;
}
}
#endregion
colorWheel.Children.Add(e);
items.Add(new ColorMapItemModel() { MainHerb = c, point = p });
}
Line l = new Line();
l.Fill = new SolidColorBrush(Colors.Bisque);
l.X1 = items[6].point.Y-7.5;
l.Y1 = items[6].point.X + 7.5;
l.X2 = items[15].point.Y - 7.5;
l.Y2 = items[15].point.X + 7.5;
l.Stroke = Brushes.Black;
l.StrokeThickness = 5;
colorWheel.Children.Add(l);
}
}
}
<file_sep>using System;
using System.Xml.Serialization;
namespace NastoiModels
{
[Serializable]
public class NastoiModel
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("price")]
public double Price { get; set; }
[XmlElement("href")]
public string Href { get; set; }
public string Type { get; set; }
public NastoiDescrition Description { get; set; }
}
}
<file_sep>using MahApps.Metro.Controls;
using NastoiModels;
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;
namespace NastoiList
{
/// <summary>
/// Логика взаимодействия для NastoiConstructor.xaml
/// </summary>
public partial class NastoiConstructor_s1 : MetroWindow
{
IList<string> _volumes = new List<string>();
List<Herb> _herbs = new List<Herb>();
public NastoiConstructor_s1()
{
InitializeComponent();
}
private void flowerList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
//var a = (flowerList.SelectedItem as ListBoxItem).Content as DockPanel;
//var s = a.Children[1] as Label;
//bool addingFlag = true;
//if (newNastoiConsist.Children.Count != 0)
//{
// foreach(var i in newNastoiConsist.Children)
// {
// if(((i as DockPanel).Children[1] as Label).Content == s.Content)
// {
// MessageBox.Show("Такой компонент уже добавлен!");
// addingFlag = false;
// }
// }
//}
//if (addingFlag)
//{
// var label = new Label() { Content = s.Content as string, Margin = new Thickness(15, 0,15,0), VerticalAlignment = System.Windows.VerticalAlignment.Center};
// var dock = new DockPanel() { LastChildFill = true };
// //var cbx = new ComboBox() { Margin = new Thickness(10) };
// //cbx.Items.Add(new ComboBoxItem() { Content = "10 %" });
// //cbx.Items.Add(new ComboBoxItem() { Content = "20 %" });
// //cbx.Items.Add(new ComboBoxItem() { Content = "30 %" });
// //cbx.Items.Add(new ComboBoxItem() { Content = "40 %" });
// //cbx.Items.Add(new ComboBoxItem() { Content = "50 %" });
// var tmp = new Slider() { Width = 200, Minimum = 1, Maximum = 99/(newNastoiConsist.Children.Count - 1), Value = 10, Interval = 5, IsSnapToTickEnabled = true, TickFrequency = 1, AutoToolTipPlacement = System.Windows.Controls.Primitives.AutoToolTipPlacement.BottomRight };
// DockPanel.SetDock(tmp, Dock.Right);
// dock.Children.Add(tmp);
// dock.Children.Add(label);
// newNastoiConsist.Children.Add(dock);
// resultColor.Fill = (a.Children[0] as Ellipse).Fill;
//}
}
private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
{
flowerList.Items.Clear();
FileExtract fe = new FileExtract();
_herbs = fe.GetHerbs();
(_herbs as List<Herb>).Sort(delegate(Herb left, Herb right)
{
return left.RGBColor.CompareTo(right.RGBColor);
});
foreach (var h in _herbs)
{
var lbi = new ListBoxItem() { Margin = new Thickness(15, 0, 15, 0) };
var dp = new DockPanel() { LastChildFill = true };
var ell = new Ellipse() { Width = 15, Height = 15 };
ell.Margin = new Thickness(5);
DockPanel.SetDock(ell, Dock.Right);
var scb = new SolidColorBrush(new Color() { A = h.RGBColor.A, B = h.RGBColor.B, G = h.RGBColor.G, R = h.RGBColor.R });
ell.Fill = scb;
var l = new Label() { Content = h.Name };
dp.Children.Add(ell);
dp.Children.Add(l);
lbi.Content = dp;
flowerList.Items.Add(lbi);
}
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
if (flowerList.SelectedItems.Count != 0)
{
var selecdetItems = flowerList.SelectedItems;
//MetroWindow mw = new MetroWindow();
content.Content = new NastoiConstructor_s2(GetSelectedItems(selecdetItems));
//mw.Show();
//this.Close();
}
else
{
MessageBox.Show("Ничего не выбрано!");
}
}
private IList<Herb> GetSelectedItems(System.Collections.IList i)
{
List<Herb> res = new List<Herb>();
foreach(var item in i)
{
var lbi = item as ListBoxItem;
var dp = lbi.Content as DockPanel;
var l = (dp.Children[1] as Label).Content as string;
res.Add(_herbs.FirstOrDefault(r => r.Name == l));
}
return res;
}
}
}
<file_sep>using ColorModel;
using HtmlAgilityPack;
using NastoiModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Xml.Serialization;
namespace NastoiList
{
public class FileExtract
{
public List<Herb> GetHerbs()
{
var res = new List<Herb>();
string line;
using (System.IO.StreamReader file = new System.IO.StreamReader("Herbs.txt", Encoding.Default))
{
while ((line = file.ReadLine()) != null)
{
var strs = line.Split(new string[] { "'" }, StringSplitOptions.RemoveEmptyEntries);
var rgb = strs[5].Split(new string[] { "{", "}", "," }, StringSplitOptions.RemoveEmptyEntries);
var name = strs[9];
res.Add(new Herb() { Name = name, RGBColor = new RGBColor() { A = 255, R = Convert.ToByte(rgb[0]), G = Convert.ToByte(rgb[1]), B = Convert.ToByte(rgb[2]) } });
}
}
return res;
}
public static List<NastoiModel> GetFitoaptekaNastoiList()
{
List<NastoiModel> nastoi = new List<NastoiModel>();
//string line;
//System.IO.StreamReader file = new System.IO.StreamReader("pages.txt");
//while ((line = file.ReadLine()) != null)
//{
// Console.WriteLine(line);
// string urlAddress = line;
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
// HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// if (response.StatusCode == HttpStatusCode.OK)
// {
// Stream receiveStream = response.GetResponseStream();
// StreamReader readStream = null;
// if (response.CharacterSet == null)
// {
// readStream = new StreamReader(receiveStream);
// }
// else
// {
// readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
// }
// string data = readStream.ReadToEnd();
// //var strs = data.Split(new string[] {"<",">"," ", "\""}, StringSplitOptions.RemoveEmptyEntries);
// HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
// doc.LoadHtml(data);
// HtmlAgilityPack.HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@id='produce']");
// foreach (HtmlNode link in node.ChildNodes)
// {
// if (link.HasChildNodes)
// {
// HtmlAgilityPack.HtmlDocument doc2 = new HtmlAgilityPack.HtmlDocument();
// doc2.LoadHtml(link.InnerHtml);
// HtmlAgilityPack.HtmlNodeCollection node2 = doc2.DocumentNode.SelectNodes("//p");
// var name = node2[0];
// var price = node2[1];
// nastoi.Add(new Nastoi()
// {
// Name = name.ChildNodes[1].InnerText,
// Href = "http://fitoapteka.com" + name.ChildNodes[1].Attributes.FirstOrDefault(r => r.Name == "href").Value,
// Price = Convert.ToDouble(price.InnerText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0])
// });
// //foreach (HtmlNode a in node2)
// //{
// // nastoi.Add(new Nastoi() { Name = a.InnerText });
// // Console.WriteLine(a.InnerText);
// // break;
// //}
// }
// }
// response.Close();
// readStream.Close();
// }
//}
//file.Close();
var ser = new XmlSerializer(typeof(List<NastoiModel>));
TextReader reader = new StreamReader(@"nastoiList.xml");
nastoi = ser.Deserialize(reader) as List<NastoiModel>;
foreach(var n in nastoi)
{
n.Type = "Фитоаптека";
if (n.Name == "Алоэ сок 50мл " ||
n.Name == "Белокопытник настойка корня 50 мл " ||
n.Name == "Годжи настойка ягод 100мл " ||
n.Name == "Зизифус (унаби) настойка плодов 100мл " ||
n.Name == "Какалия настойка травы 50мл " ||
n.Name == "Каланхоэ сок 20мл " ||
n.Name == "Лавр настойка листьев 50мл " ||
n.Name == "Настойка пчелиного подмора " ||
n.Name == "Настойка серебристой восковой моли " ||
n.Name == "Пантокрин настойка 100мл " ||
n.Name == "Роза крымская настойка цвет 50мл " ||
n.Name == "Сныть настойка корня,травы 100мл " ||
n.Name == "Чистец лесной настойка травы 50мл " ||
n.Name == "Кордицепс капли 50мл " ||
n.Name == "Лисички капли 50мл " ||
n.Name == "Рейши капли 50мл " ||
n.Name == "Шиитаке капли 50мл ")
{
continue;
}
//SaveNastoiImage(n.Href);
}
return nastoi;
}
public static void SaveNastoiImage(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
}
string data = readStream.ReadToEnd();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(data);
HtmlAgilityPack.HtmlNode productImageNode = doc.DocumentNode.SelectSingleNode("//div[@id='product_image']");
HtmlAgilityPack.HtmlNode productDescriptionNode = doc.DocumentNode.SelectSingleNode("//div[@id='description_product']");
var imageHrefNode = productImageNode.ChildNodes.FirstOrDefault(r => r.Name == "a");
if (imageHrefNode.HasAttributes)
{
WebClient wc = new WebClient();
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("http://fitoapteka.com" + imageHrefNode.Attributes["href"].Value);
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream2 = response2.GetResponseStream();
StreamReader readStream2 = null;
if (response2.CharacterSet == null)
{
readStream2 = new StreamReader(receiveStream2);
}
else
{
readStream2 = new StreamReader(receiveStream2, Encoding.GetEncoding(response2.CharacterSet));
}
string data2 = readStream2.ReadToEnd();
HtmlAgilityPack.HtmlDocument doc3 = new HtmlDocument();
doc3.LoadHtml(data2);
var tmp = doc3.DocumentNode.SelectSingleNode("//img");
try
{
wc.DownloadFile("http://fitoapteka.com/" + tmp.Attributes["src"].Value, "images/" + imageHrefNode.Attributes["title"].Value + ".jpg");
Thread.Sleep(1000);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
readStream2.Close();
}
response2.Close();
}
response.Close();
readStream.Close();
}
}
}
}
<file_sep>using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace FitoaptekaParser
{
[Serializable]
public class Nastoi
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("price")]
public double Price { get; set; }
[XmlElement("href")]
public string Href { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Nastoi> nastoi = new List<Nastoi>();
string line;
System.IO.StreamReader file = new System.IO.StreamReader("pages.txt");
while ((line = file.ReadLine()) != null)
{
Console.WriteLine(line);
string urlAddress = line;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
}
string data = readStream.ReadToEnd();
//var strs = data.Split(new string[] {"<",">"," ", "\""}, StringSplitOptions.RemoveEmptyEntries);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(data);
HtmlAgilityPack.HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@id='produce']");
foreach(HtmlNode link in node.ChildNodes)
{
if(link.HasChildNodes)
{
HtmlDocument doc2 = new HtmlDocument();
doc2.LoadHtml(link.InnerHtml);
HtmlAgilityPack.HtmlNodeCollection node2 = doc2.DocumentNode.SelectNodes("//p");
var name = node2[0];
var price = node2[1];
nastoi.Add(new Nastoi() {
Name = name.ChildNodes[1].InnerText,
Href = "http://fitoapteka.com" + name.ChildNodes[1].Attributes.FirstOrDefault(r=> r.Name=="href").Value,
Price = Convert.ToDouble(price.InnerText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0]) });
//foreach (HtmlNode a in node2)
//{
// nastoi.Add(new Nastoi() { Name = a.InnerText });
// Console.WriteLine(a.InnerText);
// break;
//}
}
}
response.Close();
readStream.Close();
}
}
file.Close();
var ser = new XmlSerializer(typeof(List<Nastoi>));
TextWriter writer = new StreamWriter(@"nastoiList.xml");
ser.Serialize(writer, nastoi);
}
}
}
<file_sep>using Npgsql;
using System;
namespace DatabaseManager
{
public class DBManager
{
public DBManager()
{
try
{
// PostgeSQL-style connection string
string connstring = String.Format("Server={0};Port={1};" +
"User Id={2};Password={3};Database={4};",
"localhost", "5432", "postgres",
"123456", "rezonansHerbs");
// Making connection with Npgsql provider
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
// quite complex sql statement
string sql = "SELECT * FROM indication";
// data adapter making request from our connection
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
var s = string.Format("{0}\t{1} \n", dr[0], dr[1]);
}
conn.Close();
}
catch (Exception msg)
{
// something went wrong, and you wanna know why
throw;
}
}
}
}
<file_sep>using System;
namespace ColorModel
{
public class RGBColor : IComparable
{
public byte R { get; set; }
public byte G { get; set; }
public byte B { get; set; }
public byte A { get; set; }
public int CompareTo(object ob)
{
var r = ob as RGBColor;
//(0.2126 * r.R + 0.7152 * r.B + 0.0722 * r.B); от холодного к теплому
//sqrt( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 ) сотритует цвета по яркости, от черного к желтому
//( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 ) сортирует по насыщености цвета
double c1 = Math.Sqrt(Math.Pow(0.299 * this.R, 2) + Math.Pow(0.587 * this.G, 2) + Math.Pow(0.114 * this.B, 2));
double c2 = Math.Sqrt(Math.Pow(0.299 * r.R, 2) + Math.Pow(0.587 * r.G, 2) + Math.Pow(0.114 * r.B, 2));
//return c1.CompareTo(c2);
return this.ToHSV().H.CompareTo(r.ToHSV().H); // сортирует по HSV модели. почти точно
}
public HSVColor ToHSV()
{
HSVColor res = new HSVColor();
float min, max, delta;
min = Math.Min(this.R, Math.Min(this.G, this.B));
max = Math.Max(this.R, Math.Max(this.G, this.B));
res.V = max;
delta = max - min;
if (max != 0)
{
res.S = delta / max; // s
}
else
{
// r = g = b = 0 // s = 0, v is undefined
res.S = 0;
res.H = -1;
return res;
}
if(delta == 0)
{
res.H = 0;
}
if (this.R == max)
res.H = ((this.G - this.B) / delta)%6; // between yellow & magenta
else if (this.G == max)
res.H = 2 + (this.B - this.R) / delta; // between cyan & yellow
else
res.H = 4 + (this.R - this.G) / delta; // between magenta & cyan
res.H *= 60; // degrees
if (res.H < 0)
res.H += 360;
return res;
}
}
}
<file_sep>using ColorModel;
namespace NastoiModels
{
public class Herb
{
public string Name { get; set; }
public RGBColor RGBColor { get; set; }
public string ImageURL { get; set; }
}
}
|
b0515499369c4eeb029807aa58d1b550e4fbd2d0
|
[
"C#"
] | 14
|
C#
|
yuramanzyuk/nastoiList
|
ef719517f028cbdc71d1e9661ce0bfb71963ae7e
|
da81998fbe5b3ef00fe223a8b6930d3cf599a908
|
refs/heads/master
|
<file_sep>from flask import Flask, render_template, request, redirect
import requests
import json
import pandas as pd
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, RangeTool, HoverTool, CrosshairTool
from bokeh.layouts import column
from bokeh.io import show
from bokeh.embed import components
from bokeh.resources import CDN
app = Flask(__name__)
# api_key = U1XTGOBRHDKLZ1G4
def bokeh_plot(df):
dates = df['Date']
source = ColumnDataSource(data={
'date': dates,
'close': df['Adj_Close'],
'high': df['High'],
'low': df['Low'],
'volume': df['Adj_Volume']
})
p = figure(title="Drag to change range", plot_height=300, plot_width=700, tools="xpan", toolbar_location=None,
x_axis_type="datetime", x_axis_location="below", sizing_mode="scale_width",
background_fill_color="#f5f5f5", x_range=(dates[len(dates)-300], dates[len(dates)-1]))
hover_tool = HoverTool(
tooltips=[
('Date', '@date{%F}'), # use @{ } for field names with spaces
('Close', '$@close{%0.2f}'),
('High', '$@high{%0.2f}'),
('Low', '$@low{%0.2f}'),
('Volume', '@volume{0.00 a}'),
],
formatters={
'date': 'datetime', # use 'datetime' formatter for 'date' field
'close': 'printf', # use 'printf' formatter for 'adj close' field
'high': 'printf',
'low': 'printf'
# use default 'numeral' formatter for other fields
},
# display a tooltip whenever the cursor is vertically in line with a glyph
mode='vline'
)
# cross_tool = CrosshairTool()
p.add_tools(hover_tool)
p.line('date', 'close', source=source)
p.yaxis.axis_label = 'Price'
select = figure(title="Drag to change the range",
plot_height=130, plot_width=930, y_range=p.y_range,
x_axis_type="datetime", y_axis_type=None, sizing_mode="scale_width",
tools="", toolbar_location=None, background_fill_color="#f5f5f5")
range_tool = RangeTool(x_range=p.x_range)
range_tool.overlay.fill_color = "navy"
range_tool.overlay.fill_alpha = 0.2
select.line('date', 'close', source=source)
select.ygrid.grid_line_color = "white"
select.add_tools(range_tool)
select.toolbar.active_multi = range_tool
c = column(p, select)
script, div = components(p)
return script, div
@app.route('/', methods=['GET'])
def index():
# if request.method == 'GET':
# ticker = defualt_ticker
# else:
# ticker = request.form['ticker']
# app.logger.info("ticker is {}".format(ticker))
return render_template('index.html')
@app.route('/graph', methods=['POST'])
def graph():
ticker = request.form['ticker']
url = "https://www.quandl.com/api/v3/datasets/EOD/{}.json?api_key=<KEY>".format(
str(ticker).upper())
response = requests.get(url)
if response.status_code == 200:
# with open(ticker.upper()+".json", 'w') as output:
# json.dump(response.json(), output)
# message = "some info about ticker {}".format(ticker)
data = response.json()['dataset']
df = pd.DataFrame(data['data'], columns=data['column_names'])
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
df = df.sort_values(by=['Date'], ascending=True).reset_index(drop=True)
script, div = bokeh_plot(df)
# return json.dumps(json_item(plot, "plot"))
message = ticker.upper()
app.logger.info(div)
return render_template('index.html', msg=message, script=script, div=div)
elif response.status_code == 403:
message = "Sorry, this ticker is not yet supported. Please try another one."
return render_template('index.html', msg=message)
else:
message = "Invalid ticker! Please try another one."
return render_template('index.html', msg=message)
if __name__ == '__main__':
app.run(debug=True)
<file_sep># Stock Lookup [Flask x Bokeh]
This is a simple stock lookup tool that displays the historic daily closing price of your ticker of choice.
Deployed on Heroku [here][https://pyboken-stock-picker.herokuapp.com/] if you want to play with it.
This repo contains the code that can reproduce this app ready for Heroku deployment.
### The virtual environment
- This repo uses `pipenv` to manage its virtual environment. All dependencies are stored in the `Pipfile` and `Pipfile.lock`.
They can be used by Heroku directly, but if you prefer the good old requirement.txt file, you can generate it by using the `pipenv lock -r` command.
- The `Procfile` contains settings to be used by Heroku.
- There is some boilerplate HTML in `templates/`
### The data
- Data for the stock information are pulled from Quandl's [End of Day US Stock Prices][https://www.quandl.com/data/EOD-End-of-Day-US-Stock-Prices].
The free tier account can only access a small sample of the entire database, so not all tickers are available.
- The app will parse the json file obtained from Quandl's api and turn the json file into pandas dataframe for further analysis.
### The app
- The app is built with Bokeh, a python library that provides interactive plots and graphs. It enables many abilities such as hover-over tool tips, drag and zoom, and etc. without having to write javascript.
### Next steps / TODO
- 1. Explore other free libraries that have a larger inclusion of stocks
- 2. Autocomplete
- 3. Zoom ability on different time frame (1D, 1M, 1Y, 5Y, Max)
<file_sep>from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, RangeTool, HoverTool, CrosshairTool
from bokeh.layouts import column
from bokeh.io import show
from bokeh.embed import components
import requests
import json
import pandas as pd
api_key = "<KEY>"
end_pt = "https://www.quandl.com/api/v3/datasets/EOD/"
# https://www.quandl.com/api/v3/datasets/EOD/AAPL.csv?api_key=<KEY>
response = requests.get(
"https://www.quandl.com/api/v3/datasets/EOD/AAPL.json?api_key=<KEY>")
# print(response.headers.get('Content-Type'))
# with open("aapl.json", 'w') as output:
# json.dump(response.json(), output)
data = response.json()['dataset']
df = pd.DataFrame(data['data'], columns=data['column_names'])
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
df = df.sort_values(by=['Date'], ascending=True).reset_index(drop=True)
# print(df)
# df = df.set_index('Date')
# dates = np.array(AAPL['date'], dtype=np.datetime64)
# source = ColumnDataSource(data=dict(date=dates, close=AAPL['adj_close']))
dates = df['Date']
# source = ColumnDataSource(data=dict(date=dates, close=df['Adj_Close']))
source = ColumnDataSource(data={
'date': dates,
'close': df['Adj_Close'],
'high': df['High'],
'low': df['Low'],
'volume': df['Adj_Volume']
})
hover_tool = HoverTool(
tooltips=[
('Date', '@date{%F}'), # use @{ } for field names with spaces
('Close', '$@close{%0.2f}'),
('High', '$@high{%0.2f}'),
('Low', '$@low{%0.2f}'),
('Volume', '@volume{0.00 a}'),
],
formatters={
'date': 'datetime', # use 'datetime' formatter for 'date' field
'close': 'printf', # use 'printf' formatter for 'adj close' field
'high': 'printf',
'low': 'printf'
# use default 'numeral' formatter for other fields
},
# display a tooltip whenever the cursor is vertically in line with a glyph
mode='vline'
)
# cross_tool = CrosshairTool()
p = figure(plot_height=500, plot_width=800, tools="xpan", toolbar_location=None, x_axis_type="datetime", x_axis_location="below",
sizing_mode="scale_width", background_fill_color="#efefef", x_range=(dates[800], dates[1000]))
p.add_tools(hover_tool)
p.line('date', 'close', source=source)
p.yaxis.axis_label = 'Price'
select = figure(title="Drag the middle and edges of the selection box to change the range above",
plot_height=130, plot_width=800, y_range=p.y_range,
x_axis_type="datetime", y_axis_type=None,
tools="", toolbar_location=None, background_fill_color="#efefef")
range_tool = RangeTool(x_range=p.x_range)
range_tool.overlay.fill_color = "navy"
range_tool.overlay.fill_alpha = 0.2
select.line('date', 'close', source=source)
select.ygrid.grid_line_color = "white"
select.add_tools(range_tool)
select.toolbar.active_multi = range_tool
script, div = components(p)
ids = div.split("\"")
div_id = ids[3]
data_root_id = ids[5]
print(id[5])
# show(column(p, select))
|
3cc89e7fe92be93801ebaab802c4e4df6a64e4e1
|
[
"Markdown",
"Python"
] | 3
|
Python
|
alssica/pyBoken-stock-picker
|
4513e3880cebf6db666b168bf12c6c934451e2dd
|
218b14f6a34a758f96100571fcad4a23c5718076
|
refs/heads/master
|
<repo_name>giangnhattruong/warbler_frontend<file_sep>/src/store/reducers/currentUser.js
import { SET_CURRENT_USER } from "../actionTypes";
// after a user logged in, they will be authenticated
// and we will see all of their info
// when they log out, we change the state back to it's default
const DEFAULT_USER_STATE = {
isAuthenticated: false,
user: {}
}
const currentUser = (state=DEFAULT_USER_STATE, action) => {
switch(action.type) {
case SET_CURRENT_USER:
return {
...state,
// "!!" turn 0 into false, any other number into true
// is works the same as Object.keys(action.user).length !== 0
// if user log out, we run SET_CURRENT_USER again, then user will be set as {} so isAuthenticated become false
// so we don't need action LOG_OUT
isAuthenticated: !!Object.keys(action.user).length,
user: action.user
}
default:
return state
}
};
export default currentUser;<file_sep>/src/components/Homepage.js
import React from 'react';
import {Link} from "react-router-dom";
import MessageTimeline from './MessageTimeline';
const Homepage = ({currentUser}) => {
if(!currentUser.isAuthenticated) {
return (
<div className="home-hero">
<h1>Welcome to Warbler!</h1>
<h4>You don't have an account?</h4>
<Link to="/signup" className="btn btn-primary">
Sign up here
</Link>
</div>
)
}
const {username, profileImageUrl} = currentUser.user;
return (
<MessageTimeline
profileImageUrl={profileImageUrl}
username={username}
/>
)
};
export default Homepage;
<file_sep>/src/store/actions/errors.js
import {ADD_ERROR, REMOVE_ERROR} from "../actionTypes";
export const addError = errorMessage => ({
type: ADD_ERROR,
errorMessage
});
export const removeError = () => ({
type: REMOVE_ERROR
})<file_sep>/src/store/actions/auth.js
import { apiCall, setTokenHeader } from "../../services/api";
import {SET_CURRENT_USER} from "../actionTypes";
import { addError, removeError } from "./errors";
export const setCurrentUser = user => ({
type: SET_CURRENT_USER,
user
});
export const setAuthorizationToken = token => {
setTokenHeader(token);
}
export const signOut = () => {
return dispatch => {
localStorage.clear();
setAuthorizationToken(false);
dispatch(setCurrentUser({}));
}
};
export const authUser = (type, userData) => {
return async (dispatch) => {
try{
const res = await apiCall("post", `/api/auth/${type}`, userData);
const {token, ...user} = res;
if(token) {
localStorage.setItem("jwtToken", token);
setAuthorizationToken(token);
dispatch(setCurrentUser(user));
dispatch(removeError());
}
}
catch(err) {
const {message} = err;
dispatch(addError(message));
}
}
};<file_sep>/src/containers/MessageForm.js
import React, { Component } from "react";
import {connect} from "react-redux";
import {postNewMessage} from "../store/actions/messages";
class MessageForm extends Component {
constructor(props) {
super(props);
this.state = {
message: ""
};
}
handleNewMessage = event => {
event.preventDefault();
this.props.postNewMessage(this.state.message);
this.setState({
message: ""
})
this.props.history.push("/");
}
handleMessageInput = event => {
this.setState({
[event.target.name]: event.target.value
})
}
render() {
const {message} = this.state;
return (
<form
className="input-group"
onSubmit={this.handleNewMessage}
>
{this.props.error.message && (
<div className="alert alert-danger">
{this.props.error.message}
</div>
)}
<input
type="text"
className="form-control"
name="message"
value={message}
onChange={this.handleMessageInput}
required
/>
<button className="btn btn-primary">Submit</button>
</form>
)
}
}
function mapStateToProps(state) {
return {
error: state.error
}
}
export default connect(mapStateToProps, {postNewMessage}) (MessageForm);
|
b26a902ed0f204034523f395ba0a1cecb69bb23b
|
[
"JavaScript"
] | 5
|
JavaScript
|
giangnhattruong/warbler_frontend
|
b7b9ecafa19aa6f13483181538cdbc10ae038c38
|
0d94b74e360d3727b78fd6896769b6d8bd3cbea4
|
refs/heads/master
|
<repo_name>jotatoledo/Graphiti<file_sep>/test/Graphiti.Test/Edges/EdgeTests.cs
// <copyright file="EdgeTests.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test
{
using System;
using System.Collections.Generic;
using FluentAssertions;
using Xunit;
public class EdgeTests
{
public static IEnumerable<object[]> ValueTypeData => new[]
{
new object[] { 'a', 'b' },
new object[] { 2.0, 1.0 },
new object[] { 1, 2 },
new object[] { "a", "b" }
};
[Fact]
public void ThrowsIfAnyVertexIsNull()
{
Action nullSource = () => new Edge<string>(null, string.Empty);
Action nullTarget = () => new Edge<string>(string.Empty, null);
nullSource.Should().Throw<ArgumentNullException>();
nullTarget.Should().Throw<ArgumentNullException>();
}
[Theory]
[MemberData(nameof(ValueTypeData))]
[Trait("VertexType", "ValueType")]
public void Equals_Should_ReturnTrue_When_EquatingAgainstsCaller<TVertex>(TVertex source, TVertex target)
{
var sut = this.CreateSystemUnderTest(source, target);
var result = sut.Equals(sut);
result.Should().BeTrue();
}
[Theory]
[MemberData(nameof(ValueTypeData))]
[Trait("VertexType", "ValueType")]
public void Equals_Should_ReturnTrue_When_EquatingAgainstEdgeWithSameVertices<TVertex>(TVertex source, TVertex target)
{
var sut = this.CreateSystemUnderTest(source, target);
var result = sut.Equals(this.CreateSystemUnderTest(source, target));
result.Should().BeTrue();
}
[Theory]
[MemberData(nameof(ValueTypeData))]
[Trait("VertexType", "ValueType")]
public void Equals_Should_ReturnFalse_When_EquatingAgainstEdgeWithDifferentVertices<TVertex>(TVertex source, TVertex target)
{
var sut = this.CreateSystemUnderTest(source, target);
var result = sut.Equals(this.CreateSystemUnderTest(target, source));
result.Should().BeFalse();
}
[Fact]
public void Equals_Should_HandleTypeWithNoEqualsOverride()
{
var testId = 1;
TestTypeWithoutEquals typeFactory(int val) => new TestTypeWithoutEquals(val);
var sut = this.CreateSystemUnderTest(typeFactory(testId), typeFactory(testId));
var equalsToCaller = sut.Equals(sut);
var equalsToOtherWithSameVertices = sut.Equals(this.CreateSystemUnderTest(typeFactory(testId), typeFactory(testId)));
equalsToCaller
.Should()
.BeTrue("because default `Equals` equates references and the caller was passed as argument");
equalsToOtherWithSameVertices
.Should()
.BeFalse("because default `Equals` equates references and a new instance was passed as argument");
}
[Fact]
public void Equals_Should_HandleTypeWithEqualsOverride()
{
var testId = 1;
TestTypeWithEquals typeFactory(int val) => new TestTypeWithEquals(val);
var sut = this.CreateSystemUnderTest(typeFactory(testId), typeFactory(testId));
var equalsToCaller = sut.Equals(sut);
var equalsToOtherWithSameVertices = sut.Equals(this.CreateSystemUnderTest(typeFactory(testId), typeFactory(testId)));
equalsToCaller
.Should()
.BeTrue("because overriden `Equals` equates references and the caller was passed as argument");
equalsToOtherWithSameVertices
.Should()
.BeTrue("because overriden `Equals` considers properties and a new instance with same props. was passed as argument");
}
private Edge<TVertex> CreateSystemUnderTest<TVertex>(TVertex source, TVertex target)
{
return new Edge<TVertex>(source, target);
}
private sealed class TestTypeWithoutEquals
{
public TestTypeWithoutEquals(int id)
{
this.Id = id;
}
public int Id { get; }
}
private sealed class TestTypeWithEquals
{
public TestTypeWithEquals(int id)
{
this.Id = id;
}
public int Id { get; }
public override int GetHashCode() => this.Id.GetHashCode();
public override bool Equals(object obj) => obj is TestTypeWithEquals other
&& (other == this || this.Id.Equals(other.Id));
}
}
}
<file_sep>/test/Graphiti.Test/Directed/DirectedAdjacencyListGraphTests.cs
// <copyright file="DirectedAdjacencyListGraphTests.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;
public class DirectedAdjacencyListGraphTests
{
public static IEnumerable<object[]> Edges => new List<object[]>
{
// TODO: once c#@8 lands, the wrap functionality can be deprecated
// as the ctor method can be invoked by simple using `new`, when the
// type of the collection is expicitely declared
new object[] { Enumerable.Empty<TestEdge>() },
new object[] { new TestEdge[] { TestEdge.Wrap('a', 'b') } },
new object[] { new TestEdge[] { TestEdge.Wrap('a', 'b'), TestEdge.Wrap('b', 'c'), TestEdge.Wrap('c', 'a') } }
};
[Fact]
public void ItCorrectlyMarksItselfAsDirected()
{
var sut = CreateSystemUnderTest();
sut.IsDirected.Should()
.BeTrue();
}
[Theory]
[MemberData(nameof(Edges))]
public void ItCorrectlyCalculatesItsMaximumNumberOfEdges(IEnumerable<TestEdge> edges)
{
var sut = CreateSystemUnderTest(edges);
var numberOfVertices = sut.VertexCount;
var expectedMaxNumberOfEdges = numberOfVertices * (numberOfVertices - 1);
sut.MaxNumberOfEdges.Should()
.Be(expectedMaxNumberOfEdges);
}
[Theory]
[MemberData(nameof(Edges))]
public void ItCorrectlyCountsCurrentVertices(IEnumerable<TestEdge> edges)
{
var vertices = Utils.ExtractDistinctVertices(edges);
var sut = CreateSystemUnderTest(edges);
sut.VertexCount.Should()
.Be(vertices.Count());
}
[Fact]
public void Should_UpdateCurrentVertices_When_VerticesAreMutated()
{
var sut = CreateSystemUnderTest();
var aToB = TestEdge.Wrap('a', 'b');
var bToC = TestEdge.Wrap('b', 'c');
var cToD = TestEdge.Wrap('c', 'd');
var dToA = TestEdge.Wrap('d', 'a');
TestVertex[] asVertices(params char[] vertices) => vertices.Select(TestVertex.Wrap).ToArray();
void addEdge(TestEdge e) => sut.AddVerticesAndEdge(e);
void removeVertex(TestVertex v) => sut.RemoveVertex(v);
AssertCurrentVertices(sut, "because the graph was created without vertices");
addEdge(aToB);
AssertCurrentVertices(sut, $"because the vertices of {aToB} were added", asVertices('a', 'b'));
addEdge(bToC);
AssertCurrentVertices(sut, $"because the vertices of {bToC} were added", asVertices('a', 'b', 'c'));
removeVertex(aToB.Target);
AssertCurrentVertices(sut, $"because {aToB.Target} was removed", asVertices('a', 'c'));
addEdge(cToD);
AssertCurrentVertices(sut, $"because the vertices of {cToD} were added", asVertices('a', 'c', 'd'));
addEdge(dToA);
AssertCurrentVertices(sut, $"because the vertices of {dToA} were added", asVertices('a', 'c', 'd'));
removeVertex(dToA.Target);
AssertCurrentVertices(sut, $"because {dToA.Target} was removed", asVertices('c', 'd'));
removeVertex(dToA.Source);
AssertCurrentVertices(sut, $"because {dToA.Source} was removed", asVertices('c'));
removeVertex(cToD.Source);
AssertCurrentVertices(sut, $"because {cToD.Source} was removed");
}
[Theory]
[MemberData(nameof(Edges))]
public void ItCorrectlyCountsCurrentEdges(IEnumerable<TestEdge> edges)
{
var sut = CreateSystemUnderTest(edges);
sut.EdgeCount.Should()
.Be(edges.Count());
}
[Fact]
public void Should_UpdateCurrentEdges_When_VerticesAreMutated()
{
var sut = CreateSystemUnderTest();
var aToB = TestEdge.Wrap('a', 'b');
var aToC = TestEdge.Wrap('a', 'c');
var bToC = TestEdge.Wrap('b', 'c');
var cToD = TestEdge.Wrap('c', 'd');
var dToA = TestEdge.Wrap('d', 'a');
void addEdge(TestEdge e) => sut.AddVerticesAndEdge(e);
void removeVertex(TestVertex v) => sut.RemoveVertex(v);
AssertTrackedEdges(sut, "because the graph was created without edges");
addEdge(aToB);
AssertTrackedEdges(sut, $"because {aToB} was added", aToB);
addEdge(aToC);
AssertTrackedEdges(sut, $"because {aToC} was added", aToB, aToC);
addEdge(bToC);
AssertTrackedEdges(sut, $"because {bToC} was added", aToB, aToC, bToC);
addEdge(cToD);
AssertTrackedEdges(sut, $"because {cToD} was added", aToB, aToC, bToC, cToD);
removeVertex(aToB.Target);
AssertTrackedEdges(sut, $"because {aToB.Target} was removed", aToC, cToD);
addEdge(dToA);
AssertTrackedEdges(sut, $"because {dToA} was added", aToC, cToD, dToA);
removeVertex(aToC.Source);
AssertTrackedEdges(sut, $"because {aToC.Source} was removed", cToD);
removeVertex(cToD.Source);
AssertTrackedEdges(sut, $"because {cToD.Source} was removed");
}
[Fact]
public void Should_UpdateCurrentEdges_When_EdgesAreMutated()
{
var sut = CreateSystemUnderTest();
var aToB = TestEdge.Wrap('a', 'b');
var aToC = TestEdge.Wrap('a', 'c');
var bToC = TestEdge.Wrap('b', 'c');
var cToA = TestEdge.Wrap('c', 'a');
void addEdge(TestEdge e) => sut.AddVerticesAndEdge(e);
void removeEdge(TestEdge e) => sut.RemoveEdge(e);
AssertTrackedEdges(sut, "because thr graph was created withouth edges");
addEdge(aToB);
AssertTrackedEdges(sut, $"because {aToB} was added", aToB);
addEdge(aToC);
AssertTrackedEdges(sut, $"because {aToC} was added", aToB, aToC);
addEdge(bToC);
AssertTrackedEdges(sut, $"because {bToC} was added", aToB, aToC, bToC);
removeEdge(TestEdge.Wrap('b', 'a'));
AssertTrackedEdges(sut, $"because {TestEdge.Wrap('b', 'a')} does not exist", aToB, aToC, bToC);
addEdge(cToA);
AssertTrackedEdges(sut, $"because {cToA} was added", aToB, aToC, bToC, cToA);
removeEdge(aToC);
AssertTrackedEdges(sut, $"because {aToC} was removed", aToB, bToC, cToA);
removeEdge(bToC);
AssertTrackedEdges(sut, $"because {bToC} was removed", aToB, cToA);
removeEdge(aToB);
AssertTrackedEdges(sut, $"because {aToB} was removed", cToA);
removeEdge(cToA);
AssertTrackedEdges(sut, $"because {aToB} was removed");
}
[Fact]
public void AddingAVertex_Should_NotAddTheVertex_When_VertexAlreadyPresent()
{
var vertex = TestVertex.Wrap('a');
var sut = CreateSystemUnderTest();
var result = sut.AddVertex(vertex) && sut.AddVertex(vertex);
result.Should()
.BeFalse($"because the {vertex} was added 2 times");
AssertCurrentVertices(sut, "because the vertex was added the first time", vertex);
}
[Fact]
public void AddingAVertex_Should_AddTheVertex_When_VertexNotPresent()
{
var vertex = TestVertex.Wrap('a');
var sut = CreateSystemUnderTest();
var result = sut.AddVertex(vertex);
result.Should()
.BeTrue($"because the {vertex} was not present");
AssertCurrentVertices(sut, "because the vertex was added the first time", vertex);
}
[Fact]
public void RemovingAVertex_Should_NotRemoveTheVertex_When_VertexNotPresent()
{
var vertex = TestVertex.Wrap('a');
var sut = CreateSystemUnderTest();
var result = sut.RemoveVertex(vertex);
result.Should()
.BeFalse($"because {vertex} is not present in the graph");
AssertCurrentVertices(sut, "because the graph is empty");
}
[Fact]
public void RemovingAVertex_Should_Work_RemoveTheVertex_VertexPresent()
{
var vertex = TestVertex.Wrap('a');
var sut = CreateSystemUnderTest();
var result = sut.AddVertex(vertex) && sut.RemoveVertex(vertex);
result.Should()
.BeTrue("because the vertex was removed");
AssertCurrentVertices(sut, "because the graph is empty");
}
[Fact]
public void RemovingAVertex_Should_RemoveInAndOutEdgesOfIt()
{
var vertexToRemove = TestVertex.Wrap('a');
var sut = CreateSystemUnderTest();
var edges = new TestEdge[]
{
TestEdge.Wrap(vertexToRemove.Id, 'b'),
TestEdge.Wrap('b', 'c'),
TestEdge.Wrap('c', vertexToRemove.Id)
};
sut.AddVerticesAndEdgeRange(edges);
var removed = sut.RemoveVertex(vertexToRemove);
var expectedEdges = edges.Where(edge => !(edge.Target.Equals(vertexToRemove) || edge.Source.Equals(vertexToRemove)));
var expectedVertices = Utils.ExtractDistinctVertices(expectedEdges);
removed.Should()
.BeTrue("because the vertex was present");
AssertCurrentVertices(sut, $"because only {vertexToRemove} was removed", expectedVertices.ToArray());
AssertTrackedEdges(sut, $"because the in and out edges of {vertexToRemove} were removed", expectedEdges.ToArray());
}
[Fact]
public void OutEdges_Should_Throw_When_VertexNotPresent()
{
var vertex = TestVertex.Wrap('c');
var sut = CreateSystemUnderTest();
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'b'));
Action outEdges = () => sut.OutEdges(vertex);
Action outDegree = () => sut.OutDegree(vertex);
Action hasOutEdges = () => sut.HasOutEdges(vertex);
outEdges.Should()
.Throw<VertexNotFoundException<TestVertex>>();
outDegree.Should()
.Throw<VertexNotFoundException<TestVertex>>();
hasOutEdges.Should()
.Throw<VertexNotFoundException<TestVertex>>();
}
[Fact]
public void ItCorrectlyCalculatesOutEdges()
{
var sut = CreateSystemUnderTest();
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'b'));
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'c'));
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'd'));
sut.AddVerticesAndEdge(TestEdge.Wrap('b', 'c'));
sut.AddVerticesAndEdge(TestEdge.Wrap('c', 'b'));
void assertOutEdges(TestVertex vertex, int expectedDegree, string because = null)
{
because = because ?? string.Empty;
sut.HasOutEdges(vertex)
.Should()
.Be(expectedDegree != 0);
sut.OutDegree(vertex).Should()
.Be(expectedDegree, because);
sut.OutEdges(vertex)
.Should()
.HaveCount(expectedDegree)
.And
.OnlyHaveUniqueItems();
if (expectedDegree > 0)
{
sut.OutEdges(vertex)
.Should()
.OnlyContain(edge => edge.Source.Equals(vertex));
}
}
assertOutEdges(TestVertex.Wrap('a'), 3);
assertOutEdges(TestVertex.Wrap('b'), 1);
assertOutEdges(TestVertex.Wrap('c'), 1);
assertOutEdges(TestVertex.Wrap('d'), 0);
}
[Fact]
public void InEdges_Should_Throw_When_VertexNotPresent()
{
var vertex = TestVertex.Wrap('c');
var sut = CreateSystemUnderTest();
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'b'));
Action inEdges = () => sut.InEdges(vertex);
Action inDegree = () => sut.InDegree(vertex);
Action hasInEdges = () => sut.HasInEdges(vertex);
inEdges.Should()
.Throw<VertexNotFoundException<TestVertex>>();
inDegree.Should()
.Throw<VertexNotFoundException<TestVertex>>();
hasInEdges.Should()
.Throw<VertexNotFoundException<TestVertex>>();
}
[Fact]
public void ItCorrectlyCalculatesInEdges()
{
var sut = CreateSystemUnderTest();
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'b'));
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'c'));
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'd'));
sut.AddVerticesAndEdge(TestEdge.Wrap('b', 'c'));
sut.AddVerticesAndEdge(TestEdge.Wrap('c', 'b'));
void assertInEdges(TestVertex vertex, int expectedDegree, string because = null)
{
because = because ?? string.Empty;
sut.HasInEdges(vertex)
.Should()
.Be(expectedDegree != 0);
sut.InDegree(vertex).Should()
.Be(expectedDegree, because);
sut.InEdges(vertex)
.Should()
.HaveCount(expectedDegree)
.And
.OnlyHaveUniqueItems();
if (expectedDegree > 0)
{
sut.InEdges(vertex)
.Should()
.OnlyContain(edge => edge.Target.Equals(vertex));
}
}
assertInEdges(TestVertex.Wrap('a'), 0);
assertInEdges(TestVertex.Wrap('b'), 2);
assertInEdges(TestVertex.Wrap('c'), 2);
assertInEdges(TestVertex.Wrap('d'), 1);
}
private static TestDirectedAdjacencyListGraph CreateSystemUnderTest(IEnumerable<TestEdge> edges = null)
{
var graph = new TestDirectedAdjacencyListGraph();
graph.AddVerticesAndEdgeRange(edges ?? Enumerable.Empty<TestEdge>());
return graph;
}
private static void AssertCurrentVertices(TestDirectedAdjacencyListGraph graph, string because, params TestVertex[] expectedVertices)
{
graph.HasNoVertices.Should()
.Be(!expectedVertices.Any(), because);
graph.Vertices.Should()
.BeEquivalentTo(expectedVertices, because);
graph.VertexCount.Should()
.Be(expectedVertices.Length, because);
}
private static void AssertTrackedEdges(TestDirectedAdjacencyListGraph graph, string because, params TestEdge[] expectedEdges)
{
graph.HasNoEdges.Should()
.Be(!expectedEdges.Any(), because);
graph.Edges.Should()
.BeEquivalentTo(expectedEdges, because);
graph.EdgeCount.Should()
.Be(expectedEdges.Length, because);
}
private sealed class TestDirectedAdjacencyListGraph : DirectedAdjacencyListGraph<TestVertex, TestEdge>
{
}
}
}
<file_sep>/src/Graphiti/Exceptions/VertexNotFoundException.cs
// <copyright file="VertexNotFoundException.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System;
/// <summary>
/// Thrown when a vertex is expected to exist in data structure but it does not.
/// </summary>
/// <typeparam name="TVertex">The vertex type</typeparam>
public class VertexNotFoundException<TVertex> : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="VertexNotFoundException{TVertex}"/> class.
/// </summary>
/// <param name="vertex">The vertex</param>
public VertexNotFoundException(TVertex vertex)
: base("Vertex not found")
{
this.Vertex = vertex;
}
/// <summary>
/// Gets the vertex value
/// </summary>
public TVertex Vertex { get; }
}
}
<file_sep>/src/Graphiti/Directed/DirectedAdjacencyListGraph.cs
// <copyright file="DirectedAdjacencyListGraph.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
using System.Linq;
using Graphiti.Collections;
/// <summary>
/// A directed graph based on adjacency lists
/// </summary>
/// <typeparam name="TVertex">Type of the verties</typeparam>
/// <typeparam name="TEdge">Type of the edges</typeparam>
public class DirectedAdjacencyListGraph<TVertex, TEdge>
: IMutableVertexAndEdgeSet<TVertex, TEdge>,
IDirectedGraph<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
private readonly IVertexEdgeDictionary<TVertex, TEdge> vertexEdges;
/// <summary>
/// Initializes a new instance of the <see cref="DirectedAdjacencyListGraph{TVertex, TEdge}"/> class.
/// </summary>
public DirectedAdjacencyListGraph()
: this(-1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DirectedAdjacencyListGraph{TVertex, TEdge}"/> class
/// with the given initial capacity
/// </summary>
/// <param name="capacity">Initial capacity</param>
public DirectedAdjacencyListGraph(int capacity)
{
if (capacity > -1)
{
this.vertexEdges = new VertexEdgeDictionary<TVertex, TEdge>(capacity);
}
else
{
this.vertexEdges = new VertexEdgeDictionary<TVertex, TEdge>();
}
}
private DirectedAdjacencyListGraph(DirectedAdjacencyListGraph<TVertex, TEdge> graph)
{
this.vertexEdges = graph.vertexEdges.Clone();
}
/// <inheritdoc/>
public bool IsDirected => true;
/// <inheritdoc/>
public bool HasNoVertices => this.VertexCount == 0;
/// <inheritdoc/>
public int VertexCount => this.vertexEdges.Count;
/// <inheritdoc/>
public IEnumerable<TVertex> Vertices => this.vertexEdges.Keys;
/// <inheritdoc/>
public bool HasNoEdges => this.EdgeCount == 0;
/// <inheritdoc/>
public int EdgeCount { get; private set; } = 0;
/// <inheritdoc/>
public IEnumerable<TEdge> Edges => this.vertexEdges.Values.SelectMany(edges => edges);
/// <inheritdoc/>
public int MaxNumberOfEdges => this.VertexCount * (this.VertexCount - 1);
/// <inheritdoc/>
public virtual bool AddEdge(TEdge v)
{
var edgeAdded = false;
if (!this.ContainsEdge(v))
{
this.vertexEdges[v.Source].Add(v);
this.EdgeCount++;
edgeAdded = true;
}
return edgeAdded;
}
/// <inheritdoc/>
public virtual bool AddVertex(TVertex v)
{
var added = false;
if (!this.ContainsVertex(v))
{
this.vertexEdges.Add(v, new VertexEdges<TVertex, TEdge>());
added = true;
}
return added;
}
/// <inheritdoc/>
public int AddVertexRange(IEnumerable<TVertex> vertices)
{
return vertices.Select(v => this.AddVertex(v))
.Count(added => added);
}
/// <inheritdoc/>
public bool AddVerticesAndEdge(TEdge edge)
{
this.AddVertex(edge.Source);
this.AddVertex(edge.Target);
return this.AddEdge(edge);
}
/// <inheritdoc/>
public int AddVerticesAndEdgeRange(IEnumerable<TEdge> edges) => edges
.Select(this.AddVerticesAndEdge)
.Count(added => added);
/// <inheritdoc/>
public IDirectedGraph<TVertex, TEdge> Clone()
{
return new DirectedAdjacencyListGraph<TVertex, TEdge>(this);
}
/// <inheritdoc/>
public bool ContainsEdge(TEdge edge)
{
return this.vertexEdges.TryGetValue(edge.Source, out var edges)
&& edges.Contains(edge);
}
/// <inheritdoc/>
public bool ContainsVertex(TVertex vertex)
{
return this.vertexEdges.ContainsKey(vertex);
}
/// <inheritdoc/>
public bool HasInEdges(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.InDegree(v) != 0;
}
/// <inheritdoc/>
public bool HasOutEdges(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.OutDegree(v) != 0;
}
/// <inheritdoc/>
public int InDegree(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.InEdges(v).Count();
}
/// <inheritdoc/>
public IEnumerable<TEdge> InEdges(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
// TODO revisit for optimizations
return this.vertexEdges
.Where(pair => !pair.Key.Equals(v))
.Select(pair => pair.Value)
.SelectMany(vertices => vertices.Where(vertex => vertex.Target.Equals(v)));
}
/// <inheritdoc/>
public int OutDegree(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.vertexEdges[v].Count;
}
/// <inheritdoc/>
public IEnumerable<TEdge> OutEdges(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.vertexEdges[v];
}
/// <inheritdoc/>
public virtual bool RemoveEdge(TEdge v)
{
var removed = false;
if (this.vertexEdges.TryGetValue(v.Source, out var outEdges)
&& outEdges.Remove(v))
{
this.EdgeCount--;
removed = true;
}
return removed;
}
/// <inheritdoc/>
public virtual bool RemoveVertex(TVertex v)
{
var removed = false;
if (this.ContainsVertex(v))
{
// Remove out-edges
var edges = this.vertexEdges[v];
this.EdgeCount -= edges.Count;
edges.Clear();
// Remove before iteration in order to save key-value pair comparision to target vertex
this.vertexEdges.Remove(v);
// Remove in-edges
foreach (var pair in this.vertexEdges)
{
// The vertex edges need to be enumerated otherwise
// the enumeration could be mutated during the loop
foreach (var edge in pair.Value.ToList())
{
if (edge.Target.Equals(v))
{
pair.Value.Remove(edge);
this.EdgeCount--;
}
}
}
removed = true;
}
return removed;
}
private void ThrowIfVertexNotPresent(TVertex v)
{
if (!this.ContainsVertex(v))
{
throw new VertexNotFoundException<TVertex>(v);
}
}
}
}
<file_sep>/README.md
# Graphiti
Lightweight graph data structures and algorithms for .NET Core and .NET Framework.
## Installation
## Example
## Documentation<file_sep>/src/Graphiti/IShallowCloneable.cs
// <copyright file="IShallowCloneable.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
/// <summary>
/// Supports shallow cloning, which creates a new instance of a class
/// with the same value as an existing instance.
/// </summary>
/// <typeparam name="T">The type to be cloned</typeparam>
public interface IShallowCloneable<out T>
{
/// <summary>
/// Generates a shallow clone of this
/// </summary>
/// <returns>A new instance of <typeparamref name="T"/></returns>
T Clone();
}
}
<file_sep>/src/Graphiti/Undirected/UndirectedAdjacencyListGraph.cs
// <copyright file="UndirectedAdjacencyListGraph.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
using System.Linq;
using Graphiti.Collections;
/// <summary>
/// A mutable undirected graph data structure
/// </summary>
/// <typeparam name="TVertex">Type of the vertices</typeparam>
/// <typeparam name="TEdge">Type of the edges</typeparam>
public class UndirectedAdjacencyListGraph<TVertex, TEdge>
: IMutableVertexAndEdgeSet<TVertex, TEdge>,
IUndirectedGraph<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
private readonly IEqualityComparer<TEdge> edgeComparer;
private readonly IVertexEdgeDictionary<TVertex, TEdge> vertexEdges;
/// <summary>
/// Initializes a new instance of the <see cref="UndirectedAdjacencyListGraph{TVertex, TEdge}"/> class
/// with the default initial capacity
/// </summary>
public UndirectedAdjacencyListGraph()
: this(-1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UndirectedAdjacencyListGraph{TVertex, TEdge}"/> class
/// with the given initial capacity
/// </summary>
/// <param name="capacity">The capacity</param>
public UndirectedAdjacencyListGraph(int capacity)
{
if (capacity > -1)
{
this.vertexEdges = new VertexEdgeDictionary<TVertex, TEdge>(capacity);
}
else
{
this.vertexEdges = new VertexEdgeDictionary<TVertex, TEdge>();
}
this.edgeComparer = new UnorderedEdgeComparer<TVertex, TEdge>();
}
private UndirectedAdjacencyListGraph(UndirectedAdjacencyListGraph<TVertex, TEdge> graph)
{
this.vertexEdges = graph.vertexEdges.Clone();
this.edgeComparer = new UnorderedEdgeComparer<TVertex, TEdge>();
}
/// <inheritdoc/>
public bool HasNoEdges => this.EdgeCount == 0;
/// <inheritdoc/>
public int EdgeCount { get; private set; }
/// <inheritdoc/>
public IEnumerable<TEdge> Edges => this.vertexEdges.SelectMany(pair => pair.Value).Distinct(this.edgeComparer);
/// <inheritdoc/>
public bool HasNoVertices => this.VertexCount == 0;
/// <inheritdoc/>
public int VertexCount => this.vertexEdges.Count;
/// <inheritdoc/>
public IEnumerable<TVertex> Vertices => this.vertexEdges.Keys;
/// <inheritdoc/>
public bool IsDirected => false;
/// <inheritdoc/>
public int MaxNumberOfEdges => this.VertexCount * (this.VertexCount - 1) / 2;
/// <inheritdoc/>
public virtual bool AddEdge(TEdge v)
{
var added = false;
if (!this.ContainsEdge(v))
{
this.vertexEdges[v.Source].Add(v);
this.vertexEdges[v.Target].Add(v);
this.EdgeCount++;
added = true;
}
return added;
}
/// <inheritdoc/>
public virtual bool AddVertex(TVertex v)
{
var added = false;
if (!this.ContainsVertex(v))
{
this.vertexEdges.Add(v, this.CreateVertexEdges());
added = true;
}
return added;
}
/// <inheritdoc/>
public int AddVertexRange(IEnumerable<TVertex> vertices)
{
return vertices.Select(v => this.AddVertex(v))
.Where(added => added)
.Count();
}
/// <inheritdoc/>
public bool AddVerticesAndEdge(TEdge edge)
{
this.AddVertex(edge.Source);
this.AddVertex(edge.Target);
return this.AddEdge(edge);
}
/// <inheritdoc/>
public int AddVerticesAndEdgeRange(IEnumerable<TEdge> edges) => edges
.Select(this.AddVerticesAndEdge)
.Count(added => added);
/// <inheritdoc/>
public IEnumerable<TEdge> AdjacentEdges(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.vertexEdges[v];
}
/// <inheritdoc/>
public IUndirectedGraph<TVertex, TEdge> Clone()
{
return new UndirectedAdjacencyListGraph<TVertex, TEdge>(this);
}
/// <inheritdoc/>
public bool ContainsEdge(TEdge edge) => this.vertexEdges.TryGetValue(edge.Source, out var edges)
&& edges.Contains(edge);
/// <inheritdoc/>
public bool ContainsVertex(TVertex vertex)
{
return this.vertexEdges.ContainsKey(vertex);
}
/// <inheritdoc/>
public int Degree(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.vertexEdges[v].Count;
}
/// <inheritdoc/>
public bool HasAdjacentEdges(TVertex v)
{
this.ThrowIfVertexNotPresent(v);
return this.Degree(v) != 0;
}
/// <inheritdoc/>
public virtual bool RemoveEdge(TEdge v)
{
var removed = false;
if (this.ContainsEdge(v))
{
this.vertexEdges[v.Source].Remove(v);
this.vertexEdges[v.Target].Remove(v);
this.EdgeCount--;
removed = true;
}
return removed;
}
/// <inheritdoc/>
public virtual bool RemoveVertex(TVertex v)
{
var removed = false;
if (this.ContainsVertex(v))
{
// Remove directly associated adjacent edges
var adjacentEdges = this.vertexEdges[v];
this.EdgeCount -= adjacentEdges.Count;
TVertex pickNotRemovedVertex(TEdge edge) => edge.Source.Equals(v) ? edge.Target : edge.Source;
// Remove the adjacent edges from the
// edge sets associated to the edge target
foreach (var edge in adjacentEdges)
{
this.vertexEdges[pickNotRemovedVertex(edge)].Remove(edge);
}
this.vertexEdges.Remove(v);
adjacentEdges.Clear();
removed = true;
}
return removed;
}
private void ThrowIfVertexNotPresent(TVertex v)
{
if (!this.ContainsVertex(v))
{
throw new VertexNotFoundException<TVertex>(v);
}
}
private VertexEdges<TVertex, TEdge> CreateVertexEdges()
{
return new VertexEdges<TVertex, TEdge>(this.edgeComparer);
}
}
}
<file_sep>/test/Graphiti.Test/Collections/VertexEdgeDictionaryTests.cs
// <copyright file="VertexEdgeDictionaryTests.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test.Collections
{
using System.Linq;
using FluentAssertions;
using Graphiti.Collections;
using Xunit;
public class VertexEdgeDictionaryTests
{
[Fact]
public void Clone_Should_CorrectlyRun()
{
var sut = this.CreateSystemUnderTest<char, Edge<char>>();
sut.Add('a', CreateEdgeSet<char, Edge<char>>(new Edge<char>('a', 'b')));
sut.Add('b', CreateEdgeSet<char, Edge<char>>(new Edge<char>('b', 'c'), new Edge<char>('a', 'b')));
var clone = sut.Clone();
clone.Should()
.NotBeSameAs(sut, "because a new instance was created")
.And
.BeEquivalentTo(clone, "because the keys and associated vertex sets were copied");
clone.Values.Should()
.OnlyContain(clonedSet => !CloneSetPresentInSourceValues(clonedSet, sut), "because the mapped sets were (shallow) copied");
}
private static IVertexEdges<TVertex, TEdge> CreateEdgeSet<TVertex, TEdge>(params TEdge[] edges)
where TEdge : IEdge<TVertex>
{
var set = new VertexEdges<TVertex, TEdge>();
foreach (var edge in edges)
{
set.Add(edge);
}
return set;
}
private static bool CloneSetPresentInSourceValues<TVertex, TEdge>(
IVertexEdges<TVertex, TEdge> cloneSet,
IVertexEdgeDictionary<TVertex, TEdge> dict)
where TEdge : IEdge<TVertex> => dict.Values.Any(sourceSet => ReferenceEquals(sourceSet, cloneSet));
private VertexEdgeDictionary<TVertex, TEdge> CreateSystemUnderTest<TVertex, TEdge>()
where TEdge : IEdge<TVertex> => new VertexEdgeDictionary<TVertex, TEdge>();
}
}
<file_sep>/src/Graphiti/IGraph.cs
// <copyright file="IGraph.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
/// <summary>
/// A graph structure with vertices of type <typeparamref name="TVertex"/>
/// and edges of type <typeparamref name="TEdge"/>
/// </summary>
/// <typeparam name="TVertex">The type of the vertices</typeparam>
/// <typeparam name="TEdge">The type of the edges</typeparam>
public interface IGraph<TVertex, TEdge>
: IVertexSet<TVertex>,
IEdgeSet<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Gets a value indicating whether the graph is directed or not
/// </summary>
bool IsDirected { get; }
/// <summary>
/// Gets the maximum number of edges that the graph can contain
/// </summary>
int MaxNumberOfEdges { get; }
}
}
<file_sep>/src/Graphiti/Edges/Edge.cs
// <copyright file="Edge.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System;
/// <summary>
/// Default implementation of <see cref="IEdge{TVertex}"/>
/// </summary>
/// <typeparam name="TVertex">The type of the vertices</typeparam>
[Serializable]
#pragma warning disable CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
public sealed class Edge<TVertex> : AbstractEdge<TVertex>
#pragma warning restore CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
{
/// <summary>
/// Initializes a new instance of the <see cref="Edge{TVertex}"/> class.
/// </summary>
/// <param name="source">Source vertex</param>
/// <param name="target">Target vertex</param>
public Edge(TVertex source, TVertex target)
: base(source, target)
{
}
/// <inheritdoc/>
public override bool Equals(object obj) => obj is Edge<TVertex> other && base.Equals(other);
/// <inheritdoc/>
public override IEdge<TVertex> Invert() => new Edge<TVertex>(this.Target, this.Source);
}
}
<file_sep>/src/Graphiti/Undirected/UnorderedEdgeComparer.cs
// <copyright file="UnorderedEdgeComparer.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// Equates edges as unordered pairs
/// </summary>
/// <typeparam name="TVertex">The vertex type</typeparam>
/// <typeparam name="TEdge">The edge type</typeparam>
internal sealed class UnorderedEdgeComparer<TVertex, TEdge> : IEqualityComparer<TEdge>
where TEdge : IEdge<TVertex>
{
/// <inheritdoc/>
public bool Equals(TEdge x, TEdge y) => x.Equals(y) || x.Equals(y.Invert());
/// <inheritdoc/>
/// <remarks>
/// Based on https://stackoverflow.com/a/70375/5394220
/// </remarks>
public int GetHashCode(TEdge obj) => obj.Source.GetHashCode() ^ obj.Target.GetHashCode();
}
}
<file_sep>/test/Graphiti.Test/Utils.cs
// <copyright file="Utils.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test
{
using System.Collections.Generic;
using System.Linq;
internal static class Utils
{
internal static IEnumerable<TestVertex> ExtractDistinctVertices(IEnumerable<TestEdge> edges) => edges
.SelectMany(edge => new[] { edge.Source, edge.Target })
.Distinct();
}
}
<file_sep>/src/Graphiti/IMutableVertexSet.cs
// <copyright file="IMutableVertexSet.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// A mutable set of vertices
/// </summary>
/// <typeparam name="TVertex">The type of the vertices</typeparam>
public interface IMutableVertexSet<TVertex> : IVertexSet<TVertex>
{
/// <summary>
/// Adds a vertex
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>
/// <c>true</c> if the vertex was added; <c>false</c> otherwise
/// </returns>
bool AddVertex(TVertex v);
/// <summary>
/// Adds the vertices of the given collection
/// </summary>
/// <param name="vertices">The vertices</param>
/// <returns>The number of succesfully added vertices</returns>
int AddVertexRange(IEnumerable<TVertex> vertices);
/// <summary>
/// Removes a vertex
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>
/// <c>true</c> if the vertex was removed; <c>false</c> otherwise
/// </returns>
bool RemoveVertex(TVertex v);
}
}
<file_sep>/src/Graphiti/IVertexEdges.cs
// <copyright file="IVertexEdges.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// A set of edges associated to a vertex
/// </summary>
/// <typeparam name="TVertex">The vertex type</typeparam>
/// <typeparam name="TEdge">The vertices type</typeparam>
public interface IVertexEdges<TVertex, TEdge>
: ISet<TEdge>,
IShallowCloneable<IVertexEdges<TVertex, TEdge>>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Gets the edge comparer
/// </summary>
IEqualityComparer<TEdge> EdgeComparer { get; }
}
}
<file_sep>/src/Graphiti/IVertexSet.cs
// <copyright file="IVertexSet.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// A set of vertices
/// </summary>
/// <typeparam name="TVertex">The type of vertex</typeparam>
public interface IVertexSet<TVertex>
{
/// <summary>
/// Gets a value indicating whether this is empty or not
/// </summary>
bool HasNoVertices { get; }
/// <summary>
/// Gets the number of elements contained in this
/// </summary>
int VertexCount { get; }
/// <summary>
/// Gets an enumeration of the vertices in this
/// </summary>
IEnumerable<TVertex> Vertices { get; }
/// <summary>
/// Determines whether the given vertex is contained in this.
/// </summary>
/// <param name="vertex">The vertex.</param>
/// <returns>
/// <c>true</c> if the given vertex is contained in this; otherwise, <c>false</c>.
/// </returns>
bool ContainsVertex(TVertex vertex);
}
}
<file_sep>/src/Graphiti/IDirectedGraph.cs
// <copyright file="IDirectedGraph.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// Behavior contract for a directed graph
/// </summary>
/// <typeparam name="TVertex">The vertices type</typeparam>
/// <typeparam name="TEdge">The edges type</typeparam>
public interface IDirectedGraph<TVertex, TEdge>
: IGraph<TVertex, TEdge>,
IShallowCloneable<IDirectedGraph<TVertex, TEdge>>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Determines whether there are out-edges associated to <paramref name="v"/>.
/// </summary>
/// <param name="v">The vertex.</param>
/// <returns>
/// <c>true</c> if <paramref name="v"/> has no out-edges; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
bool HasOutEdges(TVertex v);
/// <summary>
/// Gets the count of out-edges of <paramref name="v"/>
/// </summary>
/// <param name="v">The vertex.</param>
/// <returns>The count of out-edges of <paramref name="v"/></returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
int OutDegree(TVertex v);
/// <summary>
/// Gets the out-edges of <paramref name="v"/>.
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>An enumeration of the out-edges of <paramref name="v"/></returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when this does not contain the given vertex</exception>
IEnumerable<TEdge> OutEdges(TVertex v);
/// <summary>
/// Determines whether there are in-edges associated to <paramref name="v"/>.
/// </summary>
/// <param name="v">The vertex.</param>
/// <returns>
/// <c>true</c> if <paramref name="v"/> has no in-edges; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
bool HasInEdges(TVertex v);
/// <summary>
/// Gets the count of in-edges of <paramref name="v"/>
/// </summary>
/// <param name="v">The vertex.</param>
/// <returns>The count of in-edges of <paramref name="v"/></returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
int InDegree(TVertex v);
/// <summary>
/// Gets the in-edges of <paramref name="v"/>.
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>An enumeration of the in-edges of <paramref name="v"/></returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
IEnumerable<TEdge> InEdges(TVertex v);
}
}
<file_sep>/src/Graphiti/Edges/AbstractEdge.cs
// <copyright file="AbstractEdge.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System;
/// <summary>
/// Base class for implemenations of the <see cref="IEdge{TVertex}"/>
/// </summary>
/// <typeparam name="TVertex">The vertices type</typeparam>
public abstract class AbstractEdge<TVertex> : IEdge<TVertex>
{
/// <summary>
/// Initializes a new instance of the <see cref="AbstractEdge{TVertex}"/> class
/// with the given vertices.
/// </summary>
/// <param name="source">The source vertex</param>
/// <param name="target">The target vertex</param>
public AbstractEdge(TVertex source, TVertex target)
{
this.Source = source;
this.Target = target;
}
/// <inheritdoc/>
public TVertex Source { get; }
/// <inheritdoc/>
public TVertex Target { get; }
/// <inheritdoc/>
public abstract IEdge<TVertex> Invert();
/// <inheritdoc/>
public override bool Equals(object obj) => obj is AbstractEdge<TVertex> other
&& this.Source.Equals(other.Source)
&& this.Target.Equals(other.Target);
/// <inheritdoc/>
public override int GetHashCode()
{
return Tuple.Create(this.Source, this.Target).GetHashCode();
}
/// <inheritdoc/>
public override string ToString()
{
return $"({this.Source},{this.Target})";
}
}
}
<file_sep>/src/Graphiti/Edges/WeightedEdge.cs
// <copyright file="WeightedEdge.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System;
/// <summary>
/// Default implementation of <see cref="IWeightedEdge{TVertex}"/>
/// </summary>
/// <typeparam name="TVertex">Type of the vertices</typeparam>
[Serializable]
#pragma warning disable CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
public class WeightedEdge<TVertex> : AbstractEdge<TVertex>, IWeightedEdge<TVertex>
#pragma warning restore CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
{
/// <summary>
/// Initializes a new instance of the <see cref="WeightedEdge{TVertex}"/> class with default weight
/// </summary>
/// <param name="source">The source vertex</param>
/// <param name="target">The target vertex</param>
public WeightedEdge(TVertex source, TVertex target)
: this(default(double), source, target)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WeightedEdge{TVertex}"/> class.
/// </summary>
/// <param name="weight">The weight</param>
/// <param name="source">The source vertex</param>
/// <param name="target">The target vertex</param>
public WeightedEdge(double weight, TVertex source, TVertex target)
: base(source, target)
{
}
/// <inheritdoc/>
public double Weight { get; set; }
/// <inheritdoc/>
public override bool Equals(object obj) => obj is WeightedEdge<TVertex> && base.Equals(obj);
/// <inheritdoc/>
public override IEdge<TVertex> Invert() => new WeightedEdge<TVertex>(this.Weight, this.Target, this.Source);
}
}
<file_sep>/src/Graphiti/IUndirectedGraph.cs
// <copyright file="IUndirectedGraph.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// Behavior contract for an undirected graph
/// </summary>
/// <typeparam name="TVertex">The vertices type</typeparam>
/// <typeparam name="TEdge">The edges type</typeparam>
public interface IUndirectedGraph<TVertex, TEdge>
: IGraph<TVertex, TEdge>,
IShallowCloneable<IUndirectedGraph<TVertex, TEdge>>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Gets the adjacent edges to a vertex
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>An enumeration with the adjacent edges</returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
IEnumerable<TEdge> AdjacentEdges(TVertex v);
/// <summary>
/// Determines whether there are adjacent edges associated to <paramref name="v"/>.
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>
/// <c>true</c> if <paramref name="v"/> has no adjacent edges; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
bool HasAdjacentEdges(TVertex v);
/// <summary>
/// Gets the count of adjacent edges of <paramref name="v"/>
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>The count of adjacent edges of <paramref name="v"/></returns>
/// <exception cref="VertexNotFoundException{TVertex}">Thrown when the given vertex is not present</exception>
int Degree(TVertex v);
}
}
<file_sep>/test/Graphiti.Test/TestEdge.cs
// <copyright file="TestEdge.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test
{
public sealed class TestEdge : AbstractEdge<TestVertex>
{
public TestEdge(TestVertex source, TestVertex target)
: base(source, target)
{
}
public static TestEdge Wrap(char source, char target) => new TestEdge(TestVertex.Wrap(source), TestVertex.Wrap(target));
public override IEdge<TestVertex> Invert() => new TestEdge(this.Target, this.Source);
}
}
<file_sep>/src/Graphiti/IVertexEdgeDictionary.cs
// <copyright file="IVertexEdgeDictionary.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// Represents the association between a vertex and a set of edges
/// </summary>
/// <typeparam name="TVertex">The vertex type</typeparam>
/// <typeparam name="TEdge">The edges type</typeparam>
public interface IVertexEdgeDictionary<TVertex, TEdge>
: IDictionary<TVertex, IVertexEdges<TVertex, TEdge>>,
IShallowCloneable<IVertexEdgeDictionary<TVertex, TEdge>>
where TEdge : IEdge<TVertex>
{
}
}
<file_sep>/src/Graphiti/IEdgeSet.cs
// <copyright file="IEdgeSet.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// A set of edges
/// </summary>
/// <typeparam name="TVertex">The type of the vertices in the edges</typeparam>
/// <typeparam name="TEdge">The type of the edges</typeparam>
public interface IEdgeSet<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Gets a value indicating whether this is empty or not
/// </summary>
bool HasNoEdges { get; }
/// <summary>
/// Gets the number of elements contained in this
/// </summary>
int EdgeCount { get; }
/// <summary>
/// Gets an enumeration of the edges in this
/// </summary>
IEnumerable<TEdge> Edges { get; }
/// <summary>
/// Determines whether a given edge is container in this.
/// </summary>
/// <param name="edge">The edge.</param>
/// <returns>
/// <c>true</c> if this contains the edge; otherwise, <c>false</c>.
/// </returns>
bool ContainsEdge(TEdge edge);
}
}
<file_sep>/test/Graphiti.Test/README.md
# README
## Approach
The usage of _mock_ classes that extend the generic ones in order to
unit test the package was taken from [here](https://stackoverflow.com/q/2818125/5394220)
<file_sep>/src/Graphiti/IMutableVertexAndEdgeSet.cs
// <copyright file="IMutableVertexAndEdgeSet.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
using System.Collections.Generic;
/// <summary>
/// A mutable vertex and edge set
/// </summary>
/// <typeparam name="TVertex">The vertices type</typeparam>
/// <typeparam name="TEdge">The edges type</typeparam>
public interface IMutableVertexAndEdgeSet<TVertex, TEdge>
: IVertexAndEdgeSet<TVertex, TEdge>,
IMutableEdgeSet<TVertex, TEdge>,
IMutableVertexSet<TVertex>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Adds an edge, and its vertices if necessary
/// </summary>
/// <param name="edge">The edge</param>
/// <returns>true if the edge was added, otherwise false.</returns>
bool AddVerticesAndEdge(TEdge edge);
/// <summary>
/// Adds a collection of edges, and it's vertices if necessary
/// </summary>
/// <param name="edges">The edges</param>
/// <returns>the number of edges added.</returns>
int AddVerticesAndEdgeRange(IEnumerable<TEdge> edges);
}
}
<file_sep>/test/Graphiti.Test/Collections/VertexEdgesTests.cs
// <copyright file="VertexEdgesTests.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test.Collections
{
using System.Collections.Generic;
using FluentAssertions;
using Graphiti.Collections;
using Xunit;
public class VertexEdgesTests
{
[Fact]
public void Clone_Should_CorrectlyRun()
{
var comparer = EqualityComparer<Edge<int>>.Default;
var sut = this.CreateSystemUnderTest<int, Edge<int>>(comparer);
sut.Add(new Edge<int>(1, 2));
sut.Add(new Edge<int>(3, 4));
var clone = sut.Clone();
clone.Should()
.NotBeSameAs(sut)
.And
.HaveSameCount(sut)
.And
.BeEquivalentTo(sut);
clone.EdgeComparer.Should()
.Be(sut.EdgeComparer);
}
private VertexEdges<TVertex, TEdge> CreateSystemUnderTest<TVertex, TEdge>(IEqualityComparer<TEdge> comparer)
where TEdge : IEdge<TVertex>
{
return new VertexEdges<TVertex, TEdge>(comparer);
}
}
}
<file_sep>/test/Graphiti.Test/TestVertex.cs
// <copyright file="TestVertex.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test
{
public struct TestVertex
{
private TestVertex(char id)
{
this.Id = id;
}
public char Id { get; }
public static TestVertex Wrap(char id) => new TestVertex(id);
public override bool Equals(object obj) => obj is TestVertex other && this.Id.Equals(other.Id);
public override int GetHashCode() => this.Id.GetHashCode();
public override string ToString() => $"Vertex: {this.Id}";
}
}
<file_sep>/src/Graphiti/IVertexAndEdgeSet.cs
// <copyright file="IVertexAndEdgeSet.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
/// <summary>
/// A set of vertices and edges
/// </summary>
/// <typeparam name="TVertex">The vertices type</typeparam>
/// <typeparam name="TEdge">The edges type</typeparam>
public interface IVertexAndEdgeSet<TVertex, TEdge>
: IVertexSet<TVertex>,
IEdgeSet<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
}
}
<file_sep>/test/Graphiti.Test/Undirected/UndirectedAdjacencyListGraphTests.cs
// <copyright file="UndirectedAdjacencyListGraphTests.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;
public class UndirectedAdjacencyListGraphTests
{
private readonly IEqualityComparer<TestEdge> edgeComparer;
public UndirectedAdjacencyListGraphTests()
{
this.edgeComparer = new UnorderedEdgeComparer<TestVertex, TestEdge>();
}
public static IEnumerable<object[]> Edges => new List<object[]>
{
// TODO: once c#@8 lands, the wrap functionality can be deprecated
// as the ctor method can be invoked by simple using `new`, when the
// type of the collection is expicitely declared
new object[] { Enumerable.Empty<TestEdge>() },
new object[] { new TestEdge[] { TestEdge.Wrap('a', 'b') } },
new object[] { new TestEdge[] { TestEdge.Wrap('a', 'b'), TestEdge.Wrap('b', 'c'), TestEdge.Wrap('c', 'a') } },
new object[] { new TestEdge[] { TestEdge.Wrap('a', 'b'), TestEdge.Wrap('a', 'b'), TestEdge.Wrap('b', 'c'), TestEdge.Wrap('c', 'a') } }
};
[Fact]
public void ItCorrectlyMarksItselfAsUndirected()
{
var sut = CreateSystemUnderTest();
sut.IsDirected.Should()
.BeFalse();
}
[Theory]
[MemberData(nameof(Edges))]
public void ItCorrectlyCalculatesItsMaximumNumberOfEdges(IEnumerable<TestEdge> edges)
{
var sut = CreateSystemUnderTest(edges);
var numberOfVertices = sut.VertexCount;
var expectedMaxNumberOfEdges = numberOfVertices * (numberOfVertices - 1) / 2;
sut.MaxNumberOfEdges.Should()
.Be(expectedMaxNumberOfEdges);
}
[Fact]
public void AdjacentEdges_Should_Throw_When_VertexNotPresent()
{
var vertex = TestVertex.Wrap('c');
var sut = CreateSystemUnderTest();
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'b'));
Action edges = () => sut.AdjacentEdges(vertex);
Action degree = () => sut.Degree(vertex);
Action hasEdges = () => sut.HasAdjacentEdges(vertex);
edges.Should()
.Throw<VertexNotFoundException<TestVertex>>();
degree.Should()
.Throw<VertexNotFoundException<TestVertex>>();
hasEdges.Should()
.Throw<VertexNotFoundException<TestVertex>>();
}
[Fact]
public void ItCorrectlyCalculatesAdjacentEdges()
{
var sut = CreateSystemUnderTest();
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'b'));
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'c'));
sut.AddVerticesAndEdge(TestEdge.Wrap('a', 'd'));
sut.AddVerticesAndEdge(TestEdge.Wrap('b', 'c'));
void assertAdjacentEdges(TestVertex vertex, int expectedDegree, string because = null)
{
because = because ?? string.Empty;
sut.HasAdjacentEdges(vertex)
.Should()
.Be(expectedDegree > 0, because);
sut.AdjacentEdges(vertex)
.Should()
.HaveCount(expectedDegree, because)
.And
.OnlyHaveUniqueItems(because);
if (expectedDegree > 0)
{
sut.AdjacentEdges(vertex)
.Should()
.OnlyContain(edge => edge.Target.Equals(vertex) || edge.Source.Equals(vertex), because);
}
}
assertAdjacentEdges(TestVertex.Wrap('a'), 3);
assertAdjacentEdges(TestVertex.Wrap('b'), 2);
assertAdjacentEdges(TestVertex.Wrap('c'), 2);
assertAdjacentEdges(TestVertex.Wrap('d'), 1);
}
[Theory]
[MemberData(nameof(Edges))]
public void ItCorrectlyCountsCurrentEdges(IEnumerable<TestEdge> edges)
{
var sut = CreateSystemUnderTest(edges);
var uniqueEdges = new HashSet<TestEdge>(edges, this.edgeComparer);
sut.EdgeCount.Should()
.Be(uniqueEdges.Count());
}
[Fact]
public void Should_UpdateCurrentEdges_When_EdgesAreMutated()
{
var sut = CreateSystemUnderTest();
var aToB = TestEdge.Wrap('a', 'b');
var aToC = TestEdge.Wrap('a', 'c');
void addEdge(TestEdge e) => sut.AddVerticesAndEdge(e);
void removeEdge(TestEdge e) => sut.RemoveEdge(e);
AssertCurrentEdges(sut, "because thr graph was created withouth edges");
addEdge(aToB);
AssertCurrentEdges(sut, $"because {aToB} was added", aToB);
addEdge(aToB.Invert() as TestEdge);
AssertCurrentEdges(sut, $"because inverted {aToB} wont be added", aToB);
addEdge(aToC);
AssertCurrentEdges(sut, $"because {aToC} was added", aToB, aToC);
removeEdge(aToB);
AssertCurrentEdges(sut, $"because {aToB} was removed", aToC);
removeEdge(aToC);
AssertCurrentEdges(sut, $"because {aToC} was removed");
}
[Fact]
public void Should_UpdateCurrentEdges_When_VerticesAreMutated()
{
var sut = CreateSystemUnderTest();
var aToB = TestEdge.Wrap('a', 'b');
var aToC = TestEdge.Wrap('a', 'c');
var bToD = TestEdge.Wrap('b', 'd');
var cToD = TestEdge.Wrap('c', 'd');
void addEdge(TestEdge e) => sut.AddVerticesAndEdge(e);
void removeVertex(TestVertex v) => sut.RemoveVertex(v);
AssertCurrentEdges(sut, "because thr graph was created withouth edges");
addEdge(aToB);
AssertCurrentEdges(sut, $"because {aToB} was added", aToB);
addEdge(bToD);
AssertCurrentEdges(sut, $"because {bToD} was added", aToB, bToD);
addEdge(aToC);
AssertCurrentEdges(sut, $"because {aToC} was added", aToB, bToD, aToC);
removeVertex(bToD.Source);
AssertCurrentEdges(sut, $"because vertex {bToD.Source} was removed", aToC);
addEdge(cToD);
AssertCurrentEdges(sut, $"because {cToD} was added", aToC, cToD);
removeVertex(cToD.Source);
AssertCurrentEdges(sut, $"because vertex {cToD.Source} was removed");
}
[Fact]
public void Should_NotAddEdge_When_InvertedValueAlreadyExist()
{
var edge = TestEdge.Wrap('a', 'b');
var sut = CreateSystemUnderTest(new[] { edge });
var result = sut.AddEdge(edge.Invert() as TestEdge);
result.Should().BeFalse($"because {edge} was already added");
}
[Theory]
[MemberData(nameof(Edges))]
public void ItCorrectlyCountsCurrentVertices(IEnumerable<TestEdge> edges)
{
var sut = CreateSystemUnderTest(edges);
var uniqueVertices = Utils.ExtractDistinctVertices(edges);
sut.VertexCount.Should()
.Be(uniqueVertices.Count());
}
[Fact]
public void Should_UpdateCurrentVertices_When_VerticesAreMutated()
{
var sut = CreateSystemUnderTest();
var aToB = TestEdge.Wrap('a', 'b');
var bToC = TestEdge.Wrap('b', 'c');
var cToD = TestEdge.Wrap('c', 'd');
TestVertex[] asVertices(params char[] vertices) => vertices.Select(TestVertex.Wrap).ToArray();
void addEdge(TestEdge e) => sut.AddVerticesAndEdge(e);
void removeVertex(TestVertex v) => sut.RemoveVertex(v);
AssertCurrentVertices(sut, "because the graph was created without vertices");
addEdge(aToB);
AssertCurrentVertices(sut, $"because {aToB} was added", asVertices('a', 'b'));
addEdge(bToC);
AssertCurrentVertices(sut, $"because {bToC} was added", asVertices('a', 'b', 'c'));
removeVertex(aToB.Target);
AssertCurrentVertices(sut, $"because {aToB.Target} was removed", asVertices('a', 'c'));
addEdge(cToD);
AssertCurrentVertices(sut, $"because {cToD} was added", asVertices('a', 'c', 'd'));
addEdge(cToD.Invert() as TestEdge);
AssertCurrentVertices(sut, $"because {cToD.Invert()} had no effects", asVertices('a', 'c', 'd'));
removeVertex(TestVertex.Wrap('a'));
AssertCurrentVertices(sut, $"because {TestVertex.Wrap('a')} was removed", asVertices('c', 'd'));
removeVertex(TestVertex.Wrap('c'));
AssertCurrentVertices(sut, $"because {TestVertex.Wrap('c')} was removed", asVertices('d'));
removeVertex(TestVertex.Wrap('d'));
AssertCurrentVertices(sut, $"because {TestVertex.Wrap('d')} was removed");
}
private static void AssertCurrentVertices(TestUndirectedAdjacencyListGraph graph, string because, params TestVertex[] expectedVertices)
{
graph.HasNoVertices.Should()
.Be(!expectedVertices.Any(), because);
graph.Vertices.Should()
.BeEquivalentTo(expectedVertices, because);
graph.VertexCount.Should()
.Be(expectedVertices.Length, because);
}
private static void AssertCurrentEdges(TestUndirectedAdjacencyListGraph graph, string because, params TestEdge[] expectedEdges)
{
graph.HasNoEdges.Should()
.Be(!expectedEdges.Any(), because);
graph.Edges.Should()
.BeEquivalentTo(expectedEdges, because);
graph.EdgeCount.Should()
.Be(expectedEdges.Length, because);
}
private static TestUndirectedAdjacencyListGraph CreateSystemUnderTest(IEnumerable<TestEdge> edges = null)
{
var graph = new TestUndirectedAdjacencyListGraph();
graph.AddVerticesAndEdgeRange(edges ?? Enumerable.Empty<TestEdge>());
return graph;
}
private sealed class TestUndirectedAdjacencyListGraph : UndirectedAdjacencyListGraph<TestVertex, TestEdge>
{
}
}
}
<file_sep>/src/Graphiti/IEdge.cs
// <copyright file="IEdge.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
/// <summary>
/// An edge between two vertices
/// </summary>
/// <typeparam name="TValue">The type of the vertices</typeparam>
public interface IEdge<TValue>
{
/// <summary>
/// Gets the source vertex
/// </summary>
TValue Source { get; }
/// <summary>
/// Gets the target vertex
/// </summary>
TValue Target { get; }
/// <summary>
/// Creates a new edge with interchanged source and target vertices
/// </summary>
/// <returns>A new edge with the swaped vertices</returns>
IEdge<TValue> Invert();
}
}
<file_sep>/test/Graphiti.Test/Undirected/UnorderedEdgeComparerTests.cs
// <copyright file="UnorderedEdgeComparerTests.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Test
{
using System.Collections.Generic;
using FluentAssertions;
using Xunit;
public class UnorderedEdgeComparerTests
{
public static IEnumerable<object[]> Edges => new[]
{
new object[] { TestEdge.Wrap('a', 'b') },
new object[] { new Edge<char>('a', 'b') },
new object[] { new Edge<double>(1.0, 2.0) },
new object[] { new Edge<int>(1, 0) }
};
[Theory]
[MemberData(nameof(Edges))]
public void Equals_Should_ReturnTrue_When_EquatingSameEdges<TVertex>(IEdge<TVertex> edge)
{
var sut = this.CreateSystemUnderTest<TVertex>();
var result = sut.Equals(edge, edge);
result.Should()
.BeTrue();
}
[Theory]
[MemberData(nameof(Edges))]
public void Equals_Should_ReturnTrue_When_EquatingDifferentEdgesWithSameVertices<TVertex>(IEdge<TVertex> edge)
{
var sut = this.CreateSystemUnderTest<TVertex>();
var result = sut.Equals(edge, CloneEdge(edge));
result.Should()
.BeTrue();
}
[Theory]
[MemberData(nameof(Edges))]
public void Equals_Should_ReturnTrue_When_EquatingAgainstEdgeWithInvertedOrder<TVertex>(IEdge<TVertex> edge)
{
var sut = this.CreateSystemUnderTest<TVertex>();
var result = sut.Equals(edge, edge.Invert());
result.Should()
.BeTrue();
}
[Theory]
[MemberData(nameof(Edges))]
public void Should_GenerateSameHashCode_When_HashingInvertedEdges<TVertex>(IEdge<TVertex> edge)
{
var sut = this.CreateSystemUnderTest<TVertex>();
var expectedHashCode = sut.GetHashCode(edge.Invert());
var edgeHashCode = sut.GetHashCode(edge);
edgeHashCode.Should()
.Be(expectedHashCode);
}
[Theory]
[MemberData(nameof(Edges))]
public void Should_GenerateSameHashCode_When_HashingSameEdgeMultipleTimes<TVertex>(IEdge<TVertex> edge)
{
var sut = this.CreateSystemUnderTest<TVertex>();
var edgeHashCode = sut.GetHashCode(edge);
edgeHashCode.Should()
.Be(sut.GetHashCode(edge));
}
[Theory]
[MemberData(nameof(Edges))]
public void Should_GenerateSameHashCode_When_HashingDifferentEdgesWithSameVertices<TVertex>(IEdge<TVertex> edge)
{
var sut = this.CreateSystemUnderTest<TVertex>();
var edgeWithSameVertices = edge.Invert().Invert();
var expectedHashCode = sut.GetHashCode(edgeWithSameVertices);
var edgeHashCode = sut.GetHashCode(edge);
edge.Should()
.NotBeSameAs(edgeWithSameVertices);
edgeHashCode.Should()
.Be(expectedHashCode);
}
private static IEdge<TVertex> CloneEdge<TVertex>(IEdge<TVertex> edge)
{
return CreateEdge(edge.Source, edge.Target);
}
private static IEdge<TVertex> CreateEdge<TVertex>(TVertex source, TVertex target)
{
return new Edge<TVertex>(source, target);
}
private UnorderedEdgeComparer<TVertex, IEdge<TVertex>> CreateSystemUnderTest<TVertex>()
{
return new UnorderedEdgeComparer<TVertex, IEdge<TVertex>>();
}
}
}
<file_sep>/src/Graphiti/Collections/VertexEdges.cs
// <copyright file="VertexEdges.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Collections
{
using System.Collections.Generic;
/// <summary>
/// Internal implementation of <see cref="IVertexEdges{TVertex, TEdge}"/> based on <see cref="HashSet{T}"/>
/// </summary>
/// <typeparam name="TVertex">The vertices type</typeparam>
/// <typeparam name="TEdge">The edges type</typeparam>
internal sealed class VertexEdges<TVertex, TEdge> : HashSet<TEdge>, IVertexEdges<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Initializes a new instance of the <see cref="VertexEdges{TVertex, TEdge}"/> class
/// with default equality comparer.
/// </summary>
public VertexEdges()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="VertexEdges{TVertex, TEdge}"/> class
/// with the given equality comparer
/// </summary>
/// <param name="equalityComparer">The equality comparer</param>
public VertexEdges(IEqualityComparer<TEdge> equalityComparer)
: base(equalityComparer)
{
}
private VertexEdges(VertexEdges<TVertex, TEdge> source)
: base(source, source.Comparer)
{
}
/// <inheritdoc/>
public IEqualityComparer<TEdge> EdgeComparer => this.Comparer;
/// <inheritdoc/>
public IVertexEdges<TVertex, TEdge> Clone()
{
return new VertexEdges<TVertex, TEdge>(this);
}
}
}
<file_sep>/src/Graphiti/IMutableEdgeSet.cs
// <copyright file="IMutableEdgeSet.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
/// <summary>
/// A mutable set of edges
/// </summary>
/// <typeparam name="TVertex">The type of the vertices</typeparam>
/// <typeparam name="TEdge">The type of edges</typeparam>
public interface IMutableEdgeSet<TVertex, TEdge> : IEdgeSet<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Adds an edge
/// </summary>
/// <param name="v">The vertex</param>
/// <returns>
/// <c>true</c> if the edge was added; <c>false</c> otherwise
/// </returns>
bool AddEdge(TEdge v);
/// <summary>
/// Removes an edge
/// </summary>
/// <param name="v">The edge</param>
/// <returns>
/// <c>true</c> if the edge was removed; <c>false</c> otherwise
/// </returns>
bool RemoveEdge(TEdge v);
}
}
<file_sep>/src/Graphiti/Collections/VertexEdgeDictionary.cs
// <copyright file="VertexEdgeDictionary.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti.Collections
{
using System.Collections.Generic;
/// <summary>
/// Internal implementation of <see cref="IVertexEdgeDictionary{TVertex, TEdge}"/> based on <see cref="Dictionary{TKey, TValue}"/>
/// </summary>
/// <typeparam name="TVertex">The vertices type</typeparam>
/// <typeparam name="TEdge">The edges type</typeparam>
internal sealed class VertexEdgeDictionary<TVertex, TEdge>
: Dictionary<TVertex, IVertexEdges<TVertex, TEdge>>,
IVertexEdgeDictionary<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
/// <summary>
/// Initializes a new instance of the <see cref="VertexEdgeDictionary{TVertex, TEdge}"/> class.
/// </summary>
public VertexEdgeDictionary()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="VertexEdgeDictionary{TVertex, TEdge}"/> class
/// with the given initial capacity
/// </summary>
/// <param name="capacity">Initial capacity</param>
public VertexEdgeDictionary(int capacity)
: base(capacity)
{
}
/// <inheritdoc/>
public IVertexEdgeDictionary<TVertex, TEdge> Clone()
{
var clone = new VertexEdgeDictionary<TVertex, TEdge>(this.Count);
foreach (var pair in this)
{
// Ensure that the mapped edge sets are shallow cloned
clone.Add(pair.Key, pair.Value.Clone());
}
return clone;
}
}
}
<file_sep>/src/Graphiti/IWeightedEdge.cs
// <copyright file="IWeightedEdge.cs" company="Graphiti">
// Copyright (c) Graphiti. All rights reserved.
//
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace Graphiti
{
/// <summary>
/// An edge with a numeric weight
/// </summary>
/// <typeparam name="TVertex">The type of the vertices</typeparam>
public interface IWeightedEdge<TVertex> : IEdge<TVertex>
{
/// <summary>
/// Gets or sets the weight of the edge
/// </summary>
double Weight { get; set; }
}
}
|
a73b3cf297b4290e735c77303813cf396aa00d3d
|
[
"Markdown",
"C#"
] | 34
|
C#
|
jotatoledo/Graphiti
|
352f6a3abc7481e16689f4a3115efd917bf55e42
|
b358c18beeb2753ce663dfaaee363486a13d0261
|
refs/heads/master
|
<file_sep>import utilities.custom_logger as cl
from selenium.webdriver.common.by import By
import logging
from base.basepage import BasePage
from pages.home_page.navigation import NavigationPage
from pages.home_page.login_page import LoginPage
class DiscountsPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
self.nav = NavigationPage(driver)
self.lp = LoginPage(driver)
#Loctors
_discount_info_clothes_page = "//div[@class='products row']//span[@class='discount-percentage discount-product']" #byXpath
_panda_tshirt = "//div[@id='js-product-list']/div[@class='products row']//a[contains(text(),'T-shirt Panda')]" #byXpath
_discount_info_element = "//div[@class='product-prices']//span[@class='discount discount-percentage']"
_panda_tshirt_current_price = "//section[@id='main']//div[@class='product-prices']/div[2]//span[1]"
_panda_tshirt_regular_price = "//div[@class='product-prices']//span[@class='regular-price']"
def priceCheck(self, discountnum):
currentPrice = self.driver.find_element(By.XPATH, self._panda_tshirt_current_price).get_attribute("content")
currentPrice= currentPrice.replace(",", ".")
regularPrice = self.driver.find_element(By.XPATH,self._panda_tshirt_regular_price).text
regularPrice = regularPrice.replace("zł", "")
regularPrice = regularPrice.replace(",",".")
discount = float(regularPrice) * float(discountnum)
if (float(regularPrice) - float(discount)) == float(currentPrice):
return True
return False
def discountForLoggedInClientSuccessful(self, email, password, discountnum):
self.lp.login(email, password)
self.nav.goToClothesPage()
self.waitForElement(locator=self._panda_tshirt, locatorType='xpath')
self.elementClick(locator=self._panda_tshirt, locatorType='xpath')
discountInfo = self.isElementPresent(locator=self._discount_info_element, locatorType='xpath')
if discountInfo and self.priceCheck(discountnum):
result = True
else:
result = False
self.lp.logout()
return result
def discountForLoggedInClientFailed(self):
self.nav.goToClothesPage()
self.waitForElement(locator=self._panda_tshirt, locatorType='xpath')
self.elementClick(locator=self._panda_tshirt, locatorType='xpath')
result = self.isElementPresent(locator=self._discount_info_element, locatorType='xpath')
return result
def discountInfoOnClothesPageElements(self,email,password, elementNum):
self.lp.login(email, password)
self.nav.goToClothesPage()
self.waitForElement(locator="//div[@id='js-product-list']/div[@class='products row']/article[1]",
locatorType='xpath')
discountInfo = self.driver.find_elements(By.XPATH,self._discount_info_clothes_page)
if len(discountInfo) == elementNum:
result = True
else:
result = False
self.lp.logout()
return result
<file_sep>import utilities.custom_logger as cl
from selenium.webdriver.common.by import By
import logging
from base.basepage import BasePage
from pages.home_page.navigation import NavigationPage
from pages.home_page.login_page import LoginPage
import time
class CartPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
self.nav = NavigationPage(self.driver)
self.lp = LoginPage(self.driver)
#Loctors
_cart = "_desktop_cart" #byID
_add_to_cart = "//form[@id='add-to-cart-or-refresh']//button[@type='submit']"
_panda_tshirt = "//div[@id='js-product-list']/div[@class='products row']//a[contains(text(),'T-shirt Panda')]" # byXpath
_bluzka_Fiona = "//div[@class='products row']//a[contains(text(),'Bluzka Fiona')]"
_select_size = "group[1]" #byName
_size_M = "//select[@name='group[1]']/option[@title='M']"
_color = "group[2]" #byName
_quantity = "quantity_wanted" #byID
_go_to_fulfill_the_order_button = "//div[@class='modal-content']//a" #byxpath
_continue_shopping_button = "//button[contains(text(),'Kontynuuj zakupy')]" #byxpath
_num_of_products_in_cart = "//div[@id='cart-subtotal-products']/span[1]"
_first_product_trashcan = "//ul[@class='cart-items']//a[@href='http://localhost/prestashop/koszyk?delete=1&id_product=30&id_product_attribute=150&token=<KEY>']/i[.='delete']"
_products_in_cart = "//div[@class='card cart-container']//ul[@class='cart-items']/li"
_touchspin_down = "//div[@class='card cart-container']//li[1]/div[@class='product-line-grid']//span[@class='input-group-btn-vertical']/button[2]"
def getProductToCartPanda(self, quantity):
self.nav.goToClothesPage()
self.waitForElement(locator="//div[@id='js-product-list']/div[@class='products row']/article[1]",
locatorType='xpath')
self.elementClick(locator=self._panda_tshirt, locatorType='xpath')
self.waitForElement(locator=self._size_M, locatorType="xpath")
self.elementClick(locator=self._select_size, locatorType="name")
self.elementClick(locator=self._size_M, locatorType="xpath")
self.elementClick(locator=self._color, locatorType="name")
self.clearField(locator=self._quantity)
self.sendKeys(quantity, locator=self._quantity)
time.sleep(2)
self.elementClick(locator=self._add_to_cart, locatorType="xpath")
self.waitForElement(locator="cart-content", locatorType="class")
def getProductToCartFiona(self,quantity):
self.nav.goToClothesPage()
self.waitForElement(locator=self._bluzka_Fiona, locatorType='xpath')
self.elementClick(locator=self._bluzka_Fiona, locatorType='xpath')
self.waitForElement(locator=self._add_to_cart, locatorType="xpath")
self.elementClick(locator=self._select_size, locatorType="name")
self.elementClick(locator=self._size_M, locatorType="xpath")
self.elementClick(locator=self._color, locatorType="name")
self.clearField(locator=self._quantity)
self.sendKeys(quantity, locator=self._quantity)
self.elementClick(locator=self._add_to_cart, locatorType="xpath")
self.waitForElement(locator=self._go_to_fulfill_the_order_button, locatorType="xpath")
def getFewProductsToCart(self, quantity):
self.getProductToCartPanda(quantity)
self.elementClick(locator=self._continue_shopping_button, locatorType="xpath")
self.waitForElement(locator=self._select_size, locatorType="name")
time.sleep(2)
self.getProductToCartFiona(quantity)
self.elementClick(locator=self._go_to_fulfill_the_order_button, locatorType="xpath")
self.waitForElement(locator="cart-detailed-totals",locatorType="class")
def getFewProductsToCartSuccessful(self, quantity):
self.getFewProductsToCart(quantity)
num = self.driver.find_element(By.XPATH, self._num_of_products_in_cart).text
if str((quantity*2)) in str(num):
result = True
else:
result = False
return result
def priceOfProductsInBasket(self,quantity):
self.getFewProductsToCart(quantity)
elements = self.driver.find_elements(By.XPATH, "//div[@class='current-price']/span[@class='price']")
prices = []
for el in elements:
price = el.text
price = price.replace("zł", "")
price = price.replace(",",".")
price = price.rstrip()
price = float(price)
price = format(price,".2f")
prices.append(price)
numOfProducts = self.driver.find_elements(By.NAME, "product-quantity-spin")
numsOfProducts = []
for num in numOfProducts:
number = num.get_attribute("value")
number = float(number)
number = format(number,".2f")
numsOfProducts.append(number)
multiplyProducts = []
for i in range(0,len(prices)):
multiply = float(numsOfProducts[i])*float(prices[i])
multiplyProducts.append(multiply)
sumOfProducts = sum(multiplyProducts)
sumOfProductss = format(sumOfProducts,".2f")
sumNum = self.driver.find_element(By.XPATH, "//div[@id='cart-subtotal-products']/span[@class='value']").text.replace("zł","")
sumNum = sumNum.replace(",",".")
if float(sumOfProductss) == float(sumNum):
result = True
else:
result = False
return result
def deleteFromCart(self):
self.getFewProductsToCart(quantity=1)
self.elementClick(locator=self._go_to_fulfill_the_order_button, locatorType="xpath")
self.waitForElement(locator="cart-detailed-totals", locatorType="class")
quantityOfProducts = self.driver.find_elements(By.XPATH, self._products_in_cart)
quantity1 = len(quantityOfProducts)
self.elementClick(locator=self._first_product_trashcan, locatorType="xpath")
time.sleep(2)
quantityOfProducts2 = self.driver.find_elements(By.XPATH, self._products_in_cart)
quantity2 = len(quantityOfProducts2)
if quantity1 > quantity2:
result = True
else:
result = False
return result
def changeQuantity(self):
self.getProductToCartPanda(quantity=2)
self.elementClick(locator=self._go_to_fulfill_the_order_button, locatorType="xpath")
self.waitForElement(locator="cart-detailed-totals", locatorType="class")
firstPrice = self.driver.find_element(By.XPATH, "//div[@id='cart-subtotal-products']/span[@class='value']").text
price1 = firstPrice.replace("zł", "")
price1 = price1.replace(",",".")
price1 = float(price1)
price1 = format(price1, ".2f")
self.elementClick(locator=self._touchspin_down, locatorType="xpath")
time.sleep(2)
secondPrice = self.driver.find_element(By.XPATH, "//div[@id='cart-subtotal-products']/span[@class='value']").text
price2 = secondPrice.replace("zł", "")
price2 = price2.replace(",",".").rstrip()
price2 = float(price2)
price2 = format(price2,".2f")
if float(price1) > float(price2):
result = True
else:
result = False
return result
<file_sep>import utilities.custom_logger as cl
import logging
from base.basepage import BasePage
from pages.home_page.navigation import NavigationPage
import time
class ContactPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
self.nav = NavigationPage(driver)
# Locators
_contact_page = "link-static-page-contact-2]" #byID
_contact_form = "contact-form" #byclass
_contact_address = "data" #byclass
_contact_email = "//div[@id='left-column']//a[@href='mailto:<EMAIL>']" #byxpath
_subject_list = "id_contact" #byname
_subject_1 = "//select[@name='id_contact']//option[1]" #byxpath
_email = "from" #byname
_message = "message" #byname
_send = "submitMessage" #byname
_contact_number = "500500500" #bylink
_contact_failed ="//section[@id='content']//li[contains(text(),'Wiadomość nie może być pusta')]" #byxpath
_contact_success= "//section[@id='content']//li[contains(text(),'Twoja wiadomość została pomyślnie wysłana do obsługi.')]" #byxpath
_newsletter_email_input = "email" #byname
_submit_newsletter = "//input[@name='submitNewsletter'][1]" #byxpath
_submit_newsletter_success = "//p[contains(text(), 'Zarejestrowano do subskrypcji')]" #byxpath
_submit_newsletter_failed = "//p[contains(text(), 'Ten email już jest w bazie')]" #byxpath
_maine_page_phonenumber = "//div[@id='contact-link']/span" #byxpath
def contactEmail(self, contactemail):
self.nav.goToContactPage()
contact_email = self.getElement(locator=self._contact_email, locatorType="xpath")
email = contact_email.text
if email == contactemail:
result = True
else:
result = False
return result
def contactAddress(self,address):
self.nav.goToContactPage()
caddress = self.getElement(locator=self._contact_address, locatorType="class")
contactAddress = caddress.text.lower()
if contactAddress == address:
result = True
else:
result = False
return result
def contactNumber(self, phonenumber):
self.nav.goToContactPage()
cnumber = self.getElement(locator=self._contact_number, locatorType="link")
contactNumber = cnumber.text
if contactNumber == phonenumber:
result = True
else:
result = False
return result
def contactForm(self, email, message):
self.nav.goToContactPage()
self.elementClick(locator=self._subject_list, locatorType="name")
self.waitForElement(locator=self._subject_1, locatorType="xpath")
self.elementClick(locator=self._subject_1, locatorType="xpath")
self.sendKeys(email, locator=self._email, locatorType="name")
self.sendKeys(message, locator=self._message, locatorType="name")
self.elementClick(locator=self._send, locatorType="name")
def contactFormSuccess(self, email, message):
self.contactForm(email, message)
self.waitForElement(locator=self._contact_success, locatorType="xpath")
result = self.isElementPresent(locator=self._contact_success, locatorType="xpath")
return result
def contactFormFailed(self,email,message):
self.contactForm(email,message)
self.waitForElement(locator=self._contact_failed, locatorType="xpath")
result = self.isElementPresent(locator=self._contact_failed, locatorType="xpath")
return result
def newsletter(self, email):
self.nav.goToContactPage()
self.sendKeys(email, locator=self._newsletter_email_input, locatorType="name")
self.elementClick(locator=self._submit_newsletter, locatorType="xpath")
def newsletterSuccessed(self, email):
self.newsletter(email)
self.waitForElement(locator=self._submit_newsletter_success, locatorType="xpath")
result = self.isElementPresent(locator=self._submit_newsletter_success, locatorType="xpath")
return result
def newsletterFailed(self, email):
self.newsletter(email)
self.waitForElement(locator=self._submit_newsletter_failed, locatorType="xpath")
result = self.isElementPresent(locator=self._submit_newsletter_failed, locatorType="xpath")
return result
def maincontactNumber(self, number):
num = self.getElement(locator=self._maine_page_phonenumber, locatorType="xpath")
cnum = num.text
if cnum == number:
result = True
else:
result = False
return result
<file_sep>import utilities.custom_logger as cl
from selenium.webdriver.common.by import By
import logging
from base.basepage import BasePage
from pages.home_page.navigation import NavigationPage
from pages.home_page.login_page import LoginPage
from pages.cart_page.cart_page import CartPage
import time
class CheckoutPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
self.nav = NavigationPage(self.driver)
self.lp = LoginPage(self.driver)
self.cp = CartPage(self.driver)
#Loctors
_go_to_fulfill_the_order_button = "//div[@class='modal-content']//a" # byxpath
_proceed_to_order_completion = "PRZEJDŹ DO REALIZACJI ZAMÓWIENIA" #bylink
_checkout_form = "checkout-personal-information-step" #byid
# for visitor client
_gender = "//div[@class='col-md-6 form-control-valign']/label[1]//input[@name='id_gender']"#byxpath gender = men
_address_checkout_form = "//div[@class='js-address-form'][1]" #byxpath
_firstname = "firstname" #byname
_lastname = "lastname" #byname
_email = "//input[@name='email'][1]" #byxpath
_password = "//input[@name='password'][1]" #byxpath
_submit_first_form = "//button[@name='continue'][1]" #byxpath
_wrong_email_info = "//form[@id='customer-form']//ul/li[@class='alert alert-danger']" #byxpath
_address = "address1" #byname
_postcode = "postcode" #byname
_city = "city" #byname
_phone = "phone" #byname
_confirm_addresses = "confirm-addresses" #byname
_alert_inf_address = "//div[@id='delivery-address']//ul/li[@class='alert alert-danger']" #byxpath
_delivery_option2 = "delivery_option_2" #byid
_delivery_message = "delivery_message" #byid
_confirm_delivery_option = "confirmDeliveryOption" #byname
_payment_option2 = "payment-option-2" #byid
_conditions_acceptance = "conditions_to_approve[terms-and-conditions]" #byid
_payment_confirmation = "//div[@id='payment-confirmation']//button[@type='submit']" #byxpath
#for logged in client
_personal_inf = "//section[@id='checkout-personal-information-step']/h1" #byxpath
_user_name = "//a[@href='http://localhost/prestashop/dane-osobiste']" #byxpath
_address2 = "//div[@class='address'][1]" #byxpath
_add_new_address = "//a[@href='http://localhost/prestashop/zamówienie?newAddress=delivery']" #byxpath
def goToCheckout(self):
self.cp.getProductToCartFiona(quantity=1)
self.elementClick(locator=self._go_to_fulfill_the_order_button, locatorType="xpath")
self.waitForElement(locator="cart-detailed-totals", locatorType="class")
self.elementClick(locator=self._proceed_to_order_completion, locatorType="link")
self.waitForElement(locator=self._checkout_form)
def checkoutGuestFormPersonalInformation(self,firstname, lastname, email, password):
self.goToCheckout()
time.sleep(2)
self.elementClick(locator=self._gender, locatorType="xpath")
self.sendKeys(firstname, locator=self._firstname, locatorType="name")
self.sendKeys(lastname, locator=self._lastname, locatorType="name")
self.sendKeys(email, locator=self._email, locatorType="xpath")
self.sendKeys(password, locator=self._password, locatorType="xpath")
self.elementClick(locator=self._submit_first_form, locatorType="xpath")
def checkoutGuestFormPersonalInformationSuccessful(self, firstname, lastname,email,password):
self.checkoutGuestFormPersonalInformation(firstname, lastname, email, password)
self.waitForElement(locator=self._address_checkout_form, locatorType="xpath")
result = self.isElementPresent(locator=self._address_checkout_form, locatorType="xpath")
return result
def checkoutGuestFormPersonalInformationFailed(self,firstname, lastname, email, password):
# providing a wrong email address
self.checkoutGuestFormPersonalInformation(firstname, lastname, email, password)
self.waitForElement(locator=self._wrong_email_info, locatorType="class")
result = self.isElementPresent(locator=self._wrong_email_info, locatorType="xpath")
return result
def addressForm(self, firstname, lastname, email, password, address, postcode, city, phone):
self.checkoutGuestFormPersonalInformation(firstname,lastname,email,password)
self.waitForElement(locator=self._address_checkout_form, locatorType="xpath")
self.sendKeys(address, locator=self._address, locatorType="name")
self.sendKeys(postcode, locator=self._postcode, locatorType="name")
self.sendKeys(city, locator=self._city, locatorType="name")
self.sendKeys(phone, locator=self._phone, locatorType="name")
self.elementClick(locator=self._confirm_addresses, locatorType="name")
def addressFormSuccessful(self, firstname, lastname, email, password, address, postcode, city, phone):
self.addressForm( firstname, lastname, email, password, address, postcode, city, phone)
self.waitForElement(locator="checkout-delivery-step")
result = self.isElementPresent(locator="checkout-delivery-step")
return result
def addressFormFailed(self, firstname, lastname, email, password, address, postcode, city, phone):
self.addressForm(firstname, lastname, email, password, address, postcode, city, phone)
self.waitForElement(locator=self._alert_inf_address, locatorType="class")
result = self.isElementPresent(locator=self._alert_inf_address, locatorType="xpath")
return result
def delivery(self, firstname, lastname, email, password, address, postcode, city, phone):
self.addressForm(firstname, lastname, email, password, address, postcode, city, phone)
self.waitForElement(locator="checkout-delivery-step")
self.elementClick(locator=self._delivery_option2)
self.elementClick(locator=self._confirm_delivery_option, locatorType="name")
def deliverySuccessed(self,firstname, lastname, email, password, address, postcode, city, phone):
self.delivery(firstname, lastname, email, password, address, postcode, city, phone)
self.waitForElement(locator=self._payment_option2)
result = self.isElementPresent(locator=self._payment_option2)
return result
def payment(self,firstname, lastname, email, password, address, postcode, city, phone):
self.delivery(firstname, lastname, email, password, address, postcode, city, phone)
self.waitForElement(locator=self._payment_option2)
self.elementClick(locator=self._payment_option2)
def paymentConditionsAcceptanceVerification(self, firstname, lastname, email, password, address, postcode, city, phone):
self.payment(firstname, lastname, email, password, address, postcode, city, phone)
self.waitForElement(locator=self._payment_confirmation, locatorType="xpath")
self.elementClick(locator=self._payment_confirmation, locatorType="xpath")
element = self.getElement(locator=self._payment_confirmation, locatorType="xpath")
result = element.is_enabled()
if result == False:
return True
return False
def paymentSuccessed(self, firstname, lastname, email, password, address, postcode, city, phone):
self.payment( firstname, lastname, email, password, address, postcode, city, phone)
self.waitForElement(locator=self._conditions_acceptance)
self.elementClick(locator=self._conditions_acceptance)
self.elementClick(locator=self._payment_confirmation, locatorType="xpath")
self.waitForElement(locator="order-confirmation-table", locatorType="class")
result = self.isElementPresent(locator="order-confirmation-table", locatorType="class")
return result
def checkoutLoggedInClient(self, email, password):
self.lp.login(email,password)
self.goToCheckout()
def personalInfVerificationLoggedInClient(self, username, email, password):
self.checkoutLoggedInClient(email, password)
self.waitForElement(locator=self._personal_inf, locatorType="xpath")
self.elementClick(locator=self._personal_inf, locatorType="xpath")
self.waitForElement(locator=self._user_name, locatorType="xpath")
username1 = self.getElement(locator=self._user_name, locatorType="xpath").text
if username == username1:
result = True
else:
result = False
return result
def addressVerificationLoggedInClient(self, address, email, password):
#w tescie zrób go to main page i wyloguj najpierw
self.checkoutLoggedInClient(email,password)
self.waitForElement(locator=self._address2, locatorType="class")
element = self.getElement(locator=self._address2, locatorType="xpath")
address1 = element.text
if address1 == address:
result = True
else:
result = False
return result
def addNewAddressLoggedinClient(self, email, password, address, postcode, city, phone):
self.checkoutLoggedInClient(email, password)
self.waitForElement(locator=self._address2, locatorType="class")
self.elementClick(locator=self._add_new_address, locatorType="xpath")
self.sendKeys(address, locator=self._address, locatorType="name")
self.sendKeys(postcode, locator=self._postcode, locatorType="name")
self.sendKeys(city, locator=self._city, locatorType="name")
self.sendKeys(phone, locator=self._phone, locatorType="name")
self.elementClick(locator=self._confirm_addresses, locatorType="name")
self.waitForElement(locator="checkout-delivery-step")
result = self.isElementPresent(locator="checkout-delivery-step")
return result
<file_sep>from pages.home_page.search_page import productSearch
from pages.home_page.navigation import NavigationPage
from utilities.teststatus import TestStatus
import unittest
import pytest
import utilities.custom_logger as cl
import logging
from ddt import ddt, data, unpack
from utilities.read_cvs_data import getCSVData
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
@ddt
class SearchTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.sp = productSearch(self.driver)
self.ts = TestStatus(self.driver)
self.nav = NavigationPage(self.driver)
@pytest.mark.run(order=1)
@data(*getCSVData("textSearchSuccessful.csv"))
@unpack
def test_searchByNumSuccessful(self, text, numindatabase):
self.log.info("Test successful text search on the home page")
self.nav.backToHomePage()
self.sp.searchProductsByText(text)
result = self.sp.searchSuccesfulByNum(numindatabase)
assert result == True
@pytest.mark.run(order=2)
@data(*getCSVData("textSearchByNum.csv"))
@unpack
def test_searchByTextSuccessful(self, text):
self.log.info("Test successful text search on the home page")
self.nav.backToHomePage()
self.sp.searchProductsByText(text)
result = self.sp.searchSuccessfulByText(text)
assert result == True
@pytest.mark.run(order=3)
@data(*getCSVData("textSearchFailed.csv"))
@unpack
def test_searchByTextFailed(self,text):
self.log.info("Test failed text search on the home page")
self.nav.backToHomePage()
self.sp.searchProductsByText(text)
result = self.sp.searchFailed()
assert result == True
self.ts.markFinal("test_searchByTextFailed", result, "Text search on the home page verification SUCCESSED")
<file_sep>from base.selenium_driver import SeleniumDriver
from pages.cart_page.checkout_page import CheckoutPage
from utilities.teststatus import TestStatus
from pages.home_page.navigation import NavigationPage
from pages.home_page.login_page import LoginPage
import unittest
import pytest
import utilities.custom_logger as cl
import logging
import time
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
class CheckoutTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.chp = CheckoutPage(self.driver)
self.lp = LoginPage(self.driver)
self.ts = TestStatus(self.driver)
self.nav = NavigationPage(self.driver)
self.sd = SeleniumDriver(self.driver)
@pytest.mark.run(order=1)
def test_checkoutGuestFormPersonalInformationSuccessful(self):
self.log.info("Personal Information form for guest client successed")
email = email = "test" + str(round(time.time() * 1000)) +"@<EMAIL>"
result = self.chp.checkoutGuestFormPersonalInformationSuccessful(firstname="Adam",lastname="Kowalski",
email=email, password="<PASSWORD>")
assert result == True
@pytest.mark.run(order=2)
def test_checkoutGuestFormPersonalInformationFailed(self):
self.log.info("Personal Information form for guest client failed due to wrong email")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
result = self.chp.checkoutGuestFormPersonalInformationFailed(firstname="Adam",lastname="Kowalski",
email="<EMAIL>", password="<PASSWORD>")
assert result == True
@pytest.mark.run(order=3)
def test_addressFormSuccessful(self):
self.log.info("Address form for guest client successful")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
email = email = "test" + str(round(time.time() * 1000)) + "@test.com"
result = self.chp.addressFormSuccessful(firstname="Adam",lastname="Kowalski",email=email, password="<PASSWORD>",
address="Testowa 1/2", postcode="00-000", city="Warszawa", phone="500500500")
assert result == True
@pytest.mark.run(order=4)
def test_addressFormFailed(self):
self.log.info("Address form for guest client failed due to wrong postcode")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
email = email = "test" + str(round(time.time() * 1000)) + "@test.com"
result = self.chp.addressFormFailed(firstname="Adam",lastname="Kowalski",email=email, password="<PASSWORD>",
address="Testowa 1/2", postcode="00", city="Warszawa", phone="500500500")
assert result == True
@pytest.mark.run(order=5)
def test_addressFormFailed2(self):
self.log.info("Address form for guest client failed due to wrong phone number")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
email = email = "test" + str(round(time.time() * 1000)) + "@test.com"
result = self.chp.addressFormFailed(firstname="Adam", lastname="Kowalski", email=email, password="<PASSWORD>",
address="Testowa 1/2", postcode="00-000", city="Warszawa", phone="abc")
assert result == True
@pytest.mark.run(order=6)
def test_deliverySuccessed(self):
self.log.info("Delivery form successed")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
email = email = "test" + str(round(time.time() * 1000)) + "@test.com"
result = self.chp.deliverySuccessed(firstname="Adam",lastname="Kowalski",email=email, password="<PASSWORD>",
address="Testowa 1/2", postcode="00-000", city="Warszawa", phone="500500500")
assert result == True
@pytest.mark.run(order=7)
def test_paymentConditionsAcceptanceVerification(self):
self.log.info("Payment conditions acceptance verification successful")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
email = email = "test" + str(round(time.time() * 1000)) + "@test.com"
result = self.chp.paymentConditionsAcceptanceVerification(firstname="Adam",lastname="Kowalski",email=email,
password="<PASSWORD>",address="Testowa 1/2",
postcode="00-000", city="Warszawa", phone="500500500")
assert result == True
@pytest.mark.run(order=8)
def test_paymentSuccessed(self):
self.log.info("Address form for guest client successful")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
email = email = "test" + str(round(time.time() * 1000)) + "@test.com"
result = self.chp.paymentSuccessed(firstname="Adam",lastname="Kowalski",email=email, password="<PASSWORD>",
address="Testowa 1/2", postcode="00-000", city="Warszawa", phone="500500500")
assert result == True
@pytest.mark.run(order=9)
def test_personalInfVerificationLoggedInClient(self):
self.log.info("Personal information form for logged in client verification successful")
self.nav.clearCartAndGoToMainPage()
self.lp.logOut()
result = self.chp.personalInfVerificationLoggedInClient(username="Ewa Kowalska", email="<EMAIL>",
password="<PASSWORD>")
assert result == True
@pytest.mark.run(order=10)
def test_addressVerificationLoggedInClient(self):
self.log.info("Address form for logged in client successful")
self.nav.backToHomePage()
self.lp.logOut()
address = "Ewa Kowalska\nul. Testowa\n00-000 Warszawa\nPolska\n600600600"
result = self.chp.addressVerificationLoggedInClient(address=address, email="<EMAIL>", password="<PASSWORD>")
assert result == True
@pytest.mark.run(order=10)
def test_addNewAddressLoggedInClient(self):
self.log.info("Add address form for logged in client successful")
self.nav.backToHomePage()
self.lp.logOut()
address = "Testowa" + str(round(time.time() * 1000)) + "/2"
result = self.chp.addNewAddressLoggedinClient(email="<EMAIL>", password="<PASSWORD>", address=address,
postcode="00-000", city="Warszawa", phone="600600600")
assert result == True
self.ts.markFinal("test_addNewAddressLoggedinClient", result, "Add address form for logged in client successful"
"verification SUCCESSED")
<file_sep>import utilities.custom_logger as cl
import logging
from base.basepage import BasePage
from pages.home_page.navigation import NavigationPage
class ProductPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
self.nav = NavigationPage(driver)
# Locators
_product_title = "h1" #byclass
_product_description = "product-description-short-30" #byId
_size_S = '//div[@id="search_filters"]/section[2]/ul/li[1]//span[@class="custom-checkbox"]'
_zoom_in_img = "material-icons zoom-in" #byClass
_enlarge_img = "//div[@role='document']//figure/img" #byxpath width = 800
_img = "//div[@class='images-container']/div[1]/img" #byxpath
_panda_tshirt = "//div[@id='js-product-list']/div[@class='products row']//a[contains(text(),'T-shirt Panda')]" # byXpath
_product_availability = "product-availability" #byID
_add_to_cart = "//form[@id='add-to-cart-or-refresh']//button[@type='submit']"
def goToProductPage(self):
self.nav.goToClothesPage()
self.waitForElement(locator=self._panda_tshirt, locatorType="xpath")
self.elementClick(locator=self._panda_tshirt, locatorType="xpath")
self.waitForElement(locator=self._product_title, locatorType="class")
def productTitle(self,title):
self.goToProductPage()
product = self.getElement(locator=self._product_title, locatorType="class")
productTitle = product.text.lower()
if title == productTitle:
result = True
else:
result = False
return result
def productDescription(self,description):
self.goToProductPage()
productDescription = self.getElement(locator=self._product_description).text
if description == productDescription:
result = True
else:
result = False
return result
def imgDisplayed(self):
self.goToProductPage()
result = self.isElementDisplayed(locator=self._img, locatorType="xpath")
return result
def imgEnlarge(self):
self.goToProductPage()
self.elementClick(locator=self._zoom_in_img, locatorType="class")
self.waitForElement(locator=self._enlarge_img, locatorType="xpath")
img = self.getElement(locator=self._enlarge_img, locatorType="xpath")
width = img.get_attribute("width")
if width == "800":
result = True
else:
result = False
return result
def sizeNotAvailable(self):
self.goToProductPage()
self.elementClick(locator=self._size_S, locatorType="xpath")
self.waitForElement(locator=self._product_availability)
availability = self.isElementDisplayed(locator=self._product_availability)
addToCart = self.getElement(locator=self._add_to_cart, locatorType="xpath")
addToCartStatus = addToCart.is_enabled()
if (addToCartStatus == False) and (availability == True):
result = True
else:
result = False
return result
<file_sep>from base.selenium_driver import SeleniumDriver
from pages.cart_page.cart_page import CartPage
from utilities.teststatus import TestStatus
from pages.home_page.navigation import NavigationPage
from pages.home_page.login_page import LoginPage
import unittest
import pytest
import utilities.custom_logger as cl
import logging
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
class CartTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.cp = CartPage(self.driver)
self.lp = LoginPage(self.driver)
self.ts = TestStatus(self.driver)
self.nav = NavigationPage(self.driver)
self.sd = SeleniumDriver(self.driver)
@pytest.mark.run(order=1)
def test_fewProductsCartSuccessful(self):
self.log.info("Get few products to cart successful")
result = self.cp.getFewProductsToCartSuccessful(quantity=2)
assert result == True
@pytest.mark.run(order=2)
def test_priceOfProductsSuccessful(self):
self.log.info("Price of products in cart page successful")
self.nav.clearCartAndGoToMainPage()
result = self.cp.priceOfProductsInBasket(quantity=2)
assert result == True
@pytest.mark.run(order=3)
def test_deleteFromCartSuccessful(self):
self.log.info("Delete from cart successful")
self.nav.clearCartAndGoToMainPage()
result = self.cp.deleteFromCart()
assert result == True
@pytest.mark.run(order=4)
def test_changeQuantitySuccessful(self):
self.log.info("Change quantity of products in cart successful")
self.nav.clearCartAndGoToMainPage()
result = self.cp.changeQuantity()
assert result == True
self.ts.markFinal("test_changeQuantitySuccessful", result, "Changed quantity of products in cart Successful "
"verification SUCCESSED")
<file_sep>from pages.home_page.client_account import AccountPage
from utilities.teststatus import TestStatus
from pages.home_page.navigation import NavigationPage
import unittest
import pytest
import utilities.custom_logger as cl
import logging
import time
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
class AccountTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.ap = AccountPage(self.driver)
self.ts = TestStatus(self.driver)
self.nav = NavigationPage(self.driver)
# @pytest.mark.run(order=1)
# def test_registerFormElementsValidation(self):
# self.log.info("Validation of elements of a customer registration form successful")
# result = self.ap.registerFormElementsValidation()
# assert result == True
@pytest.mark.run(order=2)
def test_createNewAccountFailedEmail(self):
self.nav.backToHomePage()
self.log.info("Created a new customer account unsuccessful by providing an invalid email address")
result = self.ap.createNewAccountFailed(firstname="Jan", lastname="Kowalski",
email="<EMAIL>", password="<PASSWORD>")
assert result ==True
@pytest.mark.run(order=3)
def test_createNewAccountFailedFirstname(self):
self.nav.backToHomePage()
email = "test" + str(round(time.time() * 1000)) +"@test.com"
self.log.info("Created a new customer account unsuccessful by providing an invalid firstname")
result = self.ap.createNewAccountFailed(firstname="123@$", lastname="Kowalski",
email=email, password="<PASSWORD>")
assert result == True
@pytest.mark.run(order=4)
def test_createNewAccountFailedLastname(self):
self.nav.backToHomePage()
email = "test" + str(round(time.time() * 1000)) + "@test.com"
self.log.info("Created a new customer account unsuccessful by providing an invalid firstname")
result = self.ap.createNewAccountFailed(firstname="Jan", lastname="$@23",
email=email, password="<PASSWORD>")
assert result == True
@pytest.mark.run(order=5)
def test_createNewAccountSuccessful(self):
self.nav.backToHomePage()
self.log.info("Created a new customer account successful")
email = "test" + str(round(time.time() * 1000)) +"@<EMAIL>"
result = self.ap.createNewAccountSuccessful(firstname="Jan", lastname="Kowalski",
email=email, password="<PASSWORD>")
assert result == True
self.ts.markFinal("test_createNewAccountSuccessful", result, "Created a new customer account successful "
"verification SUCCESSED")
<file_sep>"""
@package base
Base Page class implementation
It implements methods which are common to all the pages throughout the application
This class needs to be inherited by all the page classes
This should not be used by creating object instances
"""
from base.selenium_driver import SeleniumDriver
from traceback import print_stack
class BasePage(SeleniumDriver):
def __init__(self, driver):
"""
Inits BasePage class
Returns:
None
"""
super(BasePage, self).__init__(driver)
self.driver = driver<file_sep>import utilities.custom_logger as cl
from selenium.webdriver.common.by import By
import logging
from base.basepage import BasePage
from pages.home_page.navigation import NavigationPage
from selenium.webdriver import ActionChains
import time
class FiltersPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
self.nav = NavigationPage(driver)
#Loctors
_clothes_page = "//a[@href='http://localhost/prestashop/3-clothes']"#by xpath
_men_page = '//ul[@class="category-sub-menu"]//a[contains(text(),"Men")]' #byXpath
_man_collapse_menu = '//div[@id="left-column"]//ul[@class="category-sub-menu"]/li[1]/div[1]]' #byXpath
_woman_page = '//ul[@class="category-sub-menu"]//a[@href="http://localhost/prestashop/5-women"]' #byXpath
_woman_collapse_menu = '//div[@id="left-column"]//ul[@class="category-sub-menu"]/li[2]/div[1]' #byXpath
_woman_collapse_menu_bluzki = '//ul[@class="category-sub-menu"]/li[2]//ul[@class="category-sub-menu"]//a[contains(text(),"Bluzki")]'
# clothes
#sizes:
_size_S = '//div[@id="search_filters"]/section[2]/ul/li[1]//span[@class="custom-checkbox"]'
_size_M = '//div[@id="search_filters"]/section[2]/ul/li[2]//span[@class="custom-checkbox"]'
_size_L = '//div[@id="search_filters"]/section[2]/ul/li[3]//span[@class="custom-checkbox"]'
_size_XL = '//div[@id="search_filters"]/section[2]/ul/li[4]//span[@class="custom-checkbox"]'
#colors:
_white_color = '//div[@id="search_filters"]/section[3]/ul/li[1]//span[@class="custom-checkbox"]/input'
_black_color = '//div[@id="search_filters"]/section[3]/ul/li[2]//span[@class="custom-checkbox"]/input'
#prices:
_price_cat1 = '//div[@id="search_filters"]/section[4]/ul/li[1]//span[@class="custom-checkbox"]'
_price_cat2 = '//div[@id="search_filters"]/section[4]/ul/li[2]//span[@class="custom-checkbox"]'
_price_cat3 = '//div[@id="search_filters"]/section[4]/ul/li[3]//span[@class="custom-checkbox"]'
_price_cat4 = '//div[@id="search_filters"]/section[4]/ul/li[4]//span[@class="custom-checkbox"]'
def goToMenPageSuccessful(self):
self.nav.goToClothesPage()
self.elementClick(locator=self._men_page, locatorType='xpath')
self.waitForElement(locator='//div[@class="block-category card card-block hidden-sm-down"]/h1[contains(text(), "Men")]',
locatorType='xpath')
result = self.isElementPresent(locator='//div[@class="block-category card card-block hidden-sm-down"]/h1[contains(text(), "Men")]',
locatorType='xpath')
return result
def clothesWomenBluzkiPage(self):
self.waitForElement(locator="//div[@id='js-product-list']/div[@class='products row']/article[1]")
products = self.driver.find_elements(By.XPATH,
"//div[@id='js-product-list']/div[@class='products row']//h1[@class='h3 product-title']/a")
for el in products:
product = el.text
if 'Bluzka' not in product:
return False
return True
def clothesPagehoverOverMenu(self):
self.nav.backToHomePage()
element = self.driver.find_element(By.XPATH, self._clothes_page)
actions = ActionChains(self.driver)
actions.move_to_element(element).perform()
self.waitForElement(locator="//ul[@id='top-menu']/li[1]/div", locatorType="xpath")
self.elementClick(locator="//ul[@id='top-menu']/li[1]/div/ul/li[2]//a[contains(text(),'Bluzki')]", locatorType="xpath")
def collapseMenuWomenBlouse(self):
self.nav.goToClothesPage()
self.waitForElement(locator=self._woman_collapse_menu, locatorType="xpath")
self.elementClick(locator=self._woman_collapse_menu, locatorType="xpath")
self.waitForElement(locator=self._woman_collapse_menu_bluzki, locatorType='xpath')
self.elementClick(locator=self._woman_collapse_menu_bluzki, locatorType='xpath')
def multipleFiltersClick(self):
# Clicks on the color and size clothes
self.nav.goToClothesPage()
self.driver.execute_script("window.scrollBy(0, -300);")
self.waitForElement(locator='search_filters')
self.elementClick(locator=self._size_M, locatorType='xpath')
time.sleep(2)
self.elementClick(locator=self._black_color, locatorType='xpath')
time.sleep(2)
def multipleFiltersSuccessful(self):
# Checks if selected products are the same as products in database
products = []
text_list = []
product_list = self.driver.find_elements(By.XPATH,
"//div[@class='products row']/article//h1[@class='h3 product-title']/a")
for product in product_list:
hr = product.text
text_list.append(hr.lower())
file = open("product_list_black_m.txt", "r", encoding="utf-8")
product_list_database = file.readlines()
for line in product_list_database:
el = line.rstrip()
products.append(el.lower())
for line in products:
if line not in text_list:
return False
return True
<file_sep>import unittest
from tests.cart.cart_tests import CartTests
from tests.cart.checkout_tests import CheckoutTests
from tests.clothes.discount_tests import DiscountTests
from tests.clothes.filters_tests import FiltersTests
from tests.clothes.product_tests import ProductTests
from tests.home.account_tests import AccountTests
from tests.home.contact_tests import ContactTests
from tests.home.login_tests import LoginTests
from tests.home.search_tests import SearchTests
tc1 = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
tc2 = unittest.TestLoader().loadTestsFromTestCase(ContactTests)
tc3 = unittest.TestLoader().loadTestsFromTestCase(SearchTests)
tc4 = unittest.TestLoader().loadTestsFromTestCase(FiltersTests)
tc5 = unittest.TestLoader().loadTestsFromTestCase(ProductTests)
tc6 = unittest.TestLoader().loadTestsFromTestCase(DiscountTests)
tc7 = unittest.TestLoader().loadTestsFromTestCase(CartTests)
tc8 = unittest.TestLoader().loadTestsFromTestCase(AccountTests)
tc9 = unittest.TestLoader().loadTestsFromTestCase(CheckoutTests)
BlackWhiteTest = unittest.TestSuite([tc1, tc2, tc3, tc4, tc5, tc6, tc7, tc8, tc9])
unittest.TextTestRunner(verbosity=2).run(BlackWhiteTest)
<file_sep>import utilities.custom_logger as cl
from selenium.webdriver.common.by import By
import logging
from base.basepage import BasePage
from base.selenium_driver import SeleniumDriver
class productSearch(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
#Locators
_search_input = 's' #byName
_search_input_submit = '//div[@id="search_widget"]//button[@type="submit"]' #byXpath
_first_element_in_list = '//div[@class="products row"]/article[1]' #byXpath
_elements_list = '//div[@class="products row"]/article' #byXpath
_elements_list_ank = '//div[@class="products row"]/article//div[@class="product-description"]//a' #byXpath
_repeat_search_button = '//section[@id="content"]/div[@id="search_widget"]' #byXpath
def searchProductsByText(self, text):
self.sendKeys(text, locator=self._search_input, locatorType='name')
self.elementClick(locator=self._search_input_submit, locatorType='xpath')
def searchSuccesfulByNum(self, numindatabase):
# Compares the number of products after search on the website to the number of products in the database
self.waitForElement(locator=self._first_element_in_list, locatorType='xpath', pollFrequency=1)
product_list = self.driver.find_elements(By.XPATH, self._elements_list)
num = len(product_list)
if str(num) == numindatabase:
result = True
else:
result = False
return result
def searchFailed(self):
self.waitForElement(locator=self._repeat_search_button, locatorType='xpath')
result = self.isElementPresent(locator=self._repeat_search_button, locatorType='xpath')
return result
def searchSuccessfulByText(self, text):
product_list = self.driver.find_elements(By.XPATH, self._elements_list_ank)
if product_list is not None:
for el in product_list:
if text not in el.text.lower():
return False
return True
return False
<file_sep>from pages.clothes_page.discounts_page import DiscountsPage
from utilities.teststatus import TestStatus
from pages.home_page.navigation import NavigationPage
from pages.home_page.login_page import LoginPage
import unittest
import pytest
import utilities.custom_logger as cl
import logging
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
class DiscountTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.dp = DiscountsPage(self.driver)
self.lp = LoginPage(self.driver)
self.ts = TestStatus(self.driver)
self.nav = NavigationPage(self.driver)
@pytest.mark.run(order=1)
def test_discountforloggedInSuccesfull(self):
self.log.info("Test discount for logged in client successful")
result = self.dp.discountForLoggedInClientSuccessful(email="<EMAIL>", password="<PASSWORD>", discountnum=0.2)
assert result == True
@pytest.mark.run(order=2)
def test_discountforloggedInFailed(self):
self.log.info("Test discount for logged in client successful failed")
result = self.dp.discountForLoggedInClientFailed()
assert result == False
@pytest.mark.run(order=3)
def test_discountInfoClothesPage(self):
self.log.info("Test discount info for logged in client on element on clothes page")
result = self.dp.discountInfoOnClothesPageElements(email="<EMAIL>", password="<PASSWORD>", elementNum=35)
assert result == True
self.ts.markFinal("test_discountInfoClothesPage", result, "Discounts for logged in and logout clients "
"verification SUCCESSED")
<file_sep>import utilities.custom_logger as cl
import logging
from base.basepage import BasePage
import time
class AccountPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
# Locators
_login_link = "//div[@class='user-info']//span[contains(text(), 'Zaloguj')]"
_create_account = "No account? Create one here" #bylinktext
_register_form = 'register-form' #by class
_gender = "//input[@name='id_gender'][1]" #byxpath
_firstname = "firstname" #byname
_lastname = "lastname" #byname
_email = "//form[@id='customer-form']//input[@name='email']" #byxpath
_password = "<PASSWORD>" #byname
_submit_form = "//form[@id='customer-form']//button[@type='submit']" #byxpath
_user_info_field = "user-info" #byclass
_alert = "//div[@class='help-block']//li[@class='alert alert-danger']" #by xpath
# def registerFormElementsValidation(self):
# self.elementClick(locator=self._login_link, locatorType="xpath")
# self.waitForElement(locator=self._create_account, locatorType="link")
# self.elementClick(locator=self._create_account, locatorType="link")
# self.waitForElement(locator=self._register_form, locatorType="class")
# email = self.driver.execute_script("return document.getElementByName(\"email\")[0].validity.valid")
# password = self.driver.execute_script("return document.getElementByName(\"password\")[0].validity.valid")
# if email and password:
# return True
# return False
def createNewAccount(self,firstname,lastname,email,password,):
self.elementClick(locator=self._login_link, locatorType="xpath")
self.waitForElement(locator=self._create_account, locatorType="link")
self.elementClick(locator=self._create_account, locatorType="link")
self.waitForElement(locator=self._register_form, locatorType="class")
self.elementClick(locator=self._gender, locatorType="xpath")
self.sendKeys(data=firstname, locator=self._firstname, locatorType="name")
self.sendKeys(data=lastname, locator=self._lastname, locatorType="name")
self.clearField(locator=self._email, locatorType="xpath")
self.sendKeys(data=email, locator=self._email, locatorType="xpath")
self.clearField(locator=self._password,locatorType="name")
self.sendKeys(data=password,locator=self._password,locatorType="name")
self.elementClick(locator=self._submit_form, locatorType="xpath")
def createNewAccountFailed(self, firstname,lastname,email,password):
self.createNewAccount(firstname,lastname,email,password)
self.waitForElement(locator=self._alert,locatorType="xpath")
result = self.isElementPresent(locator=self._alert,locatorType="xpath")
return result
def createNewAccountSuccessful(self,firstname,lastname,email,password):
self.createNewAccount(firstname,lastname,email,password)
self.waitForElement(locator=self._user_info_field, locatorType="class")
result = self.isElementPresent(locator=self._user_info_field, locatorType="class")
return result
<file_sep>from pages.clothes_page.filters_page import FiltersPage
from utilities.teststatus import TestStatus
from pages.home_page.navigation import NavigationPage
import unittest
import pytest
import utilities.custom_logger as cl
import logging
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
class FiltersTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.fp = FiltersPage(self.driver)
self.ts = TestStatus(self.driver)
self.nav = NavigationPage(self.driver)
@pytest.mark.run(order=1)
def test_goToMenPage(self):
self.log.info("Test go to men page successful")
result = self.fp.goToMenPageSuccessful()
assert result == True
@pytest.mark.run(order=2)
def test_collapseMenu(self):
self.log.info("Test collapse menu women successful")
self.fp.collapseMenuWomenBlouse()
result = self.fp.clothesWomenBluzkiPage()
assert result == True
@pytest.mark.run(order=3)
def test_hoverOverMenu(self):
self.log.info("Test hover over menu clothes women successful")
self.fp.clothesPagehoverOverMenu()
result = self.fp.clothesWomenBluzkiPage()
assert result == True
@pytest.mark.run(order=4)
def test_multiFilters(self):
self.log.info("Multiple clothes used successful")
self.fp.multipleFiltersClick()
result = self.fp.multipleFiltersSuccessful()
assert result == True
self.ts.markFinal("test_multiFilters", result, "Multiple clothes use verification SUCCESSED")
<file_sep>import utilities.custom_logger as cl
import logging
from base.basepage import BasePage
from selenium.webdriver.common.by import By
class NavigationPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
# Locators
_main_page = "//div[@id='_desktop_logo']/a[@href='http://localhost/prestashop/']" #byxpath
_search_input = 's' #byName
_clothes_page ='category-3' #byID
def backToHomePage(self):
self.elementClick(locator=self._main_page, locatorType="xpath")
def goToClothesPage(self):
self.elementClick(locator=self._clothes_page)
def clearCartAndGoToMainPage(self):
self.backToHomePage()
self.waitForElement(locator="cart-products-count",locatorType="class")
self.elementClick(locator="cart-products-count",locatorType="class")
self.waitForElement(locator="//a[@href='http://localhost/prestashop/koszyk?delete=1&id_product=30&id_product_attribute=150&token=<KEY>']/i[.='delete']",
locatorType="xpath")
trashcans = self.driver.find_elements(By.XPATH, "//section[@id='main']//ul[@class='cart-items']//a/i")
for trashcan in trashcans:
self.elementClick(element=trashcan)
self.waitForElement(locator="no-items", locatorType="class")
def goToContactPage(self):
self.webScroll(direction="down")
self.elementClick(locator="link-static-page-contact-2", locatorType="id")
self.waitForElement(locator="contact-form", locatorType="class")<file_sep>from pages.home_page.contact_page import ContactPage
from utilities.teststatus import TestStatus
import unittest
import pytest
import utilities.custom_logger as cl
import logging
import time
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
class ContactTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.cp = ContactPage(self.driver)
self.ts = TestStatus(self.driver)
@pytest.mark.run(order=1)
def test_contactEmail(self):
self.log.info("verifies that the e-mail address is correct")
result = self.cp.contactEmail(contactemail="<EMAIL>")
assert result == True
@pytest.mark.run(order=2)
def test_contactNumber(self):
self.log.info("verifies that the contact phone number is correct")
result = self.cp.contactNumber(phonenumber="500500500")
assert result == True
@pytest.mark.run(order=3)
def test_mainContactNumber(self):
self.log.info("verifies that the contact phone number on main site is correct")
result = self.cp.maincontactNumber(number="500500500")
assert result == True
@pytest.mark.run(order=4)
def test_contactAddress(self):
self.log.info("verifies that the contact address is correct")
address = "black&white\nulica 1/1\n00-000 warszawa\npolska"
result = self.cp.contactAddress(address)
assert result == True
@pytest.mark.run(order=5)
def test_contactFormSuccesssed(self):
self.log.info("Check that the contact form is working correctly")
message = open("sample.txt", "r", encoding="utf-8")
message1 = message.read()
result = self.cp.contactFormSuccess(email="<EMAIL>", message=message1)
assert result == True
@pytest.mark.run(order=6)
def test_contactFormFailed(self):
self.log.info("Check that the contact form is working correctly")
result = self.cp.contactFormFailed(email="<EMAIL>", message="")
assert result == True
@pytest.mark.run(order=7)
def test_newsletterSuccessed(self):
self.log.info("Check if subscribing to the newsletter is working properly")
email = email = "test" + str(round(time.time() * 1000)) + "@test.com"
result = self.cp.newsletterSuccessed(email=email)
assert result == True
@pytest.mark.run(order=8)
def test_newsletterFailed(self):
self.log.info("Check if subscribing to the newsletter is working properly")
result = self.cp.newsletterFailed(email="<EMAIL>")
assert result == True
<file_sep>from pages.clothes_page.product_page import ProductPage
from utilities.teststatus import TestStatus
import unittest
import pytest
import utilities.custom_logger as cl
import logging
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
class ProductTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.pp = ProductPage(self.driver)
self.ts = TestStatus(self.driver)
@pytest.mark.run(order=1)
def test_productTitle(self):
self.log.info("Verify the title of product")
result = self.pp.productTitle(title="t-shirt panda")
assert result == True
@pytest.mark.run(order=2)
def test_productDescription(self):
self.log.info("Verify product description")
description = "Koszulka z krótkim rękawem i nadrukiem z pandą"
result = self.pp.productDescription(description)
assert result == True
@pytest.mark.run(order=3)
def test_imgDisplayed(self):
self.log.info("Check that the image is displayed")
result = self.pp.imgDisplayed()
assert result == True
@pytest.mark.run(order=4)
def test_imgEnlarged(self):
self.log.info("check if the picture is enlarged or not")
result = self.pp.imgEnlarge()
@pytest.mark.run(order=5)
def test_sizeNotAvailable(self):
self.log.info("Verifies the availability of an unavailable size")
result = self.pp.sizeNotAvailable()
assert result == True
<file_sep>import utilities.custom_logger as cl
import logging
from base.basepage import BasePage
from base.selenium_driver import SeleniumDriver
class LoginPage(BasePage):
log = cl.customLogger(logging.DEBUG)
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
# Locators
_login_link = "//div[@class='user-info']//span[contains(text(), 'Zaloguj')]"
_email_field = "//div[@class='col-md-6']//input[@name='email']"
_password_field = "<PASSWORD>" # ByName
_login_submit_button = "submit-login" #ByID
_login_failed_message = "//div[@class='help-block']//li[@class='alert alert-danger']" #byXpath
_logout_button = "//div[@id='_desktop_user_info']//a[@class='logout hidden-sm-down']" #byXpath
_desactivated_account_info = "//section[@id='content']//li[contains(text(),'Twoje konto nie jest w tej chwili aktywne, skontaktuj się z nami')]" #byxpath
def clickLoginLink(self):
self.elementClick(locator=self._login_link, locatorType='xpath')
def enterEmail(self, email):
self.sendKeys(email, locator=self._email_field, locatorType='xpath')
def enterPassword(self, password):
self.sendKeys(password, locator=self._password_field, locatorType='name')
def clickLoginButton(self):
self.elementClick(locator=self._login_submit_button)
def login(self, email="", password=""):
self.clickLoginLink()
self.enterEmail(email)
self.enterPassword(password)
self.clickLoginButton()
def verifyLoginSuccessful(self):
self.waitForElement(locator=self._logout_button, locatorType='xpath')
result = self.isElementPresent(self._logout_button, locatorType='xpath')
return result
def verifyLoginFailed(self):
result = self.isElementPresent(locator=self._login_failed_message, locatorType='xpath')
return result
def logout(self):
self.elementClick(locator=self._logout_button, locatorType='xpath')
def emailValidation(self, email, password):
self.clickLoginLink()
self.enterEmail(email)
self.enterPassword(password)
self.waitForElement(locator=self._email_field, locatorType="xpath", pollFrequency=1)
result = self.driver.execute_script("return document.getElementsByName(\"email\")[0].validity.valid")
return result
def passwordValidation(self, email, password):
self.clickLoginLink()
self.enterEmail(email)
self.enterPassword(password)
self.waitForElement(locator=self._password_field, locatorType="name", pollFrequency=1)
result = self.driver.execute_script("return document.getElementsByName(\"password\")[0].validity.valid")
return result
def logOut(self):
self.elementClick(locator=self._logout_button, locatorType='xpath')
def deactivatedCustomerAccountLogin(self, email,password):
self.login(email,password)
self.waitForElement(locator=self._desactivated_account_info, locatorType="xpath")
result = self.isElementPresent(locator=self._desactivated_account_info, locatorType="xpath")
return result
<file_sep># Prestashop Selenium Tests
Project includes a framework and sample tests that are covering the main functionalities of the Black&white shop. The shop is build on the prestashop and it’s using default template for the clothing shop.
Code is written in python and selenium.
## Requirements:
* Python 3.6.3,
* Pytest-3.4.2,
* Selenium,
* At least one of the browsers: Chrome, Firefox, InternetExplorer.
## Usage
1. Clone this repository.
2. Install all dependencies(paragraph above)
3. To run all test - write in command line: py.tests tests\test_suite.py --browser "selected browser"
4. To run particular test - write in command line: py.test (path to test) -- browser "selected browser"
<file_sep>from pages.home_page.login_page import LoginPage
from utilities.teststatus import TestStatus
import unittest
import pytest
import utilities.custom_logger as cl
import logging
from ddt import ddt, data, unpack
from utilities.read_cvs_data import getCSVData
@pytest.mark.usefixtures('oneTimeSetUp', 'setUp')
@ddt
class LoginTests(unittest.TestCase):
log = cl.customLogger(logging.DEBUG)
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.lp = LoginPage(self.driver)
self.ts = TestStatus(self.driver)
@pytest.mark.run(order=1)
@data(*getCSVData("invalidLogin.csv"))
@unpack
def test_invalidPasswordLogin(self, email, password):
self.log.info("Test invalid login")
self.lp.login(email, password)
result = self.lp.verifyLoginFailed()
assert result == True
@pytest.mark.run(order=2)
def test_emailInputValidationFailed(self):
# Check email input element validation based on the pattern
self.log.info("Test email input validation")
result = self.lp.emailValidation(email='testtest.com', password='<PASSWORD>')
assert result == False
@pytest.mark.run(order=3)
def test_emailInputValidationSuccessed(self):
# Check email input element validation based on the pattern
self.log.info("Test email input validation failed")
result = self.lp.emailValidation(email='<EMAIL>', password='<PASSWORD>')
assert result == True
@pytest.mark.run(order=4)
def test_passwordInputValidationFailed(self):
# Check password input element validation based on the pattern
self.log.info("Test password input validation failed")
result = self.lp.passwordValidation(email='<EMAIL>', password='abc')
assert result == False
@pytest.mark.run(order=5)
def test_passwordInputValidationSuccessed(self):
# Check password input element validation based on the pattern
self.log.info("Test password input validation successed")
result = self.lp.passwordValidation(email='<EMAIL>', password='<PASSWORD>')
assert result == True
@pytest.mark.run(order=6)
def test_deactivatedCustomerAccountLogin(self):
result = self.lp.deactivatedCustomerAccountLogin(email="<EMAIL>", password="<PASSWORD>")
assert result == True
@pytest.mark.run(order=7)
def test_successfulLogin(self):
self.log.info("Test successful login")
self.lp.login("<EMAIL>", "<PASSWORD>")
result = self.lp.verifyLoginSuccessful()
assert result == True
self.ts.markFinal("test_successfulLogin", result, "Login verification SUCCESSED")
|
0e93ebb0d3def4856703cccb3b61af492243b489
|
[
"Markdown",
"Python"
] | 22
|
Python
|
anetakanka/PrestashopSeleniumTests
|
2d59e694cb851fa7aa6e6001a5929faf092d1243
|
a94f61575f4d0154a533fd6e346ecdad2542c03e
|
refs/heads/master
|
<file_sep>// サイズ設定
const width = window.innerWidth;
const height = window.innerHeight - 200;
let isRotateX = false;
let isRotateY = false;
let isRotateZ = false;
const xrotateElement = document.getElementById('xrotate');
xrotateElement.onclick = function () { isRotateX = !isRotateX; }
const yrotateElement = document.getElementById('yrotate');
yrotateElement.onclick = function () { isRotateY = !isRotateY; }
const zrotateElement = document.getElementById('zrotate');
zrotateElement.onclick = function () { isRotateZ = !isRotateZ; }
document.getElementById('white-bg').onclick = function () { scene.background = new THREE.Color(0xFFFFFF); }
document.getElementById('black-bg').onclick = function () { scene.background = new THREE.Color(0x000000); }
document.getElementById('green-bg').onclick = function () { scene.background = new THREE.Color(0x00FF00); }
const scene = new THREE.Scene(); // シーンを作成
const camera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('#myCanvas'), });
renderer.setSize(width, height);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
// 環境光を追加
const ambientLight = new THREE.AmbientLight(0xFFFFFF, 0.5);
scene.add(ambientLight);
// 立方体オブジェクトの作成
// const geometry = new THREE.BoxGeometry(1, 1, 1);
// const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
// const cube = new THREE.Mesh(geometry, material);
// scene.add(cube);
// Collada 形式のモデルデータを読み込む
let model;
const loader = new THREE.ColladaLoader();
loader.load('/models/dae/dice.dae', (collada) => {
model = collada.scene;
model.rotation.x += getRadian(30);
model.rotation.y += getRadian(-15);
scene.add(model); // 読み込み後に3D空間に追加
});
function getRadian(degree) {
return degree * Math.PI / 180;
}
function animate() {
if (model) {
if (isRotateX) {
model.rotation.x += getRadian(1);
}
if (isRotateY) {
model.rotation.y += getRadian(1);
}
if (isRotateZ) {
model.rotation.z += getRadian(1);
}
}
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
|
cee2764fcd0eee50886a42ad54d51810411be5fc
|
[
"JavaScript"
] | 1
|
JavaScript
|
Kotokaze/three-js
|
4d8eeae4bcc61e6194731b5ed13dec5c225834c9
|
0bb5be919aa4bbee7d605f69aec4b257b8916e2e
|
refs/heads/master
|
<repo_name>hadijakay/Project-Proposal-Guide<file_sep>/proposeENG4SJproject.sh
#!/bin/bash
# This script gets a username from .gitconfig. If it indicates that your default username is an empty string, you can set it with
# git config --add github.user YOUR_GIT_USERNAME
# Gather constant vars
# CURRENTDIR=${PWD##*/}
GITHUBUSER=$(git config github.user)
ENG4SJ_TLDir=$(echo $ENG4SJ_TLDir)
if [ "$ENG4SJ_TLDir" == "" ]; then
echo " ENG4SJ_TLDir not set. Please create a parent folder for all ENG4SJ repositories and export that path to ENG4SJ_TLDir variable. Example command: export ENG4SJ_TLDir=\$(pwd)"
exit 1
fi
# Get user input
echo "Enter name for new repo"
read REPONAME
if [ "$REPONAME" == "" ]; then
echo "Repository Name Required. Script Failed."
exit 1
fi
echo "Enter username for new, or just <return> to make it $GITHUBUSER"
read USERNAME
echo "Enter description for your new repo, on one line, then <return>"
read DESCRIPTION
USERNAME=${USERNAME:-${GITHUBUSER}}
echo "Will create a new repo named $REPONAME"
echo "on github.com in the ENG4SJ organization, with this description:"
echo $DESCRIPTION
echo "Type 'y' to proceed, any other character to cancel."
read OK
if [ "$OK" != "y" ]; then
echo "User cancelled"
exit
fi
# Curl some json to the github API oh damn we so fancy
curl -u $USERNAME https://api.github.com/orgs/ENG4SJ/repos -d "{\"name\": \"$REPONAME\", \"description\": \"$DESCRIPTION\"}"
## TODO: Check the response in case the current project already exists
# Set the freshly created repo to the origin and push
# You'll need to have added your public key to your github account
cd $ENG4SJ_TLDir
mkdir $REPONAME
cd $REPONAME
git init
echo "# $REPONAME Project Proposal" > readme.md
curl https://raw.githubusercontent.com/Eng4SJ/Project-Proposal-Guide/master/template-readme.md >> readme.md
git add readme.md
git commit -m "init commit"
git remote add origin https://github.com/ENG4SJ/$REPONAME.git
git push --set-upstream origin master
cd ..
echo "Ready to write project proposal for $REPONAME in $REPONAME//readme.md"
<file_sep>/Readme.md
### Engineering For Social Justice
# Project Proposal Repository
### Welcome!
This project proposal repository is a source for engineering for social justice project proposal. Designed for use by undergraduate engineering students beginning the common capstone Senior Design Project course, it aims to provide the technologically-feasible seed idea highlighting a potential application along with the framing & guiding content necessary to learn human-centered design for community or social justice. It also provides a framework for recontextualizing Engineering for Social Justice work as integral to the role of the engineer, in better alignment with the commonly-cited engineering goal of making the world a better place.
# How to Use
## For Engineering Students or Practicing Engineers
1. **Read the [Student Usage Guide](StudentUsageGuide.md),** which clarifies the requirements and considerations relevant for all engineering for social justice projects.
1. **Find a project proposal** you find interesting and feasible! Projects are listed [here](https://github.com/Eng4SJ).
1. **Acquire permission** from your professor to tackle the project, negotiating any modifications to course requirements as explained in the Student Usage Guide.
1. **Research** the surrounding topics further. These projects commonly occupy a nuanced position, and much harm or waste has been caused in the past by engineers deprioritizing the development of sufficient understanding of the topics at play before drawing any diagrams.
1. **Fork** the project proposal!
1. **Implement the project** to the best of your ability while adhering to the project course requirements! Routine community feedback will be immensely useful in ensuring efficacy.
1. **Submit a 1st pull request** to this repository including your current course on the Collaborating Course List!
1. **Submit a 2nd pull request** to this repository describing any novel requirements your Senior Design Course included, and/or your approaches for adapting them to fit Eng4SJ projects!
1. **Continue to support the project** as time moves forward, as discussed in the Student Usage Guide and relevant to your design.
## For Engineering Educators running Senior Design Project Courses
Simply provide the students with a link to this [Engineering For Social Justice Github Repository](http://ppr.socialjustice.engineering) along with a description, like this one:
> Modern dimensions of oppression- racism, sexism, ableism, and more- are commonly dubbed 'social' problems outside the role or capacities of an engineer to address. Why? Why do we discard the entire skillset we've developed as soon as we face societal injustices? As soon as we acknowledge the significant role we play in influencing the distribution of power, we can unlearn this paralysis. **_As engineers, we have uniquely powerful potential to live not in resignation to the painful injustices of our world, but to actively work in opposition to them._** Doing so, however, requires nuance, humility, collaboration, and an explicit focus on the actual goal of mitigating, preventing, or undermining oppressive social dynamics. If you're interested in addressing existing, real problems living people face, as opposed to pursuing market needs, indulging in personal whimsy, or executing a paid contract, you can find guidance along with several suitable-difficulty project proposals at the [Eng4SJ Project Proposal Repository](http://ppr.socialjustice.engineering/#for-engineering-students-or-practicing-engineers).
The students will work with you to ensure the project they attempt can still meet course requirements. Due to the different priorities of projects in Engineering and Social Justice relative to more commonly pursued senior design projects, _it may be necessary for the students to negotiate adaptations of the class's rubrics to better assess the project's efficacy._ An example of a fairly substantive curriculum adaptation can be seen [here](StudentUsageGuide.md#example-requirements-with-possible-resolutions), which explores replacing the single-individual client company representative sponsoring a project with a 'Stakeholder Committee' whose varied perspectives are crucial to guiding and assessing the project's success.
The projects proposed here require many skills beyond the core competencies traditionally stressed in engineering education. Students will be introduced to frameworks for problem definition, human centered design, and appropriate technology, in addition to what problem-specific content they may need to investigate. While all projects have significantly 'meaty' technical challenges, additional objectives beyond the writing of code or building of electronics exist. *These projects require individuals willing to communicate, collaborate, and self-reflect.* The projects the students bring to you may also seem 'political'- that is the point, and likely what drew them to this repository in the first place.
## For Educators teaching Engineering and Social Justice content
Depending on the goals and curriculum of your course, this repository will likely be most useful as simply a source of undeniably-implementable engineering projects whose deprioritization is nigh impossible to justify, even to an ardent opponent of the development of a more socially-conscious engineering practice.
In addition, I'll soon be providing a **lesson plan teaching how to find these potential projects** and how to document them [here](ESJ-Ideation-Workshops/Overview.md). This lesson plan focuses on several key thrusts:
- *Finding Structural Causes:* Generalized Lotus Diagrams, multiple scales of analysis
- *Unblocking Engineers' Ideation:* challenging assumptions, breaking functional and field fixedness, finding better frameworks
- *Verifying Appropriateness:* seeking outside perspective, avoiding common failure modes
- *Documenting Project Proposals:* fitting engineering for social justice projects within the growing design-thinking-focused framework, clear communication of problem definition along with the proposed system's expectations and priorities.
I'd be ecstatic to collaborate on any such lesson or course, and would absolutely love contributions of project proposals that result. I'm hoping to run such a lesson myself when possible.
Note that the project proposals currently populating this repository constitute a very small fraction of the potential projects that I have gathered. Please contact my gmail at hani.awni+ENG4SJ to get in touch about the ever-growing collection of 'not-yet-fleshed-out' seed ideas at this intersection. These can additionally serve well as backup in case participants in ideation workshops have difficulty conceiving of productive social-justice-oriented applications of the engineering knowledge they have.
Lastly, ESJ educators may be interested in using the Mastodon social media instance at [m.socialjustice.engineering](https://m.socialjustice.engineering) to connect with other educators, researchers, and practicing engineers interested in engineering and social justice. For context, Mastodon is an open-source, federated social media analogous to a multitude of separate Twitters capable of cross-communication. I'm active on that instance as [@twryst](https://m.socialjustice.engineering/@twryst), and am the admin; feel free to submit a brief application as directed on the registration page itself.
# Contributing Project Proposals
1. Use the shell script provided [here](https://github.com/Eng4SJ/Project-Proposal-Guide/blob/master/proposeENG4SJproject.sh) in this repository to create a new project proposal folder of a given name in your $ENG4SJ_TLDir directory. It will also create the related github project on the Eng4SJ organization page, and setup the associated git connections. Note that this may require being added as a member of the Eng4SJ organization; contact haniawni on github to request access.
1. Fill out the remaining fields of the Project Proposal according to the documentation [here](template-readme.md). Additional documentation about how students will be using the project proposal are available [here](proposal_considerations.md).
1. Submit pull requests accordingly to contribute such projects to the repository! No further linking is necessary; students are already being directed to the organization's page as a whole.
# Providing Feedback on Project Proposals
Feel free to create issues (on the relevant repository or this repository) or reach out to [haniawni](https://github.com/haniawni). Note that many projects are deliberately intended to steer students toward reading further research in Engineering and Social Justice topics; full explanations of these complex problems cannot and should not be provided in order to avoid facilitating a 'listening for spec', Engineering Problem Solving approach in favor of encouraging the use of human centered design for social justice.
# Potential Improvements
- Of course, **the repository always could use more project proposals!** Feel free to contribute ideas of your own or to contact me to germinate seedlings into sufficiently clear projects for inclusion in this repo.
- The current projects are limited to the domains of ECE (electrical and computer engineering) and CS (computer science) bachelors-level capabilities. Other fields, more specialized domains requiring more advanced skillsets, or similar such expansions in scope are exceedingly welcome.
- The projects are currently hosted and browsed on Github. This works very well for CS & ECE projects that would likely use git for version control anyway, but there is likely potential for better interfaces, particularly around the submission of project proposals by teachers unfamiliar with git.
- When projects have been attempted, there is potential for merging the best implementations of the year into that original project proposal repo, allowing future groups to augment or learn from the original group's work. Systems for this assessment, comparison, selection, and actual merging would need to be developed.
- My currently central role in this project as holder-of-keys to project proposal contribution both is inefficient and establishes disquieting power dynamics. The analogous problem in journal reviewing is partially addressed by means of collaborative peer review, but such approaches exhibit undesireable dynamics that strike me as particularly relevant given the ever-evolving, multifaceted nature of social justice. I welcome suggestions for *decentralizing this power and responsibility*.
# Acknowledgements
- Thank you, Dr. Werpetinski and <NAME> at UIUC, for teaching the Engineering and Social Justice Scholars Program in the 2016/2017 academic year. This program has provided the background to reorient my engineering identity from one of investigating intricate shiny baubles to one of attempting to improve the lived experiences of others. This Project Proposal Repository emerges directly from that program as my culminating project, and hopefully will serve as the beginning of a career in engineering for social justice.
- Thank you, <NAME> and Dr. Carney, for collaborating with me on this project.
- Thank you, <NAME>, for the endless banter about the technological feasibility of countless applications that have seeded and will continue to help populate this repo.
- Thank you, <NAME>, <NAME>, and <NAME>, for the conscious and unconscious influence you've had in steering me toward this path.
- Thank github users [jerrykrinock](https://gist.github.com/jerrykrinock) and [robwierzbowski](https://gist.github.com/robwierzbowski) for [this github-repository-creating script](https://gist.github.com/jerrykrinock/6618003 "gitcreate.sh").
<file_sep>/StudentUsageGuide.md
---
title: Student Introductory Briefing
redirect_from:
- /SUG
- /SIB
---
# So You Want to Engineer for Social Justice?
*"Perhaps the most difficult challenge of all will be to disperse the fruits of engineering widely around the globe, to rich and poor alike."*
*-NAE Grand Challenges*
## What is Engineering for Social Justice?
When decision-making processes of engineers or engineering organizations are inspected closely, the vast majority is best characterized as pursuing one of four goals:
* **Implement the Sexy:** To apply ‘cutting-edge’ technological methods to accomplish feats that are ‘innovative’, ‘badass’, ‘formerly impossible’, or simply ‘cool’.
* **Do what we’re told to:** To satisfy the requests of our financial backers, whoever they may be, regardless of both the task and our personal beliefs.
* **Make boatloads of money:** To create a successful company, build a startup into a unicorn and get acquired, to meet a market need.
* **To satisfy our curiosity:** Essentially, because we feel like it and enjoy feeling powerful; doing a neat little project, having fun, without a goal involving anybody but ourselves.
When asked what we see as the purpose of engineering, however, many of us would claim something loftier, such as "solve people’s problems" or “improve the state of the world” or “meet people’s needs”. The four goals above don’t necessarily always align with such ends, despite what we might hope. We, however, have the potential to take a different tack.
This different tack can be summed up by the singular goal of the projects in Engineering for Social Justice:
**To substantively address a problem that materially impacts the lives of people beyond the most privileged elite.**
Other dimensions - whether the method of choice is currently vogue in our field, whether it’s attractive to potential investors seeking to turn a profit, and whether our colleagues are comfortable with it - *are* *explicitly and consciously deprioritized*. Engineers who make this transition in mentality rapidly find ourselves facing problems which our forebears disregarded, that our education has inadequately prepared us for, and which traditional engineering problem solving approaches are extremely ill-suited for. Some example problems we might now try to face include:
* **How do we break cycles of poverty?**
* **How do we foster healthy communities?**
* **How do we prevent police brutality and remove underlying causes?**
* **How do we ensure universal access to quality healthcare?**
* **How do we protect the environment?**
* **How do we empower marginalized groups in pursuit of justice?**
These problems are not new to any of us; all that is new here is how we perceive our role in relation to them. It’s extremely unlikely we could ‘solve’ them in entirety by our skill set alone. We must first acknowledge *why* that is before we investigate *how* we can help.
## Why are these problems different in practice?
#### Complexity
The most immediate difference when we adopt this perspective is the sheer complexity of the problems in question. While all of electrical engineering is reducible to a set of 2 equations, no such reduction can be found for the problem of poverty. We are forced to acknowledge that the problems we’ve been taught to solve, featuring force diagrams, known equations, data structures, or chemical formulae, are dwarfed by the intricacy of people’s lived experiences. We must first **_acknowledge the existence of emergent dynamics_** at the scale of a person finding meaning or interacting with their cultural surroundings.
#### Interdisciplinary
None of the coursework of a current engineering degree explores the causes, mechanisms, and effects of the school-to-prison pipeline, environmental racism, or sexism. **_We must consult experts_** to ensure we do not act from a place of ignorance. Such experts may be scholars, activists, community leaders, artists, librarians- essentially, all the people our ‘technical’ coursework has rarely held up as important.
Our engineering culture encourages us to balk at such a suggestion, asking how their knowledge is ‘meaningful’ if it’s not expressed ‘mathematically’. However, we must check our assumption- the systems of interest constitute a multitude of complex dynamics above and beyond the current expressivity of mathematics. There is no closed-form solution to questions of oppression. Such an idea is blatantly absurd; how would one possibly mathematically express the role an individual’s disability plays in their lived experiences in a job, in the context of the cultural and social history of mankind? As such, **_we must look to other, more capable means of knowing and analyzing these dynamics,_** which said experts commonly employ.
This also implies that while we’ve been taught to conceive of ‘the project’ as only the ‘technical’ aspects, the fact that our goal is at the scale of social systems means **_the ‘social’ components are just as integral to the project_** as any code, circuitry, or mechanisms. There are not ‘technical’ and ‘social’ aspects of this project as entities separable from each other, instead, we are constructing sociotechnical syntheses using any and all available manipulatable mediums.
#### Multifaceted
In addition, we as individuals are not ‘outside’ the systems at play; who we are, our experiences, and our identity (collectively our "social location") are integral to and inseparable from our ability to address such problems. When an engineer is attempting to analyze conductivity of a transmission line, their lived experiences are independent of the result. In contrast, given the differences in social location between me, having grown up in upper-middle class suburbs of Chicago, and my cousins who grew up on a farm in rural Minnesota, there’s a substantial difference in our potential to understand and address causes of rural poverty in the small towns of the Midwest. They’ll be familiar with dynamics I am not, they’ll understand perspectives and have lived experiences I have not, and they’ll know history I do not. When seeking information or collaboration, the relationships they create will differ from those I develop, as does the cultural meaning of our involvement. Thus, **_we must seek out perspectives of and collaboration from the community._**
We must actively attend to not only the voices that step forward to collaborate, but also **_seek out whose perspectives are being excluded,_** even as we attempt to interface with the communities we’re serving. In doing so, **_we have to resist homogenizing our acting model of the ‘community’._** Note that this requires acknowledging the possibility of competing or adversarial dynamics between subgroups of the community and thus being deliberate in our choices of listening. For example, the parents of children may be their abusers and autists themselves may have different goals than even parents ostensibly advocating on their behalf.
#### Consequential
If a more routine senior project fails- a twitter bot produces semicoherent babble, a robotic fish flails uselessly with arrhythmic spasming, or a touchscreen table can only recognize one finger at a time- there’s not really much sunk cost beyond the opportunity cost of your lost time. Regardless of the resultant creation, if one such a project is attempted, added onto your resume’s project list, and forgotten in a dusty closet, the engineering student has de-facto achieved their goal. Our goal differs; for us to succeed at our goal, **_there must be longevity to the project, with plans in place to perpetuate it_** including handling whatever ongoing work or cost is necessary. In addition, as marginalized communities or activists are most likely to be critically time-limited, our endeavors have substantive costs in human effort or resources. **_Being deliberate about the distribution of these burdens during design of the project_** help maximize our impact relative to the imposed cost.
## How do I do a project?
*"After years of having been educated to accept the authority of pre-defined problems coming to them in engineering textbooks, students are trained not to question the legitimacy of specifications (specs), the authority of the client, or the sensibility of the client’s intentions. After receiving the specs, students then embark in a one or two-semester design experience marked by a design concept review, client meetings, prototype testing (with data gathering and analysis), mid-point reviews, manufacturing and budget analyses, and a final design review."*
*-Dr. Leydens, 2014*
#### Instead of Listening for Spec and Designing for Technology?
Leydens is speaking to a very important distinction between goals. Our new goal, expressed in brief as *"address a problem"*, is markedly different from the currently common *“Do what we’re told to”*. **We cannot simply accept the project proposal as it is given**, and must instead apply creativity, research, humility, and whatever else is necessary to actually address the problem in question. **This applies to the project proposals listed here as well.**
While engineering work, coursework, and research are commonly *technology-centric* because they focus on particular technologies, our design process must shift to recenter the problem itself. As explained exceptionally well in Leydens 2014 "What is Design for Social Justice?", this refocusing requires listening for underlying user needs, cultural context, and structural conditions at play in the problem instead of simply listening for the prescribed solution’s technical specifications. Leydens 2014 is highly recommended reading on this distinction.
The proposed projects here will hopefully land in the ballpark of a decent design, but it is important to keep in mind that they’re limited by the social location of the original uploaders, and as such they are limited by their background and assumptions. **These project proposals are intended as a launching-off point for you to tailor or change according to the complications above.** Because of this, the problem dimensions mentioned earlier- namely their complexity, interdisciplinarity, multifacetedness, and consequentiality- must be incorporated in your approach to this project in order for it to succeed at its goal.
#### Instead of ‘Ooh! What if we built-’?
Crucial to engineering for social justice is keeping in mind the project priorities. By constantly checking ourselves with the question "Why are we trying to do this?", we can stay on track and maximize impact by avoiding what amount to shiny distractions. Efficacy, suitability, and longevity are more important than incorporating our field’s flavor-of-the-week method or model. These concerns are further explored in discussions of *appropriate technology*, like in Murphy 2009.
## How do I get course credit for my senior design course?
Because this project proposal repository serves many different engineering senior design courses across colleges, **students must negotiate with course instructors to tailor the project to fit their particular course requirements.** Example types of requirements your class may include are listed here; please feel free to submit pull requests to this repository if you encounter and/or overcome new requirements in your own courses. Please submit a PR to the Collaborating Courses list to represent your course, university, and year.
#### Example Requirements with Possible Resolutions:
##### Client Information Gathering & Project Feedback:
Engineering Senior Design courses are increasingly commonly including a client collaboration component that entails meeting with an industry contact about the project. The purpose of this involvement often entails aspects spanning gathering information and seeking feedback. One such example requirement can be seen [here](proposal_considerations.html#uiuc-cs-492-senior-design-project). Due to our projects’ different goal, while others have specific sponsor companies, we are working in service to an often loosely-affiliated community. In addition, while a company might have a designated contact point person assigned to interact with the student groups, any single contact person is antithetical to our goals due to the multifaceted nature of the project.
Accordingly, seeking feedback and information gathering could be approached by **_creating a ‘Stakeholders Committee’ of ~4 people spanning multiple different perspectives and backgrounds,_** akin to an interdisciplinary PhD’s committee. Such a committee should ideally include a mixture of relevant scholars, practicing community activists, members of the marginalized community themselves, and associated representatives. The purpose in selecting this committee is to ensure accountability in our creation of an effective, integrated sociotechnical project to substantively address the problem of interest. Committee members may disagree with each other in understanding or priorities around the problem; this is a feature, not a bug, as not everybody tackling or facing the same problem is the same.
For example, a project automating around common difficulties faced by ADHD individuals might have its Stakeholders Committee consist of:
* Two people with ADHD with differing symptoms, degree of expression, and/or social location
* A therapist or social worker who focuses on or routinely works with cases of ADHD
* A vocal and active member of a neurodivergent/mental disability advocacy network
* An academic researching social impact of adult adhd in the workplace from a cognitive science, human factors, or disability studies background
These varied perspectives help ensure that the different scales, dimensions, and dynamics of the problem-in-context are adequately highlighted and accounted for. Note how while an individual with ADHD may be focused on alleviating their immediate needs or difficulties, a disability studies academic or neurodivergent advocate may have insight to broader structural components that shift the design.
## Collaborating Courses:
<table>
<tr>
<td>University</td>
<td>Course & Semester(s)</td>
<td>Project</td>
</tr>
<tr>
<td>University of Illinois at Urbana-Champaign</td>
<td>ECE 445 (2017 Spring)</td>
<td>Initial project proposal format</td>
</tr>
<tr>
<td>University of Illinois at Urbana-Champaign</td>
<td>CS 492/494 (2017 Spring)</td>
<td>Initial project proposal format</td>
</tr>
</table>
## Citations:
1. <NAME>., <NAME>, and <NAME>. "Appropriate technology–A comprehensive approach for water and sanitation in the developing world." *Technology in Society* 31.2 (2009): 158-167.
2. <NAME>., <NAME>, and <NAME>. "What is design for social justice." *ASEE Annual Conference and Exposition*. 2014.
3. <NAME>. "Engineering and social justice (Synthesis lectures on engineering, technology, and society)." *Morgan & Claypool Publishers, Washington* (2008). ([Amazon link](https://www.amazon.com/Engineering-Synthesis-Lectures-Engineers-Technology/dp/1598296264))
<file_sep>/proposal_considerations.md
# Additional Considerations for Project Proposals
Here is a smattering of relevant course content of the engineering senior design project courses that this collection is intended to serve.
Reading some of this may help guide the level of clarity, background, and specificity provided in the project proposals.
## [UIUC CS 492: Senior Design Project](https://seniorprojects.cs.illinois.edu/confluence/display/CourseContent/Syllabus)

## [UIUC ECE 445: Senior Design Project](https://courses.engr.illinois.edu/ece445/)
Project proposal ideas are fairly freeform at first, entailling just a description in conversational language. Unfortunately, access to see example posts of students past requires login with university credentials.<file_sep>/ESJ-Ideation-Workshops/Overview.md
# CURRENTLY IN DEVELOPMENT
## Ideation Workshop & Lesson Plan
### Objectives:
This add-on lesson plan follows a ‘diagnostic’ event exploring current social injustices in order to engage future engineers with finding ‘targeted interventions’, in the form of feasible project proposals, that can undermine or prevent such injustice or address related needs.
### Themes:
- Finding Structural Causes and Consequences: Generalized Lotus Diagrams, multiple scales of analysis
- Unblocking Engineers' Ideation: challenging assumptions, breaking functional and field fixedness, finding better frameworks
- Verifying Appropriateness: seeking outside perspective, avoiding common failure modes
- Documenting Project Proposals: fitting engineering for social justice projects within the growing design-thinking-focused framework, clear communication of problem definition along with the proposed system's expectations and priorities.
### Takeaways:
- To internalize that engineers of all disciplines are capable of working toward social justice, driven home with a fleshed-out personally-relevant example.
- Learn to notice underlying limiting assumptions at play impairing this effort, including:
- Problems span multiple scales of analysis
- Target causes rather than symptoms
- Few problems have 3 or fewer causes, even if that’s where it stops being easy.
- There’s no meaningful distinction between technical vs social problem or solution dynamics.
- The purpose is the problem, not how it needs my narrowly-defined subfield.
- My tools are useful in nonstandard ways.
- I know more than my specialization.
<file_sep>/template-readme.md
## Background
Brief (1paragraph) overview of the context surrounding the problem of focus.
## Objective
How would a technological component be able help here?
## High Level Requirements
### Minimum Requirements
What specific functionality is necessary for the project to be meaningfully complete in good faith?
### Basic Requirements
What would the project need in order to have truly substantive impact?
### Ideal Capabilities
What would constitute stretch goals of the project?
## Ethics/Social Justice Concerns
+ How might this project reinforce the unjustices at play if the engineers on it do not seek sufficiently broad perspective about their implementation?
+ What oft-overlooked pitfalls exist in the technical space the users are likely to enter that the engineers should put forth active effort to avoid?
+ What subtleties exist around the social dimensions that an unfamiliar but well-intentioned engineer might overlook?
## Provided Materials & Recommended Research Topics
+ Are there any materials provided which the engineering students may find useful?
+ Are there any recommended terms for further research by the engineers exploring this project?
## Questions for Reflection
+ Why has this problem not been addressed by now?
+
|
764737a0ecad6efcadb3ba586352c34628ef014d
|
[
"Markdown",
"Shell"
] | 6
|
Shell
|
hadijakay/Project-Proposal-Guide
|
1e22860b460ae5555cc80c319c4dd635c5fd85f2
|
903a61781f0a8257fdcf6c93354961c074ec6c3c
|
refs/heads/main
|
<file_sep>#include <stdio.h>
#include <stdint.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <sys/time.h>
#include <hd44780.h>
#include <pcf8574.h>
#include <string.h>
#include "periph_sdcard.h"
#include "LCD/LCD.h"
#include "home.h"
#include "RotaryEncoder_Adapter.h"
#include "../menutools/statusbar/statusbar.h"
#include "AudioSetup/AudioSetup.h"
#include "audioRecognition.h"
#include "audioRecognition.h"
#define SDA_GPIO 18
#define SCL_GPIO 23
#define I2C_ADDR 0x27
void initializeRotary() {
commands_t void_func_ptr;
void_func_ptr.left = &scrollLeft;;
void_func_ptr.right = &scrollRight;;
void_func_ptr.press = &getSelectedOption;
RotaryEncoder_AdapterInit(void_func_ptr);
}
/*end of example*/
void app_main() {
ESP_ERROR_CHECK(i2cdev_init());
//START OF ROTARY TASK
initializeRotary();
while (1) {
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
<file_sep>#ifndef RotaryEncoder_Adapter_H
#define RotaryEncoder_Adapter_H
#include "esp_err.h"
typedef void(*commandLeft_t)(); // void function pointer.
typedef void(*commandright_t)(); // void function pointer.
typedef void(*commandpress_t)(); // void function pointer.
// void function pointers as callbacks
typedef struct{
commandLeft_t left;
commandright_t right;
commandpress_t press;
}commands_t;
/**
* Initializes the adapter.
* @param void_Function_Calls callbacks as defined in struct.
* @return error code.
*/
esp_err_t RotaryEncoder_AdapterInit(commands_t void_Function_Calls);
/**
* Frees the adapter from memory.
* @return error code.
*/
esp_err_t RotaryEncoder_AdapterFree();
#endif<file_sep>idf_component_register(
SRCS "RotaryEncoder_Driver.c" "RotaryEncoder_Adapter.c"
INCLUDE_DIRS .
REQUIRES i2cdev
)<file_sep>if(${IDF_TARGET} STREQUAL esp8266)
set(req esp8266 freertos esp_idf_lib_helpers)
else()
set(req driver freertos esp_idf_lib_helpers)
endif()
idf_component_register(
SRCS "i2cdev.c"
INCLUDE_DIRS .
REQUIRES ${req}
)
<file_sep>Beschrijving:
Deze code bestuurt de Rotary Encoder welke wij tijdens het project gebruikt hebben door middel van het gebruik van een driver en een adapter.
Eigen code:
De code welke staat in de Rotary Encoder component en in de main is eigen code. Deze code was voor het project al geschreven en was gebaseerd op al bestaande code van een mode student. Echter is deze driver van scratch herschreven om thread safe te kunnen opereren door de i2cDev library te gebruiken, deze library is niet zelf geschreven.<file_sep>COMPONENT_ADD_INCLUDEDIRS = .
ifdef CONFIG_IDF_TARGET_ESP8266
COMPONENT_DEPENDS = esp8266 freertos
else
COMPONENT_DEPENDS = driver freertos
endif
<file_sep>#include "RotaryEncoder_Adapter.h"
#include "RotaryEncoder_Driver.h"
#include "esp_log.h"
#define SDA_GPIO 18
#define SCL_GPIO 23
i2c_dev_t dev;
commands_t commands;
void RotaryEncoder_Read();
esp_err_t RotaryEncoder_get_diff(uint16_t *val);
esp_err_t RotaryEncoder_get_command(uint8_t val);
esp_err_t RotaryEncoder_AdapterFree();
/**
* Reads and processes raw 8-bit data from the Rotary Driver.
*/
void RotaryEncoder_Read() {
uint8_t val = 0;
while (1) {
RotaryEncoder_port_read(&dev,STAT,&val);
RotaryEncoder_port_write(&dev,STAT,0);
if (val > 0) {
RotaryEncoder_get_command(val);
}
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
/**
* Interprets the 16-bit diff value and generates an action.
* @param val diff value.
* @return error code.
*/
esp_err_t RotaryEncoder_get_command(uint8_t val){
uint16_t data = 0;
switch (val)
{
case 1:
RotaryEncoder_get_diff(&data);
if(data > 0 && data < 1000) {
ESP_LOGI("Rotary Encoder", "Turning Right");
commands.right();
}
else {
ESP_LOGI("Rotary Encoder", "Turning Left");
commands.left();
}
break;
case 4:
ESP_LOGI("Rotary Encoder", "Button Pressed");
commands.press();
break;
default:
ESP_LOGI("Rotary Encoder", "Adapter read misfire with value: %d", val);
}
return ESP_OK;
}
/**
* Interprets the raw 16-bit data received from the driver.
* @param val raw value of rotary driver.
* @return error code.
*/
esp_err_t RotaryEncoder_get_diff(uint16_t *val){
RotaryEncoder_port_read16(&dev,RE_COUNT_LSB,val);
RotaryEncoder_port_write16(&dev,RE_COUNT_LSB,0);
return ESP_OK;
}
/**
* Initializes the adapter.
* @param void_Function_Calls callbacks as defined in struct.
* @return error code.
*/
esp_err_t RotaryEncoder_AdapterInit(commands_t void_Function_Calls){
RotaryEncoder_init(&dev,0,0x3F,SDA_GPIO,SCL_GPIO); // 0x3F is the address of the Rotary Encoder.
commands = void_Function_Calls;
xTaskCreate(RotaryEncoder_Read, "Rotary_read_task", configMINIMAL_STACK_SIZE * 5, NULL, 5, NULL);
return ESP_OK;
}
/**
* Frees the adapter from memory.
* @return error code.
*/
esp_err_t RotaryEncoder_AdapterFree(){
RotaryEncoder_free(&dev);
return ESP_OK;
}
<file_sep>#include "RotaryEncoder_Driver.h"
#include <stdint.h>
#define I2C_FREQ_HZ 100000
//region Memory Allocation / Thread Safety
/**
* Initializes the Rotary Driver.
* @param dev Thread safe handle for I2C.
* @param port The I2C port to communicate with.
* @param addr Address of the device.
* @param sda_gpio SDA address of the GPIO PIN.
* @param scl_gpio SLC address of the GPIO PIN.
* @return Error code.
*/
esp_err_t RotaryEncoder_init(i2c_dev_t *dev, i2c_port_t port, uint8_t addr, int sda_gpio, int scl_gpio){
dev->port = port;
dev->addr = addr;
dev->cfg.sda_io_num = sda_gpio;
dev->cfg.scl_io_num = scl_gpio;
#if HELPER_TARGET_IS_ESP32
dev->cfg.master.clk_speed = I2C_FREQ_HZ;
#endif
return i2c_dev_create_mutex(dev);
}
/**
* Thread safe helper function for reading data from the rotary.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return
*/
static esp_err_t read_port(i2c_dev_t *dev, int8_t reg, uint8_t *val)
{
I2C_DEV_TAKE_MUTEX(dev);
I2C_DEV_CHECK(dev, i2c_dev_read(dev, ®, sizeof(int8_t), val, 1));
I2C_DEV_GIVE_MUTEX(dev);
return ESP_OK;
}
/**
* Thread safe helper function for writing data to the rotary.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
static esp_err_t write_port(i2c_dev_t *dev, int8_t reg ,uint8_t val)
{
I2C_DEV_TAKE_MUTEX(dev);
I2C_DEV_CHECK(dev, i2c_dev_write(dev, ®, sizeof(int8_t), &val, 1));
I2C_DEV_GIVE_MUTEX(dev);
return ESP_OK;
}
/**
* Frees the Rotary Driver from Memory.
* @param dev Thread safe handle for I2C.
* @return Error code.
*/
esp_err_t RotaryEncoder_free(i2c_dev_t *dev)
{
return i2c_dev_delete_mutex(dev);
}
//endregion
//region 8Bit
/**
* Reads the 8-Bit raw value from the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_read(i2c_dev_t *dev, uint8_t reg, uint8_t *val)
{
return read_port(dev,reg,val);
}
/**
* writes the 8-Bit raw value to the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_write(i2c_dev_t *dev, uint8_t reg, uint8_t val)
{
return write_port(dev,reg,val);
}
//endregion
//region 16Bit
/**
* Reads the 16-Bit raw value from the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_read16(i2c_dev_t *dev, uint8_t reg, uint16_t *val)
{
//define bits for 2 registers
uint8_t LSB = 0x00;
uint8_t MSB = 0x00;
//get values of both registers
read_port(dev,reg,&LSB);
read_port(dev,reg+1,&MSB);
//shift them into eachother and send them back
*val = ((uint16_t)MSB << 8 | LSB);
return ESP_OK;
}
/**
* writes the 16-Bit raw value to the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_write16(i2c_dev_t *dev, uint8_t reg, uint16_t val)
{
// writes to the 8bit regs separately.
write_port(dev,reg,(uint8_t)val << 8); //write to the first reg.
write_port(dev,reg+1,(uint8_t)val >> 8); //write to the second reg.
return ESP_OK;
}
//endregion<file_sep>#ifndef RotaryEncoder_H
#define RotaryEncoder_H
#include "esp_err.h"
#include "i2cdev.h"
typedef enum{
STAT = 0x01, //Status of the Qwiic Twist. 3:0 = buttonPressed(3),
RE_COUNT_LSB = 0x05,
}RE_reg_t;
//region Memory Allocation / Thread Safety
/**
* Initializes the Rotary Driver.
* @param dev Thread safe handle for I2C.
* @param port The I2C port to communicate with.
* @param addr Address of the device.
* @param sda_gpio SDA address of the GPIO PIN.
* @param scl_gpio SLC address of the GPIO PIN.
* @return Error code.
*/
esp_err_t RotaryEncoder_init(i2c_dev_t *dev, i2c_port_t port, uint8_t addr, int sda_gpio, int scl_gpio);
/**
* Thread safe helper function for reading data from the rotary.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return
*/
esp_err_t RotaryEncoder_free(i2c_dev_t *dev);
//endregion
//region 8Bit
/**
* Reads the 8-Bit raw value from the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_read(i2c_dev_t *dev, uint8_t reg, uint8_t *val);
/**
* writes the 8-Bit raw value to the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_write(i2c_dev_t *dev, uint8_t reg, uint8_t val);
//endregion
//region 16Bit
/**
* Reads the 16-Bit raw value from the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_read16(i2c_dev_t *dev, uint8_t reg, uint16_t *val);
/**
* writes the 16-Bit raw value to the Rotary Encoder.
* @param dev Thread safe handle for I2C.
* @param reg Registry address.
* @param val Value to fill with raw data.
* @return Error code.
*/
esp_err_t RotaryEncoder_port_write16(i2c_dev_t *dev, uint8_t reg, uint16_t val);
//endregion
#endif
|
e6829ba723ee6c12337c7de59b1866e74c1e1756
|
[
"Text",
"C",
"CMake",
"Makefile"
] | 9
|
C
|
MickWerf/Proftaak-2.3-Individueel-Rotary-Encoder
|
fbb351237b2623ca26ff7f342f250afd5bf081f6
|
333f17f37bda534e1048305772f8f2c002a8bd18
|
refs/heads/master
|
<repo_name>RPadilla3/contacts<file_sep>/src/js/detail-view.js
(function() {
'use strict';
window.contacts = window.contacts || {};
window.contacts.showDetails = showDetails;
/**
* Show details of current contact
* @param {Object} contact information about contact
*/
function showDetails(contact) {
if(typeof(contact) !== 'object') {
return;
}
$('#details')
.html('')
.append(
'<p>'+ 'Name: ' + contact.name.first + '</p><p>' +'Date of Birth: '
+ contact.dob + '</p>' + '<p>' + 'Email: ' + contact.email + '</p>'
+ '<p>' + 'gender: ' + contact.gender + '</p>'
);
}
})();
|
f06b202740f78e10e60a86487cd9817bf508f424
|
[
"JavaScript"
] | 1
|
JavaScript
|
RPadilla3/contacts
|
823f6b93d3b143ecfa7ad9cfd4e8d5829408c32b
|
b377b2f2dc16deeb2dcb3b335a6cb7ae739c7e96
|
refs/heads/master
|
<file_sep>public double GetRandomNumber1() {
Random random = new Random();
return (random.nextDouble() - 0.5) * 2;
}
public double GetRandomNumber2() {
Random random = new Random();
return (random.nextDouble() - 0.5) * 2.99;
}
Commit comm = new commit;
Hello World!!!<file_sep>
public class CodeReview {
/// <summary>
/// This method returns integer parsed from the source.
/// If parsing fails it should return zero.
/// </summary>
/// <param name="o">Object with data to parse.</param>
/// <returns>Parsed value</returns>
public int Parse(Object o) {
try {
return (int)o;
} catch (Exception e) {
return 0;
}
}
/// <summary>
/// This method returns concatenated string from the array of the strings.
/// </summary>
/// <param name="lines">Array of strings with lines.</param>
/// <returns>Concatenated string.</returns>
public String Concat(String[] lines) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
result.append(lines[i]);
}
return result.toString();
}
}
|
701f69f2c4a1c167d7cf882e438fcfb7116addd1
|
[
"C#"
] | 2
|
C#
|
armanok/CodeReview
|
03df46d65d8a48d5c25b9a324c485d022167940f
|
caaee8728d9a56c26655a7d2f1ccbf213231d9bd
|
refs/heads/master
|
<repo_name>jaycork93/BCGame<file_sep>/FBullCowGame.cpp
#pragma once
#include "FBullCowGame.h"
#include <map>
#define TMap std::map // to make syntaz more Unreal freindly
using int32 = int;
FBullCowGame::FBullCowGame() { Reset(1); } // Default Constructor
int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; }
int32 FBullCowGame::GetHiddenWordLength() const { return MyHiddenWord.length(); }
bool FBullCowGame::IsGameWon() const { return bGameIsWon; }
int32 FBullCowGame::GetMaxTries() const
{
TMap <int32, int32> WordLengthToMaxTries{ { 2,3 },{ 3,4 },{ 4,7 },{ 5,10 },{ 6,16 },{ 7,20 },{ 8,24 },{ 9,28 },{ 10,32 },{ 11,40 },{ 12,45 },{ 13,50 },{ 14,58 },{ 15,65 } };
return WordLengthToMaxTries[MyHiddenWord.length()];
}
FString FBullCowGame::GetWordDifficulty(int32 WordDifficulty) const
{
FString ChosenWord;
FString SimpleWords[] = { "arm", "ore", "rig", "sat", "nut" };
FString MediumWords[] = { "guilty", "rapids", "wraith", "knights", "workday" };
FString HardWords[] = { "chandlers", "godfarthers", "zephyr", "lifeguard", "neighborly" };
switch (WordDifficulty)
{
case 1:
ChosenWord = SimpleWords[rand() % 5];
break;
case 2:
ChosenWord = MediumWords[rand() % 5];
break;
case 3:
ChosenWord = HardWords[rand() % 5];
break;
default:
break;
}
return ChosenWord;
}
void FBullCowGame::Reset(int32 Difficulty)
{
const FString HIDDEN_WORD = GetWordDifficulty(Difficulty);
MyHiddenWord = HIDDEN_WORD;
MyCurrentTry = 1;
bGameIsWon = false;
return;
}
EGuessStatus FBullCowGame::CheckGuessValidity(FString Guess) const
{
//if guess isn't an isogram then return an error
if (!IsIsogram(Guess))
{
return EGuessStatus::Not_Isogram;
}
//if the guess in't all lower case
else if (!IsLowercase(Guess))
{
return EGuessStatus::Not_Lowercase;
}
//Check to see if guess is the correct length
else if (Guess.length() != GetHiddenWordLength())
{
return EGuessStatus::Wrong_Length;
}
else
{
return EGuessStatus::OK;
}
}
// receives a VALID guess, incriments turn, and returns count
FBullCowCount FBullCowGame::SubmitValidGuess(FString Guess)
{
MyCurrentTry++;
FBullCowCount BullCowCount;
// loop through all letters in the hidden word
int32 WordLength = MyHiddenWord.length(); //assuming same length as guess
for (int32 MHWChar = 0; MHWChar < WordLength; MHWChar++) {
// compare letters against the guess
for (int32 GChar = 0; GChar < WordLength; GChar++) {
// if they match then
if (Guess[GChar] == MyHiddenWord[MHWChar]) {
if (MHWChar == GChar) { // if they're in the same place
BullCowCount.Bulls++; // incriment bulls
}
else {
BullCowCount.Cows++; // must be a cow
}
}
}
}
if (BullCowCount.Bulls >= WordLength)
{
bGameIsWon = true;
}
else
{
bGameIsWon = false;
}
return BullCowCount;
}
bool FBullCowGame::IsIsogram(FString Word) const
{
// treat 0 and 1 letter words as isograms
if (Word.length() <= 1) { return true; }
TMap <char, bool> LetterSeen;
for (auto Letter : Word) // Means (for all letters of the word)
{
Letter = tolower(Letter); // handle mixed case letter
if (LetterSeen[Letter])
{ return false; }
else
{ LetterSeen[Letter] = true; }
}
return true; //for example in cases were \0 is entered
}
bool FBullCowGame::IsLowercase(FString Word) const
{
//Loop through all the letters
for (auto Letter : Word) //Means (for all letters of the word)
{
if (!islower(Letter)) // Check to see if the character is lowercase
{ return false; }
else
{ return true; }
}
}
<file_sep>/README.md
# BCGame
The Bull and Cow Game Thing
<file_sep>/main.cpp
/* This is the console executable, that makes use of the BullCow class
This acts as the view in a MVC pattern, and is responsible for all
user interaction. For game logic see the FBullCowGame class.
*/
#pragma once
#include <iostream>
#include <string>
#include "FBullCowGame.h"
// to make the sysntax unreal frienndly
using FString = std::string;
using int32 = int;
// function prototypes as outside a class
int32 AskSinglePlayer();
void PrintIntro();
void PlayGame();
FString GetValidGuess();
bool AskToPlayAgain();
void PrintGameSummary();
FString GetCustomWord();
int32 AskDifficulty();
FBullCowGame BCGame; // instantiate a new game, which we use across plays
// the entry point for our application
int main()
{
bool bPlayAgain = false;
do
{
PrintIntro();
PlayGame();
bPlayAgain = AskToPlayAgain();
} while (bPlayAgain);
return 0; // exit the application
}
// TODO Ask if the want a single player version of the game
// TODO Ask how many player's are there
void PrintIntro()
{
std::cout << "Welcome to Bulls and Cows, an animal themed Mastermind rip off!\n\n";
std::cout << " } { ___ " << std::endl;
std::cout << " (o o) (o o) " << std::endl;
std::cout << " /-------\\ / \\ /-------\\ " << std::endl;
std::cout << " / | BULL |O O| COW | \\ " << std::endl;
std::cout << " * |-,--- | |------| * " << std::endl;
std::cout << " ^ ^ ^ ^ " << std::endl;
std::cout << "A Cow means you got a letter right but in the wrong position.\n";
std::cout << "A Bull means you got the letter right and it's in the correct position.\n";
std::cout << "Good luck!\n";
std::cout << std::endl;
return;
}
// plays a single game to completion
void PlayGame()
{
int32 Players = AskSinglePlayer();
std::cout << "\nStarting a " << Players << " player game.\n\n";
if (Players == 1)
{
int32 Difficulty = AskDifficulty();
BCGame.Reset(Difficulty);
}
if (Players == 2)
{
BCGame.Reset(1);
GetCustomWord();
}
std::cout << "Can you guess the " << BCGame.GetHiddenWordLength() << " letter isogram I'm thinking of?\n";
std::cout << "You have " << BCGame.GetMaxTries() << " valid attempts to get it right.\n";
int32 MaxTries = BCGame.GetMaxTries();
// loop asking for guesses while the game is NOT won
//and there are still triesd remaining
while (!BCGame.IsGameWon() && BCGame.GetCurrentTry() <= MaxTries )
{
FString Guess = GetValidGuess();
// submit valid guess to the game, and receive counts
FBullCowCount BullCowCount = BCGame.SubmitValidGuess(Guess);
std::cout << "Bulls = " << BullCowCount.Bulls;
std::cout << ". Cows = " << BullCowCount.Cows << "\n";
}
PrintGameSummary();
return;
}
// Loop until the user gives a valid guess
FString GetValidGuess()
{
int32 CurrentTry = BCGame.GetCurrentTry();
FString Guess = "";
EGuessStatus Status = EGuessStatus::Invalid_Status;
do {
// get a guess from the player
std::cout << "\nTry " << CurrentTry << " of " << BCGame.GetMaxTries() <<". Enter your guess: ";
std::getline(std::cin, Guess);
Status = BCGame.CheckGuessValidity(Guess);
switch (Status)
{
case EGuessStatus::Wrong_Length:
std::cout << "Please enter a " << BCGame.GetHiddenWordLength() << " letter word.\n\n";
break;
case EGuessStatus::Not_Isogram:
std::cout << "PLease enter a word without repeating letters. \n\n";
break;
case EGuessStatus::Not_Lowercase:
std::cout << "Please refrain from using anything but lowercase letters. Thank you!\n\n";
break;
default: //asunme the guess is valid
break;
}
} while (Status != EGuessStatus::OK); //Keep looping untill we get no errors
return Guess;
}
bool AskToPlayAgain()
{
std::cout << "Do you want to play again (y/n)? ";
FString Response = "";
std::getline(std::cin, Response);
return (Response[0] == 'y') || (Response[0] == 'Y');
}
void PrintGameSummary()
{
if (BCGame.IsGameWon())
{
std::cout << "GOOD JOB - YOU WIN!\n";
}
else
{
std::cout << "Better luck next time!\n";
}
}
int32 AskSinglePlayer()
{
std::cout << "How many player's are the 1 or 2?\n";
int Response;
std::cin >> Response;
return Response;
}
FString GetCustomWord()
{
std::cout << "Enter an isogram (lower case) for Player 2. Then give them control.\n";
FString responce = "";
std::cin >> responce;
std::cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; //clear screen
return BCGame.MyHiddenWord = responce;
}
int32 AskDifficulty()
{
int32 DifficultyLevel;
do
{
std::cout << "Please select a diffuculty rating from 1 to 3.\n";
std::cin >> DifficultyLevel;
std::cout << std::endl;
} while (DifficultyLevel != 1 && DifficultyLevel != 2 && DifficultyLevel != 3);
return DifficultyLevel;
}
|
1b29cb79a68fbd524a69882db61a9a4a4426b891
|
[
"Markdown",
"C++"
] | 3
|
C++
|
jaycork93/BCGame
|
6b97f7efd6ffcaa55bce9d68fbdb31cfc02f0af1
|
b8b97445124eb080096dba6780f3ddedd33aad3b
|
refs/heads/master
|
<file_sep>require 'json'
require_relative 'backstageadapter.rb'
class ScriptRunner
BACKSTAGE_URI = "http://www.backstage.com/casting/open-casting-calls/nyc-auditions/?page="
def run
adapter = BackstageAdapter.new
# parser = Parser.new
# lpn = adapter.getLastPageNumber
# newList = []
# (1..lpn).each do | i |
# data = adapter.scrape(BACKSTAGE_URI + i)
# parsedData = parser.parse(data)
# newList << parsedData
# end
list = adapter.scrape(BACKSTAGE_URI + 1.to_s)
json = JSON.dump(list)
File.open("file.json", 'w') {|f| f.write(list) }
end
end
ScriptRunner.new.run
<file_sep>require 'nokogiri'
require 'open-uri'
require 'pry'
class BackstageAdapter
def scrape(link)
doc = Nokogiri::HTML(open(link))
all_listings = []
doc.css('li.callListing').each do |listing|
items = {}
items["title"] = listing.css('div.castingRoleToggle p.title a.callLink strong').text
items["description"] = listing.css('ul.castingInformation li')[0].text
items["job"] = listing.css('p.castingInformation').text
tagArr = []
listing.css('div.article-tags span.tag a').each do |tag|
tagArr << tag.text
end
items["tags"] = tagArr.join(", ")
items["link"] = 'http://www.backstage.com' + listing.css('p.title a').attribute('href').value
items["time_listed"] = listing.css('span.timeTag').text
all_listings << items
end
all_listings
end
end
|
f79e1d6e4e950c48ede360f4bd4c78a17f0df3b3
|
[
"Ruby"
] | 2
|
Ruby
|
skoltz/for-jake
|
8f49030cad2c00518c0e5e1f1d5d2549711430c9
|
4f1fb2bc717f910af579336aa9d07593c62907d6
|
refs/heads/master
|
<repo_name>Emurasoft/HTMLBar<file_sep>/mui/HTMLBar_loce/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by htmlbar_loce.rc
//
#define IDS_SURE_TO_UNINSTALL 1
#define IDS_VERSION 2
#define IDS_MENU_TEXT 3
#define IDS_STATUS_MESSAGE 4
#define IDS_TITLE 5
#define IDS_INVALID_VERSION 7
#define IDS_FILTER_IMAGE 8
#define IDS_PICTURE 9
#define IDS_FILTER_HYPERLINK 10
#define IDS_HYPERLINK 11
#define IDS_CONFIGS 12
#define IDS_PARAMETER 13
#define IDS_VALUE 14
#define IDS_SURE_RESET 15
#define IDD_FONT 100
#define IDD_DIALOGBAR 103
#define IDD_PROP 116
#define IDD_INPUT_PARAMS 131
#define IDR_POPUP_HEADER 135
#define IDR_POPUP_FONT 136
#define IDD_TABLE 137
#define IDR_POPUP_FORM 138
#define IDD_CUSTOMIZE 146
#define IDD_CUST_PROP 147
#define IDR_ARG_POPUP 178
#define IDC_RESET 1004
#define IDC_LIST 1008
#define IDC_ROWS 1020
#define IDC_COLUMNS 1021
#define IDC_AUTO_DISPLAY 1022
#define IDC_NEW 1025
#define IDC_DELETE 1026
#define IDC_COPY 1027
#define IDC_UP 1028
#define IDC_DOWN 1029
#define IDC_PROP 1030
#define IDC_TITLE 1034
#define IDC_TAGS 1035
#define IDC_TAG_BEGIN 1036
#define IDC_TAG_END 1037
#define IDC_SPECIAL 1039
#define IDC_COMBO_SPECIAL 1042
#define IDC_BROWSE_BEGIN 1043
#define IDC_BROWSE_END 1044
#define IDC_SEPARATOR 1045
#define IDC_CUSTOMIZE 1046
#define IDC_COMBO_ICON 1047
#define ID_HEADER 40000
#define ID_PARAGRAPH 40001
#define ID_BREAK 40002
#define ID_BOLD 40003
#define ID_ITALIC 40004
#define ID_UNDERLINE 40005
#define ID_FONT 40006
#define ID_COLOR 40007
#define ID_PICTURE 40008
#define ID_HYPERLINK 40009
#define ID_TABLE 40010
#define ID_HORZ_LINE 40011
#define ID_COMMENT 40012
#define ID_ALIGN_LEFT 40013
#define ID_CENTER 40014
#define ID_ALIGN_RIGHT 40015
#define ID_JUSTIFY 40016
#define ID_NUMBERING 40017
#define ID_BULLETS 40018
#define ID_UNINDENT 40019
#define ID_INDENT 40020
#define ID_HIGHLIGHT 40021
#define ID_FONT_COLOR 40022
#define ID_FORM 40023
#define ID_CUSTOMIZE 40024
#define ID_FORM_FORM 40025
#define ID_TEXTBOX 40026
#define ID_PASSWORD 40027
#define ID_TEXTAREA 40028
#define ID_CHECKBOX 40029
#define ID_OPTIONBUTTON 40030
#define ID_GROUPBOX 40031
#define ID_DROPDOWNBOX 40032
#define ID_LISTBOX 40033
#define ID_PUSHBUTTON 40034
#define ID_ADVANCEDBUTTON 40035
#define ID_HIDDENINPUT 40036
#define ID_OBJECT 40037
#define ID_CAMERA 40038
#define ID_CD 40039
#define ID_SCANNER 40040
#define ID_PRINTER 40041
#define ID_FUNCTION 40042
#define ID_CRITICALERROR 40043
#define ID_WARNING 40044
#define ID_INFORMATION 40045
#define ID_BLUEFLAG 40046
#define ID_BACKGROUNDSOUND 40047
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/myreg.h
#pragma once
void GetProfileStringReg( HKEY hKey, LPCTSTR lpszEntry, LPTSTR lpszBuf, DWORD cchBufSize, LPCTSTR lpszDefault )
{
DWORD dwType, dwCount;
dwCount = cchBufSize * sizeof( TCHAR );
if( hKey == NULL
|| RegQueryValueEx( hKey, lpszEntry, NULL, &dwType, (LPBYTE)lpszBuf, &dwCount) != ERROR_SUCCESS ){
StringCopy( lpszBuf, cchBufSize, lpszDefault );
}
}
<file_sep>/HTMLBar.cpp
// WordCount.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "resource.h"
#include "mui\htmlbar_loce\resource.h"
// the following line is needed before #include <etlframe.h>
#define ETL_FRAME_CLASS_NAME CMyFrame
#include <etlframe.h>
#include "mystring.h"
#include "myreg.h"
#ifdef _DEBUG
#define new _DEBUG_NEW
#else
#define new _RELEASE_NEW
#endif
//#include "HighDPI.h"
#include "HTMLBar.h"
//CDPI g_metrics;
<file_sep>/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by HTMLBar.rc
//
#define IDB_BITMAP 101
#define IDB_TRUE_16_BW 109
#define IDB_TRUE_16_DEFAULT 110
#define IDB_TRUE_16_HOT 111
#define IDB_TRUE_24_BW 112
#define IDB_TRUE_24_DEFAULT 113
#define IDB_TRUE_24_HOT 114
#define IDB_16C_24 115
#define IDB_TOOLBAR 134
#define IDB_BITMAP1 148
#define IDB_TOOLBAR_LARGE 148
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 149
#define _APS_NEXT_COMMAND_VALUE 40008
#define _APS_NEXT_CONTROL_VALUE 1049
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/HTMLBar.h
// implementatin of this specific plug-in is here:
//
#define MAX_BUTTON_TITLE 260
#define MAX_TAG_FIELD 260
#define BUTTON_SIZE_SMALL 22
#define BUTTON_SIZE_LARGE 30
#define SIGNATURE_CMD_ARRAY 0x00FE0100
#define MAX_RECENT_FONT 8
#define ID_COMMAND_BASE 100
#define ZERO_INIT_FIRST_MEM(classname, firstmem) ZeroMemory( &firstmem, sizeof( classname ) - ((char*)&firstmem - (char*)this) );
INT_PTR CALLBACK NewProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
INT_PTR CALLBACK TableDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
INT_PTR CALLBACK PropDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
INT_PTR CALLBACK InputParamsDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
LRESULT CALLBACK EditProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
INT_PTR CALLBACK CustomizeDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
INT_PTR CALLBACK CustPropDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam );
//extern CDPI g_metrics;
LPCTSTR szCmdArrayEntry = _T("CmdArray");
LPCTSTR const szLargeToolbar = _T("LargeToolbar");
#define MAX_SNIPPET_LENGTH 260
#define TOOL_ARG_PATH 0
#define TOOL_ARG_DIR 1
#define TOOL_ARG_FILENAME 2
#define TOOL_ARG_EXT 3
#define TOOL_ARG_CURLINE 4
#define TOOL_ARG_SELTEXT 5
#define TOOL_ARG_DATE 6
#define TOOL_ARG_TIME 7
#define TOOL_ARG_PICK_FULL_PATH 8
#define TOOL_ARG_PICK_RELATIVE_PATH 9
#define TOOL_ARG_PICK_COLOR 10
#define TOOL_ARG_DEF_COLOR 11
#define MAX_TOOL_ARG_NO_INTERFACE 8
#define MAX_TOOL_ARG 12
LPCTSTR const szCustColors = _T("CustColors");
LPCTSTR szToolArgs[MAX_TOOL_ARG] = {
_T("Path"),
_T("Dir"),
_T("Filename"),
_T("Ext"),
_T("CurLine"),
_T("SelText"),
_T("Date"),
_T("Time"),
_T("PickFullPath"),
_T("PickRelativePath"),
_T("PickColor"),
_T("DefColor"),
};
HBITMAP MyLoadBitmap( HINSTANCE hInstance, LPCTSTR lpBitmapName )
{
return (HBITMAP)LoadImage( hInstance, lpBitmapName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION );
}
int GetBitmapCount( HBITMAP hbm, int cxUnitWidth )
{
BITMAP bm = {0};
VERIFY( GetObject( hbm, sizeof(bm), &bm ) );
int nNumImages = bm.bmWidth / cxUnitWidth;
return nNumImages;
}
BOOL StretchBitmap( HBITMAP* phbm, int cxDstImg, int cyDstImg, int cImagesX, int cImagesY )
{
HBITMAP hbmImage = (HBITMAP)CopyImage( *phbm, IMAGE_BITMAP, cxDstImg * cImagesX, cyDstImg * cImagesY, LR_CREATEDIBSECTION );
if( hbmImage ){
VERIFY( DeleteObject( *phbm ) );
*phbm = hbmImage;
return TRUE;
}
return FALSE;
}
void CenterWindow( HWND hDlg )
{
RECT myrt, prrt;
HWND hWndParent = GetParent(hDlg);
if (!hWndParent || IsIconic(hWndParent)){
hWndParent = GetDesktopWindow();
}
if( GetWindowRect(hWndParent, &prrt) && GetWindowRect(hDlg, &myrt) ){
SetWindowPos(hDlg, NULL, prrt.left + (((prrt.right - prrt.left) - (myrt.right - myrt.left)) / 2), prrt.top + (((prrt.bottom - prrt.top) - (myrt.bottom - myrt.top)) / 2), 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
}
WCHAR HexToDec( LPWSTR& p )
{
WCHAR sz[5];
WCHAR* po = sz;
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p;
}
}
}
*po++ = '\0';
return (WCHAR)wcstoul( sz, NULL, 16 );
}
WCHAR OctToDec( LPWSTR& p )
{
WCHAR sz[7];
WCHAR* po = sz;
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p++;
if( *p != '\0' ){
*po++ = *p;
}
}
}
}
}
*po++ = '\0';
return (WCHAR)wcstoul( sz, NULL, 8 );
}
#define CMD_SEPARATOR 0
#define CMD_TAGS 1
#define CMD_INSERT_TABLE 2
#define CMD_FONT 3
#define CMD_UNINDENT 4
#define CMD_DROPDOWN_HEADER 5
#define CMD_DROPDOWN_FORM 6
#define CMD_CUSTOMIZE 7
#define MAX_CMD 8
class CCmd
{
public:
int m_iIcon;
int m_iCmd;
wstring m_sTitle;
wstring m_sTagBegin;
wstring m_sTagEnd;
public:
CCmd( int iIcon, int iCmd, LPCWSTR pszTitle, LPCWSTR pszTagBegin, LPCWSTR pszTagEnd )
{
m_iIcon = iIcon;
m_iCmd = iCmd;
if( pszTitle ) m_sTitle = pszTitle;
if( pszTagBegin ) m_sTagBegin = pszTagBegin;
if( pszTagEnd ) m_sTagEnd = pszTagEnd;
}
};
struct CDefCmd
{
int m_iIcon;
int m_iCmd;
int m_nTitleID;
LPCWSTR m_pszTagBegin;
LPCWSTR m_pszTagEnd;
};
static WORD SpecialStringID[] =
{
ID_TABLE,
ID_FONT,
ID_UNINDENT,
ID_HEADER,
ID_FORM,
ID_CUSTOMIZE,
};
static struct CDefCmd DefCmd[] =
{
{ 0, CMD_DROPDOWN_HEADER, ID_HEADER, L"", L"" },
{ 1, CMD_TAGS, ID_PARAGRAPH, L"<p>", L"</p>" },
{ 2, CMD_TAGS, ID_BREAK, L"<br />", L"" },
{ -1, CMD_SEPARATOR, 0, L"", L"" },
{ 3, CMD_TAGS, ID_BOLD, L"<strong>", L"</strong>" },
{ 4, CMD_TAGS, ID_ITALIC, L"<em>", L"</em>" },
{ 5, CMD_TAGS, ID_UNDERLINE, L"<u>", L"</u>" },
{ -1, CMD_SEPARATOR, 0, L"", L"" },
{ 6, CMD_FONT, ID_FONT, L"", L"" },
{ 7, CMD_TAGS, ID_COLOR, L"\\{PickColor}", L"" },
//{ 8, CMD_TAGS, ID_PICTURE, L"\\{PickRelativePath,%s,%s}", L"" },
{ 8, CMD_TAGS, ID_PICTURE, L"<img src=\"\\{PickRelativePath,%s,%s}\" width=\"\" height=\"\" alt=\"\" />", L"" },
{ 9, CMD_TAGS, ID_HYPERLINK, L"<a href=\"\\{PickRelativePath,%s,%s}\">", L"</a>" },
{ -1, CMD_SEPARATOR, 0, L"", L"" },
{ 10, CMD_INSERT_TABLE, ID_TABLE, L"", L"" },
{ 11, CMD_TAGS, ID_HORZ_LINE, _T("<hr />"), _T("") },
{ 12, CMD_TAGS, ID_COMMENT, _T("<!-- "), _T(" -->") },
{ -1, CMD_SEPARATOR, 0, L"", L"" },
{ 13, CMD_TAGS, ID_ALIGN_LEFT, _T("<p align=\"left\">"), _T("</p>") },
{ 14, CMD_TAGS, ID_CENTER, _T("<p align=\"center\">"), _T("</p>") },
{ 15, CMD_TAGS, ID_ALIGN_RIGHT, _T("<p align=\"right\">"), _T("</p>") },
{ 16, CMD_TAGS, ID_JUSTIFY, _T("<p align=\"justify\">"), _T("</p>") },
{ -1, CMD_SEPARATOR, 0, L"", L"" },
{ 17, CMD_TAGS, ID_NUMBERING, _T("<ol>\n\t<li>"), _T("</li>\n</ol>") },
{ 18, CMD_TAGS, ID_BULLETS, _T("<ul>\n\t<li>"), _T("</li>\n</ul>") },
{ 19, CMD_UNINDENT, ID_UNINDENT, L"", L"" },
{ 20, CMD_TAGS, ID_INDENT, _T("<blockquote>"), _T("</blockquote>") },
{ -1, CMD_SEPARATOR, 0, L"", L"" },
{ 21, CMD_TAGS, ID_HIGHLIGHT, _T("<span style=\"background-color: \\{DefColor}\">"), L"</span>" },
{ 22, CMD_TAGS, ID_FONT_COLOR, _T("<font color=\"\\{DefColor}\">"), L"</font>" },
{ 23, CMD_DROPDOWN_FORM, ID_FORM, L"", L"" },
{ -1, CMD_SEPARATOR, 0, L"", L"" },
{ 24, CMD_CUSTOMIZE, ID_CUSTOMIZE, L"", L"" },
{ 25, CMD_TAGS, ID_FORM_FORM, L"<form method=\"post\" action=\"\">\n\t", L"\n<input type=\"submit\"><input type=\"reset\"></form>\n" },
{ 26, CMD_TAGS, ID_TEXTBOX, L"<input type=\"text\" id=\"\" />", L"" },
{ 27, CMD_TAGS, ID_PASSWORD, L"<input type=\"password\" id=\"\" />", L"" },
{ 28, CMD_TAGS, ID_TEXTAREA, L"<textarea id=\"\" rows=\"3\" cols=\"30\">", L"</textarea>" },
{ 29, CMD_TAGS, ID_CHECKBOX, L"<input type=\"checkbox\" id=\"\" />", L"" },
{ 30, CMD_TAGS, ID_OPTIONBUTTON, L"<input type=\"radio\" id=\"\" />", L"" },
{ 31, CMD_TAGS, ID_GROUPBOX, L"<fieldset style=\"padding: 2\">\n<legend>Group Box", L"</legend></fieldset>" },
{ 32, CMD_TAGS, ID_DROPDOWNBOX, L"<select size=\"1\" id=\"\">", L"</select>" },
{ 33, CMD_TAGS, ID_LISTBOX, L"<asp:ListBox runat=\"server\" id=\"\">", L"</asp:ListBox>" },
{ 34, CMD_TAGS, ID_PUSHBUTTON, L"<input type=\"button\" value=\"Button\" id=\"\">", L"" },
{ 35, CMD_TAGS, ID_ADVANCEDBUTTON, L"<button id=\"\">Type Here", L"</button>" },
{ 36, CMD_TAGS, ID_HIDDENINPUT, L"<input type=\"hidden\" id=\"\" />", L"" },
{ 37, CMD_TAGS, ID_OBJECT, L"", L"" },
{ 38, CMD_TAGS, ID_CAMERA, L"", L"" },
{ 39, CMD_TAGS, ID_CD, L"", L"" },
{ 40, CMD_TAGS, ID_SCANNER, L"", L"" },
{ 41, CMD_TAGS, ID_PRINTER, L"", L"" },
{ 42, CMD_TAGS, ID_FUNCTION, L"", L"" },
{ 43, CMD_TAGS, ID_CRITICALERROR, L"", L"" },
{ 44, CMD_TAGS, ID_WARNING, L"", L"" },
{ 45, CMD_TAGS, ID_INFORMATION, L"", L"" },
{ 46, CMD_TAGS, ID_BLUEFLAG, L"", L"" },
{ 47, CMD_TAGS, ID_BACKGROUNDSOUND, L"", L"" },
};
typedef vector<CCmd> CCmdArray;
class CMyFrame : public CETLFrame<CMyFrame>
{
public:
// _loc.dll in MUI sub folder?
enum { _USE_LOC_DLL = TRUE };
// string ID
enum { _IDS_MENU = IDS_MENU_TEXT }; // name of command, menu
enum { _IDS_STATUS = IDS_STATUS_MESSAGE }; // description of command, status bar
enum { _IDS_NAME = IDS_MENU_TEXT }; // name of plug-in, plug-in settings dialog box
enum { _IDS_VER = IDS_VERSION }; // version string of plug-in, plug-in settings dialog box
// bitmaps
enum { _IDB_BITMAP = IDB_BITMAP };
enum { _IDB_16C_24 = IDB_16C_24 };
//enum { _IDB_256C_16_DEFAULT = IDB_TRUE_16_DEFAULT };
//enum { _IDB_256C_16_HOT = IDB_TRUE_16_HOT };
//enum { _IDB_256C_16_BW = IDB_TRUE_16_BW };
//enum { _IDB_256C_24_DEFAULT = IDB_TRUE_24_DEFAULT };
//enum { _IDB_256C_24_HOT = IDB_TRUE_24_HOT };
//enum { _IDB_256C_24_BW = IDB_TRUE_24_BW };
enum { _IDB_TRUE_16_DEFAULT = IDB_TRUE_16_DEFAULT };
enum { _IDB_TRUE_16_HOT = IDB_TRUE_16_HOT };
enum { _IDB_TRUE_16_BW = IDB_TRUE_16_BW };
enum { _IDB_TRUE_24_DEFAULT = IDB_TRUE_24_DEFAULT };
enum { _IDB_TRUE_24_HOT = IDB_TRUE_24_HOT };
enum { _IDB_TRUE_24_BW = IDB_TRUE_24_BW };
// masks
enum { _MASK_TRUE_COLOR = CLR_NONE };
//enum { _MASK_256_COLOR = CLR_NONE };
// whether to allow a file is opened in the same window group during the plug-in execution.
enum { _ALLOW_OPEN_SAME_GROUP = TRUE };
// whether to allow multiple instances.
enum { _ALLOW_MULTIPLE_INSTANCES = TRUE };
// supporting EmEditor newest version * 1000
enum { _MAX_EE_VERSION = 14900 };
// supporting EmEditor oldest version * 1000
enum { _MIN_EE_VERSION = 12000 };
// supports EmEditor Professional
enum { _SUPPORT_EE_PRO = TRUE };
// supports EmEditor Standard
enum { _SUPPORT_EE_STD = FALSE };
// user-defined members
vector<tstring> m_RecentFontArray;
vector<tstring> m_AutoConfigArray;
CCmdArray m_CmdArray;
vector<wstring> m_asUndefinedParam;
vector<wstring> m_asUndefinedValue;
vector<wstring> m_asPickParam;
vector<wstring> m_asPickValue;
// data that can be set zeros below
WNDPROC m_lpOldEditProc; // common
CCmd* m_pcmdProp;
HWND m_hwndToolbar;
HIMAGELIST m_himageToolbar;
HWND m_hDlg;
TCHAR m_szOldConfig[MAX_CONFIG_NAME];
DWORD m_dwFindFlags;
UINT m_nClientID;
UINT m_cx;
UINT m_fStyle;
UINT m_nBand;
DWORD m_dwDefColor;
//DWORD m_crCustClr[16];
WORD m_wRows;
WORD m_wColumns;
bool m_bProfileLoaded;
bool m_bAutoDisplay;
bool m_bVisible;
bool m_bUninstalling;
bool m_bPropModified;
bool m_bPropInitialized;
bool m_bCmdArrayModified;
bool m_bOpenStartup;
bool m_bLargeToolbar;
//////// common start
BOOL DisableAutoComplete( HWND /* hwnd */ )
{
return FALSE;
}
BOOL UseDroppedFiles( HWND /* hwnd */ )
{
return FALSE;
}
LRESULT UserMessage( HWND /*hwnd*/, WPARAM /*wParam*/, LPARAM /*lParam*/ )
{
return 0;
}
BOOL ChooseFile( LPTSTR pszRelative, LPCTSTR pszDlgTitle, LPCTSTR pszFilter, bool bRelative )
{
*pszRelative = 0;
TCHAR szFile[MAX_PATH] = { 0 };
TCHAR szFolder[MAX_PATH] = { 0 };
Editor_DocInfo( m_hWnd, -1, EI_GET_FILE_NAMEW, (LPARAM)szFolder );
if( szFolder[0] ){
PathRemoveFileSpec( szFolder );
}
OPENFILENAME ofn = { 0 };
ofn.lStructSize = sizeof( ofn );
ofn.hwndOwner = m_hWnd;
TCHAR szFilter[200] = { 0 };
if( pszFilter ){
StringCopy( szFilter, _countof( szFilter ), pszFilter );
}
LPTSTR p = szFilter;
while( *p ){
if( *p == _T('|') ) *p = 0;
p++;
}
ofn.lpstrFilter = szFilter;
ofn.lpstrFile = szFile;
ofn.nMaxFile = _countof( szFile );
ofn.lpstrInitialDir = szFolder;
ofn.lpstrTitle = pszDlgTitle;
ofn.Flags = /*OFN_FILEMUSTEXIST | */ OFN_HIDEREADONLY;
if( GetOpenFileName( &ofn ) ){
TCHAR szRelativePath[MAX_PATH] = { 0 };
LPTSTR pRelative = szRelativePath;
if( !PathRelativePathTo( szRelativePath, szFolder, FILE_ATTRIBUTE_DIRECTORY, szFile, 0 ) ){
pRelative = szFile;
}
else if( _tcsncmp( pRelative, _T(".\\"), 2 ) == 0 ){
pRelative += 2;
}
if( bRelative && PathIsRelative( pRelative ) ) {
StringCopy( pszRelative, MAX_PATH, pRelative );
}
else {
StringCopy( pszRelative, MAX_PATH, _T("file:///") );
// StringCat( pszRelative, MAX_PATH, pRelative );
StringCat( pszRelative, MAX_PATH, szFile );
}
p = pszRelative;
while( *p ){
if( *p == '\\' ) *p = '/';
p++;
}
return TRUE;
}
return FALSE;
}
bool ReplaceParam( LPWSTR pszBuf, int cchBuf, LPCWSTR pszParam )
{
for( int i = 0; i < MAX_TOOL_ARG_NO_INTERFACE; i++ ){
if( lstrcmpW( pszParam, szToolArgs[i] ) == 0 ){
switch( i ){
case TOOL_ARG_PATH:
{
TCHAR sz[MAX_PATH] = { 0 };
Editor_Info( m_hWnd, EI_GET_FILE_NAMEW, (LPARAM)sz );
StringCopy( pszBuf, cchBuf, sz );
}
break;
case TOOL_ARG_DIR:
{
TCHAR sz[MAX_PATH] = { 0 };
Editor_Info( m_hWnd, EI_GET_CURRENT_FOLDER, (LPARAM)sz );
StringCopy( pszBuf, cchBuf, sz );
}
break;
case TOOL_ARG_FILENAME:
{
TCHAR sz[MAX_PATH] = { 0 };
Editor_Info( m_hWnd, EI_GET_FILE_NAMEW, (LPARAM)sz );
PathStripPathW( sz );
PathRemoveExtension( sz );
StringCopy( pszBuf, cchBuf, sz );
}
break;
case TOOL_ARG_EXT:
{
TCHAR sz[MAX_PATH] = { 0 };
Editor_Info( m_hWnd, EI_GET_FILE_NAMEW, (LPARAM)sz );
LPTSTR pszExt = PathFindExtension( PathFindFileName( sz ) );
if( *pszExt == '.' ){
StringCopy( pszBuf, cchBuf, pszExt + 1 );
}
}
break;
case TOOL_ARG_CURLINE:
{
POINT_PTR ptCaret;
Editor_GetCaretPos( m_hWnd, POS_LOGICAL_W, &ptCaret );
TCHAR sz[20];
StringPrintf( sz, _countof( sz ), _T("%d"), ptCaret.y + 1 );
StringCopy( pszBuf, cchBuf, sz );
}
break;
case TOOL_ARG_SELTEXT:
{
Editor_GetSelTextW( m_hWnd, cchBuf, pszBuf );
}
break;
case TOOL_ARG_DATE:
{
SYSTEMTIME time;
GetLocalTime(&time);
GetDateFormat( LOCALE_USER_DEFAULT, DATE_SHORTDATE, &time, NULL, pszBuf, cchBuf );
}
break;
case TOOL_ARG_TIME:
{
SYSTEMTIME time;
GetLocalTime(&time);
GetTimeFormat( LOCALE_USER_DEFAULT, TIME_NOSECONDS, &time, NULL, pszBuf, cchBuf );
}
break;
}
return true;
}
}
if( !m_asUndefinedValue.empty() || !m_asPickValue.empty() ){
{
_ASSERT( m_asUndefinedParam.size() == m_asUndefinedValue.size() );
vector<wstring>::iterator itV = m_asUndefinedValue.begin();
for( vector<wstring>::iterator it = m_asUndefinedParam.begin(); it != m_asUndefinedParam.end(); it++, itV++ ){
if( lstrcmpW( pszParam, it->c_str() ) == 0 ){
StringCopy( pszBuf, cchBuf, itV->c_str() );
return true;
}
}
}
{
_ASSERT( m_asPickParam.size() == m_asPickValue.size() );
vector<wstring>::iterator itV = m_asPickValue.begin();
for( vector<wstring>::iterator it = m_asPickParam.begin(); it != m_asPickParam.end(); it++, itV++ ){
if( lstrcmpW( pszParam, it->c_str() ) == 0 ){
StringCopy( pszBuf, cchBuf, itV->c_str() );
return true;
}
}
}
}
return false;
}
wstring UnescapeString( LPCWSTR szSrc, BOOL* pbResult )
{
*pbResult = FALSE;
_ASSERT( m_asUndefinedParam.empty() );
_ASSERT( m_asUndefinedValue.empty() );
m_asUndefinedParam.clear();
m_asUndefinedValue.clear();
_ASSERT( m_asPickParam.empty() );
_ASSERT( m_asPickValue.empty() );
m_asPickParam.clear();
m_asPickValue.clear();
LPWSTR pi = (LPWSTR)szSrc;
while( *pi != L'\0' ){
if( *pi == L'\\' ){
pi++;
if( *pi == L'{' ){
LPWSTR pRight = wcschr( pi + 1, L'}' );
if( pRight ){
WCHAR szParam[MAX_SNIPPET_LENGTH];
StringCopyNW( szParam, _countof( szParam ), pi + 1, pRight - (pi + 1) );
WCHAR szValue[MAX_SNIPPET_LENGTH];
if( !ReplaceParam( szValue, _countof( szValue ), szParam ) ){
m_asUndefinedParam.push_back( szParam );
}
pi = pRight;
}
}
}
pi++;
}
if( !m_asUndefinedParam.empty() ){
for( int iParam = 0; iParam < (int)m_asUndefinedParam.size(); iParam++ ){
WCHAR szCmd[260];
LPWSTR pDlgTitle = NULL;
LPWSTR pFilter = NULL;
StringCopy( szCmd, _countof( szCmd ), m_asUndefinedParam[iParam].c_str() );
LPWSTR p = wcschr( szCmd, L',' );
if( p ){
*p++ = 0;
pDlgTitle = p;
p = wcschr( pDlgTitle, L',' );
if( p ){
*p++ = 0;
pFilter = p;
}
}
for( int i = MAX_TOOL_ARG_NO_INTERFACE; i < MAX_TOOL_ARG; i++ ){
if( lstrcmpW( szCmd, szToolArgs[i] ) == 0 ){
switch( i ){
case TOOL_ARG_PICK_FULL_PATH:
case TOOL_ARG_PICK_RELATIVE_PATH:
{
bool bRelative = (i == TOOL_ARG_PICK_RELATIVE_PATH);
TCHAR szPath[MAX_PATH];
if( !ChooseFile( szPath, pDlgTitle, pFilter, bRelative ) ){
m_asUndefinedParam.clear();
return L"";
}
m_asPickParam.push_back( m_asUndefinedParam[iParam].c_str() );
m_asUndefinedParam.erase( m_asUndefinedParam.begin() + iParam-- );
m_asPickValue.push_back( szPath );
}
break;
case TOOL_ARG_PICK_COLOR:
{
DWORD adwCustomColors[16], adwOrgColors[16];
for( int j = 0; j < 16; j++ ) {
adwCustomColors[j] = RGB( 255, 255, 255 );
}
GetProfileBinary( EEREG_COMMON, NULL, szCustColors, (LPBYTE)adwCustomColors, sizeof( adwCustomColors ) );
CopyMemory( adwOrgColors, adwCustomColors, sizeof( adwOrgColors ) );
CHOOSECOLOR cc = { 0 };
cc.lStructSize = sizeof( cc );
cc.hwndOwner = m_hWnd;
cc.lpCustColors = adwCustomColors;
if( !ChooseColor( &cc ) ){
m_asUndefinedParam.clear();
return L"";
}
m_dwDefColor = cc.rgbResult;
if( memcmp( adwOrgColors, adwCustomColors, sizeof( adwOrgColors ) ) != 0 ) {
WriteProfileBinary( EEREG_COMMON, NULL, szCustColors, (LPBYTE)adwCustomColors, sizeof( adwCustomColors ), false );
}
TCHAR sz[16];
StringPrintf( sz, _countof( sz ), _T("#%02x%02x%02x"), GetRValue( cc.rgbResult ), GetGValue( cc.rgbResult ), GetBValue( cc.rgbResult ) );
m_asPickParam.push_back( m_asUndefinedParam[iParam].c_str() );
m_asUndefinedParam.erase( m_asUndefinedParam.begin() + iParam-- );
m_asPickValue.push_back( sz );
}
break;
case TOOL_ARG_DEF_COLOR:
{
TCHAR sz[16];
StringPrintf( sz, _countof( sz ), _T("#%02x%02x%02x"), GetRValue( m_dwDefColor ), GetGValue( m_dwDefColor ), GetBValue( m_dwDefColor ) );
m_asPickParam.push_back( m_asUndefinedParam[iParam].c_str() );
m_asUndefinedParam.erase( m_asUndefinedParam.begin() + iParam-- );
m_asPickValue.push_back( sz );
}
break;
}
}
}
}
if( !m_asUndefinedParam.empty() ){
if( DialogBox( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_INPUT_PARAMS ), m_hWnd, InputParamsDlg ) != IDOK ){
m_asUndefinedParam.clear();
m_asPickParam.clear();
m_asPickValue.clear();
return L"";
}
}
}
int cchBuf = MAX_SNIPPET_LENGTH * 4;
LPWSTR szDest = new WCHAR[ cchBuf ];
LPWSTR pEnd = szDest + cchBuf;
LPWSTR po = szDest;
pi = (LPWSTR)szSrc;
while( *pi != L'\0' && po < pEnd - 1 ){
if( *pi == L'\\' ){
pi++;
switch( *pi ){
case L'a': *po = L'\a'; break;
case L'b': *po = L'\b'; break;
case L'f': *po = L'\f'; break;
case L'n': *po = L'\n'; break;
case L'r': *po = L'\r'; break;
case L't': *po = L'\t'; break;
case L'v': *po = L'\v'; break;
case L'{':
{
LPWSTR pRight = wcschr( pi + 1, L'}' );
if( pRight ){
WCHAR szParam[MAX_SNIPPET_LENGTH];
StringCopyNW( szParam, _countof( szParam ), pi + 1, pRight - (pi + 1) );
WCHAR szValue[MAX_SNIPPET_LENGTH];
if( ReplaceParam( szValue, _countof( szValue ), szParam ) ){
pi = pRight;
StringCopy( po, pEnd - po, szValue );
po += lstrlenW( szValue ) - 1;
}
else {
*po = L'{';
}
}
else {
*po = *pi;
if( *pi == '\0' ){
pi--;
break;
}
}
}
break;
case L'x': case L'X':
pi++;
*po = HexToDec( pi );
if( *pi == '\0' ){
po++;
goto unescape_exit;
}
break;
default:
if( *pi >= '0' && *pi <= '9' ){
*po = OctToDec( pi );
if( *pi == '\0' ){
po++;
goto unescape_exit;
}
break;
}
else {
*po = *pi;
if( *pi == '\0' ){
pi--;
break;
}
}
}
pi++;
po++;
}
else {
*po++ = *pi++;
}
}
unescape_exit:;
*po = L'\0';
wstring sDest = szDest;
delete [] szDest;
m_asUndefinedParam.clear();
m_asUndefinedValue.clear();
m_asPickParam.clear();
m_asPickValue.clear();
*pbResult = TRUE;
return sDest;
}
BOOL OnInputInitDialog( HWND hwnd )
{
CenterWindow( hwnd );
HWND hwndList = GetDlgItem( hwnd, IDC_LIST );
if( !hwndList ) return TRUE;
ListView_SetExtendedListViewStyleEx( hwndList, LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT, LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT );
TCHAR sz[80];
LV_COLUMN lvC = { 0 };
lvC.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvC.pszText = sz;
RECT rc;
GetWindowRect( hwndList, &rc );
lvC.cx = rc.right - rc.left - GetSystemMetrics( SM_CXVSCROLL ) - GetSystemMetrics( SM_CXEDGE ) * 2 - 80;
LoadString( EEGetLocaleInstanceHandle(), IDS_VALUE, sz, _countof( sz ) );
VERIFY( ListView_InsertColumn( hwndList, 0, &lvC ) != -1 );
lvC.cx = 80;
LoadString( EEGetLocaleInstanceHandle(), IDS_PARAMETER, sz, _countof( sz ) );
VERIFY( ListView_InsertColumn( hwndList, 1, &lvC ) != -1 );
int anOrder[2] = { 1, 0 };
ListView_SetColumnOrderArray( hwndList, 2, anOrder );
int i = 0;
for( vector<wstring>::iterator it = m_asUndefinedParam.begin(); it != m_asUndefinedParam.end(); it++, i++ ){
LVITEM item = { 0 };
item.mask = LVIF_TEXT;
item.iItem = i;
item.pszText = L"";
ListView_InsertItem( hwndList, &item );
item.iSubItem = 1;
item.pszText = (LPWSTR)it->c_str();
ListView_SetItem( hwndList, &item );
}
ListView_SetItemState( hwndList, 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED );
SetFocus( hwndList );
ListView_EditLabel( hwndList, 0 );
return FALSE;
}
void OnInputDlgCommand( HWND hwnd, WPARAM wParam )
{
if( wParam == IDOK ){
_ASSERT( m_asUndefinedValue.empty() );
HWND hwndList = GetDlgItem( hwnd, IDC_LIST );
if( !hwndList ) return;
int nCount = (int)m_asUndefinedParam.size();
for( int i = 0; i < nCount; i++ ) {
TCHAR szText[260];
ListView_GetItemText( hwndList, i, 0, szText, _countof( szText ) );
if( szText[0] == 0 ){
m_asUndefinedValue.clear();
SetFocus( hwndList );
ListView_EditLabel( hwndList, i );
return;
}
m_asUndefinedValue.push_back( szText );
}
EndDialog( hwnd, IDOK );
}
else if( wParam == IDCANCEL ){
m_asUndefinedValue.clear();
_ASSERT( m_asUndefinedValue.empty() );
EndDialog( hwnd, IDCANCEL );
}
}
BOOL OnInputDlgNotify( HWND hwnd, int idCtrl, LPNMHDR pnmh )
{
BOOL bResult = FALSE;
if( idCtrl == IDC_LIST ){
switch( pnmh->code ){
case LVN_BEGINLABELEDIT:
{
HWND hwndList = GetDlgItem( hwnd, IDC_LIST );
HWND hwndEdit = ListView_GetEditControl( hwndList );
if( hwndEdit ){
_ASSERTE( m_lpOldEditProc == NULL );
m_lpOldEditProc = (WNDPROC)SetWindowLongPtr( hwndEdit, GWLP_WNDPROC, (LONG_PTR)EditProc );
}
}
break;
case LVN_ENDLABELEDIT:
{
HWND hwndList = GetDlgItem( hwnd, IDC_LIST );
NMLVDISPINFO* pdi = (NMLVDISPINFO*)pnmh;
if( m_lpOldEditProc != NULL ){
HWND hwndEdit = ListView_GetEditControl( hwndList );
_ASSERT( hwndEdit );
if( hwndEdit ){
SetWindowLongPtr( hwndEdit, GWLP_WNDPROC, (LONG_PTR)m_lpOldEditProc );
m_lpOldEditProc = NULL;
}
}
if( pdi->item.pszText != NULL ){
bResult = TRUE;
SetWindowLongPtr( hwnd, DWLP_MSGRESULT, bResult );
}
}
break;
case LVN_KEYDOWN:
{
HWND hwndList = GetDlgItem( hwnd, IDC_LIST );
LV_KEYDOWN* pLVKeyDow = (LV_KEYDOWN*)pnmh;
if( pLVKeyDow->wVKey == VK_F2 ){
int iItem = ListView_GetNextItem( hwndList, -1, LVNI_SELECTED );
if( iItem >= 0 ){
VERIFY( ListView_EditLabel( hwndList, iItem ) );
}
}
}
break;
}
}
return bResult;
}
void OnEditKeyDown( HWND hwnd, WPARAM wParam, LPARAM /*lParam*/ )
{
if( wParam == VK_DOWN || wParam == VK_UP ){
HWND hwndList = GetParent( hwnd );
int iSel = ListView_GetNextItem( hwndList, -1, LVNI_SELECTED );
_ASSERT( iSel >= 0 );
if( wParam == VK_DOWN ){
iSel++;
}
else {
iSel--;
}
if( iSel == ListView_GetItemCount( hwndList ) ){
HWND hDlg = GetParent( hwndList );
_ASSERT( hDlg );
SendMessage( hDlg, WM_NEXTDLGCTL, 0, 0 );
return;
}
if( iSel >= 0 && iSel < ListView_GetItemCount( hwndList ) ){
ListView_EditLabel( hwndList, iSel );
}
}
}
//////// common end
BOOL LoadCmdArray()
{
BOOL bResult = FALSE;
m_CmdArray.clear();
DWORD dwCount = GetProfileBinary( szCmdArrayEntry, NULL, 0 );
if( dwCount ){
char* pBuf = new char[ dwCount ];
if( pBuf ){
if( GetProfileBinary( szCmdArrayEntry, (LPBYTE)pBuf, dwCount ) ){
int nMax, nLen, iCmd, iIcon;
char* p = pBuf;
DWORD dwSign = *((DWORD*)p);
p += sizeof( DWORD );
if( dwSign == SIGNATURE_CMD_ARRAY ) {
nMax = *((int*)p);
p += sizeof( int );
for( int i = 0; i < nMax; i ++ ){
iCmd = *((int*)p);
p += sizeof( int );
iIcon = *((int*)p);
p += sizeof( int );
nLen = *((int*)p);
p += sizeof( int );
wstring sTitle( (LPCWSTR)p, nLen );
p += nLen * sizeof(WCHAR);
nLen = *((int*)p);
p += sizeof( int );
wstring sTagBegin( (LPCWSTR)p, nLen );
p += nLen * sizeof(WCHAR);
nLen = *((int*)p);
p += sizeof( int );
wstring sTagEnd( (LPCWSTR)p, nLen );
p += nLen * sizeof(WCHAR);
CCmd cmd( iIcon, iCmd, sTitle.c_str(), sTagBegin.c_str(), sTagEnd.c_str() );
m_CmdArray.push_back( cmd );
}
_ASSERT( p == pBuf + dwCount );
bResult = ( p == pBuf + dwCount );
}
}
delete [] pBuf;
}
}
return bResult;
}
void SaveCmdArray()
{
if( m_bCmdArrayModified ){
int nLen;
BOOL bSuccess = FALSE;
DWORD_PTR dwCount = sizeof( int );
dwCount += sizeof(DWORD);
CCmdArray::iterator it = m_CmdArray.begin();
int nMax = 0;
while( it != m_CmdArray.end() ){
dwCount += (it->m_sTagBegin.length() + it->m_sTagEnd.length() + it->m_sTitle.length()) * sizeof(WCHAR) + 5 * sizeof( int );
nMax++;
it++;
}
char *pBuf;
pBuf = new char[dwCount];
if( pBuf != NULL ){
char* p = pBuf;
*((DWORD*)p) = SIGNATURE_CMD_ARRAY;
p += sizeof( DWORD );
*((int*)p) = nMax;
p += sizeof( int );
it = m_CmdArray.begin();
while( it != m_CmdArray.end() ){
*((int*)p) = it->m_iCmd;
p += sizeof( int );
*((int*)p) = it->m_iIcon;
p += sizeof( int );
nLen = (int)it->m_sTitle.length();
*((int*)p) = nLen;
p += sizeof( int );
memcpy( p, it->m_sTitle.c_str(), nLen * sizeof(WCHAR) );
p += nLen * sizeof(WCHAR);
nLen = (int)it->m_sTagBegin.length();
*((int*)p) = nLen;
p += sizeof( int );
memcpy( p, it->m_sTagBegin.c_str(), nLen * sizeof(WCHAR) );
p += nLen * sizeof(WCHAR);
nLen = (int)it->m_sTagEnd.length();
*((int*)p) = nLen;
p += sizeof( int );
memcpy( p, it->m_sTagEnd.c_str(), nLen * sizeof(WCHAR) );
p += nLen * sizeof(WCHAR);
it++;
}
_ASSERT( p == pBuf + dwCount );
bSuccess = ( p == pBuf + dwCount );
WriteProfileBinary( szCmdArrayEntry, (LPBYTE)pBuf, (UINT)dwCount, true );
delete [] pBuf;
}
}
//else {
// EraseEntry( szCmdArrayEntry );
//}
}
void InsertCmdAt( int iPos, int iIcon, int iCmd, LPCWSTR pszTitle, LPCWSTR pszTagBegin, LPCWSTR pszTagEnd )
{
CCmd cmd( iIcon, iCmd, pszTitle, pszTagBegin, pszTagEnd );
m_CmdArray.insert( m_CmdArray.begin() + iPos, cmd );
}
void ResetCmdArray()
{
m_CmdArray.clear();
for( int i = 0; i < _countof( DefCmd ); i++ ){
WCHAR sz[80];
LoadString( EEGetLocaleInstanceHandle(), DefCmd[i].m_nTitleID, sz, _countof( sz ) );
TCHAR szTagBegin[300];
if( DefCmd[i].m_nTitleID == ID_PICTURE || DefCmd[i].m_nTitleID == ID_HYPERLINK ){
bool bHyperlink = DefCmd[i].m_nTitleID == ID_HYPERLINK;
TCHAR szDlgTitle[80], szFilter[200];
LoadString( EEGetLocaleInstanceHandle(), bHyperlink ? IDS_HYPERLINK : IDS_PICTURE, szDlgTitle, _countof( szDlgTitle ) );
LoadString( EEGetLocaleInstanceHandle(), bHyperlink ? IDS_FILTER_HYPERLINK : IDS_FILTER_IMAGE, szFilter, _countof( szFilter ) );
StringPrintf( szTagBegin, _countof( szTagBegin ), DefCmd[i].m_pszTagBegin, szDlgTitle, szFilter );
}
else {
StringCopy( szTagBegin, _countof( szTagBegin ), DefCmd[i].m_pszTagBegin );
}
InsertCmdAt( i, DefCmd[i].m_iIcon, DefCmd[i].m_iCmd, sz, szTagBegin, DefCmd[i].m_pszTagEnd );
if( DefCmd[i].m_iCmd == CMD_CUSTOMIZE ) break;
}
EraseEntry( szCmdArrayEntry );
m_bCmdArrayModified = false;
}
void AddButtons( HWND hwndToolbar )
{
for( ;; ){
if( !SendMessage( hwndToolbar, TB_DELETEBUTTON, 0, 0 ) ){
break;
}
}
TBBUTTON* atb = new TBBUTTON[ m_CmdArray.size() ];
ZeroMemory( atb, sizeof( TBBUTTON ) * m_CmdArray.size() );
int i = 0;
for( CCmdArray::iterator it = m_CmdArray.begin(); it != m_CmdArray.end(); it++, i++ ) {
atb[i].iBitmap = it->m_iIcon;
atb[i].idCommand = i + ID_COMMAND_BASE;
atb[i].fsState = TBSTATE_ENABLED;
atb[i].fsStyle = 0;
if( it->m_iCmd == CMD_SEPARATOR ){
atb[i].fsStyle = TBSTYLE_SEP;
}
if( it->m_iCmd == CMD_FONT ){
atb[i].fsStyle = BTNS_DROPDOWN;
}
if( it->m_iCmd == CMD_DROPDOWN_HEADER || it->m_iCmd == CMD_DROPDOWN_FORM ){
atb[i].fsStyle = BTNS_WHOLEDROPDOWN;
}
}
//TBBUTTON atb[_countof( anDefToolbarIndex )];
//ZeroMemory( atb, sizeof( atb ) );
//BYTE* pnIndex = anDefToolbarIndex;
//int i = 0;
//while( *pnIndex != (BYTE)-2 ){
// BYTE nIndex = *pnIndex++;
// if( nIndex != (BYTE)-1 ){
// atb[i].iBitmap = buttons[nIndex].iBitmap;
// atb[i].idCommand = buttons[nIndex].nID;
// atb[i].fsStyle = buttons[nIndex].fStyle;
// }
// else { // separator
// atb[i].fsStyle = TBSTYLE_SEP;
// }
// atb[i].fsState = TBSTATE_ENABLED;
// i++;
//}
SendMessage( hwndToolbar, TB_ADDBUTTONSA, m_CmdArray.size(), (LPARAM)atb );
delete [] atb;
}
bool IsVisible()
{
return m_hwndToolbar && m_bVisible;
}
void CheckToolbarSize()
{
DWORD dwValue = 0;
DWORD dwSize = sizeof(DWORD);
Editor_RegQueryValue( m_hWnd, EEREG_COMMON, NULL, szLargeToolbar, REG_DWORD, (BYTE*)&dwValue, &dwSize, 0 );
m_bLargeToolbar = !!dwValue;
}
void DisplayBar( bool bVisible )
{
if( m_hwndToolbar ){
_ASSERT( m_nClientID );
Editor_ToolbarShow( m_hWnd, m_nClientID, bVisible );
m_bVisible = bVisible;
}
else {
CheckToolbarSize();
m_bVisible = false;
//TCHAR sz[260];
//TCHAR szAppName[80];
//LoadString( EEGetLocaleInstanceHandle(), IDS_MENU_TEXT, szAppName, _countof( szAppName ) );
//if( Editor_GetVersion( m_hWnd ) < 8000 ){
// LoadString( EEGetLocaleInstanceHandle(), IDS_INVALID_VERSION, sz, _countof( sz ) );
// MessageBox( m_hWnd, sz, szAppName, MB_OK | MB_ICONSTOP );
// return;
//}
HWND hDlg = CreateDialog( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_DIALOGBAR ), m_hWnd, NewProc );
_ASSERT( hDlg );
if( !hDlg ){
return;
}
m_hDlg = hDlg;
int nDPI = (int)Editor_DocInfo( m_hWnd, 0, EI_GET_DPI, 0 );
int nImageDPI = (nDPI >= DEFAULT_DPI && nDPI <= 120) ? DEFAULT_DPI : nDPI;
bool bLarge = false;
if( m_bLargeToolbar || MulDiv( 16, nImageDPI, DEFAULT_DPI ) >= 24 ){
bLarge = true;
}
int cxSrc = bLarge ? 24 : 16;
int cxDest = MulDiv( m_bLargeToolbar ? 24 : 16, nImageDPI, DEFAULT_DPI );
int cxButtonSize = MulDiv( m_bLargeToolbar ? 24 : 16, nDPI, DEFAULT_DPI );
bool bNeedStretch = ( cxSrc != cxDest );
//int cx = g_metrics.ScaleY( m_bLargeToolbar ? BUTTON_SIZE_LARGE : BUTTON_SIZE_SMALL );
DWORD dwStyle = TBSTYLE_TOOLTIPS | TBSTYLE_TRANSPARENT | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | CCS_NODIVIDER | CCS_NORESIZE | WS_VISIBLE | TBSTYLE_FLAT | CCS_NOPARENTALIGN | CCS_NOMOVEY;
DWORD dwExStyle = TBSTYLE_EX_HIDECLIPPEDBUTTONS | TBSTYLE_EX_DRAWDDARROWS;
HWND hwndToolbar = CreateWindowEx( 0, TOOLBARCLASSNAME, NULL, dwStyle,
0, 0, 0, cxButtonSize, m_hDlg, (HMENU)(INT_PTR)100, NULL, NULL );
m_hwndToolbar = hwndToolbar;
SendMessage( hwndToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM) sizeof(TBBUTTON), 0 );
SendMessage( hwndToolbar, TB_SETBUTTONSIZE, 0, cxButtonSize );
SendMessage( hwndToolbar, TB_SETEXTENDEDSTYLE, 0, dwExStyle );
_ASSERT( m_himageToolbar == NULL );
if( bNeedStretch ){
m_himageToolbar = ImageList_Create( cxDest, cxDest, ILC_COLOR32 | ILC_MASK, 0, 32 );
HBITMAP hbm = MyLoadBitmap( EEGetInstanceHandle(), MAKEINTRESOURCE( bLarge ? IDB_TOOLBAR_LARGE : IDB_TOOLBAR ) );
_ASSERT( hbm );
int nNumImages = GetBitmapCount( hbm, cxSrc );
if( nNumImages != 0 ){
VERIFY( StretchBitmap( &hbm, cxDest, cxDest, nNumImages, 1 ) );
VERIFY( ImageList_AddMasked( m_himageToolbar, hbm, CLR_NONE ) == 0 );
}
}
else {
m_himageToolbar = ImageList_LoadImage( EEGetInstanceHandle(), MAKEINTRESOURCE( bLarge ? IDB_TOOLBAR_LARGE : IDB_TOOLBAR ), bLarge ? 24 : 16, 0, CLR_NONE, IMAGE_BITMAP, LR_CREATEDIBSECTION );
}
_ASSERT( m_himageToolbar );
SendMessage( hwndToolbar, TB_SETIMAGELIST, 0, (LPARAM)m_himageToolbar );
if( !LoadCmdArray() ){
ResetCmdArray();
}
AddButtons( hwndToolbar );
if( hwndToolbar ){
TCHAR szTitle[80];
LoadString( EEGetLocaleInstanceHandle(), IDS_TITLE, szTitle, _countof( szTitle ) );
RECT rcClient = { 0 };
GetClientRect( hwndToolbar, &rcClient );
TOOLBAR_INFO cri;
ZeroMemory( &cri, sizeof( cri ) );
cri.cbSize = sizeof( cri );
cri.nMask = TIM_CLIENT | TIM_TITLE | TIM_FLAGS | TIM_STYLE | TIM_MINCHILD | TIM_CX | TIM_CXIDEAL | TIM_BAND | TIM_PLUG_IN_CMD_ID;
cri.wPlugInCmdID = EEGetCmdID();
cri.pszTitle = szTitle;
cri.hwndClient = hwndToolbar;
cri.cxMinChild = 0;
cri.cyMinChild = rcClient.bottom - rcClient.top;
cri.cxIdeal = rcClient.right - rcClient.left;
cri.cx = m_cx;
if( bVisible ){
m_fStyle &= ~RBBS_HIDDEN;
}
else {
m_fStyle |= RBBS_HIDDEN;
}
cri.fStyle = m_fStyle;
cri.nBand = m_nBand;
m_nClientID = Editor_ToolbarOpen( m_hWnd, &cri );
if( !m_nClientID ){
CustomBarClosed();
}
else {
m_bVisible = bVisible;
}
ShowWindow( hwndToolbar, m_bVisible );
}
}
}
void OnCommand( HWND /*hwndView*/ )
{
DisplayBar( !IsVisible() );
}
void CustomBarClosed()
{
if( m_hwndToolbar ){
if( IsWindow( m_hwndToolbar ) ){
DestroyWindow( m_hwndToolbar );
}
if( m_himageToolbar ){
VERIFY( ImageList_Destroy( m_himageToolbar ) );
m_himageToolbar = NULL;
}
_ASSERT( !IsWindow( m_hwndToolbar ) );
m_hwndToolbar = NULL;
m_nClientID = 0;
}
if( m_hDlg ){
DestroyWindow( m_hDlg );
m_hDlg = NULL;
}
}
BOOL QueryStatus( HWND /*hwndView*/, LPBOOL pbChecked )
{
*pbChecked = IsVisible();
return TRUE;
}
void OnEvents( HWND /*hwndView*/, UINT nEvent, LPARAM lParam )
{
if( nEvent & EVENT_CREATE_FRAME ){
LoadProfile();
TCHAR szConfigName[ MAX_CONFIG_NAME ] = { 0 };
Editor_GetConfigW( m_hWnd, szConfigName );
StringCopy( m_szOldConfig, _countof( m_szOldConfig ), szConfigName );
bool bShow = (!m_bAutoDisplay && m_bOpenStartup) || (m_bAutoDisplay && ConfigExist( szConfigName ) );
DisplayBar( bShow );
// DisplayBar( m_bAutoDisplay && ConfigExist( szConfigName ) );
}
if( nEvent & EVENT_CLOSE_FRAME ){
if( m_hwndToolbar ){
_ASSERTE( m_nClientID );
Editor_ToolbarClose( m_hWnd, m_nClientID );
CustomBarClosed();
}
}
if( nEvent & EVENT_TOOLBAR_CLOSED ){
// m_bOpenStartup = false;
// this message arrives even if plug-in does not own this custom bar, so make sure it is mine.
TOOLBAR_INFO* pTI = (TOOLBAR_INFO*)lParam;
if( (pTI->nMask & TIM_ID) && pTI->nID == m_nClientID ){
_ASSERT( m_hwndToolbar != NULL );
CustomBarClosed();
// if the frame closed while the Toolbar is open, save the status for next startup.
if( pTI->nMask & TIM_CX ){
m_cx = pTI->cx;
}
if( pTI->nMask & TIM_STYLE ){
m_fStyle = pTI->fStyle;
}
if( pTI->nMask & TIM_BAND ){
m_nBand = pTI->nBand;
}
// m_bOpenStartup = true;
SaveProfile();
}
}
if( nEvent & EVENT_TOOLBAR_SHOW ){
TOOLBAR_INFO* pTI = (TOOLBAR_INFO*)lParam;
if( (pTI->nMask & TIM_ID) && pTI->nID == m_nClientID ){
_ASSERT( m_hwndToolbar != NULL );
if( pTI->nMask & TIM_STYLE ){
m_bVisible = !(pTI->fStyle & RBBS_HIDDEN);
m_bOpenStartup = m_bVisible;
WriteProfileInt( _T("OpenStartup"), m_bOpenStartup );
}
}
}
if( nEvent & (EVENT_CONFIG_CHANGED | EVENT_FILE_OPENED ) ) {
if( m_bAutoDisplay ){
TCHAR szConfigName[ MAX_CONFIG_NAME ] = { 0 };
Editor_GetConfigW( m_hWnd, szConfigName );
if( lstrcmpi( szConfigName, m_szOldConfig ) != 0 ){
if( ConfigExist( szConfigName ) ){
if( !IsVisible() ){
DisplayBar( true );
}
}
else {
if( IsVisible() ){
DisplayBar( false );
}
}
StringCopy( m_szOldConfig, _countof( m_szOldConfig ), szConfigName );
}
}
}
if( nEvent & EVENT_UI_CHANGED ){
if( lParam & (UI_CHANGED_TOOLBARS | UI_CHANGED_DPI) ){
bool bVisible = IsVisible();
bool bOld = m_bLargeToolbar;
CheckToolbarSize();
if( (lParam & UI_CHANGED_DPI) || bOld != m_bLargeToolbar ){
Editor_ToolbarClose( m_hWnd, m_nClientID );
CustomBarClosed();
DisplayBar( bVisible );
}
}
}
}
BOOL QueryUninstall( HWND /*hDlg*/ )
{
return TRUE;
}
BOOL SetUninstall( HWND hDlg, LPTSTR pszUninstallCommand, LPTSTR pszUninstallParam )
{
TCHAR szProductCode[80] = { 0 };
HKEY hKey = NULL;
if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Software\\EmSoft\\EmEditorPlugIns\\HTMLBar"), 0, KEY_READ, &hKey ) == ERROR_SUCCESS && hKey ){
GetProfileStringReg( hKey, _T("ProductCode"), szProductCode, _countof( szProductCode ), _T("") );
if( szProductCode[0] ){
GetSystemDirectory( pszUninstallCommand, MAX_PATH );
PathAppend( pszUninstallCommand, _T("msiexec.exe") );
StringPrintf( pszUninstallParam, MAX_PATH, _T("/X%s"), szProductCode );
RegCloseKey( hKey );
m_bUninstalling = true;
return UNINSTALL_RUN_COMMAND;
}
}
TCHAR sz[80];
TCHAR szAppName[80];
LoadString( EEGetLocaleInstanceHandle(), IDS_SURE_TO_UNINSTALL, sz, sizeof( sz ) / sizeof( TCHAR ) );
LoadString( EEGetLocaleInstanceHandle(), IDS_MENU_TEXT, szAppName, sizeof( szAppName ) / sizeof( TCHAR ) );
if( MessageBox( hDlg, sz, szAppName, MB_YESNO | MB_ICONEXCLAMATION ) == IDYES ){
// Delete the registry/INI key.
EraseProfile();
m_bUninstalling = true;
return UNINSTALL_SIMPLE_DELETE;
}
return UNINSTALL_FALSE;
}
BOOL QueryProperties( HWND /*hDlg*/ )
{
return TRUE;
}
BOOL SetProperties( HWND hDlg )
{
DialogBox( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_PROP ), hDlg, PropDlg );
return TRUE;
}
BOOL PreTranslateMessage( HWND /*hwndView*/, MSG* pMsg )
{
HWND hwndFocus = GetFocus();
if( hwndFocus ){
if( IsVisible() && IsChild( m_hwndToolbar, hwndFocus ) ){
if( pMsg->message == WM_KEYDOWN ){
bool bCtrl = GetKeyState( VK_CONTROL ) < 0;
bool bShift = GetKeyState( VK_SHIFT ) < 0;
if( !bCtrl ){
if( pMsg->wParam == VK_ESCAPE ){
if( !bShift ){
Editor_ExecCommand( m_hWnd, EEID_ACTIVE_PANE );
return TRUE;
}
}
}
}
if( IsDialogMessage( m_hwndToolbar, pMsg ) ){
return TRUE;
}
}
}
return FALSE;
}
CMyFrame()
{
ZERO_INIT_FIRST_MEM( CMyFrame, m_hwndToolbar );
m_nBand = (UINT)-1;
}
~CMyFrame()
{
CustomBarClosed();
}
bool ConfigExist( LPCTSTR pszConfig )
{
for( vector<tstring>::iterator it = m_AutoConfigArray.begin(); it != m_AutoConfigArray.end(); it++ ){
if( !lstrcmpi( it->c_str(), pszConfig ) ){
return true;
}
}
return false;
}
void OnCustomize( HWND hwnd )
{
if( DialogBox( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_CUSTOMIZE ), hwnd, CustomizeDlg ) == IDOK ){
}
}
void OnPropInitDialog( HWND hDlg )
{
CenterWindow( hDlg );
VERIFY( CheckDlgButton( hDlg, IDC_AUTO_DISPLAY, m_bAutoDisplay ) );
TCHAR szText[40];
LoadString( EEGetLocaleInstanceHandle(), IDS_CONFIGS, szText, _countof( szText ) );
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
ListView_SetExtendedListViewStyleEx( hwndList, LVS_EX_CHECKBOXES, LVS_EX_CHECKBOXES );
LV_COLUMN lvC;
ZeroMemory( &lvC, sizeof(lvC) );
lvC.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvC.fmt = LVCFMT_LEFT;
lvC.pszText = szText;
RECT rc;
GetWindowRect( hwndList, &rc );
lvC.cx = rc.right - rc.left - GetSystemMetrics( SM_CXVSCROLL ) - GetSystemMetrics( SM_CXEDGE ) * 2;
VERIFY( ListView_InsertColumn( hwndList, 0, &lvC ) != -1 );
_ASSERT( hwndList );
ListView_DeleteAllItems( hwndList );
LV_ITEM item;
ZeroMemory( &item, sizeof(item) );
item.mask = LVIF_TEXT;
size_t cchBuf = Editor_EnumConfig( m_hWnd, NULL, 0 );
if( !cchBuf ) return;
LPWSTR pszBuf = new WCHAR[ cchBuf ];
if( !pszBuf ) return;
if( !Editor_EnumConfig( m_hWnd, pszBuf, cchBuf ) ) return;
int i = 0;
LPWSTR p = pszBuf;
while( *p ){
item.iItem = i+1;
item.pszText = p;
i = ListView_InsertItem( hwndList, &item );
if( ConfigExist( p ) ){
ListView_SetCheckState( hwndList, i, TRUE );
}
p += wcslen( p ) + 1;
}
delete [] pszBuf;
EnableWindow( GetDlgItem( hDlg, IDC_LIST ), m_bAutoDisplay );
}
void OnPropCommand( HWND hDlg, WPARAM wParam )
{
if( wParam == IDOK ){
m_bAutoDisplay = !!IsDlgButtonChecked( hDlg, IDC_AUTO_DISPLAY );
m_AutoConfigArray.clear();
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
int nCount = ListView_GetItemCount( hwndList );
for( int i = 0; i < nCount; i++ ){
if( ListView_GetCheckState( hwndList, i ) ){
TCHAR szName[ MAX_CONFIG_NAME ];
szName[0] = 0;
ListView_GetItemText( hwndList, i, 0, szName, _countof( szName ) );
m_AutoConfigArray.push_back( szName );
}
}
SaveProfile();
EndDialog( hDlg, IDOK );
}
else if( wParam == IDCANCEL ){
EndDialog( hDlg, IDCANCEL );
}
else if( wParam == IDC_AUTO_DISPLAY ){
BOOL bEnabled = IsDlgButtonChecked( hDlg, IDC_AUTO_DISPLAY );
EnableWindow( GetDlgItem( hDlg, IDC_LIST ), bEnabled );
}
else if( wParam == IDC_CUSTOMIZE ){
OnCustomize( hDlg );
}
}
void LoadProfile()
{
if( !m_bProfileLoaded ){
m_bProfileLoaded = true;
m_bOpenStartup = !!GetProfileInt( _T("OpenStartup"), FALSE );
m_bAutoDisplay = !!GetProfileInt( _T("AutoDisplay"), FALSE );
m_cx = GetProfileInt( _T("cx"), 0 );
m_fStyle = GetProfileInt( _T("Style"), 0 );
m_nBand = GetProfileInt( _T("Band"), -1 );
m_wRows = (WORD)GetProfileInt( _T("Rows"), 3 );
m_wColumns = (WORD)GetProfileInt( _T("Columns"), 2 );
bool bSuccess = false;
m_AutoConfigArray.clear();
int cchSize = GetProfileInt( _T("Configs-Size"), 0 );
if( cchSize > 2 ){
LPTSTR pBuf = new TCHAR[ cchSize ];
if( pBuf ){
*pBuf = 0;
GetProfileString( _T("Configs"), pBuf, cchSize, _T("") );
if( *pBuf ){
LPTSTR p = pBuf;
for( ; ; ){
LPTSTR p0 = p;
p = _tcschr( p, '\\' );
if( !p ) break;
*p = 0;
if( !*p0 ) break;
m_AutoConfigArray.push_back( p0 );
p++;
}
bSuccess = true;
}
delete [] pBuf;
}
}
if( !bSuccess ){
m_AutoConfigArray.push_back( _T("HTML") );
}
}
}
void SaveProfile()
{
if( m_bUninstalling ) return;
// WriteProfileInt( _T("OpenStartup"), m_bOpenStartup );
WriteProfileInt( _T("AutoDisplay"), !!m_bAutoDisplay );
WriteProfileInt( _T("cx"), m_cx );
WriteProfileInt( _T("Style"), m_fStyle );
WriteProfileInt( _T("Band"), m_nBand );
int cchBuf = 2;
for( vector<tstring>::iterator it = m_AutoConfigArray.begin(); it != m_AutoConfigArray.end(); it++ ){
cchBuf += (int)it->length() + 1;
}
LPTSTR pBuf = new TCHAR[ cchBuf ];
LPTSTR p = pBuf;
int cch = cchBuf;
for( vector<tstring>::iterator it = m_AutoConfigArray.begin(); it != m_AutoConfigArray.end(); it++ ){
StringCopy( p, cch, it->c_str() );
p += it->length();
*p++ = _T('\\');
cch -= (int)it->length() + 1;
}
*p++ = _T('\\');
*p = 0;
_ASSERT( lstrlen( pBuf ) + 1 == cchBuf );
WriteProfileString( _T("Configs"), pBuf );
delete [] pBuf;
WriteProfileInt( _T("Configs-Size"), cchBuf );
}
int PopupMenuSub( UINT nIDCommand, UINT nIDMenu )
{
_ASSERT( m_hwndToolbar != NULL );
if( m_hwndToolbar == NULL ) return 0;
RECT rect = { 0 };
int nIndex = (int)SendMessage( m_hwndToolbar, TB_COMMANDTOINDEX, nIDCommand, 0L );
_ASSERT( nIndex >= 0 );
if( nIndex != -1 ){
SendMessage( m_hwndToolbar, TB_GETITEMRECT, nIndex, (LPARAM)&rect );
// rect.top = rect.bottom;
}
//if( nIndex == -1 ){
// ::ClientToScreen( m_hwndToolbar, (LPPOINT)&rect );
//}
::ClientToScreen( m_hwndToolbar, (LPPOINT)&rect.left );
::ClientToScreen( m_hwndToolbar, (LPPOINT)&rect.right );
HMENU hMainMenu = LoadMenu( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE(nIDMenu) );
HMENU hMenu = GetSubMenu( hMainMenu, 0 );
if( nIDMenu == IDR_POPUP_FONT ){
int i = 1;
for( vector<tstring>::iterator it = m_RecentFontArray.begin(); it != m_RecentFontArray.end(); it++ ){
InsertMenu( hMenu, 0, MF_BYPOSITION, i++, it->c_str() );
}
}
//TPMPARAMS tpmp;
//ZeroMemory( &tpmp, sizeof( tpmp ) );
//tpmp.cbSize = sizeof( tpmp );
//tpmp.rcExclude.right = rect.left;
//tpmp.rcExclude.left = INT_MIN;
//tpmp.rcExclude.top = INT_MIN;
//tpmp.rcExclude.bottom = INT_MAX;
BOOL bRightAlign = GetSystemMetrics( SM_MENUDROPALIGNMENT );
int nResult = TrackPopupMenuEx( hMenu, (bRightAlign ? TPM_RIGHTALIGN : TPM_LEFTALIGN) | TPM_RIGHTBUTTON | TPM_RETURNCMD, bRightAlign ? rect.right : rect.left, rect.bottom, m_hDlg, NULL );
DestroyMenu( hMainMenu );
return nResult;
}
void InsertTag( LPCTSTR pszTagBegin, LPCTSTR pszTagEnd )
{
int nSelType = Editor_GetSelTypeEx( m_hWnd, TRUE );
int nTagBeginLen = (int)_tcslen( pszTagBegin );
int nTagEndLen = (int)_tcslen( pszTagEnd );
if( nSelType & SEL_TYPE_SELECTED ){
UINT_PTR nBufSize = Editor_GetSelTextW( m_hWnd, 0, NULL );
nBufSize += nTagBeginLen + nTagEndLen + 8;
LPWSTR pBuf = new WCHAR[ nBufSize ];
if( pBuf ){
POINT_PTR ptSelStart;
POINT_PTR ptSelEnd;
Editor_GetSelStart( m_hWnd, POS_LOGICAL_W, &ptSelStart );
Editor_GetSelEnd( m_hWnd, POS_LOGICAL_W, &ptSelEnd );
if( ptSelStart.y > ptSelEnd.y || (ptSelStart.y == ptSelEnd.y && ptSelStart.x > ptSelEnd.x) ){
POINT_PTR pt;
pt.x = ptSelStart.x;
pt.y = ptSelStart.y;
ptSelStart.x = ptSelEnd.x;
ptSelStart.y = ptSelEnd.y;
ptSelEnd.x = pt.x;
ptSelEnd.y = pt.y;
}
StringCopy( pBuf, nBufSize, pszTagBegin );
Editor_GetSelTextW( m_hWnd, nBufSize - nTagBeginLen, pBuf + nTagBeginLen );
StringCat( pBuf, nBufSize, pszTagEnd );
bool bNL = _tcschr( pBuf, '\r' ) || _tcschr( pBuf, '\n' );
Editor_InsertW( m_hWnd, pBuf, true );
Editor_SetCaretPosEx( m_hWnd, POS_LOGICAL_W, &ptSelStart, FALSE );
ptSelEnd.x += nTagEndLen;
if( !bNL ) {
ptSelEnd.x += nTagBeginLen;
}
Editor_SetCaretPosEx( m_hWnd, POS_LOGICAL_W, &ptSelEnd, TRUE );
delete [] pBuf;
}
}
else {
if( pszTagBegin[0] ){
Editor_InsertW( m_hWnd, pszTagBegin, true );
}
if( pszTagEnd[0] ){
Editor_InsertW( m_hWnd, pszTagEnd, true );
}
for( int i = 0; i < nTagEndLen; i++ ){
Editor_ExecCommand( m_hWnd, EEID_LEFT );
}
}
}
void InsertTagFont( LPCTSTR szFaceName )
{
TCHAR szTagBegin[80];
StringPrintf( szTagBegin, _countof( szTagBegin ), _T("<font face=\"%s\">"), szFaceName );
InsertTag( szTagBegin, _T("</font>") );
for( vector<tstring>::iterator it = m_RecentFontArray.begin(); it != m_RecentFontArray.end(); it++ ){
if( lstrcmp( it->c_str(), szFaceName ) == 0 ){
m_RecentFontArray.erase( it );
break;
}
}
m_RecentFontArray.push_back( szFaceName );
if( m_RecentFontArray.size() >= MAX_RECENT_FONT ){
m_RecentFontArray.erase( m_RecentFontArray.begin() );
}
}
void Unindent()
{
int nSelType = Editor_GetSelTypeEx( m_hWnd, TRUE );
if( nSelType & SEL_TYPE_SELECTED ){
UINT_PTR nBufSize = Editor_GetSelTextW( m_hWnd, 0, NULL );
LPWSTR pBuf = new WCHAR[ nBufSize ];
if( pBuf ){
Editor_GetSelTextW( m_hWnd, nBufSize, pBuf );
LPCTSTR pszBegin = _T("<blockquote>");
int nBeginLen = lstrlen( pszBegin );
LPCTSTR pszEnd = _T("</blockquote>");
int nEndLen = lstrlen( pszEnd );
LPTSTR p1 = StrStrI( pBuf, pszBegin );
if( p1 ){
wmemmove( p1, p1 + nBeginLen, lstrlen( p1 + nBeginLen ) + 1 );
LPTSTR p2 = StrStrI( p1, pszEnd );
if( p2 ){
wmemmove( p2, p2 + nEndLen, lstrlen( p2 + nEndLen ) + 1 );
Editor_InsertW( m_hWnd, pBuf, false );
}
}
delete [] pBuf;
}
}
}
void OnFont()
{
LOGFONT lf = { 0 };
HFONT hFont = (HFONT)GetStockObject( DEFAULT_GUI_FONT );
if( hFont ){
GetObject( hFont, sizeof( lf ), &lf );
}
CHOOSEFONT cf = { 0 };
cf.lStructSize = sizeof( cf );
cf.hwndOwner = m_hDlg;
cf.lpLogFont = &lf;
cf.hInstance = EEGetLocaleInstanceHandle();
cf.lpTemplateName = MAKEINTRESOURCE( IDD_FONT );
cf.Flags = CF_SCREENFONTS | CF_NOVERTFONTS | CF_ENABLETEMPLATE | CF_INITTOLOGFONTSTRUCT;
if( ChooseFont( &cf ) ) {
InsertTagFont( lf.lfFaceName );
}
}
void OnDlgCommand( WPARAM wParam )
{
if( wParam >= ID_COMMAND_BASE && wParam < ID_COMMAND_BASE + m_CmdArray.size() ) {
CCmd& cmd = m_CmdArray[wParam - ID_COMMAND_BASE];
if( cmd.m_iCmd == CMD_TAGS ){
BOOL bResult;
wstring sTagBegin = UnescapeString( cmd.m_sTagBegin.c_str(), &bResult );
if( bResult ){
wstring sTagEnd = UnescapeString( cmd.m_sTagEnd.c_str(), &bResult );
if( bResult ){
InsertTag( sTagBegin.c_str(), sTagEnd.c_str() );
}
}
}
else if( cmd.m_iCmd == CMD_INSERT_TABLE ){
if( DialogBox( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_TABLE ), m_hDlg, TableDlg ) == IDOK ){
Editor_InsertW( m_hWnd, _T("<table>\n"), true );
for( WORD i = 0; i < m_wRows; i++ ){
Editor_InsertW( m_hWnd, _T("\t<tr>\n"), true );
for( WORD j = 0; j < m_wColumns; j++ ){
Editor_InsertW( m_hWnd, _T("\t\t<td></td>\n"), true );
}
Editor_InsertW( m_hWnd, _T("\t</tr>\n"), true );
}
Editor_InsertW( m_hWnd, _T("</table>\n"), true );
}
}
else if( cmd.m_iCmd == CMD_FONT ){
OnFont();
}
else if( cmd.m_iCmd == CMD_UNINDENT ){
Unindent();
}
else if( cmd.m_iCmd == CMD_CUSTOMIZE ){
OnCustomize( m_hWnd );
}
}
//switch( wParam ){
//case ID_PARAGRAPH:
// InsertTag( L"<p>", L"</p>" );
// break;
//case ID_BREAK:
// InsertTag( L"<br />", L"" );
// break;
//case ID_BOLD:
// InsertTag( L"<strong>", L"</strong>" );
// break;
//case ID_ITALIC:
// InsertTag( L"<em>", L"</em>" );
// break;
//case ID_UNDERLINE:
// InsertTag( L"<u>", L"</u>" );
// break;
//case ID_FONT:
// {
// LOGFONT lf = { 0 };
// HFONT hFont = (HFONT)GetStockObject( DEFAULT_GUI_FONT );
// if( hFont ){
// GetObject( hFont, sizeof( lf ), &lf );
// }
// CHOOSEFONT cf = { 0 };
// cf.lStructSize = sizeof( cf );
// cf.hwndOwner = m_hDlg;
// cf.lpLogFont = &lf;
// cf.hInstance = EEGetInstanceHandle();
// cf.lpTemplateName = MAKEINTRESOURCE( IDD_FONT );
// cf.Flags = CF_SCREENFONTS | CF_NOVERTFONTS | CF_ENABLETEMPLATE | CF_INITTOLOGFONTSTRUCT;
// if( ChooseFont( &cf ) ) {
// InsertTagFont( lf.lfFaceName );
// }
// }
// break;
//case ID_COLOR:
// {
// CHOOSECOLOR cc = { 0 };
// cc.lStructSize = sizeof( cc );
// cc.hwndOwner = m_hDlg;
// cc.lpCustColors = m_crCustClr;
// if( ChooseColor( &cc ) ){
// m_dwDefColor = cc.rgbResult;
// TCHAR sz[16];
// StringPrintf( sz, _countof( sz ), _T("#%02x%02x%02x"), GetRValue( cc.rgbResult ), GetGValue( cc.rgbResult ), GetBValue( cc.rgbResult ) );
// InsertTag( sz, _T("") );
// }
// }
// break;
//case ID_PICTURE:
// {
// TCHAR szRelativePath[MAX_PATH];
// if( ChooseFile( szRelativePath, IDS_PICTURE, IDS_FILTER_IMAGE ) ){
// TCHAR szTag[MAX_PATH+40];
// StringPrintf( szTag, _countof( szTag ), _T("<img src=\"%s\" width=\"\" height=\"\" alt=\"\" />"), szRelativePath );
// InsertTag( szTag, _T("") );
// }
// }
// break;
//case ID_HYPERLINK:
// {
// TCHAR szRelativePath[MAX_PATH];
// if( ChooseFile( szRelativePath, IDS_HYPERLINK, IDS_FILTER_HYPERLINK ) ){
// TCHAR szTag[MAX_PATH+40];
// StringPrintf( szTag, _countof( szTag ), _T("<a href=\"%s\">"), szRelativePath );
// InsertTag( szTag, _T("</a>") );
// }
// }
// break;
//case ID_TABLE:
// {
// if( DialogBox( EEGetInstanceHandle(), MAKEINTRESOURCE( IDD_TABLE ), m_hDlg, TableDlg ) == IDOK ){
// Editor_InsertW( m_hWnd, _T("<table>\n"), true );
// for( WORD i = 0; i < m_wRows; i++ ){
// Editor_InsertW( m_hWnd, _T("\t<tr>\n"), true );
// for( WORD j = 0; j < m_wColumns; j++ ){
// Editor_InsertW( m_hWnd, _T("\t\t<td></td>\n"), true );
// }
// Editor_InsertW( m_hWnd, _T("\t</tr>\n"), true );
// }
// Editor_InsertW( m_hWnd, _T("</table>\n"), true );
// }
// }
// break;
//case ID_HORZ_LINE:
// {
// InsertTag( _T("<hr />"), _T("") );
// }
// break;
//case ID_COMMENT:
// {
// InsertTag( _T("<!-- "), _T(" -->") );
// }
// break;
//case ID_ALIGN_LEFT:
// {
// InsertTag( _T("<p align=\"left\">"), _T("</p>") );
// }
// break;
//case ID_CENTER:
// {
// InsertTag( _T("<p align=\"center\">"), _T("</p>") );
// }
// break;
//case ID_ALIGN_RIGHT:
// {
// InsertTag( _T("<p align=\"right\">"), _T("</p>") );
// }
// break;
//case ID_JUSTIFY:
// {
// InsertTag( _T("<p align=\"justify\">"), _T("</p>") );
// }
// break;
//case ID_NUMBERING:
// {
// InsertTag( _T("<ol>\n\t<li>"), _T("</li>\n</ol>") );
// }
// break;
//case ID_BULLETS:
// {
// InsertTag( _T("<ul>\n\t<li>"), _T("</li>\n</ul>") );
// }
// break;
//case ID_UNINDENT:
// {
// Unindent();
// }
// break;
//case ID_INDENT:
// {
// InsertTag( _T("<blockquote>"), _T("</blockquote>") );
// }
// break;
//case ID_HIGHLIGHT:
// {
// TCHAR sz[260];
// StringPrintf( sz, _countof( sz ), _T("<span style=\"background-color: #%02x%02x%02x\">"), GetRValue( m_dwDefColor ), GetGValue( m_dwDefColor ), GetBValue( m_dwDefColor ) );
// InsertTag( sz, _T("</span>") );
// }
// break;
//case ID_FONT_COLOR:
// {
// TCHAR sz[260];
// StringPrintf( sz, _countof( sz ), _T("<font color=\"#%02x%02x%02x\">"), GetRValue( m_dwDefColor ), GetGValue( m_dwDefColor ), GetBValue( m_dwDefColor ) );
// InsertTag( sz, _T("</font>") );
// }
// break;
//}
}
void OnDlgNotify( NMHDR* pnmh )
{
switch( pnmh->code ){
case TTN_GETDISPINFO:
{
NMTTDISPINFO* pDispInfo = (NMTTDISPINFO*)pnmh;
if( pDispInfo->hdr.idFrom >= ID_COMMAND_BASE && pDispInfo->hdr.idFrom < ID_COMMAND_BASE + m_CmdArray.size() ) {
CCmd& cmd = m_CmdArray[ pDispInfo->hdr.idFrom - ID_COMMAND_BASE];
StringCopyN( pDispInfo->szText, _countof( pDispInfo->szText ), cmd.m_sTitle.c_str(), _countof( pDispInfo->szText ) - 1 );
}
}
break;
case TBN_DROPDOWN:
{
NMTOOLBAR* pToolbar = (NMTOOLBAR*)pnmh;
if( pToolbar->iItem >= ID_COMMAND_BASE && pToolbar->iItem < ID_COMMAND_BASE + (int)m_CmdArray.size() ) {
CCmd& cmd = m_CmdArray[pToolbar->iItem - ID_COMMAND_BASE];
switch( cmd.m_iCmd ){
case CMD_FONT:
{
int n = PopupMenuSub( pToolbar->iItem, IDR_POPUP_FONT );
if( n == 999 ){
OnFont();
}
else if( n > 0 ){
_ASSERT( n - 1 < (int)m_RecentFontArray.size() );
TCHAR sz[LF_FACESIZE];
StringCopy( sz, _countof( sz ), m_RecentFontArray[n - 1].c_str() );
InsertTagFont( sz );
}
}
break;
case CMD_DROPDOWN_HEADER:
{
int n = PopupMenuSub( pToolbar->iItem, IDR_POPUP_HEADER );
if( n > 0 ){
TCHAR szTagBegin[8], szTagEnd[8];
StringPrintf( szTagBegin, _countof( szTagBegin ), _T("<h%d>"), n );
StringPrintf( szTagEnd, _countof( szTagEnd ), _T("</h%d>"), n );
InsertTag( szTagBegin, szTagEnd );
}
}
break;
case CMD_DROPDOWN_FORM:
{
int n = PopupMenuSub( pToolbar->iItem, IDR_POPUP_FORM );
switch( n ) {
case 1:
InsertTag( _T("<form method=\"post\" action=\"\">\n\t"), _T("\n<input type=\"submit\"><input type=\"reset\"></form>\n") );
break;
case 2:
InsertTag( _T("<input type=\"text\" id=\"\" />"), _T("") );
break;
case 3:
InsertTag( _T("<textarea id=\"\" rows=\"3\" cols=\"30\">"), _T("</textarea>") );
break;
case 4:
InsertTag( _T("<input type=\"checkbox\" id=\"\" />"), _T("") );
break;
case 5:
InsertTag( _T("<input type=\"radio\" id=\"\" />"), _T("") );
break;
case 6:
InsertTag( _T("<fieldset style=\"padding: 2\">\n<legend>Group Box"), _T("</legend></fieldset>") );
break;
case 7:
InsertTag( _T("<select size=\"1\" id=\"\">"), _T("</select>") );
break;
case 8:
InsertTag( _T("<input type=\"button\" value=\"Button\" id=\"\">"), _T("") );
break;
case 9:
InsertTag( _T("<button id=\"\">Type Here"), _T("</button>") );
break;
}
}
break;
}
}
}
break;
}
}
void OnTableInitDialog( HWND hDlg )
{
CenterWindow( hDlg );
SetDlgItemInt( hDlg, IDC_ROWS, (UINT)m_wRows, FALSE );
SetDlgItemInt( hDlg, IDC_COLUMNS, (UINT)m_wColumns, FALSE );
}
void OnTableCommand( HWND hDlg, WPARAM wParam )
{
if( wParam == IDOK ){
BOOL bTranslated = FALSE;
WORD w = (WORD)GetDlgItemInt( hDlg, IDC_ROWS, &bTranslated, FALSE );
if( bTranslated ){
m_wRows = w;
}
w = (WORD)GetDlgItemInt( hDlg, IDC_COLUMNS, &bTranslated, FALSE );
if( bTranslated ){
m_wColumns = w;
}
EndDialog( hDlg, IDOK );
}
else if( wParam == IDCANCEL ){
EndDialog( hDlg, IDCANCEL );
}
}
void CustomizeShowHide( HWND hDlg )
{
bool bTags = false;
bool bSpecial = false;
if( IsDlgButtonChecked( hDlg, IDC_SEPARATOR ) ) {
}
else if( IsDlgButtonChecked( hDlg, IDC_TAGS ) ) {
bTags = true;
}
else {
bSpecial = true;
}
EnableWindow( GetDlgItem( hDlg, IDC_TAG_BEGIN ), bTags );
EnableWindow( GetDlgItem( hDlg, IDC_TAG_END ), bTags );
EnableWindow( GetDlgItem( hDlg, IDC_BROWSE_BEGIN ), bTags );
EnableWindow( GetDlgItem( hDlg, IDC_BROWSE_END ), bTags );
EnableWindow( GetDlgItem( hDlg, IDC_COMBO_SPECIAL ), bSpecial );
}
void CustomizeRefreshList( HWND hDlg, int iSel )
{
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
if( !hwndList ) return;
ListView_DeleteAllItems( hwndList );
for( int i = 0; i < (int)m_CmdArray.size(); i++ ) {
LV_ITEM item;
ZeroMemory( &item, sizeof(item) );
item.mask = LVIF_TEXT | LVIF_IMAGE;
item.iItem = i+1;
item.pszText = LPSTR_TEXTCALLBACK;
item.iImage = I_IMAGECALLBACK;
ListView_InsertItem( hwndList, &item );
}
ListView_SetItemState( hwndList, iSel, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED );
ListView_EnsureVisible( hwndList, iSel, TRUE );
}
void OnCustomizeProp( HWND hDlg )
{
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
if( !hwndList ) return;
int iItem = ListView_GetNextItem( hwndList, -1, LVNI_SELECTED );
if( iItem >= 0 ){
m_pcmdProp = &m_CmdArray[ iItem ];
if( DialogBox( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_CUST_PROP ), hDlg, CustPropDlg ) == IDOK ){
CustomizeRefreshList( hDlg, iItem );
AddButtons( m_hwndToolbar );
m_bCmdArrayModified = true;
}
}
}
void OnCustomizeNew( HWND hDlg )
{
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
if( !hwndList ) return;
int iItem = ListView_GetNextItem( hwndList, -1, LVNI_SELECTED );
CCmd cmd( -1, CMD_SEPARATOR, NULL, NULL, NULL );
m_pcmdProp = &cmd;
if( DialogBox( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_CUST_PROP ), hDlg, CustPropDlg ) == IDOK ){
if( iItem >= 0 ){
m_CmdArray.insert( m_CmdArray.begin() + iItem, cmd );
}
else {
m_CmdArray.push_back( cmd );
}
CustomizeRefreshList( hDlg, iItem );
AddButtons( m_hwndToolbar );
m_bCmdArrayModified = true;
}
}
void OnCustomizeDelete( HWND hDlg )
{
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
if( !hwndList ) return;
int iItem = ListView_GetNextItem( hwndList, -1, LVNI_SELECTED );
if( iItem >= 0 ){
m_CmdArray.erase( m_CmdArray.begin() + iItem );
if( iItem == (int)m_CmdArray.size() ){
iItem--;
}
CustomizeRefreshList( hDlg, iItem );
AddButtons( m_hwndToolbar );
m_bCmdArrayModified = true;
}
}
void OnCustomizeCopy( HWND hDlg )
{
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
if( !hwndList ) return;
int iItem = ListView_GetNextItem( hwndList, -1, LVNI_SELECTED );
CCmd cmd = m_CmdArray[ iItem ];
m_pcmdProp = &cmd;
if( DialogBox( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDD_CUST_PROP ), hDlg, CustPropDlg ) == IDOK ){
if( iItem >= 0 ){
m_CmdArray.insert( m_CmdArray.begin() + iItem + 1, cmd );
}
else {
m_CmdArray.push_back( cmd );
}
CustomizeRefreshList( hDlg, iItem + 1 );
AddButtons( m_hwndToolbar );
m_bCmdArrayModified = true;
}
}
void OnCustomizeUpDown( HWND hDlg, int nDir )
{
_ASSERT( nDir == 1 || nDir == -1 );
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
if( !hwndList ) return;
int iItem = ListView_GetNextItem( hwndList, -1, LVNI_SELECTED );
int iNextItem = iItem + nDir;
if( iNextItem < 0 || iNextItem >= (int)m_CmdArray.size() ){
return;
}
CCmd cmd = m_CmdArray[ iItem ];
m_CmdArray[ iItem ] = m_CmdArray[ iNextItem ];
m_CmdArray[ iNextItem ] = cmd;
CustomizeRefreshList( hDlg, iNextItem );
AddButtons( m_hwndToolbar );
m_bCmdArrayModified = true;
}
void OnCustomizeInitDialog( HWND hDlg )
{
CenterWindow( hDlg );
HWND hwndList = GetDlgItem( hDlg, IDC_LIST );
if( !hwndList ) return;
ListView_SetExtendedListViewStyleEx( hwndList, LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT );
ListView_SetImageList( hwndList, m_himageToolbar, LVSIL_SMALL );
TCHAR sz[80];
LV_COLUMN lvC = { 0 };
lvC.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvC.pszText = sz;
RECT rc;
GetWindowRect( hwndList, &rc );
lvC.cx = rc.right - rc.left - GetSystemMetrics( SM_CXVSCROLL ) - GetSystemMetrics( SM_CXEDGE ) * 2;
// LoadString( EEGetInstanceHandle(), IDS_VALUE, sz, _countof( sz ) );
GetWindowText( hDlg, sz, _countof( sz ) );
VERIFY( ListView_InsertColumn( hwndList, 0, &lvC ) != -1 );
CustomizeRefreshList( hDlg, 0 );
}
void OnCustomizeCommand( HWND hDlg, WPARAM wParam )
{
if( wParam == IDCANCEL ){
EndDialog( hDlg, IDCANCEL );
SaveCmdArray();
}
else if( wParam == IDC_PROP ){
OnCustomizeProp( hDlg );
}
else if( wParam == IDC_NEW ){
OnCustomizeNew( hDlg );
}
else if( wParam == IDC_COPY ){
OnCustomizeCopy( hDlg );
}
else if( wParam == IDC_DELETE ){
OnCustomizeDelete( hDlg );
}
else if( wParam == IDC_UP ){
OnCustomizeUpDown( hDlg, -1 );
}
else if( wParam == IDC_DOWN ){
OnCustomizeUpDown( hDlg, 1 );
}
else if( wParam == IDC_RESET ){
TCHAR sz[260], szAppName[80];
LoadString( EEGetLocaleInstanceHandle(), IDS_SURE_RESET, sz, _countof( sz ) );
LoadString( EEGetLocaleInstanceHandle(), IDS_MENU_TEXT, szAppName, sizeof( szAppName ) / sizeof( TCHAR ) );
if( MessageBox( hDlg, sz, szAppName, MB_YESNO | MB_ICONEXCLAMATION ) == IDYES ){
ResetCmdArray();
CustomizeRefreshList( hDlg, 0 );
AddButtons( m_hwndToolbar );
}
}
}
BOOL OnCustomizeNotify( HWND hDlg, int idCtrl, LPNMHDR pnmh )
{
BOOL bResult = FALSE;
if( idCtrl == IDC_LIST ){
switch( pnmh->code ){
case LVN_GETDISPINFO:
{
LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pnmh;
if( pDispInfo->item.iItem < (int)m_CmdArray.size() ) {
_ASSERT( pDispInfo->item.iItem >= 0 && pDispInfo->item.iItem < (int)m_CmdArray.size() );
CCmd& cmd = m_CmdArray[pDispInfo->item.iItem];
if( pDispInfo->item.mask & LVIF_TEXT ){
if( cmd.m_iCmd == CMD_SEPARATOR ){
StringCopy( pDispInfo->item.pszText, pDispInfo->item.cchTextMax, L"----------" );
}
else {
StringCopyN( pDispInfo->item.pszText, pDispInfo->item.cchTextMax, cmd.m_sTitle.c_str(), pDispInfo->item.cchTextMax-1 );
}
}
if( pDispInfo->item.mask & LVIF_IMAGE ){
if( cmd.m_iCmd == CMD_SEPARATOR ){
pDispInfo->item.iImage = -1;
}
else {
pDispInfo->item.iImage = cmd.m_iIcon;
}
}
}
}
break;
case NM_DBLCLK:
{
OnCustomizeProp( hDlg );
}
break;
}
}
return bResult;
}
void OnCustPropInitDialog( HWND hDlg )
{
CenterWindow( hDlg );
m_bPropInitialized = false;
SendDlgItemMessage( hDlg, IDC_TITLE, EM_LIMITTEXT, MAX_BUTTON_TITLE - 1, 0 );
SendDlgItemMessage( hDlg, IDC_TAG_BEGIN, EM_LIMITTEXT, MAX_TAG_FIELD - 1, 0 );
SendDlgItemMessage( hDlg, IDC_TAG_END, EM_LIMITTEXT, MAX_TAG_FIELD - 1, 0 );
SetDlgItemText( hDlg, IDC_TITLE, m_pcmdProp->m_sTitle.c_str() );
HWND hwndComboSpecial = GetDlgItem( hDlg, IDC_COMBO_SPECIAL );
if( !hwndComboSpecial ) return;
for( int i = 0; i < MAX_CMD - CMD_INSERT_TABLE; i++ ) {
COMBOBOXEXITEM item = { 0 };
item.mask = CBEIF_TEXT;
item.iItem = -1;
item.pszText = LPSTR_TEXTCALLBACK;
SendMessage( hwndComboSpecial, CBEM_INSERTITEM, 0, (LPARAM)&item );
}
HWND hwndCombo = GetDlgItem( hDlg, IDC_COMBO_ICON );
if( !hwndCombo ) return;
SendMessage( hwndCombo, CBEM_SETIMAGELIST, 0, (LPARAM)m_himageToolbar );
int nCount = ImageList_GetImageCount( m_himageToolbar );
for( int i = -1; i < nCount; i++ ) {
COMBOBOXEXITEM item = { 0 };
item.mask = CBEIF_IMAGE | CBEIF_SELECTEDIMAGE | CBEIF_TEXT;
item.iItem = -1;
item.iImage = i;
item.iSelectedImage = i;
item.pszText = LPSTR_TEXTCALLBACK;
SendMessage( hwndCombo, CBEM_INSERTITEM, 0, (LPARAM)&item );
}
SendMessage( hwndCombo, CB_SETCURSEL, m_pcmdProp->m_iCmd == CMD_SEPARATOR ? 0 : m_pcmdProp->m_iIcon + 1, 0 );
SendMessage( hwndComboSpecial, CB_SETCURSEL, max( 0, (m_pcmdProp->m_iCmd - CMD_INSERT_TABLE) ), 0 );
int nID;
if( m_pcmdProp->m_iCmd == CMD_SEPARATOR ){
nID = IDC_SEPARATOR;
m_bPropModified = false;
}
else if( m_pcmdProp->m_iCmd == CMD_TAGS ){
nID = IDC_TAGS;
m_bPropModified = true;
}
else {
nID = IDC_SPECIAL;
m_bPropModified = true;
}
VERIFY( CheckRadioButton( hDlg, IDC_TAGS, IDC_SEPARATOR, nID ) );
SetDlgItemText( hDlg, IDC_TAG_BEGIN, m_pcmdProp->m_sTagBegin.c_str() );
SetDlgItemText( hDlg, IDC_TAG_END, m_pcmdProp->m_sTagEnd.c_str() );
CustomizeShowHide( hDlg );
m_bPropInitialized = true;
}
void OnCustPropCommand( HWND hDlg, WPARAM wParam )
{
if( wParam == IDOK ){
TCHAR sz[MAX_BUTTON_TITLE];
GetDlgItemText( hDlg, IDC_TITLE, sz, _countof( sz ) );
m_pcmdProp->m_sTitle = sz;
if( IsDlgButtonChecked( hDlg, IDC_SEPARATOR ) ) {
m_pcmdProp->m_iIcon = -1;
m_pcmdProp->m_iCmd = CMD_SEPARATOR;
}
else if( IsDlgButtonChecked( hDlg, IDC_TAGS ) ) {
m_pcmdProp->m_iCmd = CMD_TAGS;
GetDlgItemText( hDlg, IDC_TAG_BEGIN, sz, _countof( sz ) );
m_pcmdProp->m_sTagBegin = sz;
GetDlgItemText( hDlg, IDC_TAG_END, sz, _countof( sz ) );
m_pcmdProp->m_sTagEnd = sz;
}
else {
int iSpecial = (int)SendDlgItemMessage( hDlg, IDC_COMBO_SPECIAL, CB_GETCURSEL, 0, 0 );
_ASSERT( iSpecial >= 0 && iSpecial < MAX_CMD - CMD_INSERT_TABLE );
m_pcmdProp->m_iCmd = iSpecial + CMD_INSERT_TABLE;
}
if( m_pcmdProp->m_iCmd != CMD_SEPARATOR ){
m_pcmdProp->m_iIcon = (int)SendDlgItemMessage( hDlg, IDC_COMBO_ICON, CB_GETCURSEL, 0, 0 ) - 1;
}
EndDialog( hDlg, IDOK );
}
else if( wParam == IDCANCEL ){
EndDialog( hDlg, IDCANCEL );
}
else if( wParam == IDC_SEPARATOR || wParam == IDC_TAGS || wParam == IDC_SPECIAL ){
if( wParam == IDC_SEPARATOR ){
SendDlgItemMessage( hDlg, IDC_COMBO_ICON, CB_SETCURSEL, 0, 0 );
}
CustomizeShowHide( hDlg );
m_bPropModified = true;
}
else if( wParam == MAKEWPARAM( IDC_COMBO_ICON, CBN_SELENDOK ) ){
int iIcon = (int)SendDlgItemMessage( hDlg, IDC_COMBO_ICON, CB_GETCURSEL, 0, 0 );
if( iIcon == 0 ){
VERIFY( CheckRadioButton( hDlg, IDC_TAGS, IDC_SEPARATOR, IDC_SEPARATOR ) );
SetDlgItemText( hDlg, IDC_TAG_BEGIN, L"" );
SetDlgItemText( hDlg, IDC_TAG_END, L"" );
}
else if( !m_bPropModified ){
TCHAR sz[MAX_BUTTON_TITLE];
LoadString( EEGetLocaleInstanceHandle(), ID_HEADER + iIcon - 1, sz, _countof( sz ) );
SetDlgItemText( hDlg, IDC_TITLE, sz );
for( int i = 0; i < _countof( DefCmd ); i++ ){
if( DefCmd[i].m_iIcon == iIcon - 1 ){
int nID = IDC_TAGS;
if( DefCmd[i].m_iCmd != CMD_TAGS ){
nID = IDC_SPECIAL;
int iSpecial = DefCmd[i].m_iCmd - CMD_INSERT_TABLE;
SendDlgItemMessage( hDlg, IDC_COMBO_SPECIAL, CB_SETCURSEL, iSpecial, 0 );
}
VERIFY( CheckRadioButton( hDlg, IDC_TAGS, IDC_SEPARATOR, nID ) );
SetDlgItemText( hDlg, IDC_TAG_BEGIN, DefCmd[i].m_pszTagBegin );
SetDlgItemText( hDlg, IDC_TAG_END, DefCmd[i].m_pszTagEnd );
CustomizeShowHide( hDlg );
break;
}
}
}
}
else if( wParam == MAKEWPARAM( IDC_COMBO_SPECIAL, CBN_SELENDOK ) ){
m_bPropModified = true;
}
else if( wParam == MAKEWPARAM( IDC_TAG_BEGIN, EN_CHANGE ) || wParam == MAKEWPARAM( IDC_TAG_END, EN_CHANGE )
|| wParam == MAKEWPARAM( IDC_TITLE, EN_CHANGE ) ){
// if( m_bPropInitialized ){
if( GetFocus() == GetDlgItem( hDlg, LOWORD( wParam ) ) ) {
m_bPropModified = true;
}
}
else if( wParam == IDC_BROWSE_BEGIN || wParam == IDC_BROWSE_END ){
HWND hwndButton = (HWND)GetDlgItem( hDlg, (int)wParam );
RECT rect;
GetWindowRect( hwndButton, &rect );
BOOL bRightAlign = GetSystemMetrics( SM_MENUDROPALIGNMENT );
HMENU hMenu = LoadMenu( EEGetLocaleInstanceHandle(), MAKEINTRESOURCE( IDR_ARG_POPUP ) );
HMENU hSubMenu = GetSubMenu( hMenu, 0 );
UINT uID = TrackPopupMenu( hSubMenu, (bRightAlign ? TPM_RIGHTALIGN : TPM_LEFTALIGN) | TPM_RIGHTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD, bRightAlign ? rect.right : rect.left, rect.bottom, 0, hDlg, NULL );
DestroyMenu( hMenu );
if( uID != 0 ){
TCHAR sz[80];
StringPrintf( sz, _countof( sz ), _T("\\{%s}"), szToolArgs[uID-1] );
SendDlgItemMessage( hDlg, wParam == IDC_BROWSE_BEGIN ? IDC_TAG_BEGIN : IDC_TAG_END, EM_REPLACESEL, TRUE, (LPARAM)sz );
}
}
}
BOOL OnCustPropNotify( HWND /* hDlg */, int idCtrl, LPNMHDR pnmh )
{
BOOL bResult = FALSE;
if( idCtrl == IDC_COMBO_ICON ){
switch( pnmh->code ){
case CBEN_GETDISPINFO:
{
NMCOMBOBOXEX* pComboBoxEx = (NMCOMBOBOXEX*)pnmh;
COMBOBOXEXITEM& item = pComboBoxEx->ceItem;
_ASSERT( item.iItem >= 0 && item.iItem < (int)ImageList_GetImageCount( m_himageToolbar ) + 1 );
if( item.mask & CBEIF_TEXT ){
if( item.iItem == 0 ){
StringCopy( item.pszText, item.cchTextMax, L"----------" );
}
else {
LoadString( EEGetLocaleInstanceHandle(), ID_HEADER + (int)item.iItem - 1, item.pszText, item.cchTextMax );
}
}
}
break;
}
}
else if( idCtrl == IDC_COMBO_SPECIAL ){
switch( pnmh->code ){
case CBEN_GETDISPINFO:
{
NMCOMBOBOXEX* pComboBoxEx = (NMCOMBOBOXEX*)pnmh;
COMBOBOXEXITEM& item = pComboBoxEx->ceItem;
_ASSERT( item.iItem >= 0 && item.iItem < _countof( SpecialStringID ) );
if( item.mask & CBEIF_TEXT ){
int nID = SpecialStringID[ item.iItem ];
LoadString( EEGetLocaleInstanceHandle(), nID, item.pszText, item.cchTextMax );
}
}
break;
}
}
return bResult;
}
};
INT_PTR CALLBACK NewProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
LRESULT nResult = 0;
switch( msg ){
case WM_COMMAND:
{
TRACE( _T("WM_COMMAND: wParam = %x, lParam = %x.\n"), wParam, lParam );
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
pFrame->OnDlgCommand( wParam );
}
break;
case WM_NOTIFY:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
pFrame->OnDlgNotify( (NMHDR*)lParam );
}
break;
}
return (BOOL)nResult;
}
INT_PTR CALLBACK TableDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM /*lParam*/ )
{
LRESULT nResult = 0;
switch( msg ){
case WM_INITDIALOG:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
if( pFrame ){
pFrame->OnTableInitDialog( hwnd );
}
}
break;
case WM_COMMAND:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
pFrame->OnTableCommand( hwnd, wParam );
}
break;
}
return (BOOL)nResult;
}
INT_PTR CALLBACK PropDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM /*lParam*/ )
{
LRESULT nResult = 0;
switch( msg ){
case WM_INITDIALOG:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
if( pFrame ){
pFrame->OnPropInitDialog( hwnd );
}
}
break;
case WM_COMMAND:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
pFrame->OnPropCommand( hwnd, wParam );
}
break;
}
return (BOOL)nResult;
}
INT_PTR CALLBACK InputParamsDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
BOOL bResult = FALSE;
switch( msg ){
case WM_INITDIALOG:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrameFromDlg( hwnd ));
_ASSERTE( pFrame );
bResult = pFrame->OnInputInitDialog( hwnd );
}
break;
case WM_COMMAND:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrameFromDlg( hwnd ));
_ASSERTE( pFrame );
pFrame->OnInputDlgCommand( hwnd, wParam );
}
break;
case WM_NOTIFY:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrameFromDlg( hwnd ));
_ASSERTE( pFrame );
bResult = pFrame->OnInputDlgNotify( hwnd, (int)wParam, (LPNMHDR)lParam );
}
break;
}
return bResult;
}
LRESULT CALLBACK EditProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg ){
case WM_KEYDOWN:
{
CMyFrame* pFrame = (CMyFrame*)GetFrameFromDlg( hwnd );
if( pFrame != NULL ){
pFrame->OnEditKeyDown( hwnd, wParam, lParam );
}
}
break;
}
HWND hwndFrame = GetAncestor( hwnd, GA_ROOTOWNER );
if( IsWindow( hwndFrame ) ){
CMyFrame* pFrame = (CMyFrame*)GetFrameFromFrame( hwndFrame );
// CMyFrame* pFrame = (CMyFrame*)GetFrameFromDlg( hwnd );
if( pFrame != NULL && pFrame->m_lpOldEditProc != NULL ){
return CallWindowProc( pFrame->m_lpOldEditProc, hwnd, msg, wParam, lParam);
}
}
return 0;
}
INT_PTR CALLBACK CustomizeDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
LRESULT nResult = 0;
switch( msg ){
case WM_INITDIALOG:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
if( pFrame ){
pFrame->OnCustomizeInitDialog( hwnd );
}
}
break;
case WM_COMMAND:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
pFrame->OnCustomizeCommand( hwnd, wParam );
}
break;
case WM_NOTIFY:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
_ASSERTE( pFrame );
nResult = pFrame->OnCustomizeNotify( hwnd, (int)wParam, (LPNMHDR)lParam );
}
break;
}
return (BOOL)nResult;
}
INT_PTR CALLBACK CustPropDlg( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
LRESULT nResult = 0;
switch( msg ){
case WM_INITDIALOG:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
if( pFrame ){
pFrame->OnCustPropInitDialog( hwnd );
}
}
break;
case WM_COMMAND:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
pFrame->OnCustPropCommand( hwnd, wParam );
}
break;
case WM_NOTIFY:
{
CMyFrame* pFrame = static_cast<CMyFrame*>(GetFrame( hwnd ));
_ASSERTE( pFrame );
nResult = pFrame->OnCustPropNotify( hwnd, (int)wParam, (LPNMHDR)lParam );
}
break;
}
return (BOOL)nResult;
}
// the following line is needed after CMyFrame definition
_ETL_IMPLEMENT
|
1946cd6b5a64e231f8bf6eb3d38ad8ca67701386
|
[
"C",
"C++"
] | 5
|
C
|
Emurasoft/HTMLBar
|
a5c5cc7d6c45f70aeae7d6aa34002bc4b0a2903b
|
9a12487a47dabd81dfd116f02a8aee591cad80cb
|
refs/heads/main
|
<file_sep>#!/bin/sh
if [ "$#" -eq 3 ]; then
python3 RubiksCube.py "$1" "$2" "$3"
elif [ "$#" -eq 2 ]; then
python3 RubiksCube.py "$1" "$2"
else
python3 RubiksCube.py "$1"
fi<file_sep># CubeAI
This is a program that can solve a 2x2 Rubik's cube using a variety of search methods such as Breadth-First Search, Iterative Deepening Search, and A*. The heuristic I chose was the 3D Manhattan distance of the corners and then dividing that value by 4. This provided a pretty good admissible heuristic.
## Usage
`sh run.sh <search_method> <scramble_string>`
`sh run.sh bfs "F R L"`
## Dependencies
- `python 3.9+`
## Results
In all of my testing it appears that IDS explores the most nodes and A* explores the least nodes. A* exploring the least nodes is exactly what we would expect. BFS was the slowest, another expected result. Interestingly, there are cases where my A* implementation was slower than my IDS implementation. This tells me that I could have better utilized A* by applying it to IDS to create a IDA* algorithm, instead of applying A* in BFS. This would have taken the efficiency of the IDS algorithm and combined it with the selection of states of A*. The problem with A* is that it takes a lot of time to insert the state in the best position. Another way I could have made A* better was if I had come up with a better heuristic.
<file_sep>from os import defpath
from random import choice, randint
from sys import argv
from time import time
# different moves
# https://ruwix.com/online-puzzle-simulators/2x2x2-pocket-cube-simulator.php
MOVES = {
"U": [2, 0, 3, 1, 20, 21, 6, 7, 4, 5, 10, 11, 12, 13, 14, 15, 8, 9, 18, 19, 16, 17, 22, 23],
"U'": [1, 3, 0, 2, 8, 9, 6, 7, 16, 17, 10, 11, 12, 13, 14, 15, 20, 21, 18, 19, 4, 5, 22, 23],
"R": [0, 9, 2, 11, 6, 4, 7, 5, 8, 13, 10, 15, 12, 22, 14, 20, 16, 17, 18, 19, 3, 21, 1, 23],
"R'": [0, 22, 2, 20, 5, 7, 4, 6, 8, 1, 10, 3, 12, 9, 14, 11, 16, 17, 18, 19, 15, 21, 13, 23],
"F": [0, 1, 19, 17, 2, 5, 3, 7, 10, 8, 11, 9, 6, 4, 14, 15, 16, 12, 18, 13, 20, 21, 22, 23],
"F'": [0, 1, 4, 6, 13, 5, 12, 7, 9, 11, 8, 10, 17, 19, 14, 15, 16, 3, 18, 2, 20, 21, 22, 23],
"D": [0, 1, 2, 3, 4, 5, 10, 11, 8, 9, 18, 19, 14, 12, 15, 13, 16, 17, 22, 23, 20, 21, 6, 7],
"D'": [0, 1, 2, 3, 4, 5, 22, 23, 8, 9, 6, 7, 13, 15, 12, 14, 16, 17, 10, 11, 20, 21, 18, 19],
"L": [23, 1, 21, 3, 4, 5, 6, 7, 0, 9, 2, 11, 8, 13, 10, 15, 18, 16, 19, 17, 20, 14, 22, 12],
"L'": [8, 1, 10, 3, 4, 5, 6, 7, 12, 9, 14, 11, 23, 13, 21, 15, 17, 19, 16, 18, 20, 2, 22, 0],
"B": [5, 7, 2, 3, 4, 15, 6, 14, 8, 9, 10, 11, 12, 13, 16, 18, 1, 17, 0, 19, 22, 20, 23, 21],
"B'": [18, 16, 2, 3, 4, 0, 6, 1, 8, 9, 10, 11, 12, 13, 7, 5, 14, 17, 15, 19, 21, 23, 20, 22],
}
'''
sticker indices:
0 1
2 3
16 17 8 9 4 5 20 21
18 19 10 11 6 7 22 23
12 13
14 15
face colors:
0
4 2 1 5
3
moves:
[ U , U', R , R', F , F', D , D', L , L', B , B']
'''
class Cube:
def __init__(self, string="WWWW RRRR GGGG YYYY OOOO BBBB", moves=[], parent=None, depth=0, f=0):
self.state = self.cleanState(string)
self.moves = moves
self.parent = parent
self.depth = depth
self.f = f
# Checks if the given state is valid for a 2x2 Rubik's Cube
def cleanState(self, state):
# Cleans string
state = state.replace(" ", "")
state = state.upper()
# Error if invalid length
if len(state) != 24:
raise ValueError("Invalid state. Must have exactly 24 squares.")
# Error if number of each color is not 4
colors = ["W", "R", "G", "Y", "O", "B"]
for color in colors:
if state.count(color) != 4:
raise ValueError("Invalid state. Incorrect # of colors.")
return state
def __str__(self):
s = self.state
cubeStr = " {}{} \n".format(s[0], s[1])
cubeStr += " {}{} \n".format(s[2], s[3])
cubeStr += "{}{} {}{} {}{} {}{}\n".format(
s[16], s[17], s[8], s[9], s[4], s[5], s[20], s[21])
cubeStr += "{}{} {}{} {}{} {}{}\n".format(
s[18], s[19], s[10], s[11], s[6], s[7], s[22], s[23])
cubeStr += " {}{} \n".format(s[12], s[13])
return cubeStr + " {}{} \n".format(s[14], s[15])
# Prints the state of the cube
def print(self):
print(str(self))
# Prints a sequence of moves
def printSequence(self, moves):
s1 = str(self)
n = 0
for move in moves:
n += 1
if n == 3:
n = 0
print(s1)
self.state = self.applyMove(self.state, move)
s1 = str(self)
continue
self.state = self.applyMove(self.state, move)
s2 = str(self)
s1 = "\n".join([" ".join(s3)
for s3 in zip(s1.split("\n"), s2.split("\n"))])
print(s1)
# Returns True if the state is the goal state, False otherwise
def isSolved(self):
for i in range(0, len(self.state), 4):
side = self.state[i:i+4]
if side.count(side[0]) != 4:
return False
return True
# Returns True if the cube's state is the same as the given cube, False otherwise
def equals(self, cube):
return self.norm(self.state) == self.norm(cube.state)
# Returns a clone of the cube's state
def clone(self):
return self.state
# Returns a string representing the state with the given algorithm applied
def applyMovesStr(self, alg):
# Clone the state of the cube
state = self.clone()
# Apply each move in the algorithm to the cloned state
for move in alg.split():
state = self.applyMove(state, move)
return state
# Returns a string representing the state with the given move applied
def applyMove(self, state, move):
# Error if the given move is not in the list of moves
if move not in MOVES.keys():
raise ValueError("Invalid move.")
# Move each square in the state to its position in the permutation
perm = MOVES[move]
state = "".join([state[i] for i in perm])
return state
# Returns a string of the normal form of the given state
def norm(self, state):
state = self.cleanState(state)
opps = {"O": "R", "G": "B", "Y": "W", "R": "O", "B": "G", "W": "Y"}
# Finds the opposite colors
s0, s1, s2 = state[10], state[12], state[19]
o0, o1, o2 = opps[s0], opps[s1], opps[s2]
# Creates a mapping based on 10, 12, 19 and its opposites
mapping = {s0: "G", s1: "Y", s2: "O", o0: "B", o1: "W", o2: "R"}
# Builds the normal form
normState = ""
for s in state:
normState += mapping[s]
return normState
# Returns a Cube whose state is shuffled by n moves
def shuffle(self, n):
# Choose n random moves from the list of moves and creates an algorithm to apply
moves = list(MOVES.keys())
alg = " ".join([choice(moves) for i in range(n)])
shuffledState = self.applyMovesStr(alg)
return Cube(shuffledState)
# Does a random walk through states until it reaches the goal or picks n moves
# Returns the random algorithm as a string
def randomWalk(self, n):
alg = []
moves = list(MOVES.keys())
while n:
move = choice(moves)
alg.append(move)
self.state = self.applyMove(self.state, move)
if self.isSolved():
return " ".join(alg)
n -= 1
return " ".join(alg)
# Checks if a move is valid. A move is valid if:
# move is not the inverse of the last move
# move is not the complement of the last move
# using move will result in the same move 3 times
def validMove(self, move):
if self.moves:
lastMove = self.moves[-1]
if move == self.inverse(lastMove) or move == self.complement(lastMove):
return False
elif len(self.moves) >= 2 and move == lastMove and move == self.moves[-2]:
return False
return True
# Returns the inverse of the given move
def inverse(self, move):
if len(move) == 1:
return move + "'"
else:
return move[0]
# Returns the complement of the given move
def complement(self, move):
complements = {"U": "D'", "U'": "D",
"L'": "R", "L": "R'",
"F": "B'", "F'": "B",
"D'": "U", "D": "U'",
"R": "L'", "R'": "L",
"B'": "F", "B": "F'"}
return complements[move]
# Adds a move to the cube's list of applied moves
def addMove(self, move):
self.moves.append(move)
# Computes the sum of number of moves to put each corner in its
# correct position divided by 4
def heuristic(self, state):
myCorners = []
solvedCorners = []
cornerSum = 0
s = self.norm(state)
solved = Cube().state
# Corner indices
corners = [(10, 12, 19), (6, 11, 13),
(2, 8, 17), (3, 4, 9),
(14, 18, 23), (7, 15, 22),
(0, 16, 21), (1, 5, 20)]
# Coordinates for the corners in a 3D plot
coords = [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 0),
(0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 1)]
# Goes through the corners of the state and a solved state
# and tracks them in their respective lists
for x, y, z in corners:
corner = "".join(sorted(s[x] + s[y] + s[z]))
myCorners.append(corner)
corner = "".join(sorted(solved[x] + solved[y] + solved[z]))
solvedCorners.append(corner)
# Goes through each coordinate for the 3D plot
for i in range(len(coords)):
# Gets the corner at the current coord
myCorner = myCorners[i]
myCoords = coords[i]
# Gets the coords for the corner if it was actually solved
idx = solvedCorners.index(myCorner)
solvedCoords = coords[idx]
# If the current corner's coords are not the same as its
# solved coords, then compute the 3D manhattan distance
if myCoords != solvedCoords:
x = abs(solvedCoords[0] - myCoords[0])
y = abs(solvedCoords[1] - myCoords[1])
z = abs(solvedCoords[2] - myCoords[2])
cornerSum += x + y + z
return cornerSum / 4
# Solves the cube with breadth-first search
def bfs(self):
if self.isSolved():
return self.moves, 0, 0.0
start = time()
cubes = [self]
opened = [self.state]
closed = set()
nodeCount = 0
while opened:
# Open the first state
state0 = opened.pop(0)
cube0 = cubes.pop(0)
# Close the first state
closed.add(state0)
for move in MOVES.keys():
# Skips moves that lead to inverse and complement states
if not cube0.validMove(move):
continue
# Applies move and normalizes result so we don't store duplicate states
state = self.norm(self.applyMove(cube0.state, move))
if state not in closed and state not in opened:
nodeCount += 1
# Creates a cube for this state and tracks the moves
cube = Cube(state, cube0.moves[:])
cube.addMove(move)
if cube.isSolved():
return cube.moves, nodeCount, time() - start
opened.append(state)
cubes.append(cube)
# Solves the cube using iterative deepening search
def ids(self):
if self.isSolved():
return self.moves, 0, 0.0
totalNodes = 0
start = time()
depth = 0
cube = self
while True:
# Iteratively calls depth limited search until solution is found
cube, nodeCount = self.dls(cube, depth)
totalNodes += nodeCount
print("Depth: {} d: {}".format(depth, nodeCount))
if cube.isSolved():
return cube.moves, totalNodes, time() - start, depth
depth += 1
def dls(self, cube0, limit):
nodeCount = 0
if cube0.isSolved() or limit <= 0:
return cube0, nodeCount
for move in MOVES.keys():
# Skips moves that lead to unnecessary states
if not cube0.validMove(move):
continue
# Applies move
state = self.applyMove(cube0.state, move)
cube = Cube(state, cube0.moves[:])
# Tracks the moves up to this cube
cube.addMove(move)
nodeCount += 1
# Recursively call depth limited search until limit is 0
cube, n = self.dls(cube, limit - 1)
nodeCount += n
if cube.isSolved():
return cube, nodeCount
return cube0, nodeCount
# Solves the cube with breadth-first search
def astar(self):
if self.isSolved():
return self.moves, 0, 0.0
start = time()
cubes = [self]
opened = [self.state]
closed = set()
nodeCount = 0
while opened:
# Open the first state in the list
state0 = opened.pop(0)
cube0 = cubes.pop(0)
# Close the state
closed.add(state0)
depth = cube0.depth + 1
for move in MOVES.keys():
# Skips moves that lead to inverse and complement states
if not cube0.validMove(move):
continue
# Applies move and normalizes result so we don't store duplicate states
state = self.norm(self.applyMove(cube0.state, move))
if state not in closed and state not in opened:
nodeCount += 1
# Compute heuristic function
f = depth + self.heuristic(state)
# Creates a cube for this state and tracks the moves
cube = Cube(state, cube0.moves[:], cube0, depth, f)
cube.addMove(move)
if cube.isSolved():
return cube.moves, nodeCount, time() - start
# Inserts the state depending on its heuristic
for i in range(len(cubes) + 1):
if i == len(cubes):
opened.append(state)
cubes.append(cube)
elif cube.f < cubes[i].f:
opened.insert(i, state)
cubes.insert(i, cube)
break
def main():
argc = len(argv)
cmd = argv[1]
if cmd == "print" and argc <= 2:
cube = Cube()
cube.print()
elif cmd == "print" and argc > 2:
cube = Cube(argv[2])
cube.print()
elif cmd == "goal" and argc > 2:
cube = Cube(argv[2])
print(cube.isSolved())
elif cmd == "applyMovesStr" and argc > 3:
cube = Cube(argv[3])
newState = cube.applyMovesStr(argv[2])
cube = Cube(newState)
cube.print()
elif cmd == "norm" and argc > 2:
cube = Cube()
cube.state = cube.norm(argv[2])
cube.print()
elif cmd == "shuffle" and argc > 2:
if not argv[2].isnumeric():
raise ValueError("Invalid number of moves for shuffle.")
cube = Cube()
shuffledCube = cube.shuffle(int(argv[2]))
shuffledCube.print()
elif cmd == "random" and argc > 2:
cube = Cube()
cube.state = cube.applyMovesStr(argv[2])
print(cube.randomWalk(3))
cube.print()
elif cmd == "bfs" and argc > 2:
cube = Cube()
cube.state = cube.applyMovesStr(argv[2])
moves, nodeCount, time = cube.bfs()
print(" ".join(moves))
cube.printSequence(moves)
print(nodeCount)
print(round(time, 2))
elif cmd == "ids" and argc > 2:
cube = Cube()
cube.state = cube.applyMovesStr(argv[2])
moves, nodeCount, time, depth = cube.ids()
print("IDS found a solution at depth", depth)
print(" ".join(moves))
cube.printSequence(moves)
print(nodeCount)
print(round(time, 2))
elif cmd == "astar" and argc > 2:
cube = Cube()
cube.state = cube.applyMovesStr(argv[2])
moves, nodeCount, time = cube.astar()
print(" ".join(moves))
cube.printSequence(moves)
print(nodeCount)
print(round(time, 2))
if __name__ == "__main__":
main()
|
25b686cfa5c062c1efb49b02349d0ea89fd96fb3
|
[
"Markdown",
"Python",
"Shell"
] | 3
|
Shell
|
is386/CubeAI
|
dfcf5bef210b57469439c150c5e5c46083d10515
|
1e55d9f93ab278feb6cf9b30a9f3385e4a7d50d6
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.